diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml index bc08868dc1..fc0705998f 100644 --- a/.github/workflows/documentation.yml +++ b/.github/workflows/documentation.yml @@ -10,6 +10,7 @@ on: branches: [main] paths: - 'website/**' + workflow_dispatch: jobs: check-build: diff --git a/.github/workflows/nightly_merge.yml b/.github/workflows/nightly_merge.yml index 676b00a351..1d36c89cc7 100644 --- a/.github/workflows/nightly_merge.yml +++ b/.github/workflows/nightly_merge.yml @@ -1,4 +1,4 @@ -name: Nightly Merge +name: Dev -> Main on: schedule: @@ -14,10 +14,16 @@ jobs: - name: 🚛 Checkout Code uses: actions/checkout@v2 - - name: Merge development -> main - uses: devmasx/merge-branch@v1.3.1 + - name: 🔨 Merge develop to main + uses: everlytic/branch-merge@1.1.0 with: - type: now - from_branch: develop - target_branch: main - github_token: ${{ secrets.TOKEN }} \ No newline at end of file + github_token: ${{ secrets.ADMIN_TOKEN }} + source_ref: 'develop' + target_branch: 'main' + commit_message_template: '[Automated] Merged {source_ref} into {target_branch}' + + - name: Invoke pre-release workflow + uses: benc-uk/workflow-dispatch@v1 + with: + workflow: Nightly Prerelease + token: ${{ secrets.ADMIN_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml index 0e6c7b5da9..d0853e74d6 100644 --- a/.github/workflows/prerelease.yml +++ b/.github/workflows/prerelease.yml @@ -1,8 +1,7 @@ name: Nightly Prerelease on: - push: - branches: [main] + workflow_dispatch: jobs: @@ -43,14 +42,16 @@ jobs: id: generate-full-changelog uses: heinrichreimer/github-changelog-generator-action@v2.2 with: - token: ${{ secrets.GITHUB_TOKEN }} - breakingLabel: '#### 💥 Breaking' - enhancementLabel: '#### 🚀 Enhancements' - bugsLabel: '#### 🐛 Bug fixes' - deprecatedLabel: '#### ⚠️ Deprecations' + token: ${{ secrets.ADMIN_TOKEN }} + breakingLabel: '**💥 Breaking**' + enhancementLabel: '**🚀 Enhancements**' + bugsLabel: '**🐛 Bug fixes**' + deprecatedLabel: '**⚠️ Deprecations**' addSections: '{"documentation":{"prefix":"### 📖 Documentation","labels":["documentation"]},"tests":{"prefix":"### ✅ Testing","labels":["tests"]}}' issues: false issuesWoLabels: false + sinceTag: "3.0.0" + maxIssues: 100 pullRequests: true prWoLabels: false author: false @@ -80,14 +81,20 @@ jobs: git commit -m "[Automated] Bump version" tag_name="CI/${{ steps.version.outputs.next_tag }}" git tag -a $tag_name -m "nightly build" - git push - git push origin $tag_name + + - name: Push to protected main branch + uses: CasperWA/push-protected@v2 + with: + token: ${{ secrets.ADMIN_TOKEN }} + branch: main + tags: true + unprotect_reviews: true - name: 🔨 Merge main back to develop uses: everlytic/branch-merge@1.1.0 if: steps.version_type.outputs.type != 'skip' with: - github_token: ${{ secrets.GITHUB_TOKEN }} + github_token: ${{ secrets.ADMIN_TOKEN }} source_ref: 'main' target_branch: 'develop' commit_message_template: '[Automated] Merged {source_ref} into {target_branch}' \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 782c9c8dda..37e1cb4b15 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,13 +1,14 @@ name: Stable Release on: - push: - tags: - - '*[0-9].*[0-9].*[0-9]*' + release: + types: + - prereleased jobs: create_release: runs-on: ubuntu-latest + if: github.actor != 'pypebot' steps: - name: 🚛 Checkout Code @@ -22,37 +23,31 @@ jobs: - name: Install Python requirements run: pip install gitpython semver - - name: Set env - run: | - echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV - - git config user.email ${{ secrets.CI_EMAIL }} - git config user.name ${{ secrets.CI_USER }} - git fetch - git checkout -b main origin/main - git tag -d ${GITHUB_REF#refs/*/} - git push origin --delete ${GITHUB_REF#refs/*/} - echo PREVIOUS_VERSION=`git describe --tags --match="[0-9]*" --abbrev=0` >> $GITHUB_ENV - - name: 💉 Inject new version into files id: version - if: steps.version_type.outputs.type != 'skip' run: | - python ./tools/ci_tools.py --version ${{ env.RELEASE_VERSION }} + echo ::set-output name=current_version::${GITHUB_REF#refs/*/} + RESULT=$(python ./tools/ci_tools.py --finalize ${GITHUB_REF#refs/*/}) + LASTRELEASE=$(python ./tools/ci_tools.py --lastversion release) + + echo ::set-output name=last_release::$LASTRELEASE + echo ::set-output name=release_tag::$RESULT - name: "✏️ Generate full changelog" - if: steps.version_type.outputs.type != 'skip' + if: steps.version.outputs.release_tag != 'skip' id: generate-full-changelog uses: heinrichreimer/github-changelog-generator-action@v2.2 with: - token: ${{ secrets.GITHUB_TOKEN }} - breakingLabel: '#### 💥 Breaking' - enhancementLabel: '#### 🚀 Enhancements' - bugsLabel: '#### 🐛 Bug fixes' - deprecatedLabel: '#### ⚠️ Deprecations' + token: ${{ secrets.ADMIN_TOKEN }} + breakingLabel: '**💥 Breaking**' + enhancementLabel: '**🚀 Enhancements**' + bugsLabel: '**🐛 Bug fixes**' + deprecatedLabel: '**⚠️ Deprecations**' addSections: '{"documentation":{"prefix":"### 📖 Documentation","labels":["documentation"]},"tests":{"prefix":"### ✅ Testing","labels":["tests"]}}' issues: false issuesWoLabels: false + sinceTag: "3.0.0" + maxIssues: 100 pullRequests: true prWoLabels: false author: false @@ -60,40 +55,78 @@ jobs: compareLink: true stripGeneratorNotice: true verbose: true - futureRelease: ${{ env.RELEASE_VERSION }} + futureRelease: ${{ steps.version.outputs.release_tag }} excludeTagsRegex: "CI/.+" releaseBranch: "main" - - name: "🖨️ Print changelog to console" - run: echo ${{ steps.generate-last-changelog.outputs.changelog }} - - name: 💾 Commit and Tag id: git_commit - if: steps.version_type.outputs.type != 'skip' + if: steps.version.outputs.release_tag != 'skip' run: | + git config user.email ${{ secrets.CI_EMAIL }} + git config user.name ${{ secrets.CI_USER }} git add . git commit -m "[Automated] Release" - tag_name="${{ env.RELEASE_VERSION }}" - git push - git tag -fa $tag_name -m "stable release" - git push origin $tag_name + tag_name="${{ steps.version.outputs.release_tag }}" + git tag -a $tag_name -m "stable release" - - name: "🚀 Github Release" - uses: docker://antonyurchenko/git-release:latest - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - DRAFT_RELEASE: "false" - PRE_RELEASE: "false" - CHANGELOG_FILE: "CHANGELOG.md" - ALLOW_EMPTY_CHANGELOG: "false" - ALLOW_TAG_PREFIX: "true" - - - - name: 🔨 Merge main back to develop - uses: everlytic/branch-merge@1.1.0 - if: steps.version_type.outputs.type != 'skip' + - name: 🔏 Push to protected main branch + if: steps.version.outputs.release_tag != 'skip' + uses: CasperWA/push-protected@v2 with: - github_token: ${{ secrets.GITHUB_TOKEN }} + token: ${{ secrets.ADMIN_TOKEN }} + branch: main + tags: true + unprotect_reviews: true + + - name: "✏️ Generate last changelog" + if: steps.version.outputs.release_tag != 'skip' + id: generate-last-changelog + uses: heinrichreimer/github-changelog-generator-action@v2.2 + with: + token: ${{ secrets.ADMIN_TOKEN }} + breakingLabel: '**💥 Breaking**' + enhancementLabel: '**🚀 Enhancements**' + bugsLabel: '**🐛 Bug fixes**' + deprecatedLabel: '**⚠️ Deprecations**' + addSections: '{"documentation":{"prefix":"### 📖 Documentation","labels":["documentation"]},"tests":{"prefix":"### ✅ Testing","labels":["tests"]}}' + issues: false + issuesWoLabels: false + sinceTag: ${{ steps.version.outputs.last_release }} + maxIssues: 100 + pullRequests: true + prWoLabels: false + author: false + unreleased: true + compareLink: true + stripGeneratorNotice: true + verbose: true + futureRelease: ${{ steps.version.outputs.release_tag }} + excludeTagsRegex: "CI/.+" + releaseBranch: "main" + stripHeaders: true + base: 'none' + + + - name: 🚀 Github Release + if: steps.version.outputs.release_tag != 'skip' + uses: ncipollo/release-action@v1 + with: + body: ${{ steps.generate-last-changelog.outputs.changelog }} + tag: ${{ steps.version.outputs.release_tag }} + token: ${{ secrets.ADMIN_TOKEN }} + + - name: ☠ Delete Pre-release + if: steps.version.outputs.release_tag != 'skip' + uses: cb80/delrel@latest + with: + tag: "${{ steps.version.outputs.current_version }}" + + - name: 🔁 Merge main back to develop + if: steps.version.outputs.release_tag != 'skip' + uses: everlytic/branch-merge@1.1.0 + with: + github_token: ${{ secrets.ADMIN_TOKEN }} source_ref: 'main' target_branch: 'develop' commit_message_template: '[Automated] Merged release {source_ref} into {target_branch}' \ No newline at end of file diff --git a/.gitignore b/.gitignore index 754e3698e2..221a2f2241 100644 --- a/.gitignore +++ b/.gitignore @@ -97,4 +97,5 @@ website/.docusaurus # Poetry ######## -.poetry/ \ No newline at end of file +.poetry/ +.python-version diff --git a/CHANGELOG.md b/CHANGELOG.md index 032f876aa3..96b90cd53e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,125 @@ # Changelog +## [3.2.0-nightly.4](https://github.com/pypeclub/OpenPype/tree/HEAD) + +[Full Changelog](https://github.com/pypeclub/OpenPype/compare/2.18.4...HEAD) + +**🚀 Enhancements** + +- Application executables with environment variables [\#1757](https://github.com/pypeclub/OpenPype/pull/1757) +- Settings Hosts enum [\#1739](https://github.com/pypeclub/OpenPype/pull/1739) +- Validate containers settings [\#1736](https://github.com/pypeclub/OpenPype/pull/1736) +- PS - added loader from sequence [\#1726](https://github.com/pypeclub/OpenPype/pull/1726) +- Autoupdate launcher [\#1725](https://github.com/pypeclub/OpenPype/pull/1725) +- Subset template and TVPaint subset template docs [\#1717](https://github.com/pypeclub/OpenPype/pull/1717) +- Toggle Ftrack upload in StandalonePublisher [\#1708](https://github.com/pypeclub/OpenPype/pull/1708) +- Overscan color extract review [\#1701](https://github.com/pypeclub/OpenPype/pull/1701) +- Nuke: Prerender Frame Range by default [\#1699](https://github.com/pypeclub/OpenPype/pull/1699) +- Smoother edges of color triangle [\#1695](https://github.com/pypeclub/OpenPype/pull/1695) + +**🐛 Bug fixes** + +- Backend acre module commit update [\#1745](https://github.com/pypeclub/OpenPype/pull/1745) +- hiero: precollect instances failing when audio selected [\#1743](https://github.com/pypeclub/OpenPype/pull/1743) +- Hiero: creator instance error [\#1742](https://github.com/pypeclub/OpenPype/pull/1742) +- Nuke: fixing render creator for no selection format failing [\#1741](https://github.com/pypeclub/OpenPype/pull/1741) +- Local settings UI crash on missing defaults [\#1737](https://github.com/pypeclub/OpenPype/pull/1737) +- TVPaint white background on thumbnail [\#1735](https://github.com/pypeclub/OpenPype/pull/1735) +- Ftrack missing custom attribute message [\#1734](https://github.com/pypeclub/OpenPype/pull/1734) +- Launcher project changes [\#1733](https://github.com/pypeclub/OpenPype/pull/1733) +- Ftrack sync status [\#1732](https://github.com/pypeclub/OpenPype/pull/1732) +- TVPaint use layer name for default variant [\#1724](https://github.com/pypeclub/OpenPype/pull/1724) +- Default subset template for TVPaint review and workfile families [\#1716](https://github.com/pypeclub/OpenPype/pull/1716) +- Maya: Extract review hotfix [\#1714](https://github.com/pypeclub/OpenPype/pull/1714) +- Settings: Imageio improving granularity [\#1711](https://github.com/pypeclub/OpenPype/pull/1711) +- Application without executables [\#1679](https://github.com/pypeclub/OpenPype/pull/1679) + +**Merged pull requests:** + +- TVPaint ftrack family [\#1755](https://github.com/pypeclub/OpenPype/pull/1755) + +## [2.18.4](https://github.com/pypeclub/OpenPype/tree/2.18.4) (2021-06-24) + +[Full Changelog](https://github.com/pypeclub/OpenPype/compare/2.18.3...2.18.4) + +**Merged pull requests:** + +- celaction fixes [\#1754](https://github.com/pypeclub/OpenPype/pull/1754) +- celaciton: audio subset changed data structure [\#1750](https://github.com/pypeclub/OpenPype/pull/1750) + +## [2.18.3](https://github.com/pypeclub/OpenPype/tree/2.18.3) (2021-06-23) + +[Full Changelog](https://github.com/pypeclub/OpenPype/compare/CI/3.2.0-nightly.2...2.18.3) + +**🐛 Bug fixes** + +- Tools names forwards compatibility [\#1727](https://github.com/pypeclub/OpenPype/pull/1727) + +**Merged pull requests:** + +- global: removing obsolete ftrack validator plugin [\#1710](https://github.com/pypeclub/OpenPype/pull/1710) + +## [2.18.2](https://github.com/pypeclub/OpenPype/tree/2.18.2) (2021-06-16) + +[Full Changelog](https://github.com/pypeclub/OpenPype/compare/3.1.0...2.18.2) + +**🚀 Enhancements** + +- StandalonePublisher: adding exception for adding `delete` tag to repre [\#1650](https://github.com/pypeclub/OpenPype/pull/1650) + +**🐛 Bug fixes** + +- Maya: Extract review hotfix - 2.x backport [\#1713](https://github.com/pypeclub/OpenPype/pull/1713) +- StandalonePublisher: instance data attribute `keepSequence` [\#1668](https://github.com/pypeclub/OpenPype/pull/1668) + +**Merged pull requests:** + +- 1698 Nuke: Prerender Frame Range by default [\#1709](https://github.com/pypeclub/OpenPype/pull/1709) + +## [3.1.0](https://github.com/pypeclub/OpenPype/tree/3.1.0) (2021-06-15) + +[Full Changelog](https://github.com/pypeclub/OpenPype/compare/CI/3.1.0-nightly.4...3.1.0) + +**🚀 Enhancements** + +- Log Viewer with OpenPype style [\#1703](https://github.com/pypeclub/OpenPype/pull/1703) +- Scrolling in OpenPype info widget [\#1702](https://github.com/pypeclub/OpenPype/pull/1702) +- OpenPype style in modules [\#1694](https://github.com/pypeclub/OpenPype/pull/1694) +- Sort applications and tools alphabetically in Settings UI [\#1689](https://github.com/pypeclub/OpenPype/pull/1689) +- \#683 - Validate Frame Range in Standalone Publisher [\#1683](https://github.com/pypeclub/OpenPype/pull/1683) +- Hiero: old container versions identify with red color [\#1682](https://github.com/pypeclub/OpenPype/pull/1682) +- Project Manger: Default name column width [\#1669](https://github.com/pypeclub/OpenPype/pull/1669) +- Remove outline in stylesheet [\#1667](https://github.com/pypeclub/OpenPype/pull/1667) +- TVPaint: Creator take layer name as default value for subset variant [\#1663](https://github.com/pypeclub/OpenPype/pull/1663) +- TVPaint custom subset template [\#1662](https://github.com/pypeclub/OpenPype/pull/1662) +- Editorial: conform assets validator [\#1659](https://github.com/pypeclub/OpenPype/pull/1659) +- Feature Slack integration [\#1657](https://github.com/pypeclub/OpenPype/pull/1657) +- Nuke - Publish simplification [\#1653](https://github.com/pypeclub/OpenPype/pull/1653) +- \#1333 - added tooltip hints to Pyblish buttons [\#1649](https://github.com/pypeclub/OpenPype/pull/1649) + +**🐛 Bug fixes** + +- Nuke: broken publishing rendered frames [\#1707](https://github.com/pypeclub/OpenPype/pull/1707) +- Standalone publisher Thumbnail export args [\#1705](https://github.com/pypeclub/OpenPype/pull/1705) +- Bad zip can break OpenPype start [\#1691](https://github.com/pypeclub/OpenPype/pull/1691) +- Hiero: published whole edit mov [\#1687](https://github.com/pypeclub/OpenPype/pull/1687) +- Ftrack subprocess handle of stdout/stderr [\#1675](https://github.com/pypeclub/OpenPype/pull/1675) +- Settings list race condifiton and mutable dict list conversion [\#1671](https://github.com/pypeclub/OpenPype/pull/1671) +- Mac launch arguments fix [\#1660](https://github.com/pypeclub/OpenPype/pull/1660) +- Fix missing dbm python module [\#1652](https://github.com/pypeclub/OpenPype/pull/1652) +- Transparent branches in view on Mac [\#1648](https://github.com/pypeclub/OpenPype/pull/1648) +- Add asset on task item [\#1646](https://github.com/pypeclub/OpenPype/pull/1646) +- Project manager save and queue [\#1645](https://github.com/pypeclub/OpenPype/pull/1645) +- New project anatomy values [\#1644](https://github.com/pypeclub/OpenPype/pull/1644) + +**Merged pull requests:** + +- update dependencies [\#1697](https://github.com/pypeclub/OpenPype/pull/1697) +- Bump normalize-url from 4.5.0 to 4.5.1 in /website [\#1686](https://github.com/pypeclub/OpenPype/pull/1686) +- Use poetry to build / publish OpenPype wheel [\#1636](https://github.com/pypeclub/OpenPype/pull/1636) + +# Changelog + ## [3.0.0](https://github.com/pypeclub/openpype/tree/3.0.0) @@ -1565,10 +1685,9 @@ A large cleanup release. Most of the change are under the hood. - _(avalon)_ subsets in maya 2019 weren't behaving correctly in the outliner -\* *This Changelog was automatically generated by [github_changelog_generator](https://github.com/github-changelog-generator/github-changelog-generator)* -\* *This Changelog was automatically generated by [github_changelog_generator](https://github.com/github-changelog-generator/github-changelog-generator)* -\* *This Changelog was automatically generated by [github_changelog_generator](https://github.com/github-changelog-generator/github-changelog-generator)* + + diff --git a/HISTORY.md b/HISTORY.md index ae4492bd7a..032f876aa3 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -3,7 +3,7 @@ ## [3.0.0](https://github.com/pypeclub/openpype/tree/3.0.0) -[Full Changelog](https://github.com/pypeclub/openpype/compare/CI/3.0.0-rc.6...3.0.0) +[Full Changelog](https://github.com/pypeclub/openpype/compare/2.18.1...3.0.0) ### Configuration - Studio Settings GUI: no more json configuration files. diff --git a/README.md b/README.md index 566e226538..6b4495c9b6 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ OpenPype ==== -[![documentation](https://github.com/pypeclub/pype/actions/workflows/documentation.yml/badge.svg)](https://github.com/pypeclub/pype/actions/workflows/documentation.yml) ![GitHub Requirements](https://img.shields.io/requires/github/pypeclub/pype?labelColor=303846) ![GitHub VFX Platform](https://img.shields.io/badge/vfx%20platform-2021-lightgrey?labelColor=303846) +[![documentation](https://github.com/pypeclub/pype/actions/workflows/documentation.yml/badge.svg)](https://github.com/pypeclub/pype/actions/workflows/documentation.yml) ![GitHub VFX Platform](https://img.shields.io/badge/vfx%20platform-2021-lightgrey?labelColor=303846) diff --git a/igniter/bootstrap_repos.py b/igniter/bootstrap_repos.py index 7c4f8b4b69..6eaea27116 100644 --- a/igniter/bootstrap_repos.py +++ b/igniter/bootstrap_repos.py @@ -972,8 +972,12 @@ class BootstrapRepos: "openpype/version.py") as version_file: zip_version = {} exec(version_file.read(), zip_version) - version_check = OpenPypeVersion( - version=zip_version["__version__"]) + try: + version_check = OpenPypeVersion( + version=zip_version["__version__"]) + except ValueError as e: + self._print(str(e), True) + return False version_main = version_check.get_main_version() # noqa: E501 detected_main = detected_version.get_main_version() # noqa: E501 diff --git a/igniter/version.py b/igniter/version.py index 3c627aaa1a..56d58f7f60 100644 --- a/igniter/version.py +++ b/igniter/version.py @@ -1,4 +1,4 @@ # -*- coding: utf-8 -*- """Definition of Igniter version.""" -__version__ = "1.0.0" +__version__ = "1.0.1" diff --git a/openpype/cli.py b/openpype/cli.py index 9f4561b82e..48951c7287 100644 --- a/openpype/cli.py +++ b/openpype/cli.py @@ -115,7 +115,9 @@ def extractenvironments(output_json_path, project, asset, task, app): @main.command() @click.argument("paths", nargs=-1) @click.option("-d", "--debug", is_flag=True, help="Print debug messages") -def publish(debug, paths): +@click.option("-t", "--targets", help="Targets module", default=None, + multiple=True) +def publish(debug, paths, targets): """Start CLI publishing. Publish collects json from paths provided as an argument. @@ -123,7 +125,7 @@ def publish(debug, paths): """ if debug: os.environ['OPENPYPE_DEBUG'] = '3' - PypeCommands.publish(list(paths)) + PypeCommands.publish(list(paths), targets) @main.command() diff --git a/openpype/hooks/pre_mac_launch.py b/openpype/hooks/pre_mac_launch.py index 3f07ae07db..f85557a4f0 100644 --- a/openpype/hooks/pre_mac_launch.py +++ b/openpype/hooks/pre_mac_launch.py @@ -31,4 +31,4 @@ class LaunchWithTerminal(PreLaunchHook): if len(self.launch_context.launch_args) > 1: self.launch_context.launch_args.insert(1, "--args") # Prepend open arguments - self.launch_context.launch_args.insert(0, ["open", "-a"]) + self.launch_context.launch_args.insert(0, ["open", "-na"]) diff --git a/openpype/hosts/hiero/api/lib.py b/openpype/hosts/hiero/api/lib.py index d8a235be77..876fae5da9 100644 --- a/openpype/hosts/hiero/api/lib.py +++ b/openpype/hosts/hiero/api/lib.py @@ -190,7 +190,7 @@ def get_track_items( if not item.isEnabled(): continue if track_item_name: - if item.name() in track_item_name: + if track_item_name in item.name(): return item # make sure only track items with correct track names are added if track_name and track_name in track.name(): @@ -949,6 +949,54 @@ def sync_clip_name_to_data_asset(track_items_list): print("asset was changed in clip: {}".format(ti_name)) +def check_inventory_versions(): + """ + Actual version color idetifier of Loaded containers + + Check all track items and filter only + Loader nodes for its version. It will get all versions from database + and check if the node is having actual version. If not then it will color + it to red. + """ + from . import parse_container + from avalon import io + + # presets + clip_color_last = "green" + clip_color = "red" + + # get all track items from current timeline + for track_item in get_track_items(): + container = parse_container(track_item) + + if container: + # get representation from io + representation = io.find_one({ + "type": "representation", + "_id": io.ObjectId(container["representation"]) + }) + + # Get start frame from version data + version = io.find_one({ + "type": "version", + "_id": representation["parent"] + }) + + # get all versions in list + versions = io.find({ + "type": "version", + "parent": version["parent"] + }).distinct('name') + + max_version = max(versions) + + # set clip colour + if version.get("name") == max_version: + track_item.source().binItem().setColor(clip_color_last) + else: + track_item.source().binItem().setColor(clip_color) + + def selection_changed_timeline(event): """Callback on timeline to check if asset in data is the same as clip name. @@ -958,9 +1006,15 @@ def selection_changed_timeline(event): timeline_editor = event.sender selection = timeline_editor.selection() + selection = [ti for ti in selection + if isinstance(ti, hiero.core.TrackItem)] + # run checking function sync_clip_name_to_data_asset(selection) + # also mark old versions of loaded containers + check_inventory_versions() + def before_project_save(event): track_items = get_track_items( @@ -972,3 +1026,6 @@ def before_project_save(event): # run checking function sync_clip_name_to_data_asset(track_items) + + # also mark old versions of loaded containers + check_inventory_versions() diff --git a/openpype/hosts/hiero/plugins/create/create_shot_clip.py b/openpype/hosts/hiero/plugins/create/create_shot_clip.py index 25be9f090b..0c5bf93a3f 100644 --- a/openpype/hosts/hiero/plugins/create/create_shot_clip.py +++ b/openpype/hosts/hiero/plugins/create/create_shot_clip.py @@ -1,3 +1,4 @@ +from copy import deepcopy import openpype.hosts.hiero.api as phiero # from openpype.hosts.hiero.api import plugin, lib # reload(lib) @@ -206,20 +207,24 @@ class CreateShotClip(phiero.Creator): presets = None def process(self): + # Creator copy of object attributes that are modified during `process` + presets = deepcopy(self.presets) + gui_inputs = deepcopy(self.gui_inputs) + # get key pares from presets and match it on ui inputs - for k, v in self.gui_inputs.items(): + for k, v in gui_inputs.items(): if v["type"] in ("dict", "section"): # nested dictionary (only one level allowed # for sections and dict) for _k, _v in v["value"].items(): - if self.presets.get(_k): - self.gui_inputs[k][ - "value"][_k]["value"] = self.presets[_k] - if self.presets.get(k): - self.gui_inputs[k]["value"] = self.presets[k] + if presets.get(_k): + gui_inputs[k][ + "value"][_k]["value"] = presets[_k] + if presets.get(k): + gui_inputs[k]["value"] = presets[k] # open widget for plugins inputs - widget = self.widget(self.gui_name, self.gui_info, self.gui_inputs) + widget = self.widget(self.gui_name, self.gui_info, gui_inputs) widget.exec_() if len(self.selected) < 1: diff --git a/openpype/hosts/hiero/plugins/publish/precollect_instances.py b/openpype/hosts/hiero/plugins/publish/precollect_instances.py index 92e0a70d15..4984849aa7 100644 --- a/openpype/hosts/hiero/plugins/publish/precollect_instances.py +++ b/openpype/hosts/hiero/plugins/publish/precollect_instances.py @@ -41,16 +41,10 @@ class PrecollectInstances(pyblish.api.ContextPlugin): # process all sellected timeline track items for track_item in selected_timeline_items: - data = {} clip_name = track_item.name() source_clip = track_item.source() - - # get clips subtracks and anotations - annotations = self.clip_annotations(source_clip) - subtracks = self.clip_subtrack(track_item) - self.log.debug("Annotations: {}".format(annotations)) - self.log.debug(">> Subtracks: {}".format(subtracks)) + self.log.debug("clip_name: {}".format(clip_name)) # get openpype tag data tag_data = phiero.get_track_item_pype_data(track_item) @@ -62,6 +56,12 @@ class PrecollectInstances(pyblish.api.ContextPlugin): if tag_data.get("id") != "pyblish.avalon.instance": continue + # get clips subtracks and anotations + annotations = self.clip_annotations(source_clip) + subtracks = self.clip_subtrack(track_item) + self.log.debug("Annotations: {}".format(annotations)) + self.log.debug(">> Subtracks: {}".format(subtracks)) + # solve handles length tag_data["handleStart"] = min( tag_data["handleStart"], int(track_item.handleInLength())) @@ -128,7 +128,7 @@ class PrecollectInstances(pyblish.api.ContextPlugin): "_ instance.data: {}".format(pformat(instance.data))) if not with_audio: - return + continue # create audio subset instance self.create_audio_instance(context, **data) diff --git a/openpype/hosts/maya/plugins/publish/extract_playblast.py b/openpype/hosts/maya/plugins/publish/extract_playblast.py index fa1ce7f9a9..57e3f478f1 100644 --- a/openpype/hosts/maya/plugins/publish/extract_playblast.py +++ b/openpype/hosts/maya/plugins/publish/extract_playblast.py @@ -72,7 +72,7 @@ class ExtractPlayblast(openpype.api.Extractor): # Isolate view is requested by having objects in the set besides a # camera. - if preset.pop("isolate_view", False) or instance.data.get("isolate"): + if preset.pop("isolate_view", False) and instance.data.get("isolate"): preset["isolate"] = instance.data["setMembers"] # Show/Hide image planes on request. diff --git a/openpype/hosts/maya/plugins/publish/extract_thumbnail.py b/openpype/hosts/maya/plugins/publish/extract_thumbnail.py index 5a91888781..aa8adc3986 100644 --- a/openpype/hosts/maya/plugins/publish/extract_thumbnail.py +++ b/openpype/hosts/maya/plugins/publish/extract_thumbnail.py @@ -75,7 +75,7 @@ class ExtractThumbnail(openpype.api.Extractor): # Isolate view is requested by having objects in the set besides a # camera. - if preset.pop("isolate_view", False) or instance.data.get("isolate"): + if preset.pop("isolate_view", False) and instance.data.get("isolate"): preset["isolate"] = instance.data["setMembers"] with maintained_time(): diff --git a/openpype/hosts/nuke/api/lib.py b/openpype/hosts/nuke/api/lib.py index 3c41574dbf..d7f3fdc6ba 100644 --- a/openpype/hosts/nuke/api/lib.py +++ b/openpype/hosts/nuke/api/lib.py @@ -286,7 +286,8 @@ def add_button_write_to_read(node): node.addKnob(knob) -def create_write_node(name, data, input=None, prenodes=None, review=True): +def create_write_node(name, data, input=None, prenodes=None, + review=True, linked_knobs=None): ''' Creating write node which is group node Arguments: @@ -298,18 +299,21 @@ def create_write_node(name, data, input=None, prenodes=None, review=True): review (bool): adding review knob Example: - prenodes = [( - "NameNode", # string - "NodeClass", # string - ( # OrderDict: knob and values pairs - ("knobName", "knobValue"), - ("knobName", "knobValue") - ), - ( # list outputs - "firstPostNodeName", - "secondPostNodeName" - ) - ) + prenodes = [ + { + "nodeName": { + "class": "" # string + "knobs": [ + ("knobName": value), + ... + ], + "dependent": [ + following_node_01, + ... + ] + } + }, + ... ] Return: @@ -385,35 +389,42 @@ def create_write_node(name, data, input=None, prenodes=None, review=True): prev_node.hideControlPanel() # creating pre-write nodes `prenodes` if prenodes: - for name, klass, properties, set_output_to in prenodes: + for node in prenodes: + # get attributes + name = node["name"] + klass = node["class"] + knobs = node["knobs"] + dependent = node["dependent"] + # create node now_node = nuke.createNode(klass, "name {}".format(name)) now_node.hideControlPanel() # add data to knob - for k, v in properties: + for _knob in knobs: + knob, value = _knob try: - now_node[k].value() + now_node[knob].value() except NameError: log.warning( "knob `{}` does not exist on node `{}`".format( - k, now_node["name"].value() + knob, now_node["name"].value() )) continue - if k and v: - now_node[k].setValue(str(v)) + if knob and value: + now_node[knob].setValue(value) # connect to previous node - if set_output_to: - if isinstance(set_output_to, (tuple or list)): - for i, node_name in enumerate(set_output_to): + if dependent: + if isinstance(dependent, (tuple or list)): + for i, node_name in enumerate(dependent): input_node = nuke.createNode( "Input", "name {}".format(node_name)) input_node.hideControlPanel() now_node.setInput(1, input_node) - elif isinstance(set_output_to, str): + elif isinstance(dependent, str): input_node = nuke.createNode( "Input", "name {}".format(node_name)) input_node.hideControlPanel() @@ -455,12 +466,16 @@ def create_write_node(name, data, input=None, prenodes=None, review=True): GN.addKnob(nuke.Text_Knob('', 'Rendering')) # Add linked knobs. - linked_knob_names = [ - "_grp-start_", - "use_limit", "first", "last", - "_grp-end_", - "Render" - ] + linked_knob_names = [] + + # add input linked knobs and create group only if any input + if linked_knobs: + linked_knob_names.append("_grp-start_") + linked_knob_names.extend(linked_knobs) + linked_knob_names.append("_grp-end_") + + linked_knob_names.append("Render") + for name in linked_knob_names: if "_grp-start_" in name: knob = nuke.Tab_Knob( @@ -471,13 +486,20 @@ def create_write_node(name, data, input=None, prenodes=None, review=True): "rnd_attr_end", "Rendering attributes", nuke.TABENDGROUP) GN.addKnob(knob) else: - link = nuke.Link_Knob("") - link.makeLink(write_node.name(), name) - link.setName(name) - if "Render" in name: - link.setLabel("Render Local") - link.setFlag(0x1000) - GN.addKnob(link) + if "___" in name: + # add devider + GN.addKnob(nuke.Text_Knob("")) + else: + # add linked knob by name + link = nuke.Link_Knob("") + link.makeLink(write_node.name(), name) + link.setName(name) + + # make render + if "Render" in name: + link.setLabel("Render Local") + link.setFlag(0x1000) + GN.addKnob(link) # adding write to read button add_button_write_to_read(GN) diff --git a/openpype/hosts/nuke/plugins/create/create_write_prerender.py b/openpype/hosts/nuke/plugins/create/create_write_prerender.py index 6e1a2ddd96..1b925014ad 100644 --- a/openpype/hosts/nuke/plugins/create/create_write_prerender.py +++ b/openpype/hosts/nuke/plugins/create/create_write_prerender.py @@ -103,7 +103,8 @@ class CreateWritePrerender(plugin.PypeCreator): write_data, input=selected_node, prenodes=[], - review=False) + review=False, + linked_knobs=["channels", "___", "first", "last", "use_limit"]) # relinking to collected connections for i, input in enumerate(inputs): @@ -122,19 +123,9 @@ class CreateWritePrerender(plugin.PypeCreator): w_node = n write_node.end() - # add inner write node Tab - write_node.addKnob(nuke.Tab_Knob("WriteLinkedKnobs")) - - # linking knobs to group property panel - linking_knobs = ["channels", "___", "first", "last", "use_limit"] - for k in linking_knobs: - if "___" in k: - write_node.addKnob(nuke.Text_Knob('')) - else: - lnk = nuke.Link_Knob(k) - lnk.makeLink(w_node.name(), k) - lnk.setName(k.replace('_', ' ').capitalize()) - lnk.clearFlag(nuke.STARTLINE) - write_node.addKnob(lnk) + if self.presets.get("use_range_limit"): + w_node["use_limit"].setValue(True) + w_node["first"].setValue(nuke.root()["first_frame"].value()) + w_node["last"].setValue(nuke.root()["last_frame"].value()) return write_node diff --git a/openpype/hosts/nuke/plugins/create/create_write_render.py b/openpype/hosts/nuke/plugins/create/create_write_render.py index 04983e9c75..a1381122ee 100644 --- a/openpype/hosts/nuke/plugins/create/create_write_render.py +++ b/openpype/hosts/nuke/plugins/create/create_write_render.py @@ -99,10 +99,35 @@ class CreateWriteRender(plugin.PypeCreator): "fpath_template": ("{work}/renders/nuke/{subset}" "/{subset}.{frame}.{ext}")}) + # add crop node to cut off all outside of format bounding box + # get width and height + try: + width, height = (selected_node.width(), selected_node.height()) + except AttributeError: + actual_format = nuke.root().knob('format').value() + width, height = (actual_format.width(), actual_format.height()) + + _prenodes = [ + { + "name": "Crop01", + "class": "Crop", + "knobs": [ + ("box", [ + 0.0, + 0.0, + width, + height + ]) + ], + "dependent": None + } + ] + write_node = lib.create_write_node( self.data["subset"], write_data, - input=selected_node) + input=selected_node, + prenodes=_prenodes) # relinking to collected connections for i, input in enumerate(inputs): diff --git a/openpype/hosts/nuke/plugins/publish/precollect_instances.py b/openpype/hosts/nuke/plugins/publish/precollect_instances.py index cdb0589525..00d96c6cd1 100644 --- a/openpype/hosts/nuke/plugins/publish/precollect_instances.py +++ b/openpype/hosts/nuke/plugins/publish/precollect_instances.py @@ -81,17 +81,18 @@ class PreCollectNukeInstances(pyblish.api.ContextPlugin): if target == "Use existing frames": # Local rendering self.log.info("flagged for no render") + families.append(family) elif target == "Local": # Local rendering self.log.info("flagged for local render") families.append("{}.local".format(family)) - family = families_ak.lower() elif target == "On farm": # Farm rendering self.log.info("flagged for farm render") instance.data["transfer"] = False families.append("{}.farm".format(family)) - family = families_ak.lower() + + family = families_ak.lower() node.begin() for i in nuke.allNodes(): diff --git a/openpype/hosts/nuke/plugins/publish/precollect_writes.py b/openpype/hosts/nuke/plugins/publish/precollect_writes.py index 5eaac89e84..0b5fbc0479 100644 --- a/openpype/hosts/nuke/plugins/publish/precollect_writes.py +++ b/openpype/hosts/nuke/plugins/publish/precollect_writes.py @@ -1,5 +1,6 @@ import os import re +from pprint import pformat import nuke import pyblish.api import openpype.api as pype @@ -17,6 +18,7 @@ class CollectNukeWrites(pyblish.api.InstancePlugin): def process(self, instance): _families_test = [instance.data["family"]] + instance.data["families"] + self.log.debug("_families_test: {}".format(_families_test)) node = None for x in instance: @@ -133,22 +135,29 @@ class CollectNukeWrites(pyblish.api.InstancePlugin): "outputDir": output_dir, "ext": ext, "label": label, - "handleStart": handle_start, - "handleEnd": handle_end, - "frameStart": first_frame + handle_start, - "frameEnd": last_frame - handle_end, - "frameStartHandle": first_frame, - "frameEndHandle": last_frame, "outputType": output_type, "colorspace": colorspace, "deadlineChunkSize": deadlineChunkSize, "deadlinePriority": deadlinePriority }) - if "prerender" in _families_test: + if self.is_prerender(_families_test): instance.data.update({ - "family": "prerender", - "families": [] + "handleStart": 0, + "handleEnd": 0, + "frameStart": first_frame, + "frameEnd": last_frame, + "frameStartHandle": first_frame, + "frameEndHandle": last_frame, + }) + else: + instance.data.update({ + "handleStart": handle_start, + "handleEnd": handle_end, + "frameStart": first_frame + handle_start, + "frameEnd": last_frame - handle_end, + "frameStartHandle": first_frame, + "frameEndHandle": last_frame, }) # * Add audio to instance if exists. @@ -170,4 +179,7 @@ class CollectNukeWrites(pyblish.api.InstancePlugin): "filename": api.get_representation_path(repre_doc) }] - self.log.debug("instance.data: {}".format(instance.data)) + self.log.debug("instance.data: {}".format(pformat(instance.data))) + + def is_prerender(self, families): + return next((f for f in families if "prerender" in f), None) diff --git a/openpype/hosts/nuke/plugins/publish/validate_rendered_frames.py b/openpype/hosts/nuke/plugins/publish/validate_rendered_frames.py index 8b71aff1ac..0c88014649 100644 --- a/openpype/hosts/nuke/plugins/publish/validate_rendered_frames.py +++ b/openpype/hosts/nuke/plugins/publish/validate_rendered_frames.py @@ -61,7 +61,6 @@ class ValidateRenderedFrames(pyblish.api.InstancePlugin): hosts = ["nuke", "nukestudio"] actions = [RepairCollectionActionToLocal, RepairCollectionActionToFarm] - def process(self, instance): for repre in instance.data["representations"]: @@ -78,10 +77,10 @@ class ValidateRenderedFrames(pyblish.api.InstancePlugin): collection = collections[0] - frame_length = int( - instance.data["frameEndHandle"] - - instance.data["frameStartHandle"] + 1 - ) + fstartH = instance.data["frameStartHandle"] + fendH = instance.data["frameEndHandle"] + + frame_length = int(fendH - fstartH + 1) if frame_length != 1: if len(collections) != 1: @@ -95,7 +94,16 @@ class ValidateRenderedFrames(pyblish.api.InstancePlugin): raise ValidationException(msg) collected_frames_len = int(len(collection.indexes)) + coll_start = min(collection.indexes) + coll_end = max(collection.indexes) + self.log.info("frame_length: {}".format(frame_length)) + self.log.info("collected_frames_len: {}".format( + collected_frames_len)) + self.log.info("fstartH-fendH: {}-{}".format(fstartH, fendH)) + self.log.info( + "coll_start-coll_end: {}-{}".format(coll_start, coll_end)) + self.log.info( "len(collection.indexes): {}".format(collected_frames_len) ) @@ -103,8 +111,11 @@ class ValidateRenderedFrames(pyblish.api.InstancePlugin): if ("slate" in instance.data["families"]) \ and (frame_length != collected_frames_len): collected_frames_len -= 1 + fstartH += 1 - assert (collected_frames_len == frame_length), ( + assert ((collected_frames_len >= frame_length) + and (coll_start <= fstartH) + and (coll_end >= fendH)), ( "{} missing frames. Use repair to render all frames" ).format(__name__) diff --git a/openpype/hosts/nuke/plugins/publish/validate_write_bounding_box.py b/openpype/hosts/nuke/plugins/publish/validate_write_bounding_box.py deleted file mode 100644 index e4b7c77a25..0000000000 --- a/openpype/hosts/nuke/plugins/publish/validate_write_bounding_box.py +++ /dev/null @@ -1,106 +0,0 @@ -import nuke - -import pyblish.api - - -class RepairNukeBoundingBoxAction(pyblish.api.Action): - - label = "Repair" - icon = "wrench" - on = "failed" - - def process(self, context, plugin): - - # Get the errored instances - failed = [] - for result in context.data["results"]: - if (result["error"] is not None and result["instance"] is not None - and result["instance"] not in failed): - failed.append(result["instance"]) - - # Apply pyblish.logic to get the instances for the plug-in - instances = pyblish.api.instances_by_plugin(failed, plugin) - - for instance in instances: - crop = instance[0].dependencies()[0] - if crop.Class() != "Crop": - crop = nuke.nodes.Crop(inputs=[instance[0].input(0)]) - - xpos = instance[0].xpos() - ypos = instance[0].ypos() - 26 - - dependent_ypos = instance[0].dependencies()[0].ypos() - if (instance[0].ypos() - dependent_ypos) <= 51: - xpos += 110 - - crop.setXYpos(xpos, ypos) - - instance[0].setInput(0, crop) - - crop["box"].setValue( - ( - 0.0, - 0.0, - instance[0].input(0).width(), - instance[0].input(0).height() - ) - ) - - -class ValidateNukeWriteBoundingBox(pyblish.api.InstancePlugin): - """Validates write bounding box. - - Ffmpeg does not support bounding boxes outside of the image - resolution a crop is needed. This needs to validate all frames, as each - rendered exr can break the ffmpeg transcode. - """ - - order = pyblish.api.ValidatorOrder - optional = True - families = ["render", "render.local", "render.farm"] - label = "Write Bounding Box" - hosts = ["nuke"] - actions = [RepairNukeBoundingBoxAction] - - def process(self, instance): - - # Skip bounding box check if a crop node exists. - if instance[0].dependencies()[0].Class() == "Crop": - return - - msg = "Bounding box is outside the format." - assert self.check_bounding_box(instance), msg - - def check_bounding_box(self, instance): - node = instance[0] - - first_frame = instance.data["frameStart"] - last_frame = instance.data["frameEnd"] - - format_width = node.format().width() - format_height = node.format().height() - - # The trick is that we need to execute() some node every time we go to - # a next frame, to update the context. - # So we create a CurveTool that we can execute() on every frame. - temporary_node = nuke.nodes.CurveTool() - bbox_check = True - for frame in range(first_frame, last_frame + 1): - # Workaround to update the tree - nuke.execute(temporary_node, frame, frame) - - x = node.bbox().x() - y = node.bbox().y() - w = node.bbox().w() - h = node.bbox().h() - - if x < 0 or (x + w) > format_width: - bbox_check = False - break - - if y < 0 or (y + h) > format_height: - bbox_check = False - break - - nuke.delete(temporary_node) - return bbox_check diff --git a/openpype/hosts/photoshop/plugins/lib.py b/openpype/hosts/photoshop/plugins/lib.py new file mode 100644 index 0000000000..74aff06114 --- /dev/null +++ b/openpype/hosts/photoshop/plugins/lib.py @@ -0,0 +1,26 @@ +import re + + +def get_unique_layer_name(layers, asset_name, subset_name): + """ + Gets all layer names and if 'asset_name_subset_name' is present, it + increases suffix by 1 (eg. creates unique layer name - for Loader) + Args: + layers (list) of dict with layers info (name, id etc.) + asset_name (string): + subset_name (string): + + Returns: + (string): name_00X (without version) + """ + name = "{}_{}".format(asset_name, subset_name) + names = {} + for layer in layers: + layer_name = re.sub(r'_\d{3}$', '', layer.name) + if layer_name in names.keys(): + names[layer_name] = names[layer_name] + 1 + else: + names[layer_name] = 1 + occurrences = names.get(name, 0) + + return "{}_{:0>3d}".format(name, occurrences + 1) diff --git a/openpype/hosts/photoshop/plugins/load/load_image.py b/openpype/hosts/photoshop/plugins/load/load_image.py index 44cc96c96f..d043323768 100644 --- a/openpype/hosts/photoshop/plugins/load/load_image.py +++ b/openpype/hosts/photoshop/plugins/load/load_image.py @@ -1,7 +1,9 @@ -from avalon import api, photoshop -import os import re +from avalon import api, photoshop + +from openpype.hosts.photoshop.plugins.lib import get_unique_layer_name + stub = photoshop.stub() @@ -15,8 +17,9 @@ class ImageLoader(api.Loader): representations = ["*"] def load(self, context, name=None, namespace=None, data=None): - layer_name = self._get_unique_layer_name(context["asset"]["name"], - name) + layer_name = get_unique_layer_name(stub.get_layers(), + context["asset"]["name"], + name) with photoshop.maintained_selection(): layer = stub.import_smart_object(self.fname, layer_name) @@ -69,25 +72,3 @@ class ImageLoader(api.Loader): def switch(self, container, representation): self.update(container, representation) - - def _get_unique_layer_name(self, asset_name, subset_name): - """ - Gets all layer names and if 'name' is present in them, increases - suffix by 1 (eg. creates unique layer name - for Loader) - Args: - name (string): in format asset_subset - - Returns: - (string): name_00X (without version) - """ - name = "{}_{}".format(asset_name, subset_name) - names = {} - for layer in stub.get_layers(): - layer_name = re.sub(r'_\d{3}$', '', layer.name) - if layer_name in names.keys(): - names[layer_name] = names[layer_name] + 1 - else: - names[layer_name] = 1 - occurrences = names.get(name, 0) - - return "{}_{:0>3d}".format(name, occurrences + 1) diff --git a/openpype/hosts/photoshop/plugins/load/load_image_from_sequence.py b/openpype/hosts/photoshop/plugins/load/load_image_from_sequence.py new file mode 100644 index 0000000000..8704627b12 --- /dev/null +++ b/openpype/hosts/photoshop/plugins/load/load_image_from_sequence.py @@ -0,0 +1,98 @@ +import os + +from avalon import api +from avalon import photoshop +from avalon.pipeline import get_representation_path_from_context +from avalon.vendor import qargparse + +from openpype.lib import Anatomy +from openpype.hosts.photoshop.plugins.lib import get_unique_layer_name + +stub = photoshop.stub() + + +class ImageFromSequenceLoader(api.Loader): + """ Load specifing image from sequence + + Used only as quick load of reference file from a sequence. + + Plain ImageLoader picks first frame from sequence. + + Loads only existing files - currently not possible to limit loaders + to single select - multiselect. If user selects multiple repres, list + for all of them is provided, but selection is only single file. + This loader will be triggered multiple times, but selected name will + match only to proper path. + + Loader doesnt do containerization as there is currently no data model + of 'frame of rendered files' (only rendered sequence), update would be + difficult. + """ + + families = ["render"] + representations = ["*"] + options = [] + + def load(self, context, name=None, namespace=None, data=None): + if data.get("frame"): + self.fname = os.path.join(os.path.dirname(self.fname), + data["frame"]) + if not os.path.exists(self.fname): + return + + stub = photoshop.stub() + layer_name = get_unique_layer_name(stub.get_layers(), + context["asset"]["name"], + name) + + with photoshop.maintained_selection(): + layer = stub.import_smart_object(self.fname, layer_name) + + self[:] = [layer] + namespace = namespace or layer_name + + return namespace + + @classmethod + def get_options(cls, repre_contexts): + """ + Returns list of files for selected 'repre_contexts'. + + It returns only files with same extension as in context as it is + expected that context points to sequence of frames. + + Returns: + (list) of qargparse.Choice + """ + files = [] + for context in repre_contexts: + fname = get_representation_path_from_context(context) + _, file_extension = os.path.splitext(fname) + + for file_name in os.listdir(os.path.dirname(fname)): + if not file_name.endswith(file_extension): + continue + files.append(file_name) + + # return selection only if there is something + if not files or len(files) <= 1: + return [] + + return [ + qargparse.Choice( + "frame", + label="Select specific file", + items=files, + default=0, + help="Which frame should be loaded?" + ) + ] + + def update(self, container, representation): + """No update possible, not containerized.""" + pass + + def remove(self, container): + """No update possible, not containerized.""" + pass + diff --git a/openpype/hosts/standalonepublisher/plugins/publish/collect_context.py b/openpype/hosts/standalonepublisher/plugins/publish/collect_context.py index 43ab13cd79..6913e0836d 100644 --- a/openpype/hosts/standalonepublisher/plugins/publish/collect_context.py +++ b/openpype/hosts/standalonepublisher/plugins/publish/collect_context.py @@ -34,7 +34,6 @@ class CollectContextDataSAPublish(pyblish.api.ContextPlugin): # presets batch_extensions = ["edl", "xml", "psd"] - default_families = ["ftrack"] def process(self, context): # get json paths from os and load them @@ -213,10 +212,6 @@ class CollectContextDataSAPublish(pyblish.api.ContextPlugin): subset = in_data["subset"] # If instance data already contain families then use it instance_families = in_data.get("families") or [] - # Make sure default families are in instance - for default_family in self.default_families or []: - if default_family not in instance_families: - instance_families.append(default_family) instance = context.create_instance(subset) instance.data.update( diff --git a/openpype/hosts/standalonepublisher/plugins/publish/collect_instances.py b/openpype/hosts/standalonepublisher/plugins/publish/collect_instances.py index eb04217136..d753a3d9bb 100644 --- a/openpype/hosts/standalonepublisher/plugins/publish/collect_instances.py +++ b/openpype/hosts/standalonepublisher/plugins/publish/collect_instances.py @@ -16,12 +16,12 @@ class CollectInstances(pyblish.api.InstancePlugin): subsets = { "referenceMain": { "family": "review", - "families": ["clip", "ftrack"], + "families": ["clip"], "extensions": [".mp4"] }, "audioMain": { "family": "audio", - "families": ["clip", "ftrack"], + "families": ["clip"], "extensions": [".wav"], }, "shotMain": { diff --git a/openpype/hosts/standalonepublisher/plugins/publish/collect_matchmove.py b/openpype/hosts/standalonepublisher/plugins/publish/collect_matchmove.py deleted file mode 100644 index 5d9e8ddfb4..0000000000 --- a/openpype/hosts/standalonepublisher/plugins/publish/collect_matchmove.py +++ /dev/null @@ -1,29 +0,0 @@ -""" -Requires: - Nothing - -Provides: - Instance -""" - -import pyblish.api -import logging - - -log = logging.getLogger("collector") - - -class CollectMatchmovePublish(pyblish.api.InstancePlugin): - """ - Collector with only one reason for its existence - remove 'ftrack' - family implicitly added by Standalone Publisher - """ - - label = "Collect Matchmove - SA Publish" - order = pyblish.api.CollectorOrder - families = ["matchmove"] - hosts = ["standalonepublisher"] - - def process(self, instance): - if "ftrack" in instance.data["families"]: - instance.data["families"].remove("ftrack") diff --git a/openpype/hosts/standalonepublisher/plugins/publish/extract_thumbnail.py b/openpype/hosts/standalonepublisher/plugins/publish/extract_thumbnail.py index ac1dfa13d4..0792254716 100644 --- a/openpype/hosts/standalonepublisher/plugins/publish/extract_thumbnail.py +++ b/openpype/hosts/standalonepublisher/plugins/publish/extract_thumbnail.py @@ -1,6 +1,5 @@ import os import tempfile -import subprocess import pyblish.api import openpype.api import openpype.lib @@ -67,7 +66,6 @@ class ExtractThumbnailSP(pyblish.api.InstancePlugin): else: # Convert to jpeg if not yet full_input_path = os.path.join(thumbnail_repre["stagingDir"], file) - full_input_path = '"{}"'.format(full_input_path) self.log.info("input {}".format(full_input_path)) full_thumbnail_path = tempfile.mkstemp(suffix=".jpg")[1] @@ -77,30 +75,37 @@ class ExtractThumbnailSP(pyblish.api.InstancePlugin): ffmpeg_args = self.ffmpeg_args or {} - jpeg_items = [] - jpeg_items.append("\"{}\"".format(ffmpeg_path)) - # override file if already exists - jpeg_items.append("-y") + jpeg_items = [ + "\"{}\"".format(ffmpeg_path), + # override file if already exists + "-y" + ] + # add input filters from peresets jpeg_items.extend(ffmpeg_args.get("input") or []) # input file - jpeg_items.append("-i {}".format(full_input_path)) + jpeg_items.append("-i \"{}\"".format(full_input_path)) # extract only single file - jpeg_items.append("-vframes 1") + jpeg_items.append("-frames:v 1") + # Add black background for transparent images + jpeg_items.append(( + "-filter_complex" + " \"color=black,format=rgb24[c]" + ";[c][0]scale2ref[c][i]" + ";[c][i]overlay=format=auto:shortest=1,setsar=1\"" + )) jpeg_items.extend(ffmpeg_args.get("output") or []) # output file - jpeg_items.append(full_thumbnail_path) + jpeg_items.append("\"{}\"".format(full_thumbnail_path)) subprocess_jpeg = " ".join(jpeg_items) # run subprocess self.log.debug("Executing: {}".format(subprocess_jpeg)) - subprocess.Popen( - subprocess_jpeg, - stdout=subprocess.PIPE, - shell=True + openpype.api.run_subprocess( + subprocess_jpeg, shell=True, logger=self.log ) # remove thumbnail key from origin repre diff --git a/openpype/hosts/standalonepublisher/plugins/publish/validate_frame_ranges.py b/openpype/hosts/standalonepublisher/plugins/publish/validate_frame_ranges.py new file mode 100644 index 0000000000..e3086fb638 --- /dev/null +++ b/openpype/hosts/standalonepublisher/plugins/publish/validate_frame_ranges.py @@ -0,0 +1,53 @@ +import re + +import pyblish.api +import openpype.api +from openpype import lib + + +class ValidateFrameRange(pyblish.api.InstancePlugin): + """Validating frame range of rendered files against state in DB.""" + + label = "Validate Frame Range" + hosts = ["standalonepublisher"] + families = ["render"] + order = openpype.api.ValidateContentsOrder + + optional = True + # published data might be sequence (.mov, .mp4) in that counting files + # doesnt make sense + check_extensions = ["exr", "dpx", "jpg", "jpeg", "png", "tiff", "tga", + "gif", "svg"] + skip_timelines_check = [] # skip for specific task names (regex) + + def process(self, instance): + if any(re.search(pattern, instance.data["task"]) + for pattern in self.skip_timelines_check): + self.log.info("Skipping for {} task".format(instance.data["task"])) + + asset_data = lib.get_asset(instance.data["asset"])["data"] + frame_start = asset_data["frameStart"] + frame_end = asset_data["frameEnd"] + handle_start = asset_data["handleStart"] + handle_end = asset_data["handleEnd"] + duration = (frame_end - frame_start + 1) + handle_start + handle_end + + repre = instance.data.get("representations", [None]) + if not repre: + self.log.info("No representations, skipping.") + return + + ext = repre[0]['ext'].replace(".", '') + + if not ext or ext.lower() not in self.check_extensions: + self.log.warning("Cannot check for extension {}".format(ext)) + return + + frames = len(instance.data.get("representations", [None])[0]["files"]) + + err_msg = "Frame duration from DB:'{}' ". format(int(duration)) +\ + " doesn't match number of files:'{}'".format(frames) +\ + " Please change frame range for Asset or limit no. of files" + assert frames == duration, err_msg + + self.log.debug("Valid ranges {} - {}".format(int(duration), frames)) diff --git a/openpype/hosts/tvpaint/plugins/create/create_render_layer.py b/openpype/hosts/tvpaint/plugins/create/create_render_layer.py index 585f0c87d7..af6c0f0eee 100644 --- a/openpype/hosts/tvpaint/plugins/create/create_render_layer.py +++ b/openpype/hosts/tvpaint/plugins/create/create_render_layer.py @@ -1,5 +1,11 @@ -from avalon.tvpaint import pipeline, lib +from avalon.api import CreatorError +from avalon.tvpaint import ( + pipeline, + lib, + CommunicationWrapper +) from openpype.hosts.tvpaint.api import plugin +from openpype.lib import prepare_template_data class CreateRenderlayer(plugin.Creator): @@ -11,13 +17,61 @@ class CreateRenderlayer(plugin.Creator): defaults = ["Main"] rename_group = True + render_pass = "beauty" - subset_template = "{family}_{name}" rename_script_template = ( "tv_layercolor \"setcolor\"" " {clip_id} {group_id} {r} {g} {b} \"{name}\"" ) + dynamic_subset_keys = ["render_pass", "render_layer", "group"] + + @classmethod + def get_dynamic_data( + cls, variant, task_name, asset_id, project_name, host_name + ): + dynamic_data = super(CreateRenderlayer, cls).get_dynamic_data( + variant, task_name, asset_id, project_name, host_name + ) + # Use render pass name from creator's plugin + dynamic_data["render_pass"] = cls.render_pass + # Add variant to render layer + dynamic_data["render_layer"] = variant + # Change family for subset name fill + dynamic_data["family"] = "render" + + return dynamic_data + + @classmethod + def get_default_variant(cls): + """Default value for variant in Creator tool. + + Method checks if TVPaint implementation is running and tries to find + selected layers from TVPaint. If only one is selected it's name is + returned. + + Returns: + str: Default variant name for Creator tool. + """ + # Validate that communication is initialized + if CommunicationWrapper.communicator: + # Get currently selected layers + layers_data = lib.layers_data() + + selected_layers = [ + layer + for layer in layers_data + if layer["selected"] + ] + # Return layer name if only one is selected + if len(selected_layers) == 1: + return selected_layers[0]["name"] + + # Use defaults + if cls.defaults: + return cls.defaults[0] + return None + def process(self): self.log.debug("Query data from workfile.") instances = pipeline.list_instances() @@ -32,34 +86,44 @@ class CreateRenderlayer(plugin.Creator): # Raise if there is no selection if not group_ids: - raise AssertionError("Nothing is selected.") + raise CreatorError("Nothing is selected.") # This creator should run only on one group if len(group_ids) > 1: - raise AssertionError("More than one group is in selection.") + raise CreatorError("More than one group is in selection.") group_id = tuple(group_ids)[0] # If group id is `0` it is `default` group which is invalid if group_id == 0: - raise AssertionError( + raise CreatorError( "Selection is not in group. Can't mark selection as Beauty." ) self.log.debug(f"Selected group id is \"{group_id}\".") self.data["group_id"] = group_id - family = self.data["family"] - # Extract entered name - name = self.data["subset"][len(family):] - self.log.info(f"Extracted name from subset name \"{name}\".") - self.data["name"] = name + group_data = lib.groups_data() + group_name = None + for group in group_data: + if group["group_id"] == group_id: + group_name = group["name"] + break - # Change subset name by template - subset_name = self.subset_template.format(**{ - "family": self.family, - "name": name - }) - self.log.info(f"New subset name \"{subset_name}\".") + if group_name is None: + raise AssertionError( + "Couldn't find group by id \"{}\"".format(group_id) + ) + + subset_name_fill_data = { + "group": group_name + } + + family = self.family = self.data["family"] + + # Fill dynamic key 'group' + subset_name = self.data["subset"].format( + **prepare_template_data(subset_name_fill_data) + ) self.data["subset"] = subset_name # Check for instances of same group @@ -115,7 +179,7 @@ class CreateRenderlayer(plugin.Creator): # Rename TVPaint group (keep color same) # - groups can't contain spaces - new_group_name = name.replace(" ", "_") + new_group_name = self.data["variant"].replace(" ", "_") rename_script = self.rename_script_template.format( clip_id=selected_group["clip_id"], group_id=selected_group["group_id"], diff --git a/openpype/hosts/tvpaint/plugins/create/create_render_pass.py b/openpype/hosts/tvpaint/plugins/create/create_render_pass.py index 09c68930f2..ad06520210 100644 --- a/openpype/hosts/tvpaint/plugins/create/create_render_pass.py +++ b/openpype/hosts/tvpaint/plugins/create/create_render_pass.py @@ -1,5 +1,11 @@ -from avalon.tvpaint import pipeline, lib +from avalon.api import CreatorError +from avalon.tvpaint import ( + pipeline, + lib, + CommunicationWrapper +) from openpype.hosts.tvpaint.api import plugin +from openpype.lib import prepare_template_data class CreateRenderPass(plugin.Creator): @@ -14,7 +20,49 @@ class CreateRenderPass(plugin.Creator): icon = "cube" defaults = ["Main"] - subset_template = "{family}_{render_layer}_{pass}" + dynamic_subset_keys = ["render_pass", "render_layer"] + + @classmethod + def get_dynamic_data( + cls, variant, task_name, asset_id, project_name, host_name + ): + dynamic_data = super(CreateRenderPass, cls).get_dynamic_data( + variant, task_name, asset_id, project_name, host_name + ) + dynamic_data["render_pass"] = variant + dynamic_data["family"] = "render" + + return dynamic_data + + @classmethod + def get_default_variant(cls): + """Default value for variant in Creator tool. + + Method checks if TVPaint implementation is running and tries to find + selected layers from TVPaint. If only one is selected it's name is + returned. + + Returns: + str: Default variant name for Creator tool. + """ + # Validate that communication is initialized + if CommunicationWrapper.communicator: + # Get currently selected layers + layers_data = lib.layers_data() + + selected_layers = [ + layer + for layer in layers_data + if layer["selected"] + ] + # Return layer name if only one is selected + if len(selected_layers) == 1: + return selected_layers[0]["name"] + + # Use defaults + if cls.defaults: + return cls.defaults[0] + return None def process(self): self.log.debug("Query data from workfile.") @@ -32,11 +80,11 @@ class CreateRenderPass(plugin.Creator): # Raise if nothing is selected if not selected_layers: - raise AssertionError("Nothing is selected.") + raise CreatorError("Nothing is selected.") # Raise if layers from multiple groups are selected if len(group_ids) != 1: - raise AssertionError("More than one group is in selection.") + raise CreatorError("More than one group is in selection.") group_id = tuple(group_ids)[0] self.log.debug(f"Selected group id is \"{group_id}\".") @@ -53,34 +101,40 @@ class CreateRenderPass(plugin.Creator): # Beauty is required for this creator so raise if was not found if beauty_instance is None: - raise AssertionError("Beauty pass does not exist yet.") + raise CreatorError("Beauty pass does not exist yet.") - render_layer = beauty_instance["name"] + subset_name = self.data["subset"] + + subset_name_fill_data = {} + + # Backwards compatibility + # - beauty may be created with older creator where variant was not + # stored + if "variant" not in beauty_instance: + render_layer = beauty_instance["name"] + else: + render_layer = beauty_instance["variant"] + + subset_name_fill_data["render_layer"] = render_layer + + # Format dynamic keys in subset name + new_subset_name = subset_name.format( + **prepare_template_data(subset_name_fill_data) + ) + self.data["subset"] = new_subset_name + self.log.info(f"New subset name is \"{new_subset_name}\".") - # Extract entered name family = self.data["family"] - name = self.data["subset"] - # Is this right way how to get name? - name = name[len(family):] - self.log.info(f"Extracted name from subset name \"{name}\".") + variant = self.data["variant"] self.data["group_id"] = group_id - self.data["pass"] = name + self.data["pass"] = variant self.data["render_layer"] = render_layer # Collect selected layer ids to be stored into instance layer_names = [layer["name"] for layer in selected_layers] self.data["layer_names"] = layer_names - # Replace `beauty` in beauty's subset name with entered name - subset_name = self.subset_template.format(**{ - "family": family, - "render_layer": render_layer, - "pass": name - }) - self.data["subset"] = subset_name - self.log.info(f"New subset name is \"{subset_name}\".") - # Check if same instance already exists existing_instance = None existing_instance_idx = None @@ -88,7 +142,7 @@ class CreateRenderPass(plugin.Creator): if ( instance["family"] == family and instance["group_id"] == group_id - and instance["pass"] == name + and instance["pass"] == variant ): existing_instance = instance existing_instance_idx = idx @@ -97,7 +151,7 @@ class CreateRenderPass(plugin.Creator): if existing_instance is not None: self.log.info( f"Render pass instance for group id {group_id}" - f" and name \"{name}\" already exists, overriding." + f" and name \"{variant}\" already exists, overriding." ) instances[existing_instance_idx] = self.data else: diff --git a/openpype/hosts/tvpaint/plugins/publish/collect_instances.py b/openpype/hosts/tvpaint/plugins/publish/collect_instances.py index 9b11f9fe80..e496b144cd 100644 --- a/openpype/hosts/tvpaint/plugins/publish/collect_instances.py +++ b/openpype/hosts/tvpaint/plugins/publish/collect_instances.py @@ -4,6 +4,8 @@ import copy import pyblish.api from avalon import io +from openpype.lib import get_subset_name + class CollectInstances(pyblish.api.ContextPlugin): label = "Collect Instances" @@ -62,9 +64,38 @@ class CollectInstances(pyblish.api.ContextPlugin): # Different instance creation based on family instance = None if family == "review": - # Change subset name + # Change subset name of review instance + + # Collect asset doc to get asset id + # - not sure if it's good idea to require asset id in + # get_subset_name? + asset_name = context.data["workfile_context"]["asset"] + asset_doc = io.find_one( + { + "type": "asset", + "name": asset_name + }, + {"_id": 1} + ) + asset_id = None + if asset_doc: + asset_id = asset_doc["_id"] + + # Project name from workfile context + project_name = context.data["workfile_context"]["project"] + # Host name from environemnt variable + host_name = os.environ["AVALON_APP"] + # Use empty variant value + variant = "" task_name = io.Session["AVALON_TASK"] - new_subset_name = "{}{}".format(family, task_name.capitalize()) + new_subset_name = get_subset_name( + family, + variant, + task_name, + asset_id, + project_name, + host_name + ) instance_data["subset"] = new_subset_name instance = context.create_instance(**instance_data) @@ -72,8 +103,6 @@ class CollectInstances(pyblish.api.ContextPlugin): instance.data["layers"] = copy.deepcopy( context.data["layersData"] ) - # Add ftrack family - instance.data["families"].append("ftrack") elif family == "renderLayer": instance = self.create_render_layer_instance( @@ -119,19 +148,23 @@ class CollectInstances(pyblish.api.ContextPlugin): name = instance_data["name"] # Change label subset_name = instance_data["subset"] - instance_data["label"] = "{}_Beauty".format(name) - # Change subset name - # Final family of an instance will be `render` - new_family = "render" - task_name = io.Session["AVALON_TASK"] - new_subset_name = "{}{}_{}_Beauty".format( - new_family, task_name.capitalize(), name - ) - instance_data["subset"] = new_subset_name - self.log.debug("Changed subset name \"{}\"->\"{}\"".format( - subset_name, new_subset_name - )) + # Backwards compatibility + # - subset names were not stored as final subset names during creation + if "variant" not in instance_data: + instance_data["label"] = "{}_Beauty".format(name) + + # Change subset name + # Final family of an instance will be `render` + new_family = "render" + task_name = io.Session["AVALON_TASK"] + new_subset_name = "{}{}_{}_Beauty".format( + new_family, task_name.capitalize(), name + ) + instance_data["subset"] = new_subset_name + self.log.debug("Changed subset name \"{}\"->\"{}\"".format( + subset_name, new_subset_name + )) # Get all layers for the layer layers_data = context.data["layersData"] @@ -151,9 +184,6 @@ class CollectInstances(pyblish.api.ContextPlugin): instance_data["layers"] = group_layers - # Add ftrack family - instance_data["families"].append("ftrack") - return context.create_instance(**instance_data) def create_render_pass_instance(self, context, instance_data): @@ -163,20 +193,23 @@ class CollectInstances(pyblish.api.ContextPlugin): ) # Change label render_layer = instance_data["render_layer"] - instance_data["label"] = "{}_{}".format(render_layer, pass_name) - # Change subset name - # Final family of an instance will be `render` - new_family = "render" - old_subset_name = instance_data["subset"] - task_name = io.Session["AVALON_TASK"] - new_subset_name = "{}{}_{}_{}".format( - new_family, task_name.capitalize(), render_layer, pass_name - ) - instance_data["subset"] = new_subset_name - self.log.debug("Changed subset name \"{}\"->\"{}\"".format( - old_subset_name, new_subset_name - )) + # Backwards compatibility + # - subset names were not stored as final subset names during creation + if "variant" not in instance_data: + instance_data["label"] = "{}_{}".format(render_layer, pass_name) + # Change subset name + # Final family of an instance will be `render` + new_family = "render" + old_subset_name = instance_data["subset"] + task_name = io.Session["AVALON_TASK"] + new_subset_name = "{}{}_{}_{}".format( + new_family, task_name.capitalize(), render_layer, pass_name + ) + instance_data["subset"] = new_subset_name + self.log.debug("Changed subset name \"{}\"->\"{}\"".format( + old_subset_name, new_subset_name + )) layers_data = context.data["layersData"] layers_by_name = { diff --git a/openpype/hosts/tvpaint/plugins/publish/collect_workfile.py b/openpype/hosts/tvpaint/plugins/publish/collect_workfile.py index b059be90bf..b61fec895f 100644 --- a/openpype/hosts/tvpaint/plugins/publish/collect_workfile.py +++ b/openpype/hosts/tvpaint/plugins/publish/collect_workfile.py @@ -3,6 +3,8 @@ import json import pyblish.api from avalon import io +from openpype.lib import get_subset_name + class CollectWorkfile(pyblish.api.ContextPlugin): label = "Collect Workfile" @@ -20,8 +22,38 @@ class CollectWorkfile(pyblish.api.ContextPlugin): basename, ext = os.path.splitext(filename) instance = context.create_instance(name=basename) + # Get subset name of workfile instance + # Collect asset doc to get asset id + # - not sure if it's good idea to require asset id in + # get_subset_name? + family = "workfile" + asset_name = context.data["workfile_context"]["asset"] + asset_doc = io.find_one( + { + "type": "asset", + "name": asset_name + }, + {"_id": 1} + ) + asset_id = None + if asset_doc: + asset_id = asset_doc["_id"] + + # Project name from workfile context + project_name = context.data["workfile_context"]["project"] + # Host name from environemnt variable + host_name = os.environ["AVALON_APP"] + # Use empty variant value + variant = "" task_name = io.Session["AVALON_TASK"] - subset_name = "workfile" + task_name.capitalize() + subset_name = get_subset_name( + family, + variant, + task_name, + asset_id, + project_name, + host_name + ) # Create Workfile instance instance.data.update({ diff --git a/openpype/hosts/tvpaint/plugins/publish/collect_workfile_data.py b/openpype/hosts/tvpaint/plugins/publish/collect_workfile_data.py index 13c6c9eb78..d8bb03f541 100644 --- a/openpype/hosts/tvpaint/plugins/publish/collect_workfile_data.py +++ b/openpype/hosts/tvpaint/plugins/publish/collect_workfile_data.py @@ -1,5 +1,6 @@ import os import json +import tempfile import pyblish.api import avalon.api @@ -153,9 +154,45 @@ class CollectWorkfileData(pyblish.api.ContextPlugin): "sceneMarkIn": int(mark_in_frame), "sceneMarkInState": mark_in_state == "set", "sceneMarkOut": int(mark_out_frame), - "sceneMarkOutState": mark_out_state == "set" + "sceneMarkOutState": mark_out_state == "set", + "sceneBgColor": self._get_bg_color() } self.log.debug( "Scene data: {}".format(json.dumps(scene_data, indent=4)) ) context.data.update(scene_data) + + def _get_bg_color(self): + """Background color set on scene. + + Is important for review exporting where scene bg color is used as + background. + """ + output_file = tempfile.NamedTemporaryFile( + mode="w", prefix="a_tvp_", suffix=".txt", delete=False + ) + output_file.close() + output_filepath = output_file.name.replace("\\", "/") + george_script_lines = [ + # Variable containing full path to output file + "output_path = \"{}\"".format(output_filepath), + "tv_background", + "bg_color = result", + # Write data to output file + ( + "tv_writetextfile" + " \"strict\" \"append\" '\"'output_path'\"' bg_color" + ) + ] + + george_script = "\n".join(george_script_lines) + lib.execute_george_through_file(george_script) + + with open(output_filepath, "r") as stream: + data = stream.read() + + os.remove(output_filepath) + data = data.strip() + if not data: + return None + return data.split(" ") diff --git a/openpype/hosts/tvpaint/plugins/publish/extract_sequence.py b/openpype/hosts/tvpaint/plugins/publish/extract_sequence.py index 007b5c41f1..536df2adb0 100644 --- a/openpype/hosts/tvpaint/plugins/publish/extract_sequence.py +++ b/openpype/hosts/tvpaint/plugins/publish/extract_sequence.py @@ -1,5 +1,6 @@ import os import shutil +import copy import tempfile import pyblish.api @@ -13,6 +14,9 @@ class ExtractSequence(pyblish.api.Extractor): hosts = ["tvpaint"] families = ["review", "renderPass", "renderLayer"] + # Modifiable with settings + review_bg = [255, 255, 255, 255] + def process(self, instance): self.log.info( "* Processing instance \"{}\"".format(instance.data["label"]) @@ -53,6 +57,8 @@ class ExtractSequence(pyblish.api.Extractor): handle_start = instance.context.data["handleStart"] handle_end = instance.context.data["handleEnd"] + scene_bg_color = instance.context.data["sceneBgColor"] + # --- Fallbacks ---------------------------------------------------- # This is required if validations of ranges are ignored. # - all of this code won't change processing if range to render @@ -120,7 +126,8 @@ class ExtractSequence(pyblish.api.Extractor): if instance.data["family"] == "review": output_filenames, thumbnail_fullpath = self.render_review( - filename_template, output_dir, mark_in, mark_out + filename_template, output_dir, mark_in, mark_out, + scene_bg_color ) else: # Render output @@ -241,7 +248,9 @@ class ExtractSequence(pyblish.api.Extractor): for path in repre_filepaths ] - def render_review(self, filename_template, output_dir, mark_in, mark_out): + def render_review( + self, filename_template, output_dir, mark_in, mark_out, scene_bg_color + ): """ Export images from TVPaint using `tv_savesequence` command. Args: @@ -252,6 +261,8 @@ class ExtractSequence(pyblish.api.Extractor): output_dir (str): Directory where files will be stored. mark_in (int): Starting frame index from which export will begin. mark_out (int): On which frame index export will end. + scene_bg_color (list): Bg color set in scene. Result of george + script command `tv_background`. Retruns: tuple: With 2 items first is list of filenames second is path to @@ -263,7 +274,11 @@ class ExtractSequence(pyblish.api.Extractor): filename_template.format(frame=mark_in) ) + bg_color = self._get_review_bg_color() + george_script_lines = [ + # Change bg color to color from settings + "tv_background \"color\" {} {} {}".format(*bg_color), "tv_SaveMode \"PNG\"", "export_path = \"{}\"".format( first_frame_filepath.replace("\\", "/") @@ -272,6 +287,18 @@ class ExtractSequence(pyblish.api.Extractor): mark_in, mark_out ) ] + if scene_bg_color: + # Change bg color back to previous scene bg color + _scene_bg_color = copy.deepcopy(scene_bg_color) + bg_type = _scene_bg_color.pop(0) + orig_color_command = [ + "tv_background", + "\"{}\"".format(bg_type) + ] + orig_color_command.extend(_scene_bg_color) + + george_script_lines.append(" ".join(orig_color_command)) + lib.execute_george_through_file("\n".join(george_script_lines)) first_frame_filepath = None @@ -291,12 +318,13 @@ class ExtractSequence(pyblish.api.Extractor): if first_frame_filepath is None: first_frame_filepath = filepath - thumbnail_filepath = os.path.join(output_dir, "thumbnail.jpg") + thumbnail_filepath = None if first_frame_filepath and os.path.exists(first_frame_filepath): + thumbnail_filepath = os.path.join(output_dir, "thumbnail.jpg") source_img = Image.open(first_frame_filepath) - thumbnail_obj = Image.new("RGB", source_img.size, (255, 255, 255)) - thumbnail_obj.paste(source_img) - thumbnail_obj.save(thumbnail_filepath) + if source_img.mode.lower() != "rgb": + source_img = source_img.convert("RGB") + source_img.save(thumbnail_filepath) return output_filenames, thumbnail_filepath @@ -392,12 +420,35 @@ class ExtractSequence(pyblish.api.Extractor): if thumbnail_src_filepath and os.path.exists(thumbnail_src_filepath): source_img = Image.open(thumbnail_src_filepath) thumbnail_filepath = os.path.join(output_dir, "thumbnail.jpg") - thumbnail_obj = Image.new("RGB", source_img.size, (255, 255, 255)) - thumbnail_obj.paste(source_img) - thumbnail_obj.save(thumbnail_filepath) + # Composite background only on rgba images + # - just making sure + if source_img.mode.lower() == "rgba": + bg_color = self._get_review_bg_color() + self.log.debug("Adding thumbnail background color {}.".format( + " ".join([str(val) for val in bg_color]) + )) + bg_image = Image.new("RGBA", source_img.size, bg_color) + thumbnail_obj = Image.alpha_composite(bg_image, source_img) + thumbnail_obj.convert("RGB").save(thumbnail_filepath) + + else: + self.log.info(( + "Source for thumbnail has mode \"{}\" (Expected: RGBA)." + " Can't use thubmanail background color." + ).format(source_img.mode)) + source_img.save(thumbnail_filepath) return output_filenames, thumbnail_filepath + def _get_review_bg_color(self): + red = green = blue = 255 + if self.review_bg: + if len(self.review_bg) == 4: + red, green, blue, _ = self.review_bg + elif len(self.review_bg) == 3: + red, green, blue = self.review_bg + return (red, green, blue) + def _render_layer( self, layer, diff --git a/openpype/lib/abstract_submit_deadline.py b/openpype/lib/abstract_submit_deadline.py index 12014ddfb5..4a052a4ee2 100644 --- a/openpype/lib/abstract_submit_deadline.py +++ b/openpype/lib/abstract_submit_deadline.py @@ -18,6 +18,48 @@ import pyblish.api from .abstract_metaplugins import AbstractMetaInstancePlugin +def requests_post(*args, **kwargs): + """Wrap request post method. + + Disabling SSL certificate validation if ``DONT_VERIFY_SSL`` environment + variable is found. This is useful when Deadline or Muster server are + running with self-signed certificates and their certificate is not + added to trusted certificates on client machines. + + Warning: + Disabling SSL certificate validation is defeating one line + of defense SSL is providing and it is not recommended. + + """ + if 'verify' not in kwargs: + kwargs['verify'] = False if os.getenv("OPENPYPE_DONT_VERIFY_SSL", + True) else True # noqa + # add 10sec timeout before bailing out + kwargs['timeout'] = 10 + return requests.post(*args, **kwargs) + + +def requests_get(*args, **kwargs): + """Wrap request get method. + + Disabling SSL certificate validation if ``DONT_VERIFY_SSL`` environment + variable is found. This is useful when Deadline or Muster server are + running with self-signed certificates and their certificate is not + added to trusted certificates on client machines. + + Warning: + Disabling SSL certificate validation is defeating one line + of defense SSL is providing and it is not recommended. + + """ + if 'verify' not in kwargs: + kwargs['verify'] = False if os.getenv("OPENPYPE_DONT_VERIFY_SSL", + True) else True # noqa + # add 10sec timeout before bailing out + kwargs['timeout'] = 10 + return requests.get(*args, **kwargs) + + @attr.s class DeadlineJobInfo(object): """Mapping of all Deadline *JobInfo* attributes. @@ -579,7 +621,7 @@ class AbstractSubmitDeadline(pyblish.api.InstancePlugin): """ url = "{}/api/jobs".format(self._deadline_url) - response = self._requests_post(url, json=payload) + response = requests_post(url, json=payload) if not response.ok: self.log.error("Submission failed!") self.log.error(response.status_code) @@ -592,41 +634,3 @@ class AbstractSubmitDeadline(pyblish.api.InstancePlugin): self._instance.data["deadlineSubmissionJob"] = result return result["_id"] - - def _requests_post(self, *args, **kwargs): - """Wrap request post method. - - Disabling SSL certificate validation if ``DONT_VERIFY_SSL`` environment - variable is found. This is useful when Deadline or Muster server are - running with self-signed certificates and their certificate is not - added to trusted certificates on client machines. - - Warning: - Disabling SSL certificate validation is defeating one line - of defense SSL is providing and it is not recommended. - - """ - if 'verify' not in kwargs: - kwargs['verify'] = False if os.getenv("OPENPYPE_DONT_VERIFY_SSL", True) else True # noqa - # add 10sec timeout before bailing out - kwargs['timeout'] = 10 - return requests.post(*args, **kwargs) - - def _requests_get(self, *args, **kwargs): - """Wrap request get method. - - Disabling SSL certificate validation if ``DONT_VERIFY_SSL`` environment - variable is found. This is useful when Deadline or Muster server are - running with self-signed certificates and their certificate is not - added to trusted certificates on client machines. - - Warning: - Disabling SSL certificate validation is defeating one line - of defense SSL is providing and it is not recommended. - - """ - if 'verify' not in kwargs: - kwargs['verify'] = False if os.getenv("OPENPYPE_DONT_VERIFY_SSL", True) else True # noqa - # add 10sec timeout before bailing out - kwargs['timeout'] = 10 - return requests.get(*args, **kwargs) diff --git a/openpype/lib/anatomy.py b/openpype/lib/anatomy.py index c16c6e2e99..7a4a55363c 100644 --- a/openpype/lib/anatomy.py +++ b/openpype/lib/anatomy.py @@ -733,6 +733,9 @@ class Templates: continue default_key_values[key] = templates.pop(key) + # Pop "others" key before before expected keys are processed + other_templates = templates.pop("others") or {} + keys_by_subkey = {} for sub_key, sub_value in templates.items(): key_values = {} @@ -740,7 +743,6 @@ class Templates: key_values.update(sub_value) keys_by_subkey[sub_key] = cls.prepare_inner_keys(key_values) - other_templates = templates.get("others") or {} for sub_key, sub_value in other_templates.items(): if sub_key in keys_by_subkey: log.warning(( diff --git a/openpype/lib/applications.py b/openpype/lib/applications.py index d82b7cd847..9866400928 100644 --- a/openpype/lib/applications.py +++ b/openpype/lib/applications.py @@ -191,26 +191,32 @@ class Application: self.full_label = full_label self._environment = data.get("environment") or {} + arguments = data.get("arguments") + if isinstance(arguments, dict): + arguments = arguments.get(platform.system().lower()) + + if not arguments: + arguments = [] + self.arguments = arguments + + if "executables" not in data: + self.executables = [ + UndefinedApplicationExecutable() + ] + return + _executables = data["executables"] + if isinstance(_executables, dict): + _executables = _executables.get(platform.system().lower()) + if not _executables: _executables = [] - elif isinstance(_executables, dict): - _executables = _executables.get(platform.system().lower()) or [] - - _arguments = data["arguments"] - if not _arguments: - _arguments = [] - - elif isinstance(_arguments, dict): - _arguments = _arguments.get(platform.system().lower()) or [] - executables = [] for executable in _executables: executables.append(ApplicationExecutable(executable)) self.executables = executables - self.arguments = _arguments def __repr__(self): return "<{}> - {}".format(self.__class__.__name__, self.full_name) @@ -454,6 +460,12 @@ class ApplicationExecutable: if os.path.exists(_executable): executable = _executable + # Try to format executable with environments + try: + executable = executable.format(**os.environ) + except Exception: + pass + self.executable_path = executable def __str__(self): @@ -484,6 +496,27 @@ class ApplicationExecutable: return bool(self._realpath()) +class UndefinedApplicationExecutable(ApplicationExecutable): + """Some applications do not require executable path from settings. + + In that case this class is used to "fake" existing executable. + """ + def __init__(self): + pass + + def __str__(self): + return self.__class__.__name__ + + def __repr__(self): + return "<{}>".format(self.__class__.__name__) + + def as_args(self): + return [] + + def exists(self): + return True + + @six.add_metaclass(ABCMeta) class LaunchHook: """Abstract base class of launch hook.""" @@ -1126,6 +1159,9 @@ def prepare_host_environments(data, implementation_envs=True): def apply_project_environments_value(project_name, env, project_settings=None): """Apply project specific environments on passed environments. + The enviornments are applied on passed `env` argument value so it is not + required to apply changes back. + Args: project_name (str): Name of project for which environemnts should be received. @@ -1134,6 +1170,9 @@ def apply_project_environments_value(project_name, env, project_settings=None): project_settings (dict): Project settings for passed project name. Optional if project settings are already prepared. + Returns: + dict: Passed env values with applied project environments. + Raises: KeyError: If project settings do not contain keys for project specific environments. @@ -1144,10 +1183,9 @@ def apply_project_environments_value(project_name, env, project_settings=None): project_settings = get_project_settings(project_name) env_value = project_settings["global"]["project_environments"] - if not env_value: - return env - parsed = acre.parse(env_value) - return _merge_env(parsed, env) + if env_value: + env.update(_merge_env(acre.parse(env_value), env)) + return env def prepare_context_environments(data): @@ -1176,9 +1214,8 @@ def prepare_context_environments(data): # Load project specific environments project_name = project_doc["name"] - data["env"] = apply_project_environments_value( - project_name, data["env"] - ) + # Apply project specific environments on current env value + apply_project_environments_value(project_name, data["env"]) app = data["app"] workdir_data = get_workdir_data( diff --git a/openpype/lib/plugin_tools.py b/openpype/lib/plugin_tools.py index a5254af0da..1f2fb7a46e 100644 --- a/openpype/lib/plugin_tools.py +++ b/openpype/lib/plugin_tools.py @@ -34,7 +34,8 @@ def get_subset_name( asset_id, project_name=None, host_name=None, - default_template=None + default_template=None, + dynamic_data=None ): if not family: return "" @@ -68,11 +69,16 @@ def get_subset_name( if not task_name and "{task" in template.lower(): raise TaskNotSetError() - fill_pairs = ( - ("variant", variant), - ("family", family), - ("task", task_name) - ) + fill_pairs = { + "variant": variant, + "family": family, + "task": task_name + } + if dynamic_data: + # Dynamic data may override default values + for key, value in dynamic_data.items(): + fill_pairs[key] = value + return template.format(**prepare_template_data(fill_pairs)) @@ -91,7 +97,8 @@ def prepare_template_data(fill_pairs): """ fill_data = {} - for key, value in fill_pairs: + regex = re.compile(r"[a-zA-Z0-9]") + for key, value in dict(fill_pairs).items(): # Handle cases when value is `None` (standalone publisher) if value is None: continue @@ -102,13 +109,18 @@ def prepare_template_data(fill_pairs): # Capitalize only first char of value # - conditions are because of possible index errors + # - regex is to skip symbols that are not chars or numbers + # - e.g. "{key}" which starts with curly bracket capitalized = "" - if value: - # Upper first character - capitalized += value[0].upper() - # Append rest of string if there is any - if len(value) > 1: - capitalized += value[1:] + for idx in range(len(value or "")): + char = value[idx] + if not regex.match(char): + capitalized += char + else: + capitalized += char.upper() + capitalized += value[idx + 1:] + break + fill_data[key.capitalize()] = capitalized return fill_data diff --git a/openpype/modules/__init__.py b/openpype/modules/__init__.py index debeeed6bf..d6fb9c0aef 100644 --- a/openpype/modules/__init__.py +++ b/openpype/modules/__init__.py @@ -39,6 +39,7 @@ from .deadline import DeadlineModule from .project_manager_action import ProjectManagerAction from .standalonepublish_action import StandAlonePublishAction from .sync_server import SyncServerModule +from .slack import SlackIntegrationModule __all__ = ( @@ -77,5 +78,7 @@ __all__ = ( "ProjectManagerAction", "StandAlonePublishAction", - "SyncServerModule" + "SyncServerModule", + + "SlackIntegrationModule" ) diff --git a/openpype/modules/clockify/clockify_api.py b/openpype/modules/clockify/clockify_api.py index 3f0a9799b4..6af911fffc 100644 --- a/openpype/modules/clockify/clockify_api.py +++ b/openpype/modules/clockify/clockify_api.py @@ -36,6 +36,7 @@ class ClockifyAPI: self._secure_registry = None + @property def secure_registry(self): if self._secure_registry is None: self._secure_registry = OpenPypeSecureRegistry("clockify") diff --git a/openpype/modules/clockify/widgets.py b/openpype/modules/clockify/widgets.py index 76f3a3f365..fc8e7fa8a3 100644 --- a/openpype/modules/clockify/widgets.py +++ b/openpype/modules/clockify/widgets.py @@ -1,6 +1,5 @@ from Qt import QtCore, QtGui, QtWidgets -from avalon import style -from openpype import resources +from openpype import resources, style class MessageWidget(QtWidgets.QWidget): @@ -22,14 +21,6 @@ class MessageWidget(QtWidgets.QWidget): QtCore.Qt.WindowMinimizeButtonHint ) - # Font - self.font = QtGui.QFont() - self.font.setFamily("DejaVu Sans Condensed") - self.font.setPointSize(9) - self.font.setBold(True) - self.font.setWeight(50) - self.font.setKerning(True) - # Size setting self.resize(self.SIZE_W, self.SIZE_H) self.setMinimumSize(QtCore.QSize(self.SIZE_W, self.SIZE_H)) @@ -53,7 +44,6 @@ class MessageWidget(QtWidgets.QWidget): labels = [] for message in messages: label = QtWidgets.QLabel(message) - label.setFont(self.font) label.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) label.setTextFormat(QtCore.Qt.RichText) label.setWordWrap(True) @@ -103,84 +93,64 @@ class ClockifySettings(QtWidgets.QWidget): icon = QtGui.QIcon(resources.pype_icon_filepath()) self.setWindowIcon(icon) + self.setWindowTitle("Clockify settings") self.setWindowFlags( QtCore.Qt.WindowCloseButtonHint | QtCore.Qt.WindowMinimizeButtonHint ) - self._translate = QtCore.QCoreApplication.translate - - # Font - self.font = QtGui.QFont() - self.font.setFamily("DejaVu Sans Condensed") - self.font.setPointSize(9) - self.font.setBold(True) - self.font.setWeight(50) - self.font.setKerning(True) - # Size setting self.resize(self.SIZE_W, self.SIZE_H) self.setMinimumSize(QtCore.QSize(self.SIZE_W, self.SIZE_H)) self.setMaximumSize(QtCore.QSize(self.SIZE_W+100, self.SIZE_H+100)) self.setStyleSheet(style.load_stylesheet()) - self.setLayout(self._main()) - self.setWindowTitle('Clockify settings') + self._ui_init() - def _main(self): - self.main = QtWidgets.QVBoxLayout() - self.main.setObjectName("main") + def _ui_init(self): + label_api_key = QtWidgets.QLabel("Clockify API key:") - self.form = QtWidgets.QFormLayout() - self.form.setContentsMargins(10, 15, 10, 5) - self.form.setObjectName("form") + input_api_key = QtWidgets.QLineEdit() + input_api_key.setFrame(True) + input_api_key.setPlaceholderText("e.g. XX1XxXX2x3x4xXxx") - self.label_api_key = QtWidgets.QLabel("Clockify API key:") - self.label_api_key.setFont(self.font) - self.label_api_key.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor)) - self.label_api_key.setTextFormat(QtCore.Qt.RichText) - self.label_api_key.setObjectName("label_api_key") + error_label = QtWidgets.QLabel("") + error_label.setTextFormat(QtCore.Qt.RichText) + error_label.setWordWrap(True) + error_label.hide() - self.input_api_key = QtWidgets.QLineEdit() - self.input_api_key.setEnabled(True) - self.input_api_key.setFrame(True) - self.input_api_key.setObjectName("input_api_key") - self.input_api_key.setPlaceholderText( - self._translate("main", "e.g. XX1XxXX2x3x4xXxx") - ) + form_layout = QtWidgets.QFormLayout() + form_layout.setContentsMargins(10, 15, 10, 5) + form_layout.addRow(label_api_key, input_api_key) + form_layout.addRow(error_label) - self.error_label = QtWidgets.QLabel("") - self.error_label.setFont(self.font) - self.error_label.setTextFormat(QtCore.Qt.RichText) - self.error_label.setObjectName("error_label") - self.error_label.setWordWrap(True) - self.error_label.hide() + btn_ok = QtWidgets.QPushButton("Ok") + btn_ok.setToolTip('Sets Clockify API Key so can Start/Stop timer') - self.form.addRow(self.label_api_key, self.input_api_key) - self.form.addRow(self.error_label) - - self.btn_group = QtWidgets.QHBoxLayout() - self.btn_group.addStretch(1) - self.btn_group.setObjectName("btn_group") - - self.btn_ok = QtWidgets.QPushButton("Ok") - self.btn_ok.setToolTip('Sets Clockify API Key so can Start/Stop timer') - self.btn_ok.clicked.connect(self.click_ok) - - self.btn_cancel = QtWidgets.QPushButton("Cancel") + btn_cancel = QtWidgets.QPushButton("Cancel") cancel_tooltip = 'Application won\'t start' if self.optional: cancel_tooltip = 'Close this window' - self.btn_cancel.setToolTip(cancel_tooltip) - self.btn_cancel.clicked.connect(self._close_widget) + btn_cancel.setToolTip(cancel_tooltip) - self.btn_group.addWidget(self.btn_ok) - self.btn_group.addWidget(self.btn_cancel) + btn_group = QtWidgets.QHBoxLayout() + btn_group.addStretch(1) + btn_group.addWidget(btn_ok) + btn_group.addWidget(btn_cancel) - self.main.addLayout(self.form) - self.main.addLayout(self.btn_group) + main_layout = QtWidgets.QVBoxLayout(self) + main_layout.addLayout(form_layout) + main_layout.addLayout(btn_group) - return self.main + btn_ok.clicked.connect(self.click_ok) + btn_cancel.clicked.connect(self._close_widget) + + self.label_api_key = label_api_key + self.input_api_key = input_api_key + self.error_label = error_label + + self.btn_ok = btn_ok + self.btn_cancel = btn_cancel def setError(self, msg): self.error_label.setText(msg) @@ -212,6 +182,17 @@ class ClockifySettings(QtWidgets.QWidget): "Entered invalid API key" ) + def showEvent(self, event): + super(ClockifySettings, self).showEvent(event) + + # Make btns same width + max_width = max( + self.btn_ok.sizeHint().width(), + self.btn_cancel.sizeHint().width() + ) + self.btn_ok.setMinimumWidth(max_width) + self.btn_cancel.setMinimumWidth(max_width) + def closeEvent(self, event): if self.optional is True: event.ignore() diff --git a/openpype/modules/deadline/plugins/publish/submit_publish_job.py b/openpype/modules/deadline/plugins/publish/submit_publish_job.py index 52ed9bba76..41f8337fd8 100644 --- a/openpype/modules/deadline/plugins/publish/submit_publish_job.py +++ b/openpype/modules/deadline/plugins/publish/submit_publish_job.py @@ -231,7 +231,8 @@ class ProcessSubmittedJobOnFarm(pyblish.api.InstancePlugin): args = [ 'publish', - roothless_metadata_path + roothless_metadata_path, + "--targets {}".format("deadline") ] # Generate the payload for Deadline submission diff --git a/openpype/modules/deadline/plugins/publish/validate_expected_and_rendered_files.py b/openpype/modules/deadline/plugins/publish/validate_expected_and_rendered_files.py new file mode 100644 index 0000000000..c71b5106ec --- /dev/null +++ b/openpype/modules/deadline/plugins/publish/validate_expected_and_rendered_files.py @@ -0,0 +1,186 @@ +import os +import json +import pyblish.api + +from avalon.vendor import requests + +from openpype.api import get_system_settings +from openpype.lib.abstract_submit_deadline import requests_get +from openpype.lib.delivery import collect_frames + + +class ValidateExpectedFiles(pyblish.api.InstancePlugin): + """Compare rendered and expected files""" + + label = "Validate rendered files from Deadline" + order = pyblish.api.ValidatorOrder + families = ["render"] + targets = ["deadline"] + + # check if actual frame range on render job wasn't different + # case when artists wants to render only subset of frames + allow_user_override = True + + def process(self, instance): + frame_list = self._get_frame_list(instance.data["render_job_id"]) + + for repre in instance.data["representations"]: + expected_files = self._get_expected_files(repre) + + staging_dir = repre["stagingDir"] + existing_files = self._get_existing_files(staging_dir) + + expected_non_existent = expected_files.difference( + existing_files) + if len(expected_non_existent) != 0: + self.log.info("Some expected files missing {}".format( + expected_non_existent)) + + if self.allow_user_override: + file_name_template, frame_placeholder = \ + self._get_file_name_template_and_placeholder( + expected_files) + + if not file_name_template: + return + + real_expected_rendered = self._get_real_render_expected( + file_name_template, + frame_placeholder, + frame_list) + + real_expected_non_existent = \ + real_expected_rendered.difference(existing_files) + if len(real_expected_non_existent) != 0: + raise RuntimeError("Still missing some files {}". + format(real_expected_non_existent)) + self.log.info("Update range from actual job range") + repre["files"] = sorted(list(real_expected_rendered)) + else: + raise RuntimeError("Some expected files missing {}".format( + expected_non_existent)) + + def _get_frame_list(self, original_job_id): + """ + Returns list of frame ranges from all render job. + + Render job might be requeried so job_id in metadata.json is invalid + GlobalJobPreload injects current ids to RENDER_JOB_IDS. + + Args: + original_job_id (str) + Returns: + (list) + """ + all_frame_lists = [] + render_job_ids = os.environ.get("RENDER_JOB_IDS") + if render_job_ids: + render_job_ids = render_job_ids.split(',') + else: # fallback + render_job_ids = [original_job_id] + + for job_id in render_job_ids: + job_info = self._get_job_info(job_id) + frame_list = job_info["Props"]["Frames"] + if frame_list: + all_frame_lists.extend(frame_list.split(',')) + + return all_frame_lists + + def _get_real_render_expected(self, file_name_template, frame_placeholder, + frame_list): + """ + Calculates list of names of expected rendered files. + + Might be different from job expected files if user explicitly and + manually change frame list on Deadline job. + """ + real_expected_rendered = set() + src_padding_exp = "%0{}d".format(len(frame_placeholder)) + for frames in frame_list: + if '-' not in frames: # single frame + frames = "{}-{}".format(frames, frames) + + start, end = frames.split('-') + for frame in range(int(start), int(end) + 1): + ren_name = file_name_template.replace( + frame_placeholder, src_padding_exp % frame) + real_expected_rendered.add(ren_name) + + return real_expected_rendered + + def _get_file_name_template_and_placeholder(self, files): + """Returns file name with frame replaced with # and this placeholder""" + sources_and_frames = collect_frames(files) + + file_name_template = frame_placeholder = None + for file_name, frame in sources_and_frames.items(): + frame_placeholder = "#" * len(frame) + file_name_template = os.path.basename( + file_name.replace(frame, frame_placeholder)) + break + + return file_name_template, frame_placeholder + + def _get_job_info(self, job_id): + """ + Calls DL for actual job info for 'job_id' + + Might be different than job info saved in metadata.json if user + manually changes job pre/during rendering. + """ + deadline_url = ( + get_system_settings() + ["modules"] + ["deadline"] + ["DEADLINE_REST_URL"] + ) + assert deadline_url, "Requires DEADLINE_REST_URL" + + url = "{}/api/jobs?JobID={}".format(deadline_url, job_id) + try: + response = requests_get(url) + except requests.exceptions.ConnectionError: + print("Deadline is not accessible at {}".format(deadline_url)) + # self.log("Deadline is not accessible at {}".format(deadline_url)) + return {} + + if not response.ok: + self.log.error("Submission failed!") + self.log.error(response.status_code) + self.log.error(response.content) + raise RuntimeError(response.text) + + json_content = response.json() + if json_content: + return json_content.pop() + return {} + + def _parse_metadata_json(self, json_path): + if not os.path.exists(json_path): + msg = "Metadata file {} doesn't exist".format(json_path) + raise RuntimeError(msg) + + with open(json_path) as fp: + try: + return json.load(fp) + except Exception as exc: + self.log.error( + "Error loading json: " + "{} - Exception: {}".format(json_path, exc) + ) + + def _get_existing_files(self, out_dir): + """Returns set of existing file names from 'out_dir'""" + existing_files = set() + for file_name in os.listdir(out_dir): + existing_files.add(file_name) + return existing_files + + def _get_expected_files(self, repre): + """Returns set of file names from metadata.json""" + expected_files = set() + + for file_name in repre["files"]: + expected_files.add(file_name) + return expected_files diff --git a/openpype/modules/ftrack/event_handlers_server/event_push_frame_values_to_task.py b/openpype/modules/ftrack/event_handlers_server/event_push_frame_values_to_task.py index c0b3137455..81719258e1 100644 --- a/openpype/modules/ftrack/event_handlers_server/event_push_frame_values_to_task.py +++ b/openpype/modules/ftrack/event_handlers_server/event_push_frame_values_to_task.py @@ -2,7 +2,10 @@ import collections import datetime import ftrack_api -from openpype.modules.ftrack.lib import BaseEvent +from openpype.modules.ftrack.lib import ( + BaseEvent, + query_custom_attributes +) class PushFrameValuesToTaskEvent(BaseEvent): @@ -55,10 +58,6 @@ class PushFrameValuesToTaskEvent(BaseEvent): if entity_info.get("entityType") != "task": continue - # Skip `Task` entity type - if entity_info["entity_type"].lower() == "task": - continue - # Care only about changes of status changes = entity_info.get("changes") if not changes: @@ -74,6 +73,14 @@ class PushFrameValuesToTaskEvent(BaseEvent): if project_id is None: continue + # Skip `Task` entity type if parent didn't change + if entity_info["entity_type"].lower() == "task": + if ( + "parent_id" not in changes + or changes["parent_id"]["new"] is None + ): + continue + if project_id not in entities_info_by_project_id: entities_info_by_project_id[project_id] = [] entities_info_by_project_id[project_id].append(entity_info) @@ -117,11 +124,24 @@ class PushFrameValuesToTaskEvent(BaseEvent): )) return + interest_attributes = set(interest_attributes) + interest_entity_types = set(interest_entity_types) + + # Separate value changes and task parent changes + _entities_info = [] + task_parent_changes = [] + for entity_info in entities_info: + if entity_info["entity_type"].lower() == "task": + task_parent_changes.append(entity_info) + else: + _entities_info.append(entity_info) + entities_info = _entities_info + # Filter entities info with changes interesting_data, changed_keys_by_object_id = self.filter_changes( session, event, entities_info, interest_attributes ) - if not interesting_data: + if not interesting_data and not task_parent_changes: return # Prepare object types @@ -131,6 +151,289 @@ class PushFrameValuesToTaskEvent(BaseEvent): name_low = object_type["name"].lower() object_types_by_name[name_low] = object_type + # NOTE it would be nice to check if `interesting_data` do not contain + # value changs of tasks that were created or moved + # - it is a complex way how to find out + if interesting_data: + self.process_attribute_changes( + session, object_types_by_name, + interesting_data, changed_keys_by_object_id, + interest_entity_types, interest_attributes + ) + + if task_parent_changes: + self.process_task_parent_change( + session, object_types_by_name, task_parent_changes, + interest_entity_types, interest_attributes + ) + + def process_task_parent_change( + self, session, object_types_by_name, task_parent_changes, + interest_entity_types, interest_attributes + ): + """Push custom attribute values if task parent has changed. + + Parent is changed if task is created or if is moved under different + entity. We don't care about all task changes only about those that + have it's parent in interest types (from settings). + + Tasks hierarchical value should be unset or set based on parents + real hierarchical value and non hierarchical custom attribute value + should be set to hierarchical value. + """ + # Store task ids which were created or moved under parent with entity + # type defined in settings (interest_entity_types). + task_ids = set() + # Store parent ids of matching task ids + matching_parent_ids = set() + # Store all entity ids of all entities to be able query hierarchical + # values. + whole_hierarchy_ids = set() + # Store parent id of each entity id + parent_id_by_entity_id = {} + for entity_info in task_parent_changes: + # Ignore entities with less parents than 2 + # NOTE entity itself is also part of "parents" value + parents = entity_info.get("parents") or [] + if len(parents) < 2: + continue + + parent_info = parents[1] + # Check if parent has entity type we care about. + if parent_info["entity_type"] not in interest_entity_types: + continue + + task_ids.add(entity_info["entityId"]) + matching_parent_ids.add(parent_info["entityId"]) + + # Store whole hierarchi of task entity + prev_id = None + for item in parents: + item_id = item["entityId"] + whole_hierarchy_ids.add(item_id) + + if prev_id is None: + prev_id = item_id + continue + + parent_id_by_entity_id[prev_id] = item_id + if item["entityType"] == "show": + break + prev_id = item_id + + # Just skip if nothing is interesting for our settings + if not matching_parent_ids: + return + + # Query object type ids of parent ids for custom attribute + # definitions query + entities = session.query( + "select object_type_id from TypedContext where id in ({})".format( + self.join_query_keys(matching_parent_ids) + ) + ) + + # Prepare task object id + task_object_id = object_types_by_name["task"]["id"] + + # All object ids for which we're querying custom attribute definitions + object_type_ids = set() + object_type_ids.add(task_object_id) + for entity in entities: + object_type_ids.add(entity["object_type_id"]) + + attrs_by_obj_id, hier_attrs = self.attrs_configurations( + session, object_type_ids, interest_attributes + ) + + # Skip if all task attributes are not available + task_attrs = attrs_by_obj_id.get(task_object_id) + if not task_attrs: + return + + # Skip attributes that is not in both hierarchical and nonhierarchical + # TODO be able to push values if hierarchical is available + for key in interest_attributes: + if key not in hier_attrs: + task_attrs.pop(key, None) + + elif key not in task_attrs: + hier_attrs.pop(key) + + # Skip if nothing remained + if not task_attrs: + return + + # Do some preparations for custom attribute values query + attr_key_by_id = {} + nonhier_id_by_key = {} + hier_attr_ids = [] + for key, attr_id in hier_attrs.items(): + attr_key_by_id[attr_id] = key + hier_attr_ids.append(attr_id) + + conf_ids = list(hier_attr_ids) + for key, attr_id in task_attrs.items(): + attr_key_by_id[attr_id] = key + nonhier_id_by_key[key] = attr_id + conf_ids.append(attr_id) + + # Query custom attribute values + # - result does not contain values for all entities only result of + # query callback to ftrack server + result = query_custom_attributes( + session, conf_ids, whole_hierarchy_ids + ) + + # Prepare variables where result will be stored + # - hierachical values should not contain attribute with value by + # default + hier_values_by_entity_id = { + entity_id: {} + for entity_id in whole_hierarchy_ids + } + # - real values of custom attributes + values_by_entity_id = { + entity_id: { + attr_id: None + for attr_id in conf_ids + } + for entity_id in whole_hierarchy_ids + } + for item in result: + attr_id = item["configuration_id"] + entity_id = item["entity_id"] + value = item["value"] + + values_by_entity_id[entity_id][attr_id] = value + + if attr_id in hier_attr_ids and value is not None: + hier_values_by_entity_id[entity_id][attr_id] = value + + # Prepare values for all task entities + # - going through all parents and storing first value value + # - store None to those that are already known that do not have set + # value at all + for task_id in tuple(task_ids): + for attr_id in hier_attr_ids: + entity_ids = [] + value = None + entity_id = task_id + while value is None: + entity_value = hier_values_by_entity_id[entity_id] + if attr_id in entity_value: + value = entity_value[attr_id] + if value is None: + break + + if value is None: + entity_ids.append(entity_id) + + entity_id = parent_id_by_entity_id.get(entity_id) + if entity_id is None: + break + + for entity_id in entity_ids: + hier_values_by_entity_id[entity_id][attr_id] = value + + # Prepare changes to commit + changes = [] + for task_id in tuple(task_ids): + parent_id = parent_id_by_entity_id[task_id] + for attr_id in hier_attr_ids: + attr_key = attr_key_by_id[attr_id] + nonhier_id = nonhier_id_by_key[attr_key] + + # Real value of hierarchical attribute on parent + # - If is none then should be unset + real_parent_value = values_by_entity_id[parent_id][attr_id] + # Current hierarchical value of a task + # - Will be compared to real parent value + hier_value = hier_values_by_entity_id[task_id][attr_id] + + # Parent value that can be inherited from it's parent entity + parent_value = hier_values_by_entity_id[parent_id][attr_id] + # Task value of nonhierarchical custom attribute + nonhier_value = values_by_entity_id[task_id][nonhier_id] + + if real_parent_value != hier_value: + changes.append({ + "new_value": real_parent_value, + "attr_id": attr_id, + "entity_id": task_id, + "attr_key": attr_key + }) + + if parent_value != nonhier_value: + changes.append({ + "new_value": parent_value, + "attr_id": nonhier_id, + "entity_id": task_id, + "attr_key": attr_key + }) + + self._commit_changes(session, changes) + + def _commit_changes(self, session, changes): + uncommited_changes = False + for idx, item in enumerate(changes): + new_value = item["new_value"] + attr_id = item["attr_id"] + entity_id = item["entity_id"] + attr_key = item["attr_key"] + + entity_key = collections.OrderedDict() + entity_key["configuration_id"] = attr_id + entity_key["entity_id"] = entity_id + self._cached_changes.append({ + "attr_key": attr_key, + "entity_id": entity_id, + "value": new_value, + "time": datetime.datetime.now() + }) + if new_value is None: + op = ftrack_api.operation.DeleteEntityOperation( + "CustomAttributeValue", + entity_key + ) + else: + op = ftrack_api.operation.UpdateEntityOperation( + "ContextCustomAttributeValue", + entity_key, + "value", + ftrack_api.symbol.NOT_SET, + new_value + ) + + session.recorded_operations.push(op) + self.log.info(( + "Changing Custom Attribute \"{}\" to value" + " \"{}\" on entity: {}" + ).format(attr_key, new_value, entity_id)) + + if (idx + 1) % 20 == 0: + uncommited_changes = False + try: + session.commit() + except Exception: + session.rollback() + self.log.warning( + "Changing of values failed.", exc_info=True + ) + else: + uncommited_changes = True + if uncommited_changes: + try: + session.commit() + except Exception: + session.rollback() + self.log.warning("Changing of values failed.", exc_info=True) + + def process_attribute_changes( + self, session, object_types_by_name, + interesting_data, changed_keys_by_object_id, + interest_entity_types, interest_attributes + ): # Prepare task object id task_object_id = object_types_by_name["task"]["id"] @@ -216,13 +519,13 @@ class PushFrameValuesToTaskEvent(BaseEvent): task_entity_ids.add(task_id) parent_id_by_task_id[task_id] = task_entity["parent_id"] - self.finalize( + self.finalize_attribute_changes( session, interesting_data, changed_keys, attrs_by_obj_id, hier_attrs, task_entity_ids, parent_id_by_task_id ) - def finalize( + def finalize_attribute_changes( self, session, interesting_data, changed_keys, attrs_by_obj_id, hier_attrs, task_entity_ids, parent_id_by_task_id @@ -248,6 +551,7 @@ class PushFrameValuesToTaskEvent(BaseEvent): session, attr_ids, entity_ids, task_entity_ids, hier_attrs ) + changes = [] for entity_id, current_values in current_values_by_id.items(): parent_id = parent_id_by_task_id.get(entity_id) if not parent_id: @@ -272,39 +576,13 @@ class PushFrameValuesToTaskEvent(BaseEvent): if new_value == old_value: continue - entity_key = collections.OrderedDict() - entity_key["configuration_id"] = attr_id - entity_key["entity_id"] = entity_id - self._cached_changes.append({ - "attr_key": attr_key, + changes.append({ + "new_value": new_value, + "attr_id": attr_id, "entity_id": entity_id, - "value": new_value, - "time": datetime.datetime.now() + "attr_key": attr_key }) - if new_value is None: - op = ftrack_api.operation.DeleteEntityOperation( - "CustomAttributeValue", - entity_key - ) - else: - op = ftrack_api.operation.UpdateEntityOperation( - "ContextCustomAttributeValue", - entity_key, - "value", - ftrack_api.symbol.NOT_SET, - new_value - ) - - session.recorded_operations.push(op) - self.log.info(( - "Changing Custom Attribute \"{}\" to value" - " \"{}\" on entity: {}" - ).format(attr_key, new_value, entity_id)) - try: - session.commit() - except Exception: - session.rollback() - self.log.warning("Changing of values failed.", exc_info=True) + self._commit_changes(session, changes) def filter_changes( self, session, event, entities_info, interest_attributes diff --git a/openpype/modules/ftrack/event_handlers_server/event_version_to_task_statuses.py b/openpype/modules/ftrack/event_handlers_server/event_version_to_task_statuses.py index d20e2ff5a8..f215bedcc2 100644 --- a/openpype/modules/ftrack/event_handlers_server/event_version_to_task_statuses.py +++ b/openpype/modules/ftrack/event_handlers_server/event_version_to_task_statuses.py @@ -66,15 +66,7 @@ class VersionToTaskStatus(BaseEvent): )) return - _status_mapping = event_settings["mapping"] - if not _status_mapping: - self.log.debug( - "Project \"{}\" does not have set mapping for {}".format( - project_name, self.__class__.__name__ - ) - ) - return - + _status_mapping = event_settings["mapping"] or {} status_mapping = { key.lower(): value for key, value in _status_mapping.items() diff --git a/openpype/modules/ftrack/ftrack_server/socket_thread.py b/openpype/modules/ftrack/ftrack_server/socket_thread.py index fd407bb9f5..eb8ec4d06c 100644 --- a/openpype/modules/ftrack/ftrack_server/socket_thread.py +++ b/openpype/modules/ftrack/ftrack_server/socket_thread.py @@ -66,7 +66,16 @@ class SocketThread(threading.Thread): *self.additional_args, str(self.port) ) - self.subproc = subprocess.Popen(args, env=env, stdin=subprocess.PIPE) + kwargs = { + "env": env, + "stdin": subprocess.PIPE + } + if not sys.stdout: + # Redirect to devnull if stdout is None + kwargs["stdout"] = subprocess.DEVNULL + kwargs["stderr"] = subprocess.DEVNULL + + self.subproc = subprocess.Popen(args, **kwargs) # Listen for incoming connections sock.listen(1) diff --git a/openpype/modules/ftrack/lib/__init__.py b/openpype/modules/ftrack/lib/__init__.py index ce6d5284b6..9dc2d67279 100644 --- a/openpype/modules/ftrack/lib/__init__.py +++ b/openpype/modules/ftrack/lib/__init__.py @@ -13,7 +13,8 @@ from .custom_attributes import ( default_custom_attributes_definition, app_definitions_from_app_manager, tool_definitions_from_app_manager, - get_openpype_attr + get_openpype_attr, + query_custom_attributes ) from . import avalon_sync @@ -37,6 +38,7 @@ __all__ = ( "app_definitions_from_app_manager", "tool_definitions_from_app_manager", "get_openpype_attr", + "query_custom_attributes", "avalon_sync", diff --git a/openpype/modules/ftrack/lib/avalon_sync.py b/openpype/modules/ftrack/lib/avalon_sync.py index 5d1da005dc..2458308af5 100644 --- a/openpype/modules/ftrack/lib/avalon_sync.py +++ b/openpype/modules/ftrack/lib/avalon_sync.py @@ -402,16 +402,18 @@ class SyncEntitiesFactory: items = [] items.append({ "type": "label", - "value": "# Can't access Custom attribute <{}>".format( - CUST_ATTR_ID_KEY - ) + "value": ( + "# Can't access Custom attribute: \"{}\"" + ).format(CUST_ATTR_ID_KEY) }) items.append({ "type": "label", "value": ( - "

- Check if user \"{}\" has permissions" - " to access the Custom attribute

" - ).format(self._api_key) + "

- Check if your User and API key has permissions" + " to access the Custom attribute." + "
Username:\"{}\"" + "
API key:\"{}\"

" + ).format(self._api_user, self._api_key) }) items.append({ "type": "label", diff --git a/openpype/modules/ftrack/lib/custom_attributes.py b/openpype/modules/ftrack/lib/custom_attributes.py index f6b82c90b1..53facd4ab2 100644 --- a/openpype/modules/ftrack/lib/custom_attributes.py +++ b/openpype/modules/ftrack/lib/custom_attributes.py @@ -81,3 +81,60 @@ def get_openpype_attr(session, split_hierarchical=True, query_keys=None): return custom_attributes, hier_custom_attributes return custom_attributes + + +def join_query_keys(keys): + """Helper to join keys to query.""" + return ",".join(["\"{}\"".format(key) for key in keys]) + + +def query_custom_attributes(session, conf_ids, entity_ids, table_name=None): + """Query custom attribute values from ftrack database. + + Using ftrack call method result may differ based on used table name and + version of ftrack server. + + Args: + session(ftrack_api.Session): Connected ftrack session. + conf_id(list, set, tuple): Configuration(attribute) ids which are + queried. + entity_ids(list, set, tuple): Entity ids for which are values queried. + table_name(str): Table nam from which values are queried. Not + recommended to change until you know what it means. + """ + output = [] + # Just skip + if not conf_ids or not entity_ids: + return output + + if table_name is None: + table_name = "ContextCustomAttributeValue" + + # Prepare values to query + attributes_joined = join_query_keys(conf_ids) + attributes_len = len(conf_ids) + + # Query values in chunks + chunk_size = int(5000 / attributes_len) + # Make sure entity_ids is `list` for chunk selection + entity_ids = list(entity_ids) + for idx in range(0, len(entity_ids), chunk_size): + entity_ids_joined = join_query_keys( + entity_ids[idx:idx + chunk_size] + ) + + call_expr = [{ + "action": "query", + "expression": ( + "select value, entity_id from {}" + " where entity_id in ({}) and configuration_id in ({})" + ).format(table_name, entity_ids_joined, attributes_joined) + }] + if hasattr(session, "call"): + [result] = session.call(call_expr) + else: + [result] = session._call(call_expr) + + for item in result["data"]: + output.append(item) + return output diff --git a/openpype/modules/ftrack/plugins/publish/collect_ftrack_family.py b/openpype/modules/ftrack/plugins/publish/collect_ftrack_family.py index e6daed9a33..b505a429b5 100644 --- a/openpype/modules/ftrack/plugins/publish/collect_ftrack_family.py +++ b/openpype/modules/ftrack/plugins/publish/collect_ftrack_family.py @@ -1,29 +1,107 @@ +""" +Requires: + none + +Provides: + instance -> families ([]) +""" import pyblish.api +import avalon.api + +from openpype.lib.plugin_tools import filter_profiles -class CollectFtrackFamilies(pyblish.api.InstancePlugin): - """Collect family for ftrack publishing - - Add ftrack family to those instance that should be published to ftrack - +class CollectFtrackFamily(pyblish.api.InstancePlugin): """ + Adds explicitly 'ftrack' to families to upload instance to FTrack. - order = pyblish.api.CollectorOrder + 0.3 - label = 'Add ftrack family' - families = ["model", - "setdress", - "model", - "animation", - "look", - "rig", - "camera" - ] - hosts = ["maya"] + Uses selection by combination of hosts/families/tasks names via + profiles resolution. + + Triggered everywhere, checks instance against configured. + + Checks advanced filtering which works on 'families' not on main + 'family', as some variants dynamically resolves addition of ftrack + based on 'families' (editorial drives it by presence of 'review') + """ + label = "Collect Ftrack Family" + order = pyblish.api.CollectorOrder + 0.4998 + + profiles = None def process(self, instance): + if not self.profiles: + self.log.warning("No profiles present for adding Ftrack family") + return - # make ftrack publishable - if instance.data.get('families'): - instance.data['families'].append('ftrack') + task_name = instance.data.get("task", + avalon.api.Session["AVALON_TASK"]) + host_name = avalon.api.Session["AVALON_APP"] + family = instance.data["family"] + + filtering_criteria = { + "hosts": host_name, + "families": family, + "tasks": task_name + } + profile = filter_profiles(self.profiles, filtering_criteria, + logger=self.log) + + if profile: + families = instance.data.get("families") + add_ftrack_family = profile["add_ftrack_family"] + + additional_filters = profile.get("additional_filters") + if additional_filters: + add_ftrack_family = self._get_add_ftrack_f_from_addit_filters( + additional_filters, + families, + add_ftrack_family + ) + + if add_ftrack_family: + self.log.debug("Adding ftrack family for '{}'". + format(instance.data.get("family"))) + + if families and "ftrack" not in families: + instance.data["families"].append("ftrack") + else: + instance.data["families"] = ["ftrack"] else: - instance.data['families'] = ['ftrack'] + self.log.debug("Instance '{}' doesn't match any profile".format( + instance.data.get("family"))) + + def _get_add_ftrack_f_from_addit_filters(self, + additional_filters, + families, + add_ftrack_family): + """ + Compares additional filters - working on instance's families. + + Triggered for more detailed filtering when main family matches, + but content of 'families' actually matter. + (For example 'review' in 'families' should result in adding to + Ftrack) + + Args: + additional_filters (dict) - from Setting + families (list) - subfamilies + add_ftrack_family (bool) - add ftrack to families if True + """ + override_filter = None + override_filter_value = -1 + for additional_filter in additional_filters: + filter_families = set(additional_filter["families"]) + valid = filter_families <= set(families) # issubset + if not valid: + continue + + value = len(filter_families) + if value > override_filter_value: + override_filter = additional_filter + override_filter_value = value + + if override_filter: + add_ftrack_family = override_filter["add_ftrack_family"] + + return add_ftrack_family diff --git a/openpype/modules/ftrack/tray/login_dialog.py b/openpype/modules/ftrack/tray/login_dialog.py index a6360a7380..cc5689bee5 100644 --- a/openpype/modules/ftrack/tray/login_dialog.py +++ b/openpype/modules/ftrack/tray/login_dialog.py @@ -1,6 +1,6 @@ import os import requests -from avalon import style +from openpype import style from openpype.modules.ftrack.lib import credentials from . import login_tools from openpype import resources @@ -46,8 +46,11 @@ class CredentialsDialog(QtWidgets.QDialog): self.user_label = QtWidgets.QLabel("Username:") self.api_label = QtWidgets.QLabel("API Key:") - self.ftsite_input = QtWidgets.QLineEdit() - self.ftsite_input.setReadOnly(True) + self.ftsite_input = QtWidgets.QLabel() + self.ftsite_input.setTextInteractionFlags( + QtCore.Qt.TextBrowserInteraction + ) + # self.ftsite_input.setReadOnly(True) self.ftsite_input.setCursor(QtGui.QCursor(QtCore.Qt.IBeamCursor)) self.user_input = QtWidgets.QLineEdit() diff --git a/openpype/modules/log_viewer/tray/app.py b/openpype/modules/log_viewer/tray/app.py index c0e180c8a1..9aab37cd20 100644 --- a/openpype/modules/log_viewer/tray/app.py +++ b/openpype/modules/log_viewer/tray/app.py @@ -1,6 +1,6 @@ from Qt import QtWidgets, QtCore from .widgets import LogsWidget, OutputWidget -from avalon import style +from openpype import style class LogsWindow(QtWidgets.QWidget): @@ -14,7 +14,7 @@ class LogsWindow(QtWidgets.QWidget): main_layout = QtWidgets.QHBoxLayout() - log_splitter = QtWidgets.QSplitter() + log_splitter = QtWidgets.QSplitter(self) log_splitter.setOrientation(QtCore.Qt.Horizontal) log_splitter.addWidget(logs_widget) log_splitter.addWidget(log_detail) diff --git a/openpype/modules/log_viewer/tray/widgets.py b/openpype/modules/log_viewer/tray/widgets.py index cd0df283bf..b9a8499a4c 100644 --- a/openpype/modules/log_viewer/tray/widgets.py +++ b/openpype/modules/log_viewer/tray/widgets.py @@ -83,7 +83,6 @@ class CustomCombo(QtWidgets.QWidget): self.setLayout(layout) - # toolmenu.selection_changed.connect(self.on_selection_changed) toolmenu.selection_changed.connect(self.selection_changed) self.toolbutton = toolbutton @@ -119,7 +118,6 @@ class LogsWidget(QtWidgets.QWidget): filter_layout = QtWidgets.QHBoxLayout() - # user_filter = SearchComboBox(self, "Users") user_filter = CustomCombo("Users", self) users = model.dbcon.distinct("username") user_filter.populate(users) @@ -128,21 +126,18 @@ class LogsWidget(QtWidgets.QWidget): proxy_model.update_users_filter(users) level_filter = CustomCombo("Levels", self) - # levels = [(level, True) for level in model.dbcon.distinct("level")] levels = model.dbcon.distinct("level") level_filter.addItems(levels) level_filter.selection_changed.connect(self._level_changed) detail_widget.update_level_filter(levels) - spacer = QtWidgets.QWidget() - icon = qtawesome.icon("fa.refresh", color="white") refresh_btn = QtWidgets.QPushButton(icon, "") filter_layout.addWidget(user_filter) filter_layout.addWidget(level_filter) - filter_layout.addWidget(spacer, 1) + filter_layout.addStretch(1) filter_layout.addWidget(refresh_btn) view = QtWidgets.QTreeView(self) diff --git a/openpype/modules/muster/widget_login.py b/openpype/modules/muster/widget_login.py index d9af4cb99f..231b52c6bd 100644 --- a/openpype/modules/muster/widget_login.py +++ b/openpype/modules/muster/widget_login.py @@ -1,13 +1,12 @@ import os from Qt import QtCore, QtGui, QtWidgets -from avalon import style -from openpype import resources +from openpype import resources, style class MusterLogin(QtWidgets.QWidget): SIZE_W = 300 - SIZE_H = 130 + SIZE_H = 150 loginSignal = QtCore.Signal(object, object, object) @@ -123,7 +122,6 @@ class MusterLogin(QtWidgets.QWidget): super().keyPressEvent(key_event) def setError(self, msg): - self.error_label.setText(msg) self.error_label.show() @@ -149,6 +147,17 @@ class MusterLogin(QtWidgets.QWidget): def save_credentials(self, username, password): self.module.get_auth_token(username, password) + def showEvent(self, event): + super(MusterLogin, self).showEvent(event) + + # Make btns same width + max_width = max( + self.btn_ok.sizeHint().width(), + self.btn_cancel.sizeHint().width() + ) + self.btn_ok.setMinimumWidth(max_width) + self.btn_cancel.setMinimumWidth(max_width) + def closeEvent(self, event): event.ignore() self._close_widget() diff --git a/openpype/modules/settings_action.py b/openpype/modules/settings_action.py index 1035dc0dcd..9db4a252bc 100644 --- a/openpype/modules/settings_action.py +++ b/openpype/modules/settings_action.py @@ -114,6 +114,7 @@ class LocalSettingsAction(PypeModule, ITrayAction): # Tray attributes self.settings_window = None + self._first_trigger = True def connect_with_modules(self, *_a, **_kw): return @@ -153,6 +154,9 @@ class LocalSettingsAction(PypeModule, ITrayAction): self.settings_window.raise_() self.settings_window.activateWindow() - # Reset content if was not visible - if not was_visible: + # Do not reset if it's first trigger of action + if self._first_trigger: + self._first_trigger = False + elif not was_visible: + # Reset content if was not visible self.settings_window.reset() diff --git a/openpype/modules/slack/README.md b/openpype/modules/slack/README.md new file mode 100644 index 0000000000..baf0f9a1ec --- /dev/null +++ b/openpype/modules/slack/README.md @@ -0,0 +1,50 @@ +Slack notification for publishing +--------------------------------- + +This module allows configuring profiles(when to trigger, for which combination of task, host and family) +and templates(could contain {} placeholder, as "{asset} published"). + +These need to be configured in +```Project settings > Slack > Publish plugins > Notification to Slack``` + +Slack module must be enabled in System Setting, could be configured per Project. + +## App installation + +Slack app needs to be installed to company's workspace. Attached .yaml file could be +used, follow instruction https://api.slack.com/reference/manifests#using + +## Settings + +### Token +Most important for module to work is to fill authentication token +```Project settings > Slack > Publish plugins > Token``` + +This token should be available after installation of app in Slack dashboard. +It is possible to create multiple tokens and configure different scopes for them. + +### Profiles +Profiles are used to select when to trigger notification. One or multiple profiles +could be configured, 'family', 'task name' (regex available) and host combination is needed. + +Eg. If I want to be notified when render is published from Maya, setting is: + +- family: 'render' +- host: 'Maya' + +### Channel +Message could be delivered to one or multiple channels, by default app allows Slack bot +to send messages to 'public' channels (eg. bot doesn't need to join channel first). + +This could be configured in Slack dashboard and scopes might be modified. + +### Message +Placeholders {} could be used in message content which will be filled during runtime. +Only keys available in 'anatomyData' are currently implemented. + +Example of message content: +```{SUBSET} for {Asset} was published.``` + +Integration can upload 'thumbnail' file (if present in instance), for that bot must be +manually added to target channel by Slack admin! +(In target channel write: ```/invite @OpenPypeNotifier``) \ No newline at end of file diff --git a/openpype/modules/slack/__init__.py b/openpype/modules/slack/__init__.py new file mode 100644 index 0000000000..0a09d24ed4 --- /dev/null +++ b/openpype/modules/slack/__init__.py @@ -0,0 +1,9 @@ +from .slack_module import ( + SlackIntegrationModule, + SLACK_MODULE_DIR +) + +__all__ = ( + "SlackIntegrationModule", + "SLACK_MODULE_DIR" +) diff --git a/openpype/modules/slack/launch_hooks/pre_python2_vendor.py b/openpype/modules/slack/launch_hooks/pre_python2_vendor.py new file mode 100644 index 0000000000..a2c1f8a9e0 --- /dev/null +++ b/openpype/modules/slack/launch_hooks/pre_python2_vendor.py @@ -0,0 +1,34 @@ +import os +from openpype.lib import PreLaunchHook +from openpype.modules.slack import SLACK_MODULE_DIR + + +class PrePython2Support(PreLaunchHook): + """Add python slack api module for Python 2 to PYTHONPATH. + + Path to vendor modules is added to the beginning of PYTHONPATH. + """ + + def execute(self): + if not self.application.use_python_2: + return + + self.log.info("Adding Slack Python 2 packages to PYTHONPATH.") + + # Prepare vendor dir path + python_2_vendor = os.path.join(SLACK_MODULE_DIR, "python2_vendor") + + # Add Python 2 modules + python_paths = [ + # `python-ftrack-api` + os.path.join(python_2_vendor, "python-slack-sdk-1", "slackclient"), + os.path.join(python_2_vendor, "python-slack-sdk-1") + ] + self.log.info("python_paths {}".format(python_paths)) + # Load PYTHONPATH from current launch context + python_path = self.launch_context.env.get("PYTHONPATH") + if python_path: + python_paths.append(python_path) + + # Set new PYTHONPATH to launch context environments + self.launch_context.env["PYTHONPATH"] = os.pathsep.join(python_paths) diff --git a/openpype/modules/slack/manifest.yml b/openpype/modules/slack/manifest.yml new file mode 100644 index 0000000000..37d4669903 --- /dev/null +++ b/openpype/modules/slack/manifest.yml @@ -0,0 +1,23 @@ +_metadata: + major_version: 1 + minor_version: 1 +display_information: + name: OpenPypeNotifier +features: + app_home: + home_tab_enabled: false + messages_tab_enabled: true + messages_tab_read_only_enabled: true + bot_user: + display_name: OpenPypeNotifier + always_online: false +oauth_config: + scopes: + bot: + - chat:write + - chat:write.public + - files:write +settings: + org_deploy_enabled: false + socket_mode_enabled: false + is_hosted: false diff --git a/openpype/modules/slack/plugins/publish/collect_slack_family.py b/openpype/modules/slack/plugins/publish/collect_slack_family.py new file mode 100644 index 0000000000..2110c0703b --- /dev/null +++ b/openpype/modules/slack/plugins/publish/collect_slack_family.py @@ -0,0 +1,53 @@ +from avalon import io +import pyblish.api + +from openpype.lib.profiles_filtering import filter_profiles + + +class CollectSlackFamilies(pyblish.api.InstancePlugin): + """Collect family for Slack notification + + Expects configured profile in + Project settings > Slack > Publish plugins > Notification to Slack + + Add Slack family to those instance that should be messaged to Slack + """ + order = pyblish.api.CollectorOrder + 0.4999 + label = 'Collect Slack family' + + profiles = None + + def process(self, instance): + task_name = io.Session.get("AVALON_TASK") + family = self.main_family_from_instance(instance) + + key_values = { + "families": family, + "tasks": task_name, + "hosts": instance.data["anatomyData"]["app"], + } + + profile = filter_profiles(self.profiles, key_values, + logger=self.log) + + # make slack publishable + if profile: + if instance.data.get('families'): + instance.data['families'].append('slack') + else: + instance.data['families'] = ['slack'] + + instance.data["slack_channel_message_profiles"] = \ + profile["channel_messages"] + + slack_token = (instance.context.data["project_settings"] + ["slack"] + ["token"]) + instance.data["slack_token"] = slack_token + + def main_family_from_instance(self, instance): # TODO yank from integrate + """Returns main family of entered instance.""" + family = instance.data.get("family") + if not family: + family = instance.data["families"][0] + return family diff --git a/openpype/modules/slack/plugins/publish/integrate_slack_api.py b/openpype/modules/slack/plugins/publish/integrate_slack_api.py new file mode 100644 index 0000000000..7b81d3c364 --- /dev/null +++ b/openpype/modules/slack/plugins/publish/integrate_slack_api.py @@ -0,0 +1,155 @@ +import os +import six +import pyblish.api +import copy + +from openpype.lib.plugin_tools import prepare_template_data + + +class IntegrateSlackAPI(pyblish.api.InstancePlugin): + """ Send message notification to a channel. + Triggers on instances with "slack" family, filled by + 'collect_slack_family'. + Expects configured profile in + Project settings > Slack > Publish plugins > Notification to Slack. + If instance contains 'thumbnail' it uploads it. Bot must be present + in the target channel. + Message template can contain {} placeholders from anatomyData. + """ + order = pyblish.api.IntegratorOrder + 0.499 + label = "Integrate Slack Api" + families = ["slack"] + + optional = True + + def process(self, instance): + published_path = self._get_thumbnail_path(instance) + + for message_profile in instance.data["slack_channel_message_profiles"]: + message = self._get_filled_message(message_profile["message"], + instance) + if not message: + return + + for channel in message_profile["channels"]: + if six.PY2: + self._python2_call(instance.data["slack_token"], + channel, + message, + published_path, + message_profile["upload_thumbnail"]) + else: + self._python3_call(instance.data["slack_token"], + channel, + message, + published_path, + message_profile["upload_thumbnail"]) + + def _get_filled_message(self, message_templ, instance): + """Use message_templ and data from instance to get message content.""" + fill_data = copy.deepcopy(instance.context.data["anatomyData"]) + + fill_pairs = ( + ("asset", instance.data.get("asset", fill_data.get("asset"))), + ("subset", instance.data.get("subset", fill_data.get("subset"))), + ("task", instance.data.get("task", fill_data.get("task"))), + ("username", instance.data.get("username", + fill_data.get("username"))), + ("app", instance.data.get("app", fill_data.get("app"))), + ("family", instance.data.get("family", fill_data.get("family"))), + ("version", str(instance.data.get("version", + fill_data.get("version")))) + ) + + multiple_case_variants = prepare_template_data(fill_pairs) + fill_data.update(multiple_case_variants) + + message = None + try: + message = message_templ.format(**fill_data) + except Exception: + self.log.warning( + "Some keys are missing in {}".format(message_templ), + exc_info=True) + + return message + + def _get_thumbnail_path(self, instance): + """Returns abs url for thumbnail if present in instance repres""" + published_path = None + for repre in instance.data['representations']: + if repre.get('thumbnail') or "thumbnail" in repre.get('tags', []): + repre_files = repre["files"] + if isinstance(repre_files, (tuple, list, set)): + filename = repre_files[0] + else: + filename = repre_files + + published_path = os.path.join( + repre['stagingDir'], filename + ) + break + return published_path + + def _python2_call(self, token, channel, message, + published_path, upload_thumbnail): + from slackclient import SlackClient + try: + client = SlackClient(token) + if upload_thumbnail and \ + published_path and os.path.exists(published_path): + with open(published_path, 'rb') as pf: + response = client.api_call( + "files.upload", + channels=channel, + initial_comment=message, + file=pf, + title=os.path.basename(published_path) + ) + else: + response = client.api_call( + "chat.postMessage", + channel=channel, + text=message + ) + + if response.get("error"): + error_str = self._enrich_error(str(response.get("error")), + channel) + self.log.warning("Error happened: {}".format(error_str)) + except Exception as e: + # You will get a SlackApiError if "ok" is False + error_str = self._enrich_error(str(e), channel) + self.log.warning("Error happened: {}".format(error_str)) + + def _python3_call(self, token, channel, message, + published_path, upload_thumbnail): + from slack_sdk import WebClient + from slack_sdk.errors import SlackApiError + try: + client = WebClient(token=token) + if upload_thumbnail and \ + published_path and os.path.exists(published_path): + _ = client.files_upload( + channels=channel, + initial_comment=message, + file=published_path, + ) + else: + _ = client.chat_postMessage( + channel=channel, + text=message + ) + except SlackApiError as e: + # You will get a SlackApiError if "ok" is False + error_str = self._enrich_error(str(e.response["error"]), channel) + self.log.warning("Error happened {}".format(error_str)) + + def _enrich_error(self, error_str, channel): + """Enhance known errors with more helpful notations.""" + if 'not_in_channel' in error_str: + # there is no file.write.public scope, app must be explicitly in + # the channel + msg = " - application must added to channel '{}'.".format(channel) + error_str += msg + " Ask Slack admin." + return error_str diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.appveyor.yml b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.appveyor.yml new file mode 100644 index 0000000000..79475caa47 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.appveyor.yml @@ -0,0 +1,32 @@ +# credit: https://packaging.python.org/guides/supporting-windows-using-appveyor/ + +environment: + matrix: + - PYTHON: "C:\\Python27" + PYTHON_VERSION: "py27-x86" + - PYTHON: "C:\\Python34" + PYTHON_VERSION: "py34-x86" + - PYTHON: "C:\\Python35" + PYTHON_VERSION: "py35-x86" + - PYTHON: "C:\\Python27-x64" + PYTHON_VERSION: "py27-x64" + - PYTHON: "C:\\Python34-x64" + PYTHON_VERSION: "py34-x64" + - PYTHON: "C:\\Python35-x64" + PYTHON_VERSION: "py35-x64" + +install: + - "%PYTHON%\\python.exe -m pip install wheel" + - "%PYTHON%\\python.exe -m pip install -r requirements.txt" + - "%PYTHON%\\python.exe -m pip install flake8" + - "%PYTHON%\\python.exe -m pip install -r test_requirements.txt" + +build: off + +test_script: + - "%PYTHON%\\python.exe -m flake8 slackclient" + - "%PYTHON%\\python.exe -m pytest --cov-report= --cov=slackclient tests" + +# maybe `after_test:`? +on_success: + - "%PYTHON%\\python.exe -m codecov -e win-%PYTHON_VERSION%" \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.coveragerc b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.coveragerc new file mode 100644 index 0000000000..8d395b7e3b --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True +source = slackclient + +[report] +exclude_lines = + if self.debug: + pragma: no cover + raise NotImplementedError + if __name__ == .__main__.: +ignore_errors = True +omit = + tests/* \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.flake8 b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.flake8 new file mode 100644 index 0000000000..51b50a0465 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.flake8 @@ -0,0 +1,2 @@ +[flake8] +max-line-length = 100 \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.github/contributing.md b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.github/contributing.md new file mode 100644 index 0000000000..614140b037 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.github/contributing.md @@ -0,0 +1,60 @@ +# Contributors Guide + +Interested in contributing? Awesome! Before you do though, please read our +[Code of Conduct](https://slackhq.github.io/code-of-conduct). We take it very seriously, and expect that you will as +well. + +There are many ways you can contribute! :heart: + +### Bug Reports and Fixes :bug: +- If you find a bug, please search for it in the [Issues](https://github.com/slackapi/python-slackclient/issues), and if it isn't already tracked, + [create a new issue](https://github.com/slackapi/python-slackclient/issues/new). Fill out the "Bug Report" section of the issue template. Even if an Issue is closed, feel free to comment and add details, it will still + be reviewed. +- Issues that have already been identified as a bug (note: able to reproduce) will be labelled `bug`. +- If you'd like to submit a fix for a bug, [send a Pull Request](#creating_a_pull_request) and mention the Issue number. + - Include tests that isolate the bug and verifies that it was fixed. + +### New Features :bulb: +- If you'd like to add new functionality to this project, describe the problem you want to solve in a [new Issue](https://github.com/slackapi/python-slackclient/issues/new). +- Issues that have been identified as a feature request will be labelled `enhancement`. +- If you'd like to implement the new feature, please wait for feedback from the project + maintainers before spending too much time writing the code. In some cases, `enhancement`s may + not align well with the project objectives at the time. + +### Tests :mag:, Documentation :books:, Miscellaneous :sparkles: +- If you'd like to improve the tests, you want to make the documentation clearer, you have an + alternative implementation of something that may have advantages over the way its currently + done, or you have any other change, we would be happy to hear about it! + - If its a trivial change, go ahead and [send a Pull Request](#creating_a_pull_request) with the changes you have in mind. + - If not, [open an Issue](https://github.com/slackapi/python-slackclient/issues/new) to discuss the idea first. + +If you're new to our project and looking for some way to make your first contribution, look for +Issues labelled `good first contribution`. + +## Requirements + +For your contribution to be accepted: + +- [x] You must have signed the [Contributor License Agreement (CLA)](https://cla-assistant.io/slackapi/python-slackclient). +- [x] The test suite must be complete and pass. +- [x] The changes must be approved by code review. +- [x] Commits should be atomic and messages must be descriptive. Related issues should be mentioned by Issue number. + +If the contribution doesn't meet the above criteria, you may fail our automated checks or a maintainer will discuss it with you. You can continue to improve a Pull Request by adding commits to the branch from which the PR was created. + +[Interested in knowing more about about pull requests at Slack?](https://slack.engineering/on-empathy-pull-requests-979e4257d158#.awxtvmb2z) + +## Creating a Pull Request + +1. :fork_and_knife: Fork the repository on GitHub. +2. :runner: Clone/fetch your fork to your local development machine. It's a good idea to run the tests just + to make sure everything is in order. +3. :herb: Create a new branch and check it out. +4. :crystal_ball: Make your changes and commit them locally. Magic happens here! +5. :arrow_heading_up: Push your new branch to your fork. (e.g. `git push username fix-issue-16`). +6. :inbox_tray: Open a Pull Request on github.com from your new branch on your fork to `master` in this + repository. + +## Maintainers + +There are more details about processes and workflow in the [Maintainer's Guide](./maintainers_guide.md). \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.github/issue_template.md b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.github/issue_template.md new file mode 100644 index 0000000000..a39638a658 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.github/issue_template.md @@ -0,0 +1,48 @@ +### Description + +Describe your issue here. + +### What type of issue is this? (place an `x` in one of the `[ ]`) +- [ ] bug +- [ ] enhancement (feature request) +- [ ] question +- [ ] documentation related +- [ ] testing related +- [ ] discussion + +### Requirements (place an `x` in each of the `[ ]`) +* [ ] I've read and understood the [Contributing guidelines](https://github.com/slackapi/python-slackclient/blob/master/.github/contributing.md) and have done my best effort to follow them. +* [ ] I've read and agree to the [Code of Conduct](https://slackhq.github.io/code-of-conduct). +* [ ] I've searched for any related issues and avoided creating a duplicate issue. + +--- + +### Bug Report + +Filling out the following details about bugs will help us solve your issue sooner. + +#### Reproducible in: + +slackclient version: + +python version: + +OS version(s): + +#### Steps to reproduce: + +1. +2. +3. + +#### Expected result: + +What you expected to happen + +#### Actual result: + +What actually happened + +#### Attachments: + +Logs, screenshots, screencast, sample project, funny gif, etc. \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.github/maintainers_guide.md b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.github/maintainers_guide.md new file mode 100644 index 0000000000..c1f6a22232 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.github/maintainers_guide.md @@ -0,0 +1,100 @@ +# Maintainers Guide + +This document describes tools, tasks and workflow that one needs to be familiar with in order to effectively maintain +this project. If you use this package within your own software as is but don't plan on modifying it, this guide is +**not** for you. + +## Tools + +### Python (and friends) + +Not surprisingly, you will need to have Python installed on your system to work on this package. We support non-EOL, +stable versions of CPython. The current supported versions are listed in the CI configurations (e.g. `.travis.yml`). +At a minimum, you should have the latest version of Python 2 and the latest version of Python 3 to develop against. +It's tricky to set up a system that has more than that, so you can lean on the CI servers to test changes on the +in-between versions for you. + +You should also make sure you have the latest versions of `pip`, `setuptools`, `virtualenv`, `wheel`, `twine` and +[`tox`](https://tox.readthedocs.io/en/latest/) installed with your version of Python. + +On macOS, the easiest way to install these tools is by using [Homebrew](https://brew.sh/) and installing the `python` +and `python3` packages. Some of the above packages are preinstalled and you can install the remaining on your own: +`pip install virtualenv wheel twine tox && pip3 install virtualenv twine tox`. + +## Tasks + +### Testing + +Tox is used to run the test suite across multiple isolated versions of Python. It is configured in `tox.ini` to +run all the supported versions of Python, but when you invoke it, you should only select the versions you have on your +system. For example, on a system with Python 2.7.13 and Python 3.6.1, you would run the tests using the following +command: `tox -e flake8,py27,py36` (flake8 is a quality analysis tool). + +### Generating Documentation + +The documentation is generated from the source and templates in the `docs-src` directory. The generated documentation +gets committed to the repo in `docs` and also published to a GitHub Pages website. + +You can generate the documentation by running `tox -e docs`. + +### Releasing + +1. Create the commit for the release: + * Bump the version number in adherence to [Semantic Versioning](http://semver.org/) in `slackclient/version.py`. + * Commit with a message including the new version number. For example `1.0.6`. + +2. Distribute the release + * Build the distribtuions: `python setup.py sdist bdist_wheel`. This will create artifacts in the `dist` directory. + * Publish to PyPI: `twine upload dist/*`. You must have access to the credentials to publish. + * Create a GitHub Release. You will select the commit with updated version number (e.g. `1.0.6`) to assiociate with + the tag, and name the tag after this version (e.g. `1.0.6`). This will also serve as a Changelog for the project. + Add a description of changes to the Release. Mention Issue and PR #'s and @-mention contributors. + +3. (Slack Internal) Communicate the release internally. Include a link to the GitHub Release. + +4. Announce on Slack Team dev4slack in #slack-api + +5. (Slack Internal) Tweet? Not necessary for patch updates, might be needed for minor updates, definitely needed for + major updates. Include a link to the GitHub Release. + +## Workflow + +### Versioning and Tags + +This project uses semantic versioning, expressed through the numbering scheme of +[PEP-0440](https://www.python.org/dev/peps/pep-0440/). + +### Branches + +`master` is where active development occurs. Long running named feature branches are occasionally created for +collaboration on a feature that has a large scope (because everyone cannot push commits to another person's open Pull +Request). At some point in the future after a major version increment, there may be maintenance branches for older major +versions. + +### Issue Management + +Labels are used to run issues through an organized workflow. Here are the basic definitions: + +* `bug`: A confirmed bug report. A bug is considered confirmed when reproduction steps have been + documented and the issue has been reproduced. +* `enhancement`: A feature request for something this package might not already do. +* `docs`: An issue that is purely about documentation work. +* `tests`: An issue that is purely about testing work. +* `needs feedback`: An issue that may have claimed to be a bug but was not reproducible, or was otherwise missing some information. +* `discussion`: An issue that is purely meant to hold a discussion. Typically the maintainers are looking for feedback in this issues. +* `question`: An issue that is like a support request because the user's usage was not correct. +* `semver:major|minor|patch`: Metadata about how resolving this issue would affect the version number. +* `security`: An issue that has special consideration for security reasons. +* `good first contribution`: An issue that has a well-defined relatively-small scope, with clear expectations. It helps when the testing approach is also known. +* `duplicate`: An issue that is functionally the same as another issue. Apply this only if you've linked the other issue by number. + +**Triage** is the process of taking new issues that aren't yet "seen" and marking them with a basic level of information +with labels. An issue should have **one** of the following labels applied: `bug`, `enhancement`, `question`, +`needs feedback`, `docs`, `tests`, or `discussion`. + +Issues are closed when a resolution has been reached. If for any reason a closed issue seems relevant once again, +reopening is great and better than creating a duplicate issue. + +## Everything else + +When in doubt, find the other maintainers and ask. \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.github/pull_request_template.md b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.github/pull_request_template.md new file mode 100644 index 0000000000..ce8640a6bf --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.github/pull_request_template.md @@ -0,0 +1,8 @@ +### Summary + +Describe the goal of this PR. Mention any related Issue numbers. + +### Requirements (place an `x` in each `[ ]`) + +* [ ] I've read and understood the [Contributing Guidelines](https://github.com/slackapi/python-slackclient/blob/master/.github/contributing.md) and have done my best effort to follow them. +* [ ] I've read and agree to the [Code of Conduct](https://slackhq.github.io/code-of-conduct). \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.gitignore b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.gitignore new file mode 100644 index 0000000000..7290c13d39 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.gitignore @@ -0,0 +1,26 @@ +# general things to ignore +build/ +dist/ +docs/_sources/ +docs/.doctrees +*.egg-info/ +*.egg +*.py[cod] +__pycache__/ +*.so +*~ + +# virtualenv +env/ +venv/ + +# codecov / coverage +.coverage +cov_* + +# due to using tox and pytest +.tox +.cache +.pytest_cache/ +.python-version +pip \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.travis.yml b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.travis.yml new file mode 100644 index 0000000000..0ce6c9b039 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/.travis.yml @@ -0,0 +1,17 @@ +sudo: false +dist: trusty +language: python +python: + - "2.7" + - "3.4" + - "3.5" + - "3.6" +install: + - travis_retry pip install -r requirements.txt + - travis_retry pip install flake8 + - travis_retry pip install -r test_requirements.txt +script: + - flake8 slackclient + - py.test --cov-report= --cov=slackclient tests +after_success: + - codecov -e $TRAVIS_PYTHON_VERSION diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/LICENSE b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/LICENSE new file mode 100644 index 0000000000..73da6e9751 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015-2016 Slack Technologies, Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/MANIFEST.in b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/MANIFEST.in new file mode 100644 index 0000000000..1aba38f67a --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/MANIFEST.in @@ -0,0 +1 @@ +include LICENSE diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/README.rst b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/README.rst new file mode 100644 index 0000000000..3c7c031f9a --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/README.rst @@ -0,0 +1,355 @@ +python-slackclient +=================== + +A client for Slack, which supports the Slack Web API and Real Time Messaging (RTM) API. + +|build-status| |windows-build-status| |codecov| |doc-status| |pypi-version| |python-version| + +.. |build-status| image:: https://travis-ci.org/slackapi/python-slackclient.svg?branch=master + :target: https://travis-ci.org/slackapi/python-slackclient +.. |windows-build-status| image:: https://ci.appveyor.com/api/projects/status/rif04t60ptslj32x/branch/master?svg=true + :target: https://ci.appveyor.com/project/slackapi/python-slackclient +.. |codecov| image:: https://codecov.io/gh/slackapi/python-slackclient/branch/master/graph/badge.svg + :target: https://codecov.io/gh/slackapi/python-slackclient +.. |doc-status| image:: https://readthedocs.org/projects/python-slackclient/badge/?version=latest + :target: http://python-slackclient.readthedocs.io/en/latest/?badge=latest +.. |pypi-version| image:: https://badge.fury.io/py/slackclient.svg + :target: https://pypi.python.org/pypi/slackclient +.. |python-version| image:: https://img.shields.io/pypi/pyversions/slackclient.svg + :target: https://pypi.python.org/pypi/slackclient + +Overview +-------- + +Whether you're building a custom app for your team, or integrating a third party +service into your Slack workflows, Slack Developer Kit for Python allows you to leverage the flexibility +of Python to get your project up and running as quickly as possible. + +Documentation +*************** + +For comprehensive method information and usage examples, see the `full documentation `_. + +If you're building a project to receive content and events from Slack, check out the `Python Slack Events API Adapter `_ library. + +You may also review our `Development Roadmap `_ in the project wiki. + + +Requirements and Installation +****************************** + +We recommend using `PyPI `_ to install Slack Developer Kit for Python + +.. code-block:: bash + + pip install slackclient + +Of course, if you prefer doing things the hard way, you can always implement Slack Developer Kit for Python +by pulling down the source code directly into your project: + +.. code-block:: bash + + git clone https://github.com/slackapi/python-slackclient.git + pip install -r requirements.txt + +Getting Help +************* + +If you get stuck, we’re here to help. The following are the best ways to get assistance working through your issue: + +- Use our `Github Issue Tracker `_ for reporting bugs or requesting features. +- Visit the `Bot Developer Hangout `_ for getting help using Slack Developer Kit for Python or just generally bond with your fellow Slack developers. + +Basic Usage +------------ +The Slack Web API allows you to build applications that interact with Slack in more complex ways than the integrations +we provide out of the box. + +This package is a modular wrapper designed to make Slack `Web API `_ calls simpler and easier for your +app. Provided below are examples of how to interact with commonly used API endpoints, but this is by no means +a complete list. Review the full list of available methods `here `_. + + +Sending a message +******************** +The primary use of Slack is sending messages. Whether you're sending a message +to a user or to a channel, this method handles both. + +To send a message to a channel, use the channel's ID. For IMs, use the user's ID. + +.. code-block:: python + + import os + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "chat.postMessage", + channel="C0XXXXXX", + text="Hello from Python! :tada:" + ) + +There are some unique options specific to sending IMs, so be sure to read the **channels** +section of the `chat.postMessage `_ +page for a full list of formatting and authorship options. + +Sending an ephemeral message, which is only visible to an assigned user in a specified channel, is nearly the same +as sending a regular message, but with an additional ``user`` parameter. + +.. code-block:: python + + import os + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "chat.postEphemeral", + channel="C0XXXXXX", + text="Hello from Python! :tada:", + user="U0XXXXXXX" + ) + +See `chat.postEphemeral `_ for more info. + + +Replying to messages and creating threads +***************************************** +Threaded messages are just like regular messages, except thread replies are grouped together to provide greater context +to the user. You can reply to a thread or start a new threaded conversation by simply passing the original message's ``ts`` +ID in the ``thread_ts`` attribute when posting a message. If you're replying to a threaded message, you'll pass the `thread_ts` +ID of the message you're replying to. + +A channel or DM conversation is a nearly linear timeline of messages exchanged between people, bots, and apps. +When one of these messages is replied to, it becomes the parent of a thread. By default, threaded replies do not +appear directly in the channel, instead relegated to a kind of forked timeline descending from the parent message. + +.. code-block:: python + + import os + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "chat.postMessage", + channel="C0XXXXXX", + text="Hello from Python! :tada:", + thread_ts="1476746830.000003" + ) + + +By default, ``reply_broadcast`` is set to ``False``. To indicate your reply is germane to all members of a channel, +set the ``reply_broadcast`` boolean parameter to ``True``. + +.. code-block:: python + + import os + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "chat.postMessage", + channel="C0XXXXXX", + text="Hello from Python! :tada:", + thread_ts="1476746830.000003", + reply_broadcast=True + ) + + +**Note:** While threaded messages may contain attachments and message buttons, when your reply is broadcast to the +channel, it'll actually be a reference to your reply, not the reply itself. +So, when appearing in the channel, it won't contain any attachments or message buttons. Also note that updates and +deletion of threaded replies works the same as regular messages. + +See the `Threading messages together `_ +article for more information. + + +Deleting a message +******************** +Sometimes you need to delete things. + +.. code-block:: python + + import os + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "chat.delete", + channel="C0XXXXXX", + ts="1476745373.000002" + ) + +See `chat.delete `_ for more info. + +Adding or removing an emoji reaction +**************************************** +You can quickly respond to any message on Slack with an emoji reaction. Reactions +can be used for any purpose: voting, checking off to-do items, showing excitement — and just for fun. + +This method adds a reaction (emoji) to an item (``file``, ``file comment``, ``channel message``, ``group message``, or ``direct message``). One of file, file_comment, or the combination of channel and timestamp must be specified. + +.. code-block:: python + + import os + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "reactions.add", + channel="C0XXXXXXX", + name="thumbsup", + timestamp="1234567890.123456" + ) + +Removing an emoji reaction is basically the same format, but you'll use ``reactions.remove`` instead of ``reactions.add`` + +.. code-block:: python + + sc.api_call( + "reactions.remove", + channel="C0XXXXXXX", + name="thumbsup", + timestamp="1234567890.123456" + ) + + +See `reactions.add `_ and `reactions.remove `_ for more info. + +Getting a list of channels +****************************** +At some point, you'll want to find out what channels are available to your app. This is how you get that list. + +**Note:** This call requires the ``channels:read`` scope. + +.. code-block:: python + + sc.api_call("channels.list") + +Archived channels are included by default. You can exclude them by passing ``exclude_archived=1`` to your request. + +.. code-block:: python + + sc.api_call( + "channels.list", + exclude_archived=1 + ) + +See `channels.list `_ for more info. + +Getting a channel's info +************************* +Once you have the ID for a specific channel, you can fetch information about that channel. + +.. code-block:: python + + sc.api_call( + "channels.info", + channel="C0XXXXXXX" + ) + +See `channels.info `_ for more info. + +Joining a channel +******************** +Channels are the social hub of most Slack teams. Here's how you hop into one: + +.. code-block:: python + + sc.api_call( + "channels.join", + channel="C0XXXXXXY" + ) + +If you are already in the channel, the response is slightly different. +``already_in_channel`` will be true, and a limited ``channel`` object will be returned. Bot users cannot join a channel on their own, they need to be invited by another user. + +See `channels.join `_ for more info. + +Leaving a channel +******************** +Maybe you've finished up all the business you had in a channel, or maybe you +joined one by accident. This is how you leave a channel. + +.. code-block:: python + + sc.api_call( + "channels.leave", + channel="C0XXXXXXX" + ) + +See `channels.leave `_ for more info. + + +Tokens and Authentication +************************** + +The simplest way to create an instance of the client, as shown in the samples above, is to use a bot (xoxb) access token: + +.. code-block:: python + + # Get the access token from environmental variable + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + +The SlackClient library allows you to use a variety of Slack authentication tokens. + +To take advantage of automatic token refresh, you'll need to instantiate the client a little differently than when using +a bot access token. With a bot token, you have the access (xoxb) token when you create the client, when using refresh tokens, +you won't know the access token when the client is created. + +Upon the first request, the SlackClient will request a new access (xoxa) token on behalf of your application, using your app's +refresh token, client ID, and client secret. + +.. code-block:: python + + # Get the access token from environmental variable + slack_refresh_token = os.environ["SLACK_REFRESH_TOKEN"] + slack_client_id = os.environ["SLACK_CLIENT_ID"] + slack_client_secret = os.environ["SLACK_CLIENT_SECRET"] + + +Since your app's access tokens will be expiring and refreshed, the client requires a callback method to be passed in on creation of the client. +Once Slack returns an access token for your app, the SlackClient will call your provided callback to update the access token in your datastore. + +.. code-block:: python + + # This is where you'll add your data store update logic + def token_update_callback(update_data): + print("Enterprise ID: {}".format(update_data["enterprise_id"])) + print("Workspace ID: {}".format(update_data["team_id"])) + print("Access Token: {}".format(update_data["access_token"])) + print("Access Token expires in (ms): {}".format(update_data["expires_in"])) + + # When creating an instance of the client, pass the client details and token update callback + sc = SlackClient( + refresh_token=slack_refresh_token, + client_id=slack_client_id, + client_secret=slack_client_secret, + token_update_callback=token_update_callback + ) + + +Slack will send your callback function the **app's access token**, **token expiration TTL**, **team ID**, and **enterprise ID** (for enterprise workspaces) + + +See `Tokens & Authentication `_ for API token handling best practices. + + + +Additional Information +******************************************************************************************** +For comprehensive method information and usage examples, see the `full documentation`_. diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/.gitignore b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/.gitignore new file mode 100644 index 0000000000..e35d8850c9 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/.gitignore @@ -0,0 +1 @@ +_build diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/Makefile b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/Makefile new file mode 100644 index 0000000000..ecbc9e80a7 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/Makefile @@ -0,0 +1,225 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = ../docs/ + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " applehelp to make an Apple Help Book" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " epub3 to make an epub3" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " xml to make Docutils-native XML files" + @echo " pseudoxml to make pseudoxml-XML files for display purposes" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + @echo " coverage to run coverage check of the documentation (if enabled)" + @echo " dummy to check syntax errors of document sources" + +.PHONY: clean +clean: + rm -rf $(BUILDDIR)/* + +.PHONY: html +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +.PHONY: dirhtml +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +.PHONY: singlehtml +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +.PHONY: pickle +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +.PHONY: json +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +.PHONY: htmlhelp +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +.PHONY: qthelp +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-slackclient.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-slackclient.qhc" + +.PHONY: applehelp +applehelp: + $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp + @echo + @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." + @echo "N.B. You won't be able to view it unless you put it in" \ + "~/Library/Documentation/Help or install it in your application" \ + "bundle." + +.PHONY: devhelp +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/python-slackclient" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-slackclient" + @echo "# devhelp" + +.PHONY: epub +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +.PHONY: epub3 +epub3: + $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 + @echo + @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." + +.PHONY: latex +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +.PHONY: latexpdf +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +.PHONY: latexpdfja +latexpdfja: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through platex and dvipdfmx..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +.PHONY: text +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +.PHONY: man +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +.PHONY: texinfo +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +.PHONY: info +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +.PHONY: gettext +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +.PHONY: changes +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +.PHONY: linkcheck +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +.PHONY: doctest +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." + +.PHONY: coverage +coverage: + $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage + @echo "Testing of coverage in the sources finished, look at the " \ + "results in $(BUILDDIR)/coverage/python.txt." + +.PHONY: xml +xml: + $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml + @echo + @echo "Build finished. The XML files are in $(BUILDDIR)/xml." + +.PHONY: pseudoxml +pseudoxml: + $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml + @echo + @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." + +.PHONY: dummy +dummy: + $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy + @echo + @echo "Build finished. Dummy builder generates no files." diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/conf.py b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/conf.py new file mode 100644 index 0000000000..bc81579bbe --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/conf.py @@ -0,0 +1,342 @@ +# -*- coding: utf-8 -*- +# +# python-slackclient documentation build configuration file, created by +# sphinx-quickstart on Mon Jun 27 17:36:09 2016. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import sys +sys.path.insert(0, os.path.abspath('../')) + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.coverage', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['../../_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The encoding of source files. +# +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'Slack Developer Kit for Python' +copyright = u'2015–2016 Slack Technologies, Inc. and contributors' +author = u'Slack Technologies, Inc. and contributors' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = u'1.0' +# The full version, including alpha/beta/rc tags. +release = u'1.0.1' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# +# today = '' +# +# Else, today_fmt is used as the format for a strftime call. +# +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'emacs' + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = "slack" +html_theme_path = ["../../_themes", ] + +highlight_language = "python" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. +# " v documentation" by default. +# +# html_title = u'python-slackclient v1.0.1' + +# A shorter title for the navigation bar. Default is the same as html_title. +# +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# +# html_logo = None + +# The name of an image file (relative to this directory) to use as a favicon of +# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['static'] + +html_context = { + 'css_files': ['static/pygments.css'], +} + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# +# html_extra_path = [] + +# If not None, a 'Last updated on:' timestamp is inserted at every page +# bottom, using the given strftime format. +# The empty string is equivalent to '%b %d, %Y'. +# +# html_last_updated_fmt = None + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# +# html_additional_pages = {} + +# If false, no module index is generated. +# +# html_domain_indices = True + +# If false, no index is generated. +# +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' +# +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# 'ja' uses this config value. +# 'zh' user can custom change `jieba` dictionary path. +# +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = 'python-slackclientdoc' + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'python-slackclient.tex', u'python-slackclient Documentation', + u'Ryan Huber, Jeff Ammons', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# +# latex_use_parts = False + +# If true, show page references after internal links. +# +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# +# latex_appendices = [] + +# If false, no module index is generated. +# +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'python-slackclient', u'python-slackclient Documentation', + [author], 1) +] + +# If true, show URL addresses after external links. +# +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'python-slackclient', u'python-slackclient Documentation', + author, 'python-slackclient', 'A basic client for Slack.com, which can optionally connect to the Slack Real Time Messaging (RTM) API.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +# +# texinfo_appendices = [] + +# If false, no module index is generated. +# +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# +# texinfo_no_detailmenu = False diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/layout.html b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/layout.html new file mode 100644 index 0000000000..e0e77d1eb5 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/layout.html @@ -0,0 +1,104 @@ + + + + + + {{ metatags }} + + {%- block htmltitle %} + {{ title|striptags|e + " — "|safe + project|e }} + {%- endblock %} + + {%- macro css() %} + + + + + + {%- endmacro %} + + + + + {{ css() }} + {%- block linktags %} + + + {%- endblock %} + + + + + + + + + + + {%- block header %} +
+ + + + + + + {{ project }} + + +
+ {% endblock %} + +
+
+ + + + + +
+
{{ title }}
+
+ {%- block body %} + {{ body }} + {% endblock %} +
+
+
+ + +
+
+ +
+

© 2019 Slack Technologies, Inc. and contributors

+
+ + + + + + + \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/localtoc.html b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/localtoc.html new file mode 100644 index 0000000000..e0ffc3f4f7 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/localtoc.html @@ -0,0 +1,4 @@ +
Table of Contents?
+
    + {{ toc }} +
\ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/relations.html b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/relations.html new file mode 100644 index 0000000000..e3faec04a7 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/relations.html @@ -0,0 +1,19 @@ +{# + basic/relations.html + ~~~~~~~~~~~~~~~~~~~~ + + Sphinx sidebar template: relation links. + + :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. + :license: BSD, see LICENSE for details. +#} +{%- if prev %} +

{{ _('Previous topic') }}

+

{{ prev.title }}

+{%- endif %} +{%- if next %} +

{{ _('Next topic') }}

+

{{ next.title }}

+{%- endif %} diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/sidebar.html b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/sidebar.html new file mode 100644 index 0000000000..d92ca908f7 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/sidebar.html @@ -0,0 +1,15 @@ +{{ toctree(maxdepth=-1, collapse=False,includehidden=True) }} + + diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/static/default.css_t b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/static/default.css_t new file mode 100644 index 0000000000..93fc2c66b5 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/static/default.css_t @@ -0,0 +1,74 @@ +a.headerlink { + display: none !important; +} + +.section-title { + font-size: 2rem; + line-height: 2.5rem; + letter-spacing: -1px; + font-weight: 700; + margin: 0 0 1rem; +} + +nav#api_nav .toctree-l1 { + margin-bottom: 1.5rem; +} + +nav#api_nav #api_sections ul { + list-style: none; + margin: 0; + padding: 0; +} + +nav#api_nav #api_sections ul li.toctree-l1>a { + color: #1264a3; + letter-spacing: 0; + font-size: .8rem; + font-weight: 800; + text-transform: uppercase; + border: none; + padding: 0; +} + +nav#api_nav #api_sections ul li.toctree-l2 { + margin: 0; + padding: 0; +} + +nav#api_nav #api_sections ul li.toctree-l2 a { + color: #1d1c1d; + text-transform: none; + font-weight: inherit; + padding: 0; + display: block; + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; + font-size: 15px!important; + line-height:15px; + padding: 4px 8px; + border: 1px solid transparent; + border-radius: 4px; +} + +nav#api_nav #api_sections ul li.toctree-l2 a:hover { + cursor: pointer; + text-decoration: none; + background-color:#e8f5fa; + border-color:#dcf0fb; +} + +nav#api_nav #footer #footer_nav { + font-size: .9375rem; +} + +nav#api_nav #footer #footer_nav a { + border: none; + padding: 0; + color: #616061; +} + +nav#api_nav #footer #footer_nav a:hover { + text-decoration: none; + color: #1c1c1c; +} diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/static/docs.css_t b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/static/docs.css_t new file mode 100644 index 0000000000..7f360ac666 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/static/docs.css_t @@ -0,0 +1,34 @@ +/* Updates body font */ +body { + font-family: Slack-Lato,appleLogo,sans-serif; +} + +/* Replaces old sidebar styled links */ +.sidebar_menu h5 { + font-size: 0.8rem; + font-weight: 800; + margin-bottom: 3px; +} + +/* Aligns footer navigation to the left of the sidebar */ +.footer_nav { + margin: 0 !important; +} + +/* Styles the signature all nice and pretty <3 */ +#footer_signature { + color:#e01e5a; + font-size:.9rem; + margin-top: 10px; +} + +/* Fixes link hover state */ +a:hover { + text-decoration: underline; +} + +/* Makes footer consistent */ +footer { + background-color: transparent; + border: 0; +} \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/static/pygments.css_t b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/static/pygments.css_t new file mode 100644 index 0000000000..a94b170ffb --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/static/pygments.css_t @@ -0,0 +1,60 @@ +.highlight .hll { background-color: #ffffcc } +.highlight { background: #ffffff; } +.highlight .c { color: #999988; font-style: italic } /* Comment */ +.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ +.highlight .k { font-weight: bold } /* Keyword */ +.highlight .o { font-weight: bold } /* Operator */ +.highlight .cm { color: #999988; font-style: italic } /* Comment.Multiline */ +.highlight .cp { color: #999999; font-weight: bold } /* Comment.Preproc */ +.highlight .c1 { color: #999988; font-style: italic } /* Comment.Single */ +.highlight .cs { color: #999999; font-weight: bold; font-style: italic } /* Comment.Special */ +.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ +.highlight .ge { font-style: italic } /* Generic.Emph */ +.highlight .gr { color: #aa0000 } /* Generic.Error */ +.highlight .gh { color: #999999 } /* Generic.Heading */ +.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ +.highlight .go { color: #888888 } /* Generic.Output */ +.highlight .gp { color: #555555 } /* Generic.Prompt */ +.highlight .gs { font-weight: bold } /* Generic.Strong */ +.highlight .gu { color: #aaaaaa } /* Generic.Subheading */ +.highlight .gt { color: #aa0000 } /* Generic.Traceback */ +.highlight .kc { font-weight: bold } /* Keyword.Constant */ +.highlight .kd { font-weight: bold } /* Keyword.Declaration */ +.highlight .kn { font-weight: bold } /* Keyword.Namespace */ +.highlight .kp { font-weight: bold } /* Keyword.Pseudo */ +.highlight .kr { font-weight: bold } /* Keyword.Reserved */ +.highlight .kt { color: #445588; font-weight: bold } /* Keyword.Type */ +.highlight .m { color: #009999 } /* Literal.Number */ +.highlight .s { color: #bb8844 } /* Literal.String */ +.highlight .na { color: #008080 } /* Name.Attribute */ +.highlight .nb { color: #999999 } /* Name.Builtin */ +.highlight .nc { color: #445588; font-weight: bold } /* Name.Class */ +.highlight .no { color: #008080 } /* Name.Constant */ +.highlight .ni { color: #800080 } /* Name.Entity */ +.highlight .ne { color: #990000; font-weight: bold } /* Name.Exception */ +.highlight .nf { color: #990000; font-weight: bold } /* Name.Function */ +.highlight .nn { color: #555555 } /* Name.Namespace */ +.highlight .nt { color: #000080 } /* Name.Tag */ +.highlight .nv { color: #008080 } /* Name.Variable */ +.highlight .ow { font-weight: bold } /* Operator.Word */ +.highlight .w { color: #bbbbbb } /* Text.Whitespace */ +.highlight .mf { color: #009999 } /* Literal.Number.Float */ +.highlight .mh { color: #009999 } /* Literal.Number.Hex */ +.highlight .mi { color: #009999 } /* Literal.Number.Integer */ +.highlight .mo { color: #009999 } /* Literal.Number.Oct */ +.highlight .sb { color: #bb8844 } /* Literal.String.Backtick */ +.highlight .sc { color: #bb8844 } /* Literal.String.Char */ +.highlight .sd { color: #bb8844 } /* Literal.String.Doc */ +.highlight .s2 { color: #bb8844 } /* Literal.String.Double */ +.highlight .se { color: #bb8844 } /* Literal.String.Escape */ +.highlight .sh { color: #bb8844 } /* Literal.String.Heredoc */ +.highlight .si { color: #bb8844 } /* Literal.String.Interpol */ +.highlight .sx { color: #bb8844 } /* Literal.String.Other */ +.highlight .sr { color: #808000 } /* Literal.String.Regex */ +.highlight .s1 { color: #bb8844 } /* Literal.String.Single */ +.highlight .ss { color: #bb8844 } /* Literal.String.Symbol */ +.highlight .bp { color: #999999 } /* Name.Builtin.Pseudo */ +.highlight .vc { color: #008080 } /* Name.Variable.Class */ +.highlight .vg { color: #008080 } /* Name.Variable.Global */ +.highlight .vi { color: #008080 } /* Name.Variable.Instance */ +.highlight .il { color: #009999 } /* Literal.Number.Integer.Long */ diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/theme.conf b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/theme.conf new file mode 100644 index 0000000000..b13de3cbb4 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/_themes/slack/theme.conf @@ -0,0 +1,6 @@ +[theme] +inherit = default +stylesheet = default.css +show_sphinx = False + +[options] diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/about.rst b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/about.rst new file mode 100644 index 0000000000..17fad157f5 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/about.rst @@ -0,0 +1,18 @@ +============================================== +About +============================================== + +|product_name| +************** + + +Access the Slack Platform from your Python app. |product_name| lets you build on the Slack Web APIs pythonically. + +|product_name| is proudly maintained with 💖 by the Slack Developer Tools team + +- `License`_ +- `Code of Conduct`_ +- `Contributing`_ +- `Contributor License Agreement`_ + +.. include:: metadata.rst \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/auth.rst b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/auth.rst new file mode 100644 index 0000000000..9a587c3f21 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/auth.rst @@ -0,0 +1,150 @@ +============================================== +Tokens & Authentication +============================================== +.. _handling-tokens: + +Handling tokens and other sensitive data +---------------------------------------- +⚠️ **Slack tokens are the keys to your—or your customers’—data.Keep them secret. Keep them safe.** + +One way to do that is to never explicitly hardcode them. + +Try to avoid this when possible: + +.. code-block:: python + + token = 'xoxb-abc-1232' + +⚠️ **Never share test tokens with other users or applications. Do not publish test tokens in public code repositories.** + +We recommend you pass tokens in as environment variables, or persist them in a database that is accessed at runtime. You can add a token to the environment by starting your app as: + +.. code-block:: python + + SLACK_BOT_TOKEN="xoxb-abc-1232" python myapp.py + +Then retrieve the key with: + +.. code-block:: python + + import os + SLACK_BOT_TOKEN = os.environ["SLACK_BOT_TOKEN"] + +You can use the same technique for other kinds of sensitive data that ne’er-do-wells could use in nefarious ways, including + +- Incoming webhook URLs +- Slash command verification tokens +- App client ids and client secrets + +For additional information, please see our `Safely Storing Credentials `_ page. + +Single-Workspace Apps +----------------------- +If you're building an application for a single Slack workspace, there's no need to build out the entire OAuth flow. + +Once you've setup your features, click on the **Install App to Team** button found on the **Install App** page. +If you add new permission scopes or Slack app features after an app has been installed, you must reinstall the app to +your workspace for changes to take effect. + +For additional information, see the `Installing Apps `_ of our `Building Slack apps `_ page. + +The OAuth flow +------------------------- +Authentication for Slack's APIs is done using OAuth, so you'll want to read up on `OAuth `_. + +In order to implement OAuth in your app, you will need to include a web server. In this example, we'll use `Flask `_. + +As mentioned above, we're setting the app tokens and other configs in environment variables and pulling them into global variables. + +Depending on what actions your app will need to perform, you'll need different OAuth permission scopes. Review the available scopes `here `_. + +.. code-block:: python + + import os + from flask import Flask, request + from slackclient import SlackClient + + client_id = os.environ["SLACK_CLIENT_ID"] + client_secret = os.environ["SLACK_CLIENT_SECRET"] + oauth_scope = os.environ["SLACK_BOT_SCOPE"] + + app = Flask(__name__) + +**The OAuth initiation link:** + +To begin the OAuth flow, you'll need to provide the user with a link to Slack's OAuth page. +This directs the user to Slack's OAuth acceptance page, where the user will review and accept +or refuse the permissions your app is requesting as defined by the requested scope(s). + +For the best user experience, use the `Add to Slack button `_ to direct users to approve your application for access or `Sign in with Slack `_ to log users in. + +.. code-block:: python + + @app.route("/begin_auth", methods=["GET"]) + def pre_install(): + return ''' + + Add to Slack + + '''.format(oauth_scope, client_id) + +**The OAuth completion page** + +Once the user has agreed to the permissions you've requested on Slack's OAuth +page, Slack will redirect the user to your auth completion page. Included in this +redirect is a ``code`` query string param which you’ll use to request access +tokens from the ``oauth.access`` endpoint. + +Generally, Web API requests require a valid OAuth token, but there are a few endpoints +which do not require a token. ``oauth.access`` is one example of this. Since this +is the endpoint you'll use to retrieve the tokens for later API requests, +an empty string ``""`` is acceptable for this request. + +.. code-block:: python + + @app.route("/finish_auth", methods=["GET", "POST"]) + def post_install(): + + # Retrieve the auth code from the request params + auth_code = request.args['code'] + + # An empty string is a valid token for this request + sc = SlackClient("") + + # Request the auth tokens from Slack + auth_response = sc.api_call( + "oauth.access", + client_id=client_id, + client_secret=client_secret, + code=auth_code + ) + +A successful request to ``oauth.access`` will yield two tokens: A ``user`` +token and a ``bot`` token. The ``user`` token ``auth_response['access_token']`` +is used to make requests on behalf of the authorizing user and the ``bot`` +token ``auth_response['bot']['bot_access_token']`` is for making requests +on behalf of your app's bot user. + +If your Slack app includes a bot user, upon approval the JSON response will contain +an additional node containing an access token to be specifically used for your bot +user, within the context of the approving team. + +When you use Web API methods on behalf of your bot user, you should use this bot +user access token instead of the top-level access token granted to your application. + +.. code-block:: python + + # Save the bot token to an environmental variable or to your data store + # for later use + os.environ["SLACK_USER_TOKEN"] = auth_response['access_token'] + os.environ["SLACK_BOT_TOKEN"] = auth_response['bot']['bot_access_token'] + + # Don't forget to let the user know that auth has succeeded! + return "Auth complete!" + +Once your user has completed the OAuth flow, you'll be able to use the provided +tokens to make a variety of Web API calls on behalf of the user and your app's bot user. + +See the :ref:`Web API usage ` section of this documentation for usage examples. + +.. include:: metadata.rst diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/basic_usage.rst b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/basic_usage.rst new file mode 100644 index 0000000000..e61365c8a4 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/basic_usage.rst @@ -0,0 +1,435 @@ +.. _web-api-examples: + +============================================== +Basic Usage +============================================== +The Slack Web API allows you to build applications that interact with Slack in more complex ways than the integrations +we provide out of the box. + +This package is a modular wrapper designed to make Slack `Web API`_ calls simpler and easier for your +app. Provided below are examples of how to interact with commonly used API endpoints, but this is by no means +a complete list. Review the full list of available methods `here `_. + +See :ref:`Tokens & Authentication ` for API token handling best practices. + +-------- + +Sending a message +----------------------- +The primary use of Slack is sending messages. Whether you're sending a message +to a user or to a channel, this method handles both. + +To send a message to a channel, use the channel's ID. For IMs, use the user's ID. + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "chat.postMessage", + channel="C0XXXXXX", + text="Hello from Python! :tada:" + ) + +There are some unique options specific to sending IMs, so be sure to read the **channels** +section of the `chat.postMessage `_ +page for a full list of formatting and authorship options. + +Sending an ephemeral message, which is only visible to an assigned user in a specified channel, is nearly the same +as sending a regular message, but with an additional ``user`` parameter. + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "chat.postEphemeral", + channel="C0XXXXXX", + text="Hello from Python! :tada:", + user="U0XXXXXXX" + ) + +See `chat.postEphemeral `_ for more info. + +-------- + +Customizing a message's layout +----------------------- +The chat.postMessage method takes an optional blocks argument that allows you to customize the layout of a message. +Blocks for Web API methods are all specified in a single object literal, so just add additional keys for any optional argument. + +To send a message to a channel, use the channel's ID. For IMs, use the user's ID. + +.. code-block:: python + + sc.api_call( + "chat.postMessage", + channel="C0XXXXXX", + blocks=[ + { + "type": "section", + "text": { + "type": "mrkdwn", + "text": "Danny Torrence left the following review for your property:" + } + }, + { + "type": "section", + "text": { + "type": "mrkdwn", + "text": " \n :star: \n Doors had too many axe holes, guest in room " + + "237 was far too rowdy, whole place felt stuck in the 1920s." + }, + "accessory": { + "type": "image", + "image_url": "https://images.pexels.com/photos/750319/pexels-photo-750319.jpeg", + "alt_text": "Haunted hotel image" + } + }, + { + "type": "section", + "fields": [ + { + "type": "mrkdwn", + "text": "*Average Rating*\n1.0" + } + ] + } + ] + ) + +**Note:** You can use the `Block Kit Builder `for a playground where you can prototype your message's look and feel. + +-------- + +Replying to messages and creating threads +------------------------------------------ +Threaded messages are just like regular messages, except thread replies are grouped together to provide greater context +to the user. You can reply to a thread or start a new threaded conversation by simply passing the original message's ``ts`` +ID in the ``thread_ts`` attribute when posting a message. If you're replying to a threaded message, you'll pass the `thread_ts` +ID of the message you're replying to. + +A channel or DM conversation is a nearly linear timeline of messages exchanged between people, bots, and apps. +When one of these messages is replied to, it becomes the parent of a thread. By default, threaded replies do not +appear directly in the channel, instead relegated to a kind of forked timeline descending from the parent message. + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "chat.postMessage", + channel="C0XXXXXX", + text="Hello from Python! :tada:", + thread_ts="1476746830.000003" + ) + + +By default, ``reply_broadcast`` is set to ``False``. To indicate your reply is germane to all members of a channel, +set the ``reply_broadcast`` boolean parameter to ``True``. + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "chat.postMessage", + channel="C0XXXXXX", + text="Hello from Python! :tada:", + thread_ts="1476746830.000003", + reply_broadcast=True + ) + + +**Note:** While threaded messages may contain attachments and message buttons, when your reply is broadcast to the +channel, it'll actually be a reference to your reply, not the reply itself. +So, when appearing in the channel, it won't contain any attachments or message buttons. Also note that updates and +deletion of threaded replies works the same as regular messages. + +See the `Threading messages together `_ +article for more information. + + +-------- + +Updating the content of a message +---------------------------------- +Let's say you have a bot which posts the status of a request. When that request +is updated, you'll want to update the message to reflect it's state. Or your user +might want to fix a typo or change some wording. This is how you'll make those changes. + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "chat.update", + ts="1476746830.000003", + channel="C0XXXXXX", + text="Hello from Python! :tada:" + ) + +See `chat.update `_ for formatting options +and some special considerations when calling this with a bot user. + +-------- + +Deleting a message +------------------- +Sometimes you need to delete things. + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "chat.delete", + channel="C0XXXXXX", + ts="1476745373.000002" + ) + +See `chat.delete `_ for more info. + +-------- + +Adding or removing an emoji reaction +--------------------------------------- +You can quickly respond to any message on Slack with an emoji reaction. Reactions +can be used for any purpose: voting, checking off to-do items, showing excitement — and just for fun. + +This method adds a reaction (emoji) to an item (``file``, ``file comment``, ``channel message``, ``group message``, or ``direct message``). One of file, file_comment, or the combination of channel and timestamp must be specified. + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "reactions.add", + channel="C0XXXXXXX", + name="thumbsup", + timestamp="1234567890.123456" + ) + +Removing an emoji reaction is basically the same format, but you'll use ``reactions.remove`` instead of ``reactions.add`` + +.. code-block:: python + + sc.api_call( + "reactions.remove", + channel="C0XXXXXXX", + name="thumbsup", + timestamp="1234567890.123456" + ) + + +See `reactions.add `_ and `reactions.remove `_ for more info. + +-------- + +Getting a list of channels +--------------------------- +At some point, you'll want to find out what channels are available to your app. This is how you get that list. + +**Note:** This call requires the ``channels:read`` scope. + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call("channels.list") + +Archived channels are included by default. You can exclude them by passing ``exclude_archived=1`` to your request. + + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "channels.list", + exclude_archived=1 + ) + +See `channels.list `_ for more info. + +-------- + +Getting a channel's info +------------------------- +Once you have the ID for a specific channel, you can fetch information about that channel. + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "channels.info", + channel="C0XXXXXXX" + ) + +See `channels.info `_ for more info. + +-------- + +Joining a channel +------------------ +Channels are the social hub of most Slack teams. Here's how you hop into one: + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "channels.join", + channel="C0XXXXXXY" + ) + +If you are already in the channel, the response is slightly different. +``already_in_channel`` will be true, and a limited ``channel`` object will be returned. Bot users cannot join a channel on their own, they need to be invited by another user. + +See `channels.join `_ for more info. + +-------- + +Leaving a channel +------------------ +Maybe you've finished up all the business you had in a channel, or maybe you +joined one by accident. This is how you leave a channel. + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "channels.leave", + channel="C0XXXXXXX" + ) + +See `channels.leave `_ for more info. + +-------- + +Get a list of team members +------------------------------ + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call("users.list") + +See `users.list `_ for more info. + + +-------- + +Uploading files +------------------------------ + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + with open('thinking_very_much.png') as file_content: + sc.api_call( + "files.upload", + channels="C3UKJTQAC", + file=file_content, + title="Test upload" + ) + +See `files.upload `_ for more info. + + +-------- + +Web API Rate Limits +-------------------- +Slack allows applications to send no more than one message per second. We allow bursts over that +limit for short periods. However, if your app continues to exceed the limit over a longer period +of time it will be rate limited. + +Here's a very basic example of how one might deal with rate limited requests. + +If you go over these limits, Slack will start returning a HTTP 429 Too Many Requests error, +a JSON object containing the number of calls you have been making, and a Retry-After header +containing the number of seconds until you can retry. + + +.. code-block:: python + + from slackclient import SlackClient + import time + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + # Simple wrapper for sending a Slack message + def send_slack_message(channel, message): + return sc.api_call( + "chat.postMessage", + channel=channel, + text=message + ) + + # Make the API call and save results to `response` + response = send_slack_message("C0XXXXXX", "Hello, from Python!") + + # Check to see if the message sent successfully. + # If the message succeeded, `response["ok"]`` will be `True` + if response["ok"]: + print("Message posted successfully: " + response["message"]["ts"]) + # If the message failed, check for rate limit headers in the response + elif response["ok"] is False and response["headers"]["Retry-After"]: + # The `Retry-After` header will tell you how long to wait before retrying + delay = int(response["headers"]["Retry-After"]) + print("Rate limited. Retrying in " + str(delay) + " seconds") + time.sleep(delay) + send_slack_message(message, channel) + +See the documentation on `Rate Limiting `_ for more info. + +.. include:: metadata.rst + diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/changelog.rst b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/changelog.rst new file mode 100644 index 0000000000..74300a43a0 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/changelog.rst @@ -0,0 +1,156 @@ +============================================== +Changelog +============================================== + +v1.3.2 (2019-05-30) +------------------- +- Fixing an issue where reconnects used rtm.start istead of rtm.connect. #422 + + +v1.3.1 (2019-02-28) +------------------- + +- Lock websocket-client version to < 0.55.0: temp fix for #385 + + +v1.3.0 (2018-09-11) +------------------- + +## New Features +- Adds support for short lived tokens and automatic token refresh #347 (Thanks @roach!) + +## Other +- update RTM rate limiting comment and error message #308 (Thanks @benoitlavigne!) +- Use logging instead of traceback #309 (Thanks @harlowja!) +- Remove Python 3.3 from test environments #346 (Thanks @roach!) +- Enforced linting when using VSCode. #347 (Thanks @roach!) + + +v1.2.1 (2018-03-26) +------------------- + +- Added rate limit handling for rtm connections (thanks @jayalane!) + + +v1.2.0 (2018-03-20) +------------------- + +- You can now tell the RTM client to automatically reconnect by passing `auto_reconnect=True` + +v1.1.3 (2018-03-01) +------------------- + +- Fixed another API param encoding bug. It encodes things properly now. + +v1.1.2 (2018-01-31) +------------------- + +- Fixed an encoding issue which was encoding some Web API params incorrectly (sorry) + +v1.1.1 (2018-01-30) +------------------- + + - Adds HTTP response headers to `api_call` responses to expose things like rate limit info + - Moves `token` into auth header rather than request params + +v1.1.0 (2017-11-21) +------------------- + + - Aadds new SlackClientError and ResponseParseError types to describe errors - thanks @aoberoi! + - Fix Build Error (#245) - thanks @stasfilin! + - include email as user property (#173) - thanks @acaire! + - Add http reply into slack login and slack connection error (#216) - thanks @harlowja! + - Removed unused exception class (#233) + - Fix rtm_send_message bug (#225) - thanks @kt5356! + - Allow use of custom parameters on rtm_connect() (#210) - thanks @kamushadenes! + - Fix link to rtm.connect docs (#223) - @sampart! + +v1.0.9 (2017-08-31) +------------------- + + - Fixed rtm_send_message ID bug introduced in 1.0.8 + +v1.0.8 (2017-08-31) +------------------- + + - Added rtm.connect support + +v1.0.7 (2017-08-02) +------------------- + + - Fixes an issue where connecting over RTM to large teams may result in “Websocket URL expired” errors + - A load of packaging improvements + +v1.0.6 (2017-06-12) +------------------- + + - Added proxy support (thanks @timfeirg!) + - Tidied up docs (thanks @schlueter!) + - Added tox settings for Python 3 testing (thanks @cclauss!) + +v1.0.5 (2017-01-23) +------------------- + + - Allow RTM Channel.send_message to reply to a thread + - Index users by ID instead of Name (non-breaking change) + - Added timeout to api calls. + - Fixed a typo about token access in auth.rst, thanks @kelvintaywl! + - Added Message Threads to the docs + +v1.0.4 (2016-12-15) +------------------- + + - fixed the ability to search for a user by ID + +v1.0.3 (2016-12-13) +------------------- + + - fixed an issue causing RTM connections to fail for large teams + +v1.0.2 (2016-09-22) +------------------- + + - removed unused ping counter + - fixed contributor guidelines links + - updated documentation + - Fix bug preventing API calls requiring a file ID + - Removes files from api_calls before JSON encoding, so the request is properly formatted + +v1.0.1 (2016-03-25) +------------------- + + - fix for __eq__ comparison in channels using '#' in channel name + - added copyright info to the LICENSE file + +v1.0.0 (2016-02-28) +------------------- + + - the ``api_call`` function now returns a decoded JSON object, rather than a JSON encoded string + - some ``api_call`` calls now call actions on the parent server object: + - ``im.open`` + - ``mpim.open``, ``groups.create``, ``groups.createChild`` + - ``channels.create``, `channels.join`` + +v0.18.0 (2016-02-21) +-------------------- + + - Moves to use semver for versioning + - Adds support for private groups and MPDMs + - Switches to use requests instead of urllib + - Gets Travis CI integration working + - Fixes some formatting issues so the code will work for python 2.6 + - Cleans up some unused imports, some PEP-8 fixes and a couple bad default args fixes + +v0.17.0 (2016-02-15) +-------------------- + + - Fixes the server so that it doesn't add duplicate users or channels to its internal lists, https://github.com/slackapi/python-slackclient/commit/0cb4bcd6e887b428e27e8059b6278b86ee661aaa + - README updates: + - Updates the URLs pointing to Slack docs for configuring authentication, https://github.com/slackapi/python-slackclient/commit/7d01515cebc80918a29100b0e4793790eb83e7b9 + - s/channnels/channels, https://github.com/slackapi/python-slackclient/commit/d45285d2f1025899dcd65e259624ee73771f94bb + - Adds users to the local cache when they join the team, https://github.com/slackapi/python-slackclient/commit/f7bb8889580cc34471ba1ddc05afc34d1a5efa23 + - Fixes urllib py 2/3 compatibility, https://github.com/slackapi/python-slackclient/commit/1046cc2375a85a22e94573e2aad954ba7287c886 + + + +.. include:: metadata.rst diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/conf.py b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/conf.py new file mode 100644 index 0000000000..37a4011949 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/conf.py @@ -0,0 +1,338 @@ +# -*- coding: utf-8 -*- +# +# python-slackclient documentation build configuration file, created by +# sphinx-quickstart on Mon Jun 27 17:36:09 2016. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import sys +sys.path.insert(0, os.path.abspath('../')) + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.coverage', +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The encoding of source files. +# +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'python-slackclient' +copyright = u'2016, Ryan Huber, Jeff Ammons' +author = u'Ryan Huber, Jeff Ammons' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = u'1.0' +# The full version, including alpha/beta/rc tags. +release = u'1.0.1' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# +# today = '' +# +# Else, today_fmt is used as the format for a strftime call. +# +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +import sphinx_rtd_theme # noqa +html_theme = "sphinx_rtd_theme" + +html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. +# " v documentation" by default. +# +# html_title = u'python-slackclient v1.0.1' + +# A shorter title for the navigation bar. Default is the same as html_title. +# +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# +# html_logo = None + +# The name of an image file (relative to this directory) to use as a favicon of +# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +# html_static_path = ['_static'] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# +# html_extra_path = [] + +# If not None, a 'Last updated on:' timestamp is inserted at every page +# bottom, using the given strftime format. +# The empty string is equivalent to '%b %d, %Y'. +# +# html_last_updated_fmt = None + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# +# html_additional_pages = {} + +# If false, no module index is generated. +# +# html_domain_indices = True + +# If false, no index is generated. +# +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' +# +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# 'ja' uses this config value. +# 'zh' user can custom change `jieba` dictionary path. +# +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = 'python-slackclientdoc' + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'python-slackclient.tex', u'python-slackclient Documentation', + u'Ryan Huber, Jeff Ammons', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# +# latex_use_parts = False + +# If true, show page references after internal links. +# +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# +# latex_appendices = [] + +# If false, no module index is generated. +# +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'python-slackclient', u'python-slackclient Documentation', + [author], 1) +] + +# If true, show URL addresses after external links. +# +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'python-slackclient', u'python-slackclient Documentation', + author, 'python-slackclient', 'A basic client for Slack.com, which can optionally connect to the Slack Real Time Messaging (RTM) API.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +# +# texinfo_appendices = [] + +# If false, no module index is generated. +# +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# +# texinfo_no_detailmenu = False diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/conversations.rst b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/conversations.rst new file mode 100644 index 0000000000..77b0a25bb1 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/conversations.rst @@ -0,0 +1,166 @@ +.. _conversations_api: + +============================================== +Conversations API +============================================== +The Slack Conversations API provides your app with a unified interface to work with all the +channel-like things encountered in Slack; public channels, private channels, direct messages, group +direct messages, and our newest channel type, Shared Channels. + + +See `Conversations API `_ docs for more info. + +-------- + +Creating a direct message or multi-person direct message +--------------------------------------------------------- +This Conversations API method opens a multi-person direct message or just a 1:1 direct message. + +*Use conversations.create for public or private channels.* + +Provide 1 to 8 user IDs in the ``user`` parameter to open or resume a conversation. Providing only +1 ID will create a direct message. Providing more will create an ``mpim``. + +If there are no conversations already in progress including that exact set of members, a new +multi-person direct message conversation begins. + +Subsequent calls to ``conversations.open`` with the same set of users will return the already +existing conversation. + + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "conversations.open", + users=["W1234567890","U2345678901","U3456789012"] + ) + +See `conversations.open `_ additional info. + +-------- + +Creating a public or private channel +------------------------------------- +Initiates a public or private channel-based conversation + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "conversations.create", + name="myprivatechannel", + is_private=True + ) + +See `conversations.create `_ additional info. + +-------- + +Getting information about a conversation +----------------------------------------- +This Conversations API method returns information about a workspace conversation. + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "conversations.info", + channel="C0XXXXXX", + ) + +See `conversations.info `_ for more info. + + +-------- + +Getting a list of conversations +-------------------------------- +This Conversations API method returns a list of all channel-like conversations in a workspace. +The "channels" returned depend on what the calling token has access to and the directives placed +in the ``types`` parameter. + + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call("conversations.list") + +Only public conversations are included by default. You may include additional conversations types +by passing ``types`` (as a string) into your list request. Additional conversation types include +``public_channel`` and ``private_channel``. + + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + # Note that `types` is a string + sc.api_call( + "conversations.list", + types="public_channel, private_channel" + ) + +See `conversations.list `_ for more info. + + +-------- + +Leaving a conversation +----------------------- +Maybe you've finished up all the business you had in a conversation, or maybe you +joined one by accident. This is how you leave a conversation. + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call( + "conversations.leave", + channel="C0XXXXXXX" + ) + +See `conversations.leave `_ for more info. + +-------- + +Get conversation members +------------------------------ +Get a list fo the members of a conversation + +.. code-block:: python + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.api_call("conversations.members", + channel="C0XXXXXXX" + ) + +See `users.list `_ for more info. + +.. include:: metadata.rst diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/faq.rst b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/faq.rst new file mode 100644 index 0000000000..79621351c7 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/faq.rst @@ -0,0 +1,63 @@ +============================================== +Frequently Asked Questions +============================================== + +What even is |product_name| and why should I care? +************************************************** + +|product_name| is a wrapper around commonly accessed parts of the Slack Platform. It provides basic mechanisms for +using the Slack Web API from within your Python app. + +On the other hand, |product_name| does not provide access to the Events bot-building API, but +[this adapter](https://github.com/slackapi/python-slack-events-api) does. + +OMG I found a bug! +****************** + +Well, poop. Take a deep breath, and then let us know on the `Issue Tracker`_. If you're feeling particularly ambitious, +why not submit a `pull request`_ with a bug fix? + +Hey, there's a feature missing! +******************************* + +There's always something more that could be added! You can let us know in the `Issue Tracker`_ to start a discussion +around the proposed feature, that's a good start. If you're feeling particularly ambitious, why not write the feature +yourself, and submit a `pull request`_! We love feedback and we love help and we don't bite. Much. + +I'd like to contribute...but how? +********************************* + +What an excellent question. First of all, please have a look at our general `contributing guidelines`_. We'll wait for +you here. + +All done? Great! While we're super excited to incorporate your new feature into |product_name|, there are a +couple of things we want to make sure you've given thought to. + +- Please write unit tests for your new code. But don't **just** aim to increase the test coverage, rather, we expect you + to have written **thoughtful** tests that ensure your new feature will continue to work as expected, and to help future + contributors to ensure they don't break it! + +- Please document your new feature. Think about **concrete use cases** for your feature, and add a section to the + appropriate document, including a **complete** sample program that demonstrates your feature. Don't forget to update + the changelog in ``changelog.rst``! + +Including these two items with your pull request will totally make our day—and, more importantly, your future users' days! + +On that note... + +How do I compile the documentation? +*********************************** + +This project's documentation is generated with `Sphinx `_. If you are editing one of the many +reStructuredText files in the ``docs-src`` folder, you'll need to rebuild the documentation. It is recommended to run +the following steps inside a ``virtualenv`` environment. + +.. code-block:: bash + + tox -e docs + + +Do be sure to add the ``docs`` folder and its contents to your pull request! + + +.. include:: metadata.rst diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/index.rst b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/index.rst new file mode 100644 index 0000000000..30c9969730 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/index.rst @@ -0,0 +1,46 @@ +.. toctree:: + :hidden: + + self + auth + basic_usage + conversations + real_time_messaging + faq + changelog + about + +============================================== +|product_name| +============================================== + +Whether you're building a custom app for your team, or integrating a third party +service into your Slack workflows, |product_name| allows you to leverage the flexibility +of Python to get your project up and running as quickly as possible. + +Requirements and Installation +****************************** + +We recommend using `PyPI `_ to install |product_name| + +.. code-block:: bash + + pip install slackclient + +Of course, if you prefer doing things the hard way, you can always implement |product_name| +by pulling down the source code directly into your project: + +.. code-block:: bash + + git clone https://github.com/slackapi/python-slackclient.git + pip install -r requirements.txt + +Getting Help +************ + +If you get stuck, we’re here to help. The following are the best ways to get assistance working through your issue: + +- Use our `Github Issue Tracker `_ for reporting bugs or requesting features. +- Visit the `Bot Developer Hangout `_ for getting help using |product_name| or just generally bond with your fellow Slack developers. + +.. include:: metadata.rst diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/make.bat b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/make.bat new file mode 100644 index 0000000000..5a08728349 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/make.bat @@ -0,0 +1,281 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. epub3 to make an epub3 + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. xml to make Docutils-native XML files + echo. pseudoxml to make pseudoxml-XML files for display purposes + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + echo. coverage to run coverage check of the documentation if enabled + echo. dummy to check syntax errors of document sources + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + + +REM Check if sphinx-build is available and fallback to Python version if any +%SPHINXBUILD% 1>NUL 2>NUL +if errorlevel 9009 goto sphinx_python +goto sphinx_ok + +:sphinx_python + +set SPHINXBUILD=python -m sphinx.__init__ +%SPHINXBUILD% 2> nul +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +:sphinx_ok + + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\python-slackclient.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\python-slackclient.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "epub3" ( + %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdf" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf + cd %~dp0 + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "latexpdfja" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + cd %BUILDDIR%/latex + make all-pdf-ja + cd %~dp0 + echo. + echo.Build finished; the PDF files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +if "%1" == "coverage" ( + %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage + if errorlevel 1 exit /b 1 + echo. + echo.Testing of coverage in the sources finished, look at the ^ +results in %BUILDDIR%/coverage/python.txt. + goto end +) + +if "%1" == "xml" ( + %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The XML files are in %BUILDDIR%/xml. + goto end +) + +if "%1" == "pseudoxml" ( + %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. + goto end +) + +if "%1" == "dummy" ( + %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. Dummy builder generates no files. + goto end +) + +:end diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/metadata.rst b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/metadata.rst new file mode 100644 index 0000000000..75d613470c --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/metadata.rst @@ -0,0 +1,19 @@ +.. Site settings +.. |product_name| replace:: Slack Developer Kit for Python +.. |email| replace:: opensource@slack.com +.. |repo_name| replace:: python-slackclient +.. |github_username| replace:: SlackAPI +.. |twitter_username| replace:: SlackAPI + +.. _Bot Developer Hangout: https://dev4slack.slack.com/archives/sdk-python-slackclient +.. _Issue Tracker: http://github.com/SlackAPI/python-slackclient/issues +.. _pull request: http://github.com/SlackAPI/python-slackclient/pulls +.. _Python RTMBot: https://slackapi.github.io/python-rtmbot +.. _License: https://github.com/SlackAPI/python-slackclient/blob/master/LICENSE +.. _Code of Conduct: https://slackhq.github.io/code-of-conduct +.. _Contributing: https://github.com/slackapi/python-slackclient/blob/master/.github/contributing.md +.. _contributing guidelines: https://github.com/slackapi/python-slackclient/blob/master/.github/contributing.md +.. _Contributor License Agreement: https://docs.google.com/a/slack-corp.com/forms/d/e/1FAIpQLSfzjVoCM7ohBnjWf7eDYQxzti1EPpinsIJQA5RAUBwJKRUQHg/viewform +.. _Real Time Messaging (RTM) API: https://api.slack.com/rtm +.. _Web API: https://api.slack.com/web + diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/real_time_messaging.rst b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/real_time_messaging.rst new file mode 100644 index 0000000000..e651ea6875 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs-src/real_time_messaging.rst @@ -0,0 +1,130 @@ +.. _real-time-messaging: + +============================================== +Real Time Messaging (RTM) +============================================== +The `Real Time Messaging (RTM) API`_ is a WebSocket-based API that allows you to +receive events from Slack in real time and send messages as users. + +If you prefer events to be pushed to you instead, we recommend using the +HTTP-based `Events API `_ instead. +Most event types supported by the RTM API are also available +in `the Events API `_. + +See :ref:`Tokens & Authentication ` for API token handling best practices. + +Connecting to the RTM API +------------------------------------------ +:: + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + if sc.rtm_connect(): + while sc.server.connected is True: + print sc.rtm_read() + time.sleep(1) + else: + print "Connection Failed" + +If you connect successfully the first event received will be a hello: +:: + + { + u'type': u'hello' + } + +If there was a problem connecting an error will be returned, including a descriptive error message: +:: + + { + u'type': u'error', + u'error': { + u'code': 1, + u'msg': u'Socket URL has expired' + } + } + +rtm.start vs rtm.connect +--------------------------- + +If you expect your app to be used on large teams, we recommend starting the RTM client with `rtm.connect` rather than the default connection method for this client, `rtm.start`. +`rtm.connect` provides a lighter initial connection payload, without the team's channel and user information included. You'll need to request channel and user info via +the Web API separately. + +To do this, simply pass `with_team_state=False` into the `rtm_connect` call, like so: +:: + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + if sc.rtm_connect(with_team_state=False): + while True: + print sc.rtm_read() + time.sleep(1) + else: + print "Connection Failed" + + +Passing `auto_reconnect=True` will tell the websocket client to automatically reconnect if the connection gets dropped. + + +See the `rtm.start docs `_ and the `rtm.connect docs `_ +for more details. + + +RTM Events +------------- +:: + + { + u'type': u'message', + u'ts': u'1358878749.000002', + u'user': u'U023BECGF', + u'text': u'Hello' + } + +See `RTM Events `_ for a complete list of events. + +Sending messages via the RTM API +--------------------------------- +You can send a message to Slack by sending JSON over the websocket connection. + +:: + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.rtm_send_message("welcome-test", "test") + +You can send a message to a private group or direct message channel in the same +way, but using a Group ID (``C024BE91L``) or DM channel ID (``D024BE91L``). + +You can send a message in reply to a thread using the ``thread`` argument, and +optionally broadcast that message back to the channel by setting +``reply_broadcast`` to ``True``. + +:: + + from slackclient import SlackClient + + slack_token = os.environ["SLACK_API_TOKEN"] + sc = SlackClient(slack_token) + + sc.rtm_send_message("welcome-test", "test", "1482960137.003543", True) + +See `Threading messages `_ +for more details on using threads. + +The RTM API only supports posting messages with `basic formatting `_. +It does not support attachments or other message formatting modes. + + To post a more complex message as a user, see :ref:`Web API usage `. + +.. include:: metadata.rst diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs.sh b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs.sh new file mode 100644 index 0000000000..daf352aeb5 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash + +sphinx-build -c ./docs-src/_themes/slack/ -b html docs-src docs && touch ./docs/.nojekyll \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/.buildinfo b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/.buildinfo new file mode 100644 index 0000000000..1c0a8af899 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/.buildinfo @@ -0,0 +1,4 @@ +# Sphinx build info version 1 +# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. +config: 6abbc33d255b00e789666fcb765fbf2d +tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/.nojekyll b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/.nojekyll new file mode 100644 index 0000000000..e69de29bb2 diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/ajax-loader.gif b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/ajax-loader.gif new file mode 100644 index 0000000000..61faf8cab2 Binary files /dev/null and b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/ajax-loader.gif differ diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/basic.css b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/basic.css new file mode 100644 index 0000000000..104f076ae8 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/basic.css @@ -0,0 +1,676 @@ +/* + * basic.css + * ~~~~~~~~~ + * + * Sphinx stylesheet -- basic theme. + * + * :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/* -- main layout ----------------------------------------------------------- */ + +div.clearer { + clear: both; +} + +/* -- relbar ---------------------------------------------------------------- */ + +div.related { + width: 100%; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +/* -- sidebar --------------------------------------------------------------- */ + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; +} + +div.sphinxsidebar { + float: left; + width: 230px; + margin-left: -100%; + font-size: 90%; + word-wrap: break-word; + overflow-wrap : break-word; +} + +div.sphinxsidebar ul { + list-style: none; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +div.sphinxsidebar #searchbox form.search { + overflow: hidden; +} + +div.sphinxsidebar #searchbox input[type="text"] { + float: left; + width: 80%; + padding: 0.25em; + box-sizing: border-box; +} + +div.sphinxsidebar #searchbox input[type="submit"] { + float: left; + width: 20%; + border-left: none; + padding: 0.25em; + box-sizing: border-box; +} + + +img { + border: 0; + max-width: 100%; +} + +/* -- search page ----------------------------------------------------------- */ + +ul.search { + margin: 10px 0 0 20px; + padding: 0; +} + +ul.search li { + padding: 5px 0 5px 20px; + background-image: url(file.png); + background-repeat: no-repeat; + background-position: 0 7px; +} + +ul.search li a { + font-weight: bold; +} + +ul.search li div.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* -- index page ------------------------------------------------------------ */ + +table.contentstable { + width: 90%; + margin-left: auto; + margin-right: auto; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* -- general index --------------------------------------------------------- */ + +table.indextable { + width: 100%; +} + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable ul { + margin-top: 0; + margin-bottom: 0; + list-style-type: none; +} + +table.indextable > tbody > tr > td > ul { + padding-left: 0em; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +div.modindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +div.genindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +/* -- domain module index --------------------------------------------------- */ + +table.modindextable td { + padding: 2px; + border-collapse: collapse; +} + +/* -- general body styles --------------------------------------------------- */ + +div.body { + min-width: 450px; + max-width: 800px; +} + +div.body p, div.body dd, div.body li, div.body blockquote { + -moz-hyphens: auto; + -ms-hyphens: auto; + -webkit-hyphens: auto; + hyphens: auto; +} + +a.headerlink { + visibility: hidden; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink, +caption:hover > a.headerlink, +p.caption:hover > a.headerlink, +div.code-block-caption:hover > a.headerlink { + visibility: visible; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +.first { + margin-top: 0 !important; +} + +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +img.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; +} + +img.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; +} + +img.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; +} + +.align-left { + text-align: left; +} + +.align-center { + text-align: center; +} + +.align-right { + text-align: right; +} + +/* -- sidebars -------------------------------------------------------------- */ + +div.sidebar { + margin: 0 0 0.5em 1em; + border: 1px solid #ddb; + padding: 7px 7px 0 7px; + background-color: #ffe; + width: 40%; + float: right; +} + +p.sidebar-title { + font-weight: bold; +} + +/* -- topics ---------------------------------------------------------------- */ + +div.topic { + border: 1px solid #ccc; + padding: 7px 7px 0 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* -- admonitions ----------------------------------------------------------- */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +div.admonition dl { + margin-bottom: 0; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +/* -- tables ---------------------------------------------------------------- */ + +table.docutils { + border: 0; + border-collapse: collapse; +} + +table.align-center { + margin-left: auto; + margin-right: auto; +} + +table caption span.caption-number { + font-style: italic; +} + +table caption span.caption-text { +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 5px; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +table.footnote td, table.footnote th { + border: 0 !important; +} + +th { + text-align: left; + padding-right: 5px; +} + +table.citation { + border-left: solid 1px gray; + margin-left: 1px; +} + +table.citation td { + border-bottom: none; +} + +/* -- figures --------------------------------------------------------------- */ + +div.figure { + margin: 0.5em; + padding: 0.5em; +} + +div.figure p.caption { + padding: 0.3em; +} + +div.figure p.caption span.caption-number { + font-style: italic; +} + +div.figure p.caption span.caption-text { +} + +/* -- field list styles ----------------------------------------------------- */ + +table.field-list td, table.field-list th { + border: 0 !important; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} + +/* -- hlist styles ---------------------------------------------------------- */ + +table.hlist td { + vertical-align: top; +} + + +/* -- other body styles ----------------------------------------------------- */ + +ol.arabic { + list-style: decimal; +} + +ol.loweralpha { + list-style: lower-alpha; +} + +ol.upperalpha { + list-style: upper-alpha; +} + +ol.lowerroman { + list-style: lower-roman; +} + +ol.upperroman { + list-style: upper-roman; +} + +dl { + margin-bottom: 15px; +} + +dd p { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +dt:target, span.highlighted { + background-color: #fbe54e; +} + +rect.highlighted { + fill: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +.optional { + font-size: 1.3em; +} + +.sig-paren { + font-size: larger; +} + +.versionmodified { + font-style: italic; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +.footnote:target { + background-color: #ffa; +} + +.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +.line-block .line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; +} + +.guilabel, .menuselection { + font-family: sans-serif; +} + +.accelerator { + text-decoration: underline; +} + +.classifier { + font-style: oblique; +} + +abbr, acronym { + border-bottom: dotted 1px; + cursor: help; +} + +/* -- code displays --------------------------------------------------------- */ + +pre { + overflow: auto; + overflow-y: hidden; /* fixes display issues on Chrome browsers */ +} + +span.pre { + -moz-hyphens: none; + -ms-hyphens: none; + -webkit-hyphens: none; + hyphens: none; +} + +td.linenos pre { + padding: 5px 0px; + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + margin-left: 0.5em; +} + +table.highlighttable td { + padding: 0 0.5em 0 0.5em; +} + +div.code-block-caption { + padding: 2px 5px; + font-size: small; +} + +div.code-block-caption code { + background-color: transparent; +} + +div.code-block-caption + div > div.highlight > pre { + margin-top: 0; +} + +div.code-block-caption span.caption-number { + padding: 0.1em 0.3em; + font-style: italic; +} + +div.code-block-caption span.caption-text { +} + +div.literal-block-wrapper { + padding: 1em 1em 0; +} + +div.literal-block-wrapper div.highlight { + margin: 0; +} + +code.descname { + background-color: transparent; + font-weight: bold; + font-size: 1.2em; +} + +code.descclassname { + background-color: transparent; +} + +code.xref, a code { + background-color: transparent; + font-weight: bold; +} + +h1 code, h2 code, h3 code, h4 code, h5 code, h6 code { + background-color: transparent; +} + +.viewcode-link { + float: right; +} + +.viewcode-back { + float: right; + font-family: sans-serif; +} + +div.viewcode-block:target { + margin: -1px -10px; + padding: 0 10px; +} + +/* -- math display ---------------------------------------------------------- */ + +img.math { + vertical-align: middle; +} + +div.body div.math p { + text-align: center; +} + +span.eqno { + float: right; +} + +span.eqno a.headerlink { + position: relative; + left: 0px; + z-index: 1; +} + +div.math:hover a.headerlink { + visibility: visible; +} + +/* -- printout stylesheet --------------------------------------------------- */ + +@media print { + div.document, + div.documentwrapper, + div.bodywrapper { + margin: 0 !important; + width: 100%; + } + + div.sphinxsidebar, + div.related, + div.footer, + #top-link { + display: none; + } +} \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/classic.css b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/classic.css new file mode 100644 index 0000000000..6cfbfb9c3f --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/classic.css @@ -0,0 +1,261 @@ +/* + * classic.css_t + * ~~~~~~~~~~~~~ + * + * Sphinx stylesheet -- classic theme. + * + * :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +@import url("basic.css"); + +/* -- page layout ----------------------------------------------------------- */ + +body { + font-family: sans-serif; + font-size: 100%; + background-color: #11303d; + color: #000; + margin: 0; + padding: 0; +} + +div.document { + background-color: #1c4e63; +} + +div.documentwrapper { + float: left; + width: 100%; +} + +div.bodywrapper { + margin: 0 0 0 230px; +} + +div.body { + background-color: #ffffff; + color: #000000; + padding: 0 20px 30px 20px; +} + +div.footer { + color: #ffffff; + width: 100%; + padding: 9px 0 9px 0; + text-align: center; + font-size: 75%; +} + +div.footer a { + color: #ffffff; + text-decoration: underline; +} + +div.related { + background-color: #133f52; + line-height: 30px; + color: #ffffff; +} + +div.related a { + color: #ffffff; +} + +div.sphinxsidebar { +} + +div.sphinxsidebar h3 { + font-family: 'Trebuchet MS', sans-serif; + color: #ffffff; + font-size: 1.4em; + font-weight: normal; + margin: 0; + padding: 0; +} + +div.sphinxsidebar h3 a { + color: #ffffff; +} + +div.sphinxsidebar h4 { + font-family: 'Trebuchet MS', sans-serif; + color: #ffffff; + font-size: 1.3em; + font-weight: normal; + margin: 5px 0 0 0; + padding: 0; +} + +div.sphinxsidebar p { + color: #ffffff; +} + +div.sphinxsidebar p.topless { + margin: 5px 10px 10px 10px; +} + +div.sphinxsidebar ul { + margin: 10px; + padding: 0; + color: #ffffff; +} + +div.sphinxsidebar a { + color: #98dbcc; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + + + +/* -- hyperlink styles ------------------------------------------------------ */ + +a { + color: #355f7c; + text-decoration: none; +} + +a:visited { + color: #355f7c; + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + + + +/* -- body styles ----------------------------------------------------------- */ + +div.body h1, +div.body h2, +div.body h3, +div.body h4, +div.body h5, +div.body h6 { + font-family: 'Trebuchet MS', sans-serif; + background-color: #f2f2f2; + font-weight: normal; + color: #20435c; + border-bottom: 1px solid #ccc; + margin: 20px -20px 10px -20px; + padding: 3px 0 3px 10px; +} + +div.body h1 { margin-top: 0; font-size: 200%; } +div.body h2 { font-size: 160%; } +div.body h3 { font-size: 140%; } +div.body h4 { font-size: 120%; } +div.body h5 { font-size: 110%; } +div.body h6 { font-size: 100%; } + +a.headerlink { + color: #c60f0f; + font-size: 0.8em; + padding: 0 4px 0 4px; + text-decoration: none; +} + +a.headerlink:hover { + background-color: #c60f0f; + color: white; +} + +div.body p, div.body dd, div.body li, div.body blockquote { + text-align: justify; + line-height: 130%; +} + +div.admonition p.admonition-title + p { + display: inline; +} + +div.admonition p { + margin-bottom: 5px; +} + +div.admonition pre { + margin-bottom: 5px; +} + +div.admonition ul, div.admonition ol { + margin-bottom: 5px; +} + +div.note { + background-color: #eee; + border: 1px solid #ccc; +} + +div.seealso { + background-color: #ffc; + border: 1px solid #ff6; +} + +div.topic { + background-color: #eee; +} + +div.warning { + background-color: #ffe4e4; + border: 1px solid #f66; +} + +p.admonition-title { + display: inline; +} + +p.admonition-title:after { + content: ":"; +} + +pre { + padding: 5px; + background-color: #eeffcc; + color: #333333; + line-height: 120%; + border: 1px solid #ac9; + border-left: none; + border-right: none; +} + +code { + background-color: #ecf0f3; + padding: 0 1px 0 1px; + font-size: 0.95em; +} + +th { + background-color: #ede; +} + +.warning code { + background: #efc2c2; +} + +.note code { + background: #d6d6d6; +} + +.viewcode-back { + font-family: sans-serif; +} + +div.viewcode-block:target { + background-color: #f4debf; + border-top: 1px solid #ac9; + border-bottom: 1px solid #ac9; +} + +div.code-block-caption { + color: #efefef; + background-color: #1c4e63; +} \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/comment-bright.png b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/comment-bright.png new file mode 100644 index 0000000000..15e27edb12 Binary files /dev/null and b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/comment-bright.png differ diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/comment-close.png b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/comment-close.png new file mode 100644 index 0000000000..4d91bcf57d Binary files /dev/null and b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/comment-close.png differ diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/comment.png b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/comment.png new file mode 100644 index 0000000000..dfbc0cbd51 Binary files /dev/null and b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/comment.png differ diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/default.css b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/default.css new file mode 100644 index 0000000000..d614fd2cf4 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/default.css @@ -0,0 +1,74 @@ +a.headerlink { + display: none !important; +} + +.section-title { + font-size: 2rem; + line-height: 2.5rem; + letter-spacing: -1px; + font-weight: 700; + margin: 0 0 1rem; +} + +nav#api_nav .toctree-l1 { + margin-bottom: 1.5rem; +} + +nav#api_nav #api_sections ul { + list-style: none; + margin: 0; + padding: 0; +} + +nav#api_nav #api_sections ul li.toctree-l1>a { + color: #1264a3; + letter-spacing: 0; + font-size: .8rem; + font-weight: 800; + text-transform: uppercase; + border: none; + padding: 0; +} + +nav#api_nav #api_sections ul li.toctree-l2 { + margin: 0; + padding: 0; +} + +nav#api_nav #api_sections ul li.toctree-l2 a { + color: #1d1c1d; + text-transform: none; + font-weight: inherit; + padding: 0; + display: block; + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; + font-size: 15px!important; + line-height:15px; + padding: 4px 8px; + border: 1px solid transparent; + border-radius: 4px; +} + +nav#api_nav #api_sections ul li.toctree-l2 a:hover { + cursor: pointer; + text-decoration: none; + background-color:#e8f5fa; + border-color:#dcf0fb; +} + +nav#api_nav #footer #footer_nav { + font-size: .9375rem; +} + +nav#api_nav #footer #footer_nav a { + border: none; + padding: 0; + color: #616061; +} + +nav#api_nav #footer #footer_nav a:hover { + text-decoration: none; + color: #1c1c1c; +} \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/docs.css b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/docs.css new file mode 100644 index 0000000000..7f360ac666 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/docs.css @@ -0,0 +1,34 @@ +/* Updates body font */ +body { + font-family: Slack-Lato,appleLogo,sans-serif; +} + +/* Replaces old sidebar styled links */ +.sidebar_menu h5 { + font-size: 0.8rem; + font-weight: 800; + margin-bottom: 3px; +} + +/* Aligns footer navigation to the left of the sidebar */ +.footer_nav { + margin: 0 !important; +} + +/* Styles the signature all nice and pretty <3 */ +#footer_signature { + color:#e01e5a; + font-size:.9rem; + margin-top: 10px; +} + +/* Fixes link hover state */ +a:hover { + text-decoration: underline; +} + +/* Makes footer consistent */ +footer { + background-color: transparent; + border: 0; +} \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/doctools.js b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/doctools.js new file mode 100644 index 0000000000..ffadbec11f --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/doctools.js @@ -0,0 +1,315 @@ +/* + * doctools.js + * ~~~~~~~~~~~ + * + * Sphinx JavaScript utilities for all documentation. + * + * :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/** + * select a different prefix for underscore + */ +$u = _.noConflict(); + +/** + * make the code below compatible with browsers without + * an installed firebug like debugger +if (!window.console || !console.firebug) { + var names = ["log", "debug", "info", "warn", "error", "assert", "dir", + "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", + "profile", "profileEnd"]; + window.console = {}; + for (var i = 0; i < names.length; ++i) + window.console[names[i]] = function() {}; +} + */ + +/** + * small helper function to urldecode strings + */ +jQuery.urldecode = function(x) { + return decodeURIComponent(x).replace(/\+/g, ' '); +}; + +/** + * small helper function to urlencode strings + */ +jQuery.urlencode = encodeURIComponent; + +/** + * This function returns the parsed url parameters of the + * current request. Multiple values per key are supported, + * it will always return arrays of strings for the value parts. + */ +jQuery.getQueryParameters = function(s) { + if (typeof s === 'undefined') + s = document.location.search; + var parts = s.substr(s.indexOf('?') + 1).split('&'); + var result = {}; + for (var i = 0; i < parts.length; i++) { + var tmp = parts[i].split('=', 2); + var key = jQuery.urldecode(tmp[0]); + var value = jQuery.urldecode(tmp[1]); + if (key in result) + result[key].push(value); + else + result[key] = [value]; + } + return result; +}; + +/** + * highlight a given string on a jquery object by wrapping it in + * span elements with the given class name. + */ +jQuery.fn.highlightText = function(text, className) { + function highlight(node, addItems) { + if (node.nodeType === 3) { + var val = node.nodeValue; + var pos = val.toLowerCase().indexOf(text); + if (pos >= 0 && + !jQuery(node.parentNode).hasClass(className) && + !jQuery(node.parentNode).hasClass("nohighlight")) { + var span; + var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); + if (isInSVG) { + span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); + } else { + span = document.createElement("span"); + span.className = className; + } + span.appendChild(document.createTextNode(val.substr(pos, text.length))); + node.parentNode.insertBefore(span, node.parentNode.insertBefore( + document.createTextNode(val.substr(pos + text.length)), + node.nextSibling)); + node.nodeValue = val.substr(0, pos); + if (isInSVG) { + var bbox = span.getBBox(); + var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); + rect.x.baseVal.value = bbox.x; + rect.y.baseVal.value = bbox.y; + rect.width.baseVal.value = bbox.width; + rect.height.baseVal.value = bbox.height; + rect.setAttribute('class', className); + var parentOfText = node.parentNode.parentNode; + addItems.push({ + "parent": node.parentNode, + "target": rect}); + } + } + } + else if (!jQuery(node).is("button, select, textarea")) { + jQuery.each(node.childNodes, function() { + highlight(this, addItems); + }); + } + } + var addItems = []; + var result = this.each(function() { + highlight(this, addItems); + }); + for (var i = 0; i < addItems.length; ++i) { + jQuery(addItems[i].parent).before(addItems[i].target); + } + return result; +}; + +/* + * backward compatibility for jQuery.browser + * This will be supported until firefox bug is fixed. + */ +if (!jQuery.browser) { + jQuery.uaMatch = function(ua) { + ua = ua.toLowerCase(); + + var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || + /(webkit)[ \/]([\w.]+)/.exec(ua) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || + /(msie) ([\w.]+)/.exec(ua) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || + []; + + return { + browser: match[ 1 ] || "", + version: match[ 2 ] || "0" + }; + }; + jQuery.browser = {}; + jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; +} + +/** + * Small JavaScript module for the documentation. + */ +var Documentation = { + + init : function() { + this.fixFirefoxAnchorBug(); + this.highlightSearchWords(); + this.initIndexTable(); + if (DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) { + this.initOnKeyListeners(); + } + }, + + /** + * i18n support + */ + TRANSLATIONS : {}, + PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; }, + LOCALE : 'unknown', + + // gettext and ngettext don't access this so that the functions + // can safely bound to a different name (_ = Documentation.gettext) + gettext : function(string) { + var translated = Documentation.TRANSLATIONS[string]; + if (typeof translated === 'undefined') + return string; + return (typeof translated === 'string') ? translated : translated[0]; + }, + + ngettext : function(singular, plural, n) { + var translated = Documentation.TRANSLATIONS[singular]; + if (typeof translated === 'undefined') + return (n == 1) ? singular : plural; + return translated[Documentation.PLURALEXPR(n)]; + }, + + addTranslations : function(catalog) { + for (var key in catalog.messages) + this.TRANSLATIONS[key] = catalog.messages[key]; + this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); + this.LOCALE = catalog.locale; + }, + + /** + * add context elements like header anchor links + */ + addContextElements : function() { + $('div[id] > :header:first').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this headline')). + appendTo(this); + }); + $('dt[id]').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this definition')). + appendTo(this); + }); + }, + + /** + * workaround a firefox stupidity + * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 + */ + fixFirefoxAnchorBug : function() { + if (document.location.hash && $.browser.mozilla) + window.setTimeout(function() { + document.location.href += ''; + }, 10); + }, + + /** + * highlight the search words provided in the url in the text + */ + highlightSearchWords : function() { + var params = $.getQueryParameters(); + var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; + if (terms.length) { + var body = $('div.body'); + if (!body.length) { + body = $('body'); + } + window.setTimeout(function() { + $.each(terms, function() { + body.highlightText(this.toLowerCase(), 'highlighted'); + }); + }, 10); + $('') + .appendTo($('#searchbox')); + } + }, + + /** + * init the domain index toggle buttons + */ + initIndexTable : function() { + var togglers = $('img.toggler').click(function() { + var src = $(this).attr('src'); + var idnum = $(this).attr('id').substr(7); + $('tr.cg-' + idnum).toggle(); + if (src.substr(-9) === 'minus.png') + $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); + else + $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); + }).css('display', ''); + if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { + togglers.click(); + } + }, + + /** + * helper function to hide the search marks again + */ + hideSearchWords : function() { + $('#searchbox .highlight-link').fadeOut(300); + $('span.highlighted').removeClass('highlighted'); + }, + + /** + * make the url absolute + */ + makeURL : function(relativeURL) { + return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; + }, + + /** + * get the current relative url + */ + getCurrentURL : function() { + var path = document.location.pathname; + var parts = path.split(/\//); + $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { + if (this === '..') + parts.pop(); + }); + var url = parts.join('/'); + return path.substring(url.lastIndexOf('/') + 1, path.length - 1); + }, + + initOnKeyListeners: function() { + $(document).keyup(function(event) { + var activeElementType = document.activeElement.tagName; + // don't navigate when in search box or textarea + if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') { + switch (event.keyCode) { + case 37: // left + var prevHref = $('link[rel="prev"]').prop('href'); + if (prevHref) { + window.location.href = prevHref; + return false; + } + case 39: // right + var nextHref = $('link[rel="next"]').prop('href'); + if (nextHref) { + window.location.href = nextHref; + return false; + } + } + } + }); + } +}; + +// quick alias for translations +_ = Documentation.gettext; + +$(document).ready(function() { + Documentation.init(); +}); diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/documentation_options.js b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/documentation_options.js new file mode 100644 index 0000000000..ccedf6692d --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/documentation_options.js @@ -0,0 +1,10 @@ +var DOCUMENTATION_OPTIONS = { + URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), + VERSION: '1.0.1', + LANGUAGE: 'None', + COLLAPSE_INDEX: false, + FILE_SUFFIX: '.html', + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt', + NAVIGATION_WITH_KEYS: false, +}; \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/down-pressed.png b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/down-pressed.png new file mode 100644 index 0000000000..5756c8cad8 Binary files /dev/null and b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/down-pressed.png differ diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/down.png b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/down.png new file mode 100644 index 0000000000..1b3bdad2ce Binary files /dev/null and b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/down.png differ diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/file.png b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/file.png new file mode 100644 index 0000000000..a858a410e4 Binary files /dev/null and b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/file.png differ diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/jquery-3.2.1.js b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/jquery-3.2.1.js new file mode 100644 index 0000000000..d2d8ca4790 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/_static/jquery-3.2.1.js @@ -0,0 +1,10253 @@ +/*! + * jQuery JavaScript Library v3.2.1 + * https://jquery.com/ + * + * Includes Sizzle.js + * https://sizzlejs.com/ + * + * Copyright JS Foundation and other contributors + * Released under the MIT license + * https://jquery.org/license + * + * Date: 2017-03-20T18:59Z + */ +( function( global, factory ) { + + "use strict"; + + if ( typeof module === "object" && typeof module.exports === "object" ) { + + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info. + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 +// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode +// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common +// enough that all such attempts are guarded in a try block. +"use strict"; + +var arr = []; + +var document = window.document; + +var getProto = Object.getPrototypeOf; + +var slice = arr.slice; + +var concat = arr.concat; + +var push = arr.push; + +var indexOf = arr.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var fnToString = hasOwn.toString; + +var ObjectFunctionString = fnToString.call( Object ); + +var support = {}; + + + + function DOMEval( code, doc ) { + doc = doc || document; + + var script = doc.createElement( "script" ); + + script.text = code; + doc.head.appendChild( script ).parentNode.removeChild( script ); + } +/* global Symbol */ +// Defining this global in .eslintrc.json would create a danger of using the global +// unguarded in another place, it seems safer to define global only for this module + + + +var + version = "3.2.1", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }, + + // Support: Android <=4.0 only + // Make sure we trim BOM and NBSP + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([a-z])/g, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +jQuery.fn = jQuery.prototype = { + + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + + // Return all the elements in a clean array + if ( num == null ) { + return slice.call( this ); + } + + // Return just the one element from the set + return num < 0 ? this[ num + this.length ] : this[ num ]; + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + each: function( callback ) { + return jQuery.each( this, callback ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: arr.sort, + splice: arr.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[ 0 ] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + + // Only deal with non-null/undefined values + if ( ( options = arguments[ i ] ) != null ) { + + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = Array.isArray( copy ) ) ) ) { + + if ( copyIsArray ) { + copyIsArray = false; + clone = src && Array.isArray( src ) ? src : []; + + } else { + clone = src && jQuery.isPlainObject( src ) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend( { + + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isFunction: function( obj ) { + return jQuery.type( obj ) === "function"; + }, + + isWindow: function( obj ) { + return obj != null && obj === obj.window; + }, + + isNumeric: function( obj ) { + + // As of jQuery 3.0, isNumeric is limited to + // strings and numbers (primitives or objects) + // that can be coerced to finite numbers (gh-2662) + var type = jQuery.type( obj ); + return ( type === "number" || type === "string" ) && + + // parseFloat NaNs numeric-cast false positives ("") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + !isNaN( obj - parseFloat( obj ) ); + }, + + isPlainObject: function( obj ) { + var proto, Ctor; + + // Detect obvious negatives + // Use toString instead of jQuery.type to catch host objects + if ( !obj || toString.call( obj ) !== "[object Object]" ) { + return false; + } + + proto = getProto( obj ); + + // Objects with no prototype (e.g., `Object.create( null )`) are plain + if ( !proto ) { + return true; + } + + // Objects with prototype are plain iff they were constructed by a global Object function + Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; + return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; + }, + + isEmptyObject: function( obj ) { + + /* eslint-disable no-unused-vars */ + // See https://github.com/eslint/eslint/issues/6125 + var name; + + for ( name in obj ) { + return false; + } + return true; + }, + + type: function( obj ) { + if ( obj == null ) { + return obj + ""; + } + + // Support: Android <=2.3 only (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; + }, + + // Evaluates a script in a global context + globalEval: function( code ) { + DOMEval( code ); + }, + + // Convert dashed to camelCase; used by the css and data modules + // Support: IE <=9 - 11, Edge 12 - 13 + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + each: function( obj, callback ) { + var length, i = 0; + + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } else { + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } + + return obj; + }, + + // Support: Android <=4.0 only + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArrayLike( Object( arr ) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var length, value, + i = 0, + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var tmp, args, proxy; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + now: Date.now, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); + +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} + +// Populate the class2type map +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), +function( i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +} ); + +function isArrayLike( obj ) { + + // Support: real iOS 8.2 only (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, + type = jQuery.type( obj ); + + if ( type === "function" || jQuery.isWindow( obj ) ) { + return false; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v2.3.3 + * https://sizzlejs.com/ + * + * Copyright jQuery Foundation and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2016-08-08 + */ +(function( window ) { + +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf as it's faster than native + // https://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + + // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + identifier + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + identifier + ")" ), + "CLASS": new RegExp( "^\\.(" + identifier + ")" ), + "TAG": new RegExp( "^(" + identifier + "|[*])" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + + // CSS escapes + // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // CSS string/identifier serialization + // https://drafts.csswg.org/cssom/#common-serializing-idioms + rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, + fcssescape = function( ch, asCodePoint ) { + if ( asCodePoint ) { + + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if ( ch === "\0" ) { + return "\uFFFD"; + } + + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + } + + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }, + + disabledAncestor = addCombinator( + function( elem ) { + return elem.disabled === true && ("form" in elem || "label" in elem); + }, + { dir: "parentNode", next: "legend" } + ); + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var m, i, elem, nid, match, groups, newSelector, + newContext = context && context.ownerDocument, + + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; + + results = results || []; + + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { + + // ID selector + if ( (m = match[1]) ) { + + // Document context + if ( nodeType === 9 ) { + if ( (elem = context.getElementById( m )) ) { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + + // Element context + } else { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( newContext && (elem = newContext.getElementById( m )) && + contains( context, elem ) && + elem.id === m ) { + + results.push( elem ); + return results; + } + } + + // Type selector + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Class selector + } else if ( (m = match[3]) && support.getElementsByClassName && + context.getElementsByClassName ) { + + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // Take advantage of querySelectorAll + if ( support.qsa && + !compilerCache[ selector + " " ] && + (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + + if ( nodeType !== 1 ) { + newContext = context; + newSelector = selector; + + // qSA looks outside Element context, which is not what we want + // Thanks to Andrew Dupont for this workaround technique + // Support: IE <=8 + // Exclude object elements + } else if ( context.nodeName.toLowerCase() !== "object" ) { + + // Capture the context ID, setting it first if necessary + if ( (nid = context.getAttribute( "id" )) ) { + nid = nid.replace( rcssescape, fcssescape ); + } else { + context.setAttribute( "id", (nid = expando) ); + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + while ( i-- ) { + groups[i] = "#" + nid + " " + toSelector( groups[i] ); + } + newSelector = groups.join( "," ); + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); + } + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {function(string, object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key + " " ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created element and returns a boolean result + */ +function assert( fn ) { + var el = document.createElement("fieldset"); + + try { + return !!fn( el ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( el.parentNode ) { + el.parentNode.removeChild( el ); + } + // release memory in IE + el = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = arr.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + a.sourceIndex - b.sourceIndex; + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for :enabled/:disabled + * @param {Boolean} disabled true for :disabled; false for :enabled + */ +function createDisabledPseudo( disabled ) { + + // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable + return function( elem ) { + + // Only certain elements can match :enabled or :disabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled + if ( "form" in elem ) { + + // Check for inherited disabledness on relevant non-disabled elements: + // * listed form-associated elements in a disabled fieldset + // https://html.spec.whatwg.org/multipage/forms.html#category-listed + // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled + // * option elements in a disabled optgroup + // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled + // All such elements have a "form" property. + if ( elem.parentNode && elem.disabled === false ) { + + // Option elements defer to a parent optgroup if present + if ( "label" in elem ) { + if ( "label" in elem.parentNode ) { + return elem.parentNode.disabled === disabled; + } else { + return elem.disabled === disabled; + } + } + + // Support: IE 6 - 11 + // Use the isDisabled shortcut property to check for disabled fieldset ancestors + return elem.isDisabled === disabled || + + // Where there is no isDisabled, check manually + /* jshint -W018 */ + elem.isDisabled !== !disabled && + disabledAncestor( elem ) === disabled; + } + + return elem.disabled === disabled; + + // Try to winnow out elements that can't be disabled before trusting the disabled property. + // Some victims get caught in our net (label, legend, menu, track), but it shouldn't + // even exist on them, let alone have a boolean value. + } else if ( "label" in elem ) { + return elem.disabled === disabled; + } + + // Remaining elements are neither :enabled nor :disabled + return false; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== "undefined" && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, subWindow, + doc = node ? node.ownerDocument || node : preferredDoc; + + // Return early if doc is invalid or already selected + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Update global variables + document = doc; + docElem = document.documentElement; + documentIsHTML = !isXML( document ); + + // Support: IE 9-11, Edge + // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) + if ( preferredDoc !== document && + (subWindow = document.defaultView) && subWindow.top !== subWindow ) { + + // Support: IE 11, Edge + if ( subWindow.addEventListener ) { + subWindow.addEventListener( "unload", unloadHandler, false ); + + // Support: IE 9 - 10 only + } else if ( subWindow.attachEvent ) { + subWindow.attachEvent( "onunload", unloadHandler ); + } + } + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties + // (excepting IE8 booleans) + support.attributes = assert(function( el ) { + el.className = "i"; + return !el.getAttribute("className"); + }); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert(function( el ) { + el.appendChild( document.createComment("") ); + return !el.getElementsByTagName("*").length; + }); + + // Support: IE<9 + support.getElementsByClassName = rnative.test( document.getElementsByClassName ); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programmatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert(function( el ) { + docElem.appendChild( el ).id = expando; + return !document.getElementsByName || !document.getElementsByName( expando ).length; + }); + + // ID filter and find + if ( support.getById ) { + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var elem = context.getElementById( id ); + return elem ? [ elem ] : []; + } + }; + } else { + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== "undefined" && + elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + + // Support: IE 6 - 7 only + // getElementById is not reliable as a find shortcut + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var node, i, elems, + elem = context.getElementById( id ); + + if ( elem ) { + + // Verify the id attribute + node = elem.getAttributeNode("id"); + if ( node && node.value === id ) { + return [ elem ]; + } + + // Fall back on getElementsByName + elems = context.getElementsByName( id ); + i = 0; + while ( (elem = elems[i++]) ) { + node = elem.getAttributeNode("id"); + if ( node && node.value === id ) { + return [ elem ]; + } + } + } + + return []; + } + }; + } + + // Tag + Expr.find["TAG"] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); + + // DocumentFragment nodes don't have gEBTN + } else if ( support.qsa ) { + return context.querySelectorAll( tag ); + } + } : + + function( tag, context ) { + var elem, + tmp = [], + i = 0, + // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See https://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( (support.qsa = rnative.test( document.querySelectorAll )) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( el ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // https://bugs.jquery.com/ticket/12359 + docElem.appendChild( el ).innerHTML = "" + + ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( el.querySelectorAll("[msallowcapture^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !el.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ + if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push("~="); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !el.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + + // Support: Safari 8+, iOS 8+ + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibling-combinator selector` fails + if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push(".#.+[+~]"); + } + }); + + assert(function( el ) { + el.innerHTML = "" + + ""; + + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = document.createElement("input"); + input.setAttribute( "type", "hidden" ); + el.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( el.querySelectorAll("[name=d]").length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( el.querySelectorAll(":enabled").length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: IE9-11+ + // IE's :disabled selector does not pick up the children of disabled fieldsets + docElem.appendChild( el ).disabled = true; + if ( el.querySelectorAll(":disabled").length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + el.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( el ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( el, "*" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( el, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully self-exclusive + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { + return -1; + } + if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + return a === document ? -1 : + b === document ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return document; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + if ( support.matchesSelector && documentIsHTML && + !compilerCache[ expr + " " ] && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch (e) {} + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null; +}; + +Sizzle.escape = function( sel ) { + return (sel + "").replace( rcssescape, fcssescape ); +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + while ( (node = elem[i++]) ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[6] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[3] ) { + match[2] = match[4] || match[5] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, uniqueCache, outerCache, node, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType, + diff = false; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) { + + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + + // Seek `elem` from a previously-cached index + + // ...in a gzip-friendly way + node = parent; + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex && cache[ 2 ]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + } else { + // Use previously-cached element index if available + if ( useCache ) { + // ...in a gzip-friendly way + node = elem; + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex; + } + + // xml :nth-child(...) + // or :nth-last-child(...) or :nth(-last)?-of-type(...) + if ( diff === false ) { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) && + ++diff ) { + + // Cache the index of each encountered element + if ( useCache ) { + outerCache = node[ expando ] || (node[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + (outerCache[ node.uniqueID ] = {}); + + uniqueCache[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + // Don't keep the element (issue #299) + input[0] = null; + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + text = text.replace( runescape, funescape ); + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": createDisabledPseudo( false ), + "disabled": createDisabledPseudo( true ), + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( (tokens = []) ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + skip = combinator.next, + key = skip || dir, + checkNonElements = base && key === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + return false; + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, uniqueCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {}); + + if ( skip && skip === elem.nodeName.toLowerCase() ) { + elem = elem[ dir ] || elem; + } else if ( (oldCache = uniqueCache[ key ]) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return (newCache[ 2 ] = oldCache[ 2 ]); + } else { + // Reuse newcache so results back-propagate to previous elements + uniqueCache[ key ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { + return true; + } + } + } + } + } + return false; + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + // Avoid hanging onto element (issue #299) + checkContext = null; + return ret; + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), + len = elems.length; + + if ( outermost ) { + outermostContext = context === document || context || outermost; + } + + // Add elements passing elementMatchers directly to results + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + if ( !context && elem.ownerDocument !== document ) { + setDocument( elem ); + xml = !documentIsHTML; + } + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context || document, xml) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // `i` is now the count of elements visited above, and adding it to `matchedCount` + // makes the latter nonnegative. + matchedCount += i; + + // Apply set filters to unmatched elements + // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` + // equals `i`), unless we didn't visit _any_ elements in the above loop because we have + // no element matchers and no seed. + // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that + // case, which will result in a "00" `matchedCount` that differs from `i` but is also + // numerically zero. + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( (selector = compiled.selector || selector) ); + + results = results || []; + + // Try to minimize operations if there is only one selector in the list and no seed + // (the latter of which guarantees us context) + if ( match.length === 1 ) { + + // Reduce context if the leading compound selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + !context || rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Support: Chrome 14-35+ +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert(function( el ) { + // Should return 1, but returns 4 (following) + return el.compareDocumentPosition( document.createElement("fieldset") ) & 1; +}); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( el ) { + el.innerHTML = ""; + return el.firstChild.getAttribute("href") === "#" ; +}) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + }); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert(function( el ) { + el.innerHTML = ""; + el.firstChild.setAttribute( "value", "" ); + return el.firstChild.getAttribute( "value" ) === ""; +}) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert(function( el ) { + return el.getAttribute("disabled") == null; +}) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + null; + } + }); +} + +return Sizzle; + +})( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; + +// Deprecated +jQuery.expr[ ":" ] = jQuery.expr.pseudos; +jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; +jQuery.escapeSelector = Sizzle.escape; + + + + +var dir = function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; + + while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; +}; + + +var siblings = function( n, elem ) { + var matched = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; +}; + + +var rneedsContext = jQuery.expr.match.needsContext; + + + +function nodeName( elem, name ) { + + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + +}; +var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); + + + +var risSimple = /^.[^:#\[\.,]*$/; + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + return !!qualifier.call( elem, i, elem ) !== not; + } ); + } + + // Single element + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + } ); + } + + // Arraylike of elements (jQuery, arguments, Array) + if ( typeof qualifier !== "string" ) { + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not; + } ); + } + + // Simple selector that can be filtered directly, removing non-Elements + if ( risSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); + } + + // Complex selector, compare the two sets, removing non-Elements + qualifier = jQuery.filter( qualifier, elements ); + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1; + } ); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + if ( elems.length === 1 && elem.nodeType === 1 ) { + return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; + } + + return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); +}; + +jQuery.fn.extend( { + find: function( selector ) { + var i, ret, + len = this.length, + self = this; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter( function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + } ) ); + } + + ret = this.pushStack( [] ); + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + return len > 1 ? jQuery.uniqueSort( ret ) : ret; + }, + filter: function( selector ) { + return this.pushStack( winnow( this, selector || [], false ) ); + }, + not: function( selector ) { + return this.pushStack( winnow( this, selector || [], true ) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +} ); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + // Shortcut simple #id case for speed + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, + + init = jQuery.fn.init = function( selector, context, root ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Method init() accepts an alternate rootjQuery + // so migrate can support jQuery.sub (gh-2101) + root = root || rootjQuery; + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector[ 0 ] === "<" && + selector[ selector.length - 1 ] === ">" && + selector.length >= 3 ) { + + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && ( match[ 1 ] || !context ) ) { + + // HANDLE: $(html) -> $(array) + if ( match[ 1 ] ) { + context = context instanceof jQuery ? context[ 0 ] : context; + + // Option to run scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[ 1 ], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[ 2 ] ); + + if ( elem ) { + + // Inject the element directly into the jQuery object + this[ 0 ] = elem; + this.length = 1; + } + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || root ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this[ 0 ] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return root.ready !== undefined ? + root.ready( selector ) : + + // Execute immediately if ready is not present + selector( jQuery ); + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + + // Methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend( { + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; + + return this.filter( function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[ i ] ) ) { + return true; + } + } + } ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + targets = typeof selectors !== "string" && jQuery( selectors ); + + // Positional selectors never match, since there's no _selection_ context + if ( !rneedsContext.test( selectors ) ) { + for ( ; i < l; i++ ) { + for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { + + // Always skip document fragments + if ( cur.nodeType < 11 && ( targets ? + targets.index( cur ) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector( cur, selectors ) ) ) { + + matched.push( cur ); + break; + } + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); + }, + + // Determine the position of an element within the set + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } + + // Index in selector + if ( typeof elem === "string" ) { + return indexOf.call( jQuery( elem ), this[ 0 ] ); + } + + // Locate the position of the desired element + return indexOf.call( this, + + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.uniqueSort( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter( selector ) + ); + } +} ); + +function sibling( cur, dir ) { + while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} + return cur; +} + +jQuery.each( { + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return siblings( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return siblings( elem.firstChild ); + }, + contents: function( elem ) { + if ( nodeName( elem, "iframe" ) ) { + return elem.contentDocument; + } + + // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only + // Treat the template element as a regular one in browsers that + // don't support it. + if ( nodeName( elem, "template" ) ) { + elem = elem.content || elem; + } + + return jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); + } + + if ( this.length > 1 ) { + + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.uniqueSort( matched ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } + } + + return this.pushStack( matched ); + }; +} ); +var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); + + + +// Convert String-formatted options into Object-formatted ones +function createOptions( options ) { + var object = {}; + jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { + object[ flag ] = true; + } ); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + createOptions( options ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + + // Last fire value for non-forgettable lists + memory, + + // Flag to know if list was already fired + fired, + + // Flag to prevent firing + locked, + + // Actual callback list + list = [], + + // Queue of execution data for repeatable lists + queue = [], + + // Index of currently firing callback (modified by add/remove as needed) + firingIndex = -1, + + // Fire callbacks + fire = function() { + + // Enforce single-firing + locked = locked || options.once; + + // Execute callbacks for all pending executions, + // respecting firingIndex overrides and runtime changes + fired = firing = true; + for ( ; queue.length; firingIndex = -1 ) { + memory = queue.shift(); + while ( ++firingIndex < list.length ) { + + // Run callback and check for early termination + if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && + options.stopOnFalse ) { + + // Jump to end and forget the data so .add doesn't re-fire + firingIndex = list.length; + memory = false; + } + } + } + + // Forget the data if we're done with it + if ( !options.memory ) { + memory = false; + } + + firing = false; + + // Clean up if we're done firing for good + if ( locked ) { + + // Keep an empty list if we have data for future add calls + if ( memory ) { + list = []; + + // Otherwise, this object is spent + } else { + list = ""; + } + } + }, + + // Actual Callbacks object + self = { + + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + + // If we have memory from a past run, we should fire after adding + if ( memory && !firing ) { + firingIndex = list.length - 1; + queue.push( memory ); + } + + ( function add( args ) { + jQuery.each( args, function( _, arg ) { + if ( jQuery.isFunction( arg ) ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) { + + // Inspect recursively + add( arg ); + } + } ); + } )( arguments ); + + if ( memory && !firing ) { + fire(); + } + } + return this; + }, + + // Remove a callback from the list + remove: function() { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + + // Handle firing indexes + if ( index <= firingIndex ) { + firingIndex--; + } + } + } ); + return this; + }, + + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? + jQuery.inArray( fn, list ) > -1 : + list.length > 0; + }, + + // Remove all callbacks from the list + empty: function() { + if ( list ) { + list = []; + } + return this; + }, + + // Disable .fire and .add + // Abort any current/pending executions + // Clear all callbacks and values + disable: function() { + locked = queue = []; + list = memory = ""; + return this; + }, + disabled: function() { + return !list; + }, + + // Disable .fire + // Also disable .add unless we have memory (since it would have no effect) + // Abort any pending executions + lock: function() { + locked = queue = []; + if ( !memory && !firing ) { + list = memory = ""; + } + return this; + }, + locked: function() { + return !!locked; + }, + + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( !locked ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + queue.push( args ); + if ( !firing ) { + fire(); + } + } + return this; + }, + + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +function Identity( v ) { + return v; +} +function Thrower( ex ) { + throw ex; +} + +function adoptValue( value, resolve, reject, noValue ) { + var method; + + try { + + // Check for promise aspect first to privilege synchronous behavior + if ( value && jQuery.isFunction( ( method = value.promise ) ) ) { + method.call( value ).done( resolve ).fail( reject ); + + // Other thenables + } else if ( value && jQuery.isFunction( ( method = value.then ) ) ) { + method.call( value, resolve, reject ); + + // Other non-thenables + } else { + + // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: + // * false: [ value ].slice( 0 ) => resolve( value ) + // * true: [ value ].slice( 1 ) => resolve() + resolve.apply( undefined, [ value ].slice( noValue ) ); + } + + // For Promises/A+, convert exceptions into rejections + // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in + // Deferred#then to conditionally suppress rejection. + } catch ( value ) { + + // Support: Android 4.0 only + // Strict mode functions invoked without .call/.apply get global-object context + reject.apply( undefined, [ value ] ); + } +} + +jQuery.extend( { + + Deferred: function( func ) { + var tuples = [ + + // action, add listener, callbacks, + // ... .then handlers, argument index, [final state] + [ "notify", "progress", jQuery.Callbacks( "memory" ), + jQuery.Callbacks( "memory" ), 2 ], + [ "resolve", "done", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 0, "resolved" ], + [ "reject", "fail", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 1, "rejected" ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + "catch": function( fn ) { + return promise.then( null, fn ); + }, + + // Keep pipe for back-compat + pipe: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + + return jQuery.Deferred( function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + + // Map tuples (progress, done, fail) to arguments (done, fail, progress) + var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; + + // deferred.progress(function() { bind to newDefer or newDefer.notify }) + // deferred.done(function() { bind to newDefer or newDefer.resolve }) + // deferred.fail(function() { bind to newDefer or newDefer.reject }) + deferred[ tuple[ 1 ] ]( function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .progress( newDefer.notify ) + .done( newDefer.resolve ) + .fail( newDefer.reject ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( + this, + fn ? [ returned ] : arguments + ); + } + } ); + } ); + fns = null; + } ).promise(); + }, + then: function( onFulfilled, onRejected, onProgress ) { + var maxDepth = 0; + function resolve( depth, deferred, handler, special ) { + return function() { + var that = this, + args = arguments, + mightThrow = function() { + var returned, then; + + // Support: Promises/A+ section 2.3.3.3.3 + // https://promisesaplus.com/#point-59 + // Ignore double-resolution attempts + if ( depth < maxDepth ) { + return; + } + + returned = handler.apply( that, args ); + + // Support: Promises/A+ section 2.3.1 + // https://promisesaplus.com/#point-48 + if ( returned === deferred.promise() ) { + throw new TypeError( "Thenable self-resolution" ); + } + + // Support: Promises/A+ sections 2.3.3.1, 3.5 + // https://promisesaplus.com/#point-54 + // https://promisesaplus.com/#point-75 + // Retrieve `then` only once + then = returned && + + // Support: Promises/A+ section 2.3.4 + // https://promisesaplus.com/#point-64 + // Only check objects and functions for thenability + ( typeof returned === "object" || + typeof returned === "function" ) && + returned.then; + + // Handle a returned thenable + if ( jQuery.isFunction( then ) ) { + + // Special processors (notify) just wait for resolution + if ( special ) { + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ) + ); + + // Normal processors (resolve) also hook into progress + } else { + + // ...and disregard older resolution values + maxDepth++; + + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ), + resolve( maxDepth, deferred, Identity, + deferred.notifyWith ) + ); + } + + // Handle all other returned values + } else { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Identity ) { + that = undefined; + args = [ returned ]; + } + + // Process the value(s) + // Default process is resolve + ( special || deferred.resolveWith )( that, args ); + } + }, + + // Only normal processors (resolve) catch and reject exceptions + process = special ? + mightThrow : + function() { + try { + mightThrow(); + } catch ( e ) { + + if ( jQuery.Deferred.exceptionHook ) { + jQuery.Deferred.exceptionHook( e, + process.stackTrace ); + } + + // Support: Promises/A+ section 2.3.3.3.4.1 + // https://promisesaplus.com/#point-61 + // Ignore post-resolution exceptions + if ( depth + 1 >= maxDepth ) { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Thrower ) { + that = undefined; + args = [ e ]; + } + + deferred.rejectWith( that, args ); + } + } + }; + + // Support: Promises/A+ section 2.3.3.3.1 + // https://promisesaplus.com/#point-57 + // Re-resolve promises immediately to dodge false rejection from + // subsequent errors + if ( depth ) { + process(); + } else { + + // Call an optional hook to record the stack, in case of exception + // since it's otherwise lost when execution goes async + if ( jQuery.Deferred.getStackHook ) { + process.stackTrace = jQuery.Deferred.getStackHook(); + } + window.setTimeout( process ); + } + }; + } + + return jQuery.Deferred( function( newDefer ) { + + // progress_handlers.add( ... ) + tuples[ 0 ][ 3 ].add( + resolve( + 0, + newDefer, + jQuery.isFunction( onProgress ) ? + onProgress : + Identity, + newDefer.notifyWith + ) + ); + + // fulfilled_handlers.add( ... ) + tuples[ 1 ][ 3 ].add( + resolve( + 0, + newDefer, + jQuery.isFunction( onFulfilled ) ? + onFulfilled : + Identity + ) + ); + + // rejected_handlers.add( ... ) + tuples[ 2 ][ 3 ].add( + resolve( + 0, + newDefer, + jQuery.isFunction( onRejected ) ? + onRejected : + Thrower + ) + ); + } ).promise(); + }, + + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 5 ]; + + // promise.progress = list.add + // promise.done = list.add + // promise.fail = list.add + promise[ tuple[ 1 ] ] = list.add; + + // Handle state + if ( stateString ) { + list.add( + function() { + + // state = "resolved" (i.e., fulfilled) + // state = "rejected" + state = stateString; + }, + + // rejected_callbacks.disable + // fulfilled_callbacks.disable + tuples[ 3 - i ][ 2 ].disable, + + // progress_callbacks.lock + tuples[ 0 ][ 2 ].lock + ); + } + + // progress_handlers.fire + // fulfilled_handlers.fire + // rejected_handlers.fire + list.add( tuple[ 3 ].fire ); + + // deferred.notify = function() { deferred.notifyWith(...) } + // deferred.resolve = function() { deferred.resolveWith(...) } + // deferred.reject = function() { deferred.rejectWith(...) } + deferred[ tuple[ 0 ] ] = function() { + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); + return this; + }; + + // deferred.notifyWith = list.fireWith + // deferred.resolveWith = list.fireWith + // deferred.rejectWith = list.fireWith + deferred[ tuple[ 0 ] + "With" ] = list.fireWith; + } ); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( singleValue ) { + var + + // count of uncompleted subordinates + remaining = arguments.length, + + // count of unprocessed arguments + i = remaining, + + // subordinate fulfillment data + resolveContexts = Array( i ), + resolveValues = slice.call( arguments ), + + // the master Deferred + master = jQuery.Deferred(), + + // subordinate callback factory + updateFunc = function( i ) { + return function( value ) { + resolveContexts[ i ] = this; + resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( !( --remaining ) ) { + master.resolveWith( resolveContexts, resolveValues ); + } + }; + }; + + // Single- and empty arguments are adopted like Promise.resolve + if ( remaining <= 1 ) { + adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, + !remaining ); + + // Use .then() to unwrap secondary thenables (cf. gh-3000) + if ( master.state() === "pending" || + jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { + + return master.then(); + } + } + + // Multiple arguments are aggregated like Promise.all array elements + while ( i-- ) { + adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); + } + + return master.promise(); + } +} ); + + +// These usually indicate a programmer mistake during development, +// warn about them ASAP rather than swallowing them by default. +var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; + +jQuery.Deferred.exceptionHook = function( error, stack ) { + + // Support: IE 8 - 9 only + // Console exists when dev tools are open, which can happen at any time + if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { + window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); + } +}; + + + + +jQuery.readyException = function( error ) { + window.setTimeout( function() { + throw error; + } ); +}; + + + + +// The deferred used on DOM ready +var readyList = jQuery.Deferred(); + +jQuery.fn.ready = function( fn ) { + + readyList + .then( fn ) + + // Wrap jQuery.readyException in a function so that the lookup + // happens at the time of error handling instead of callback + // registration. + .catch( function( error ) { + jQuery.readyException( error ); + } ); + + return this; +}; + +jQuery.extend( { + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + } +} ); + +jQuery.ready.then = readyList.then; + +// The ready event handler and self cleanup method +function completed() { + document.removeEventListener( "DOMContentLoaded", completed ); + window.removeEventListener( "load", completed ); + jQuery.ready(); +} + +// Catch cases where $(document).ready() is called +// after the browser event has already occurred. +// Support: IE <=9 - 10 only +// Older IE sometimes signals "interactive" too soon +if ( document.readyState === "complete" || + ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { + + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); + +} else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); +} + + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + access( elems, fn, i, key[ i ], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < len; i++ ) { + fn( + elems[ i ], key, raw ? + value : + value.call( elems[ i ], i, fn( elems[ i ], key ) ) + ); + } + } + } + + if ( chainable ) { + return elems; + } + + // Gets + if ( bulk ) { + return fn.call( elems ); + } + + return len ? fn( elems[ 0 ], key ) : emptyGet; +}; +var acceptData = function( owner ) { + + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +}; + + + + +function Data() { + this.expando = jQuery.expando + Data.uid++; +} + +Data.uid = 1; + +Data.prototype = { + + cache: function( owner ) { + + // Check if the owner object already has a cache + var value = owner[ this.expando ]; + + // If not, create one + if ( !value ) { + value = {}; + + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return an empty object. + if ( acceptData( owner ) ) { + + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; + + // Otherwise secure it in a non-enumerable property + // configurable must be true to allow the property to be + // deleted when data is removed + } else { + Object.defineProperty( owner, this.expando, { + value: value, + configurable: true + } ); + } + } + } + + return value; + }, + set: function( owner, data, value ) { + var prop, + cache = this.cache( owner ); + + // Handle: [ owner, key, value ] args + // Always use camelCase key (gh-2257) + if ( typeof data === "string" ) { + cache[ jQuery.camelCase( data ) ] = value; + + // Handle: [ owner, { properties } ] args + } else { + + // Copy the properties one-by-one to the cache object + for ( prop in data ) { + cache[ jQuery.camelCase( prop ) ] = data[ prop ]; + } + } + return cache; + }, + get: function( owner, key ) { + return key === undefined ? + this.cache( owner ) : + + // Always use camelCase key (gh-2257) + owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ]; + }, + access: function( owner, key, value ) { + + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ( ( key && typeof key === "string" ) && value === undefined ) ) { + + return this.get( owner, key ); + } + + // When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, + cache = owner[ this.expando ]; + + if ( cache === undefined ) { + return; + } + + if ( key !== undefined ) { + + // Support array or space separated string of keys + if ( Array.isArray( key ) ) { + + // If key is an array of keys... + // We always set camelCase keys, so remove that. + key = key.map( jQuery.camelCase ); + } else { + key = jQuery.camelCase( key ); + + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + key = key in cache ? + [ key ] : + ( key.match( rnothtmlwhite ) || [] ); + } + + i = key.length; + + while ( i-- ) { + delete cache[ key[ i ] ]; + } + } + + // Remove the expando if there's no more data + if ( key === undefined || jQuery.isEmptyObject( cache ) ) { + + // Support: Chrome <=35 - 45 + // Webkit & Blink performance suffers when deleting properties + // from DOM nodes, so set to undefined instead + // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) + if ( owner.nodeType ) { + owner[ this.expando ] = undefined; + } else { + delete owner[ this.expando ]; + } + } + }, + hasData: function( owner ) { + var cache = owner[ this.expando ]; + return cache !== undefined && !jQuery.isEmptyObject( cache ); + } +}; +var dataPriv = new Data(); + +var dataUser = new Data(); + + + +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /[A-Z]/g; + +function getData( data ) { + if ( data === "true" ) { + return true; + } + + if ( data === "false" ) { + return false; + } + + if ( data === "null" ) { + return null; + } + + // Only convert to a number if it doesn't change the string + if ( data === +data + "" ) { + return +data; + } + + if ( rbrace.test( data ) ) { + return JSON.parse( data ); + } + + return data; +} + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = getData( data ); + } catch ( e ) {} + + // Make sure we set the data so it isn't changed later + dataUser.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} + +jQuery.extend( { + hasData: function( elem ) { + return dataUser.hasData( elem ) || dataPriv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return dataUser.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + dataUser.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to dataPriv methods, these can be deprecated. + _data: function( elem, name, data ) { + return dataPriv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + dataPriv.remove( elem, name ); + } +} ); + +jQuery.fn.extend( { + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = dataUser.get( elem ); + + if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE 11 only + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.slice( 5 ) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + dataPriv.set( elem, "hasDataAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each( function() { + dataUser.set( this, key ); + } ); + } + + return access( this, function( value ) { + var data; + + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { + + // Attempt to get data from the cache + // The key will always be camelCased in Data + data = dataUser.get( elem, key ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, key ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; + } + + // Set the data... + this.each( function() { + + // We always store the camelCased key + dataUser.set( this, key, value ); + } ); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each( function() { + dataUser.remove( this, key ); + } ); + } +} ); + + +jQuery.extend( { + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = dataPriv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || Array.isArray( data ) ) { + queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // Clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // Not public - generate a queueHooks object, or return the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { + empty: jQuery.Callbacks( "once memory" ).add( function() { + dataPriv.remove( elem, [ type + "queue", key ] ); + } ) + } ); + } +} ); + +jQuery.fn.extend( { + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[ 0 ], type ); + } + + return data === undefined ? + this : + this.each( function() { + var queue = jQuery.queue( this, type, data ); + + // Ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + } ); + }, + dequeue: function( type ) { + return this.each( function() { + jQuery.dequeue( this, type ); + } ); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +} ); +var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; + +var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); + + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var isHiddenWithinTree = function( elem, el ) { + + // isHiddenWithinTree might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + + // Inline style trumps all + return elem.style.display === "none" || + elem.style.display === "" && + + // Otherwise, check computed style + // Support: Firefox <=43 - 45 + // Disconnected elements can have computed display: none, so first confirm that elem is + // in the document. + jQuery.contains( elem.ownerDocument, elem ) && + + jQuery.css( elem, "display" ) === "none"; + }; + +var swap = function( elem, options, callback, args ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.apply( elem, args || [] ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; +}; + + + + +function adjustCSS( elem, prop, valueParts, tween ) { + var adjusted, + scale = 1, + maxIterations = 20, + currentValue = tween ? + function() { + return tween.cur(); + } : + function() { + return jQuery.css( elem, prop, "" ); + }, + initial = currentValue(), + unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), + + // Starting value computation is required for potential unit mismatches + initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && + rcssNum.exec( jQuery.css( elem, prop ) ); + + if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { + + // Trust units reported by jQuery.css + unit = unit || initialInUnit[ 3 ]; + + // Make sure we update the tween properties later on + valueParts = valueParts || []; + + // Iteratively approximate from a nonzero starting point + initialInUnit = +initial || 1; + + do { + + // If previous iteration zeroed out, double until we get *something*. + // Use string for doubling so we don't accidentally see scale as unchanged below + scale = scale || ".5"; + + // Adjust and apply + initialInUnit = initialInUnit / scale; + jQuery.style( elem, prop, initialInUnit + unit ); + + // Update scale, tolerating zero or NaN from tween.cur() + // Break the loop if scale is unchanged or perfect, or if we've just had enough. + } while ( + scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations + ); + } + + if ( valueParts ) { + initialInUnit = +initialInUnit || +initial || 0; + + // Apply relative offset (+=/-=) if specified + adjusted = valueParts[ 1 ] ? + initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : + +valueParts[ 2 ]; + if ( tween ) { + tween.unit = unit; + tween.start = initialInUnit; + tween.end = adjusted; + } + } + return adjusted; +} + + +var defaultDisplayMap = {}; + +function getDefaultDisplay( elem ) { + var temp, + doc = elem.ownerDocument, + nodeName = elem.nodeName, + display = defaultDisplayMap[ nodeName ]; + + if ( display ) { + return display; + } + + temp = doc.body.appendChild( doc.createElement( nodeName ) ); + display = jQuery.css( temp, "display" ); + + temp.parentNode.removeChild( temp ); + + if ( display === "none" ) { + display = "block"; + } + defaultDisplayMap[ nodeName ] = display; + + return display; +} + +function showHide( elements, show ) { + var display, elem, + values = [], + index = 0, + length = elements.length; + + // Determine new display value for elements that need to change + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + display = elem.style.display; + if ( show ) { + + // Since we force visibility upon cascade-hidden elements, an immediate (and slow) + // check is required in this first loop unless we have a nonempty display value (either + // inline or about-to-be-restored) + if ( display === "none" ) { + values[ index ] = dataPriv.get( elem, "display" ) || null; + if ( !values[ index ] ) { + elem.style.display = ""; + } + } + if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { + values[ index ] = getDefaultDisplay( elem ); + } + } else { + if ( display !== "none" ) { + values[ index ] = "none"; + + // Remember what we're overwriting + dataPriv.set( elem, "display", display ); + } + } + } + + // Set the display of the elements in a second loop to avoid constant reflow + for ( index = 0; index < length; index++ ) { + if ( values[ index ] != null ) { + elements[ index ].style.display = values[ index ]; + } + } + + return elements; +} + +jQuery.fn.extend( { + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + if ( typeof state === "boolean" ) { + return state ? this.show() : this.hide(); + } + + return this.each( function() { + if ( isHiddenWithinTree( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + } ); + } +} ); +var rcheckableType = ( /^(?:checkbox|radio)$/i ); + +var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i ); + +var rscriptType = ( /^$|\/(?:java|ecma)script/i ); + + + +// We have to close these tags to support XHTML (#13200) +var wrapMap = { + + // Support: IE <=9 only + option: [ 1, "" ], + + // XHTML parsers do not magically insert elements in the + // same way that tag soup parsers do. So we cannot shorten + // this by omitting or other required elements. + thead: [ 1, "", "
" ], + col: [ 2, "", "
" ], + tr: [ 2, "", "
" ], + td: [ 3, "", "
" ], + + _default: [ 0, "", "" ] +}; + +// Support: IE <=9 only +wrapMap.optgroup = wrapMap.option; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + + +function getAll( context, tag ) { + + // Support: IE <=9 - 11 only + // Use typeof to avoid zero-argument method invocation on host objects (#15151) + var ret; + + if ( typeof context.getElementsByTagName !== "undefined" ) { + ret = context.getElementsByTagName( tag || "*" ); + + } else if ( typeof context.querySelectorAll !== "undefined" ) { + ret = context.querySelectorAll( tag || "*" ); + + } else { + ret = []; + } + + if ( tag === undefined || tag && nodeName( context, tag ) ) { + return jQuery.merge( [ context ], ret ); + } + + return ret; +} + + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + dataPriv.set( + elems[ i ], + "globalEval", + !refElements || dataPriv.get( refElements[ i ], "globalEval" ) + ); + } +} + + +var rhtml = /<|&#?\w+;/; + +function buildFragment( elems, context, scripts, selection, ignored ) { + var elem, tmp, tag, wrap, contains, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (#12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { + + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; +} + + +( function() { + var fragment = document.createDocumentFragment(), + div = fragment.appendChild( document.createElement( "div" ) ), + input = document.createElement( "input" ); + + // Support: Android 4.0 - 4.3 only + // Check state lost if the name is set (#11217) + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (#14901) + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + + // Support: Android <=4.1 only + // Older WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE <=11 only + // Make sure textarea (and checkbox) defaultValue is properly cloned + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; +} )(); +var documentElement = document.documentElement; + + + +var + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +// Support: IE <=9 only +// See #13393 for more info +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +function on( elem, types, selector, data, fn, one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + on( elem, type, selector, data, types[ type ], one ); + } + return elem; + } + + if ( data == null && fn == null ) { + + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return elem; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return elem.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + } ); +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.get( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Ensure that invalid selectors throw exceptions at attach time + // Evaluate against documentElement in case elem is a non-element node (e.g., document) + if ( selector ) { + jQuery.find.matchesSelector( documentElement, selector ); + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !( events = elemData.events ) ) { + events = elemData.events = {}; + } + if ( !( eventHandle = elemData.handle ) ) { + eventHandle = elemData.handle = function( e ) { + + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend( { + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join( "." ) + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !( handlers = events[ type ] ) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || + special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); + + if ( !elemData || !( events = elemData.events ) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[ 2 ] && + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || + selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || + special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove data and the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + dataPriv.remove( elem, "handle events" ); + } + }, + + dispatch: function( nativeEvent ) { + + // Make a writable jQuery.Event from the native event object + var event = jQuery.event.fix( nativeEvent ); + + var i, j, ret, matched, handleObj, handlerQueue, + args = new Array( arguments.length ), + handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + + for ( i = 1; i < arguments.length; i++ ) { + args[ i ] = arguments[ i ]; + } + + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( ( handleObj = matched.handlers[ j++ ] ) && + !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or 2) have namespace(s) + // a subset or equal to those in the bound event (both can have no namespace). + if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || + handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( ( event.result = ret ) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, handleObj, sel, matchedHandlers, matchedSelectors, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + if ( delegateCount && + + // Support: IE <=9 + // Black-hole SVG instance trees (trac-13180) + cur.nodeType && + + // Support: Firefox <=42 + // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) + // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click + // Support: IE 11 only + // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) + !( event.type === "click" && event.button >= 1 ) ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { + matchedHandlers = []; + matchedSelectors = {}; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matchedSelectors[ sel ] === undefined ) { + matchedSelectors[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matchedSelectors[ sel ] ) { + matchedHandlers.push( handleObj ); + } + } + if ( matchedHandlers.length ) { + handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); + } + } + } + } + + // Add the remaining (directly-bound) handlers + cur = this; + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); + } + + return handlerQueue; + }, + + addProp: function( name, hook ) { + Object.defineProperty( jQuery.Event.prototype, name, { + enumerable: true, + configurable: true, + + get: jQuery.isFunction( hook ) ? + function() { + if ( this.originalEvent ) { + return hook( this.originalEvent ); + } + } : + function() { + if ( this.originalEvent ) { + return this.originalEvent[ name ]; + } + }, + + set: function( value ) { + Object.defineProperty( this, name, { + enumerable: true, + configurable: true, + writable: true, + value: value + } ); + } + } ); + }, + + fix: function( originalEvent ) { + return originalEvent[ jQuery.expando ] ? + originalEvent : + new jQuery.Event( originalEvent ); + }, + + special: { + load: { + + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { + + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + this.focus(); + return false; + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { + + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) { + this.click(); + return false; + } + }, + + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return nodeName( event.target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + } +}; + +jQuery.removeEvent = function( elem, type, handle ) { + + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle ); + } +}; + +jQuery.Event = function( src, props ) { + + // Allow instantiation without the 'new' keyword + if ( !( this instanceof jQuery.Event ) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + + // Support: Android <=2.3 only + src.returnValue === false ? + returnTrue : + returnFalse; + + // Create target properties + // Support: Safari <=6 - 7 only + // Target should not be a text node (#504, #13143) + this.target = ( src.target && src.target.nodeType === 3 ) ? + src.target.parentNode : + src.target; + + this.currentTarget = src.currentTarget; + this.relatedTarget = src.relatedTarget; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + constructor: jQuery.Event, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + isSimulated: false, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e && !this.isSimulated ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Includes all common event props including KeyEvent and MouseEvent specific props +jQuery.each( { + altKey: true, + bubbles: true, + cancelable: true, + changedTouches: true, + ctrlKey: true, + detail: true, + eventPhase: true, + metaKey: true, + pageX: true, + pageY: true, + shiftKey: true, + view: true, + "char": true, + charCode: true, + key: true, + keyCode: true, + button: true, + buttons: true, + clientX: true, + clientY: true, + offsetX: true, + offsetY: true, + pointerId: true, + pointerType: true, + screenX: true, + screenY: true, + targetTouches: true, + toElement: true, + touches: true, + + which: function( event ) { + var button = event.button; + + // Add which for key events + if ( event.which == null && rkeyEvent.test( event.type ) ) { + return event.charCode != null ? event.charCode : event.keyCode; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { + if ( button & 1 ) { + return 1; + } + + if ( button & 2 ) { + return 3; + } + + if ( button & 4 ) { + return 2; + } + + return 0; + } + + return event.which; + } +}, jQuery.event.addProp ); + +// Create mouseenter/leave events using mouseover/out and event-time checks +// so that event delegation works in jQuery. +// Do the same for pointerenter/pointerleave and pointerover/pointerout +// +// Support: Safari 7 only +// Safari sends mouseenter too often; see: +// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 +// for the description of the bug (it existed in older Chrome versions as well). +jQuery.each( { + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mouseenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +} ); + +jQuery.fn.extend( { + + on: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn ); + }, + one: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? + handleObj.origType + "." + handleObj.namespace : + handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each( function() { + jQuery.event.remove( this, types, fn, selector ); + } ); + } +} ); + + +var + + /* eslint-disable max-len */ + + // See https://github.com/eslint/eslint/issues/3229 + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, + + /* eslint-enable */ + + // Support: IE <=10 - 11, Edge 12 - 13 + // In IE/Edge using regex groups here causes severe slowdowns. + // See https://connect.microsoft.com/IE/feedback/details/1736512/ + rnoInnerhtml = /\s*$/g; + +// Prefer a tbody over its parent table for containing new rows +function manipulationTarget( elem, content ) { + if ( nodeName( elem, "table" ) && + nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { + + return jQuery( ">tbody", elem )[ 0 ] || elem; + } + + return elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + + if ( match ) { + elem.type = match[ 1 ]; + } else { + elem.removeAttribute( "type" ); + } + + return elem; +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( dataPriv.hasData( src ) ) { + pdataOld = dataPriv.access( src ); + pdataCur = dataPriv.set( dest, pdataOld ); + events = pdataOld.events; + + if ( events ) { + delete pdataCur.handle; + pdataCur.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( dataUser.hasData( src ) ) { + udataOld = dataUser.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + dataUser.set( dest, udataCur ); + } +} + +// Fix IE bugs, see support tests +function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +function domManip( collection, args, callback, ignored ) { + + // Flatten any nested arrays + args = concat.apply( [], args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = collection.length, + iNoClone = l - 1, + value = args[ 0 ], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return collection.each( function( index ) { + var self = collection.eq( index ); + if ( isFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + domManip( self, args, callback, ignored ); + } ); + } + + if ( l ) { + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item + // instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( collection[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !dataPriv.access( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { + + if ( node.src ) { + + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl ) { + jQuery._evalUrl( node.src ); + } + } else { + DOMEval( node.textContent.replace( rcleanScript, "" ), doc ); + } + } + } + } + } + } + + return collection; +} + +function remove( elem, selector, keepData ) { + var node, + nodes = selector ? jQuery.filter( selector, elem ) : elem, + i = 0; + + for ( ; ( node = nodes[ i ] ) != null; i++ ) { + if ( !keepData && node.nodeType === 1 ) { + jQuery.cleanData( getAll( node ) ); + } + + if ( node.parentNode ) { + if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { + setGlobalEval( getAll( node, "script" ) ); + } + node.parentNode.removeChild( node ); + } + } + + return elem; +} + +jQuery.extend( { + htmlPrefilter: function( html ) { + return html.replace( rxhtmlTag, "<$1>" ); + }, + + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = jQuery.contains( elem.ownerDocument, elem ); + + // Fix IE cloning issues + if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && + !jQuery.isXMLDoc( elem ) ) { + + // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], destElements[ i ] ); + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + cleanData: function( elems ) { + var data, elem, type, + special = jQuery.event.special, + i = 0; + + for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { + if ( acceptData( elem ) ) { + if ( ( data = elem[ dataPriv.expando ] ) ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataPriv.expando ] = undefined; + } + if ( elem[ dataUser.expando ] ) { + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataUser.expando ] = undefined; + } + } + } + } +} ); + +jQuery.fn.extend( { + detach: function( selector ) { + return remove( this, selector, true ); + }, + + remove: function( selector ) { + return remove( this, selector ); + }, + + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().each( function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + } ); + }, null, value, arguments.length ); + }, + + append: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + } ); + }, + + prepend: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + } ); + }, + + before: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + } ); + }, + + after: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + } ); + }, + + empty: function() { + var elem, + i = 0; + + for ( ; ( elem = this[ i ] ) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + } ); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = jQuery.htmlPrefilter( value ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch ( e ) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var ignored = []; + + // Make the changes, replacing each non-ignored context element with the new content + return domManip( this, arguments, function( elem ) { + var parent = this.parentNode; + + if ( jQuery.inArray( this, ignored ) < 0 ) { + jQuery.cleanData( getAll( this ) ); + if ( parent ) { + parent.replaceChild( elem, this ); + } + } + + // Force callback invocation + }, ignored ); + } +} ); + +jQuery.each( { + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + + // Support: Android <=4.0 only, PhantomJS 1 only + // .get() because push.apply(_, arraylike) throws on ancient WebKit + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +} ); +var rmargin = ( /^margin/ ); + +var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); + +var getStyles = function( elem ) { + + // Support: IE <=11 only, Firefox <=30 (#15098, #14150) + // IE throws on elements created in popups + // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" + var view = elem.ownerDocument.defaultView; + + if ( !view || !view.opener ) { + view = window; + } + + return view.getComputedStyle( elem ); + }; + + + +( function() { + + // Executing both pixelPosition & boxSizingReliable tests require only one layout + // so they're executed at the same time to save the second computation. + function computeStyleTests() { + + // This is a singleton, we need to execute it only once + if ( !div ) { + return; + } + + div.style.cssText = + "box-sizing:border-box;" + + "position:relative;display:block;" + + "margin:auto;border:1px;padding:1px;" + + "top:1%;width:50%"; + div.innerHTML = ""; + documentElement.appendChild( container ); + + var divStyle = window.getComputedStyle( div ); + pixelPositionVal = divStyle.top !== "1%"; + + // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 + reliableMarginLeftVal = divStyle.marginLeft === "2px"; + boxSizingReliableVal = divStyle.width === "4px"; + + // Support: Android 4.0 - 4.3 only + // Some styles come back with percentage values, even though they shouldn't + div.style.marginRight = "50%"; + pixelMarginRightVal = divStyle.marginRight === "4px"; + + documentElement.removeChild( container ); + + // Nullify the div so it wouldn't be stored in the memory and + // it will also be a sign that checks already performed + div = null; + } + + var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal, + container = document.createElement( "div" ), + div = document.createElement( "div" ); + + // Finish early in limited (non-browser) environments + if ( !div.style ) { + return; + } + + // Support: IE <=9 - 11 only + // Style of cloned element affects source element cloned (#8908) + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + + "padding:0;margin-top:1px;position:absolute"; + container.appendChild( div ); + + jQuery.extend( support, { + pixelPosition: function() { + computeStyleTests(); + return pixelPositionVal; + }, + boxSizingReliable: function() { + computeStyleTests(); + return boxSizingReliableVal; + }, + pixelMarginRight: function() { + computeStyleTests(); + return pixelMarginRightVal; + }, + reliableMarginLeft: function() { + computeStyleTests(); + return reliableMarginLeftVal; + } + } ); +} )(); + + +function curCSS( elem, name, computed ) { + var width, minWidth, maxWidth, ret, + + // Support: Firefox 51+ + // Retrieving style before computed somehow + // fixes an issue with getting wrong values + // on detached elements + style = elem.style; + + computed = computed || getStyles( elem ); + + // getPropertyValue is needed for: + // .css('filter') (IE 9 only, #12537) + // .css('--customProperty) (#3144) + if ( computed ) { + ret = computed.getPropertyValue( name ) || computed[ name ]; + + if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Android Browser returns percentage for some values, + // but width seems to be reliably pixels. + // This is against the CSSOM draft spec: + // https://drafts.csswg.org/cssom/#resolved-values + if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret !== undefined ? + + // Support: IE <=9 - 11 only + // IE returns zIndex value as an integer. + ret + "" : + ret; +} + + +function addGetHookIf( conditionFn, hookFn ) { + + // Define the hook, we'll check on the first run if it's really needed. + return { + get: function() { + if ( conditionFn() ) { + + // Hook not needed (or it's not possible to use it due + // to missing dependency), remove it. + delete this.get; + return; + } + + // Hook needed; redefine it so that the support test is not executed again. + return ( this.get = hookFn ).apply( this, arguments ); + } + }; +} + + +var + + // Swappable if display is none or starts with table + // except "table", "table-cell", or "table-caption" + // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + rcustomProp = /^--/, + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: "0", + fontWeight: "400" + }, + + cssPrefixes = [ "Webkit", "Moz", "ms" ], + emptyStyle = document.createElement( "div" ).style; + +// Return a css property mapped to a potentially vendor prefixed property +function vendorPropName( name ) { + + // Shortcut for names that are not vendor prefixed + if ( name in emptyStyle ) { + return name; + } + + // Check for vendor prefixed names + var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in emptyStyle ) { + return name; + } + } +} + +// Return a property mapped along what jQuery.cssProps suggests or to +// a vendor prefixed property. +function finalPropName( name ) { + var ret = jQuery.cssProps[ name ]; + if ( !ret ) { + ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name; + } + return ret; +} + +function setPositiveNumber( elem, value, subtract ) { + + // Any relative (+/-) values have already been + // normalized at this point + var matches = rcssNum.exec( value ); + return matches ? + + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : + value; +} + +function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { + var i, + val = 0; + + // If we already have the right measurement, avoid augmentation + if ( extra === ( isBorderBox ? "border" : "content" ) ) { + i = 4; + + // Otherwise initialize for horizontal or vertical properties + } else { + i = name === "width" ? 1 : 0; + } + + for ( ; i < 4; i += 2 ) { + + // Both box models exclude margin, so add it if we want it + if ( extra === "margin" ) { + val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); + } + + if ( isBorderBox ) { + + // border-box includes padding, so remove it if we want content + if ( extra === "content" ) { + val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // At this point, extra isn't border nor margin, so remove border + if ( extra !== "margin" ) { + val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } else { + + // At this point, extra isn't content, so add padding + val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // At this point, extra isn't content nor padding, so add border + if ( extra !== "padding" ) { + val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + return val; +} + +function getWidthOrHeight( elem, name, extra ) { + + // Start with computed style + var valueIsBorderBox, + styles = getStyles( elem ), + val = curCSS( elem, name, styles ), + isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // Computed unit is not pixels. Stop here and return. + if ( rnumnonpx.test( val ) ) { + return val; + } + + // Check for style in case a browser which returns unreliable values + // for getComputedStyle silently falls back to the reliable elem.style + valueIsBorderBox = isBorderBox && + ( support.boxSizingReliable() || val === elem.style[ name ] ); + + // Fall back to offsetWidth/Height when value is "auto" + // This happens for inline elements with no explicit setting (gh-3571) + if ( val === "auto" ) { + val = elem[ "offset" + name[ 0 ].toUpperCase() + name.slice( 1 ) ]; + } + + // Normalize "", auto, and prepare for extra + val = parseFloat( val ) || 0; + + // Use the active box-sizing model to add/subtract irrelevant styles + return ( val + + augmentWidthOrHeight( + elem, + name, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles + ) + ) + "px"; +} + +jQuery.extend( { + + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Don't automatically add "px" to these possibly-unitless properties + cssNumber: { + "animationIterationCount": true, + "columnCount": true, + "fillOpacity": true, + "flexGrow": true, + "flexShrink": true, + "fontWeight": true, + "lineHeight": true, + "opacity": true, + "order": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: { + "float": "cssFloat" + }, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = jQuery.camelCase( name ), + isCustomProp = rcustomProp.test( name ), + style = elem.style; + + // Make sure that we're working with the right name. We don't + // want to query the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Gets hook for the prefixed version, then unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // Convert "+=" or "-=" to relative numbers (#7345) + if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { + value = adjustCSS( elem, name, ret ); + + // Fixes bug #9237 + type = "number"; + } + + // Make sure that null and NaN values aren't set (#7116) + if ( value == null || value !== value ) { + return; + } + + // If a number was passed in, add the unit (except for certain CSS properties) + if ( type === "number" ) { + value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); + } + + // background-* props affect original clone's values + if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !( "set" in hooks ) || + ( value = hooks.set( elem, value, extra ) ) !== undefined ) { + + if ( isCustomProp ) { + style.setProperty( name, value ); + } else { + style[ name ] = value; + } + } + + } else { + + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && + ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { + + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var val, num, hooks, + origName = jQuery.camelCase( name ), + isCustomProp = rcustomProp.test( name ); + + // Make sure that we're working with the right name. We don't + // want to modify the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Try prefixed name followed by the unprefixed name + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + // Convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Make numeric if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || isFinite( num ) ? num || 0 : val; + } + + return val; + } +} ); + +jQuery.each( [ "height", "width" ], function( i, name ) { + jQuery.cssHooks[ name ] = { + get: function( elem, computed, extra ) { + if ( computed ) { + + // Certain elements can have dimension info if we invisibly show them + // but it must have a current display style that would benefit + return rdisplayswap.test( jQuery.css( elem, "display" ) ) && + + // Support: Safari 8+ + // Table columns in Safari have non-zero offsetWidth & zero + // getBoundingClientRect().width unless display is changed. + // Support: IE <=11 only + // Running getBoundingClientRect on a disconnected node + // in IE throws an error. + ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? + swap( elem, cssShow, function() { + return getWidthOrHeight( elem, name, extra ); + } ) : + getWidthOrHeight( elem, name, extra ); + } + }, + + set: function( elem, value, extra ) { + var matches, + styles = extra && getStyles( elem ), + subtract = extra && augmentWidthOrHeight( + elem, + name, + extra, + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + styles + ); + + // Convert to pixels if value adjustment is needed + if ( subtract && ( matches = rcssNum.exec( value ) ) && + ( matches[ 3 ] || "px" ) !== "px" ) { + + elem.style[ name ] = value; + value = jQuery.css( elem, name ); + } + + return setPositiveNumber( elem, value, subtract ); + } + }; +} ); + +jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, + function( elem, computed ) { + if ( computed ) { + return ( parseFloat( curCSS( elem, "marginLeft" ) ) || + elem.getBoundingClientRect().left - + swap( elem, { marginLeft: 0 }, function() { + return elem.getBoundingClientRect().left; + } ) + ) + "px"; + } + } +); + +// These hooks are used by animate to expand properties +jQuery.each( { + margin: "", + padding: "", + border: "Width" +}, function( prefix, suffix ) { + jQuery.cssHooks[ prefix + suffix ] = { + expand: function( value ) { + var i = 0, + expanded = {}, + + // Assumes a single number if not a string + parts = typeof value === "string" ? value.split( " " ) : [ value ]; + + for ( ; i < 4; i++ ) { + expanded[ prefix + cssExpand[ i ] + suffix ] = + parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; + } + + return expanded; + } + }; + + if ( !rmargin.test( prefix ) ) { + jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; + } +} ); + +jQuery.fn.extend( { + css: function( name, value ) { + return access( this, function( elem, name, value ) { + var styles, len, + map = {}, + i = 0; + + if ( Array.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + } +} ); + + +function Tween( elem, options, prop, end, easing ) { + return new Tween.prototype.init( elem, options, prop, end, easing ); +} +jQuery.Tween = Tween; + +Tween.prototype = { + constructor: Tween, + init: function( elem, options, prop, end, easing, unit ) { + this.elem = elem; + this.prop = prop; + this.easing = easing || jQuery.easing._default; + this.options = options; + this.start = this.now = this.cur(); + this.end = end; + this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + }, + cur: function() { + var hooks = Tween.propHooks[ this.prop ]; + + return hooks && hooks.get ? + hooks.get( this ) : + Tween.propHooks._default.get( this ); + }, + run: function( percent ) { + var eased, + hooks = Tween.propHooks[ this.prop ]; + + if ( this.options.duration ) { + this.pos = eased = jQuery.easing[ this.easing ]( + percent, this.options.duration * percent, 0, 1, this.options.duration + ); + } else { + this.pos = eased = percent; + } + this.now = ( this.end - this.start ) * eased + this.start; + + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + if ( hooks && hooks.set ) { + hooks.set( this ); + } else { + Tween.propHooks._default.set( this ); + } + return this; + } +}; + +Tween.prototype.init.prototype = Tween.prototype; + +Tween.propHooks = { + _default: { + get: function( tween ) { + var result; + + // Use a property on the element directly when it is not a DOM element, + // or when there is no matching style property that exists. + if ( tween.elem.nodeType !== 1 || + tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { + return tween.elem[ tween.prop ]; + } + + // Passing an empty string as a 3rd parameter to .css will automatically + // attempt a parseFloat and fallback to a string if the parse fails. + // Simple values such as "10px" are parsed to Float; + // complex values such as "rotate(1rad)" are returned as-is. + result = jQuery.css( tween.elem, tween.prop, "" ); + + // Empty strings, null, undefined and "auto" are converted to 0. + return !result || result === "auto" ? 0 : result; + }, + set: function( tween ) { + + // Use step hook for back compat. + // Use cssHook if its there. + // Use .style if available and use plain properties where available. + if ( jQuery.fx.step[ tween.prop ] ) { + jQuery.fx.step[ tween.prop ]( tween ); + } else if ( tween.elem.nodeType === 1 && + ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || + jQuery.cssHooks[ tween.prop ] ) ) { + jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); + } else { + tween.elem[ tween.prop ] = tween.now; + } + } + } +}; + +// Support: IE <=9 only +// Panic based approach to setting things on disconnected nodes +Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { + set: function( tween ) { + if ( tween.elem.nodeType && tween.elem.parentNode ) { + tween.elem[ tween.prop ] = tween.now; + } + } +}; + +jQuery.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p * Math.PI ) / 2; + }, + _default: "swing" +}; + +jQuery.fx = Tween.prototype.init; + +// Back compat <1.8 extension point +jQuery.fx.step = {}; + + + + +var + fxNow, inProgress, + rfxtypes = /^(?:toggle|show|hide)$/, + rrun = /queueHooks$/; + +function schedule() { + if ( inProgress ) { + if ( document.hidden === false && window.requestAnimationFrame ) { + window.requestAnimationFrame( schedule ); + } else { + window.setTimeout( schedule, jQuery.fx.interval ); + } + + jQuery.fx.tick(); + } +} + +// Animations created synchronously will run synchronously +function createFxNow() { + window.setTimeout( function() { + fxNow = undefined; + } ); + return ( fxNow = jQuery.now() ); +} + +// Generate parameters to create a standard animation +function genFx( type, includeWidth ) { + var which, + i = 0, + attrs = { height: type }; + + // If we include width, step value is 1 to do all cssExpand values, + // otherwise step value is 2 to skip over Left and Right + includeWidth = includeWidth ? 1 : 0; + for ( ; i < 4; i += 2 - includeWidth ) { + which = cssExpand[ i ]; + attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; + } + + if ( includeWidth ) { + attrs.opacity = attrs.width = type; + } + + return attrs; +} + +function createTween( value, prop, animation ) { + var tween, + collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { + + // We're done with this property + return tween; + } + } +} + +function defaultPrefilter( elem, props, opts ) { + var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, + isBox = "width" in props || "height" in props, + anim = this, + orig = {}, + style = elem.style, + hidden = elem.nodeType && isHiddenWithinTree( elem ), + dataShow = dataPriv.get( elem, "fxshow" ); + + // Queue-skipping animations hijack the fx hooks + if ( !opts.queue ) { + hooks = jQuery._queueHooks( elem, "fx" ); + if ( hooks.unqueued == null ) { + hooks.unqueued = 0; + oldfire = hooks.empty.fire; + hooks.empty.fire = function() { + if ( !hooks.unqueued ) { + oldfire(); + } + }; + } + hooks.unqueued++; + + anim.always( function() { + + // Ensure the complete handler is called before this completes + anim.always( function() { + hooks.unqueued--; + if ( !jQuery.queue( elem, "fx" ).length ) { + hooks.empty.fire(); + } + } ); + } ); + } + + // Detect show/hide animations + for ( prop in props ) { + value = props[ prop ]; + if ( rfxtypes.test( value ) ) { + delete props[ prop ]; + toggle = toggle || value === "toggle"; + if ( value === ( hidden ? "hide" : "show" ) ) { + + // Pretend to be hidden if this is a "show" and + // there is still data from a stopped show/hide + if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { + hidden = true; + + // Ignore all other no-op show/hide data + } else { + continue; + } + } + orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); + } + } + + // Bail out if this is a no-op like .hide().hide() + propTween = !jQuery.isEmptyObject( props ); + if ( !propTween && jQuery.isEmptyObject( orig ) ) { + return; + } + + // Restrict "overflow" and "display" styles during box animations + if ( isBox && elem.nodeType === 1 ) { + + // Support: IE <=9 - 11, Edge 12 - 13 + // Record all 3 overflow attributes because IE does not infer the shorthand + // from identically-valued overflowX and overflowY + opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; + + // Identify a display type, preferring old show/hide data over the CSS cascade + restoreDisplay = dataShow && dataShow.display; + if ( restoreDisplay == null ) { + restoreDisplay = dataPriv.get( elem, "display" ); + } + display = jQuery.css( elem, "display" ); + if ( display === "none" ) { + if ( restoreDisplay ) { + display = restoreDisplay; + } else { + + // Get nonempty value(s) by temporarily forcing visibility + showHide( [ elem ], true ); + restoreDisplay = elem.style.display || restoreDisplay; + display = jQuery.css( elem, "display" ); + showHide( [ elem ] ); + } + } + + // Animate inline elements as inline-block + if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { + if ( jQuery.css( elem, "float" ) === "none" ) { + + // Restore the original display value at the end of pure show/hide animations + if ( !propTween ) { + anim.done( function() { + style.display = restoreDisplay; + } ); + if ( restoreDisplay == null ) { + display = style.display; + restoreDisplay = display === "none" ? "" : display; + } + } + style.display = "inline-block"; + } + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + anim.always( function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + } ); + } + + // Implement show/hide animations + propTween = false; + for ( prop in orig ) { + + // General show/hide setup for this element animation + if ( !propTween ) { + if ( dataShow ) { + if ( "hidden" in dataShow ) { + hidden = dataShow.hidden; + } + } else { + dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); + } + + // Store hidden/visible for toggle so `.stop().toggle()` "reverses" + if ( toggle ) { + dataShow.hidden = !hidden; + } + + // Show elements before animating them + if ( hidden ) { + showHide( [ elem ], true ); + } + + /* eslint-disable no-loop-func */ + + anim.done( function() { + + /* eslint-enable no-loop-func */ + + // The final step of a "hide" animation is actually hiding the element + if ( !hidden ) { + showHide( [ elem ] ); + } + dataPriv.remove( elem, "fxshow" ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + } ); + } + + // Per-property setup + propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = propTween.start; + if ( hidden ) { + propTween.end = propTween.start; + propTween.start = 0; + } + } + } +} + +function propFilter( props, specialEasing ) { + var index, name, easing, value, hooks; + + // camelCase, specialEasing and expand cssHook pass + for ( index in props ) { + name = jQuery.camelCase( index ); + easing = specialEasing[ name ]; + value = props[ index ]; + if ( Array.isArray( value ) ) { + easing = value[ 1 ]; + value = props[ index ] = value[ 0 ]; + } + + if ( index !== name ) { + props[ name ] = value; + delete props[ index ]; + } + + hooks = jQuery.cssHooks[ name ]; + if ( hooks && "expand" in hooks ) { + value = hooks.expand( value ); + delete props[ name ]; + + // Not quite $.extend, this won't overwrite existing keys. + // Reusing 'index' because we have the correct "name" + for ( index in value ) { + if ( !( index in props ) ) { + props[ index ] = value[ index ]; + specialEasing[ index ] = easing; + } + } + } else { + specialEasing[ name ] = easing; + } + } +} + +function Animation( elem, properties, options ) { + var result, + stopped, + index = 0, + length = Animation.prefilters.length, + deferred = jQuery.Deferred().always( function() { + + // Don't match elem in the :animated selector + delete tick.elem; + } ), + tick = function() { + if ( stopped ) { + return false; + } + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + + // Support: Android 2.3 only + // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) + temp = remaining / animation.duration || 0, + percent = 1 - temp, + index = 0, + length = animation.tweens.length; + + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( percent ); + } + + deferred.notifyWith( elem, [ animation, percent, remaining ] ); + + // If there's more to do, yield + if ( percent < 1 && length ) { + return remaining; + } + + // If this was an empty animation, synthesize a final progress notification + if ( !length ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + } + + // Resolve the animation and report its conclusion + deferred.resolveWith( elem, [ animation ] ); + return false; + }, + animation = deferred.promise( { + elem: elem, + props: jQuery.extend( {}, properties ), + opts: jQuery.extend( true, { + specialEasing: {}, + easing: jQuery.easing._default + }, options ), + originalProperties: properties, + originalOptions: options, + startTime: fxNow || createFxNow(), + duration: options.duration, + tweens: [], + createTween: function( prop, end ) { + var tween = jQuery.Tween( elem, animation.opts, prop, end, + animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.tweens.push( tween ); + return tween; + }, + stop: function( gotoEnd ) { + var index = 0, + + // If we are going to the end, we want to run all the tweens + // otherwise we skip this part + length = gotoEnd ? animation.tweens.length : 0; + if ( stopped ) { + return this; + } + stopped = true; + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( 1 ); + } + + // Resolve when we played the last frame; otherwise, reject + if ( gotoEnd ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + deferred.resolveWith( elem, [ animation, gotoEnd ] ); + } else { + deferred.rejectWith( elem, [ animation, gotoEnd ] ); + } + return this; + } + } ), + props = animation.props; + + propFilter( props, animation.opts.specialEasing ); + + for ( ; index < length; index++ ) { + result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); + if ( result ) { + if ( jQuery.isFunction( result.stop ) ) { + jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = + jQuery.proxy( result.stop, result ); + } + return result; + } + } + + jQuery.map( props, createTween, animation ); + + if ( jQuery.isFunction( animation.opts.start ) ) { + animation.opts.start.call( elem, animation ); + } + + // Attach callbacks from options + animation + .progress( animation.opts.progress ) + .done( animation.opts.done, animation.opts.complete ) + .fail( animation.opts.fail ) + .always( animation.opts.always ); + + jQuery.fx.timer( + jQuery.extend( tick, { + elem: elem, + anim: animation, + queue: animation.opts.queue + } ) + ); + + return animation; +} + +jQuery.Animation = jQuery.extend( Animation, { + + tweeners: { + "*": [ function( prop, value ) { + var tween = this.createTween( prop, value ); + adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); + return tween; + } ] + }, + + tweener: function( props, callback ) { + if ( jQuery.isFunction( props ) ) { + callback = props; + props = [ "*" ]; + } else { + props = props.match( rnothtmlwhite ); + } + + var prop, + index = 0, + length = props.length; + + for ( ; index < length; index++ ) { + prop = props[ index ]; + Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; + Animation.tweeners[ prop ].unshift( callback ); + } + }, + + prefilters: [ defaultPrefilter ], + + prefilter: function( callback, prepend ) { + if ( prepend ) { + Animation.prefilters.unshift( callback ); + } else { + Animation.prefilters.push( callback ); + } + } +} ); + +jQuery.speed = function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { + complete: fn || !fn && easing || + jQuery.isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing + }; + + // Go to the end state if fx are off + if ( jQuery.fx.off ) { + opt.duration = 0; + + } else { + if ( typeof opt.duration !== "number" ) { + if ( opt.duration in jQuery.fx.speeds ) { + opt.duration = jQuery.fx.speeds[ opt.duration ]; + + } else { + opt.duration = jQuery.fx.speeds._default; + } + } + } + + // Normalize opt.queue - true/undefined/null -> "fx" + if ( opt.queue == null || opt.queue === true ) { + opt.queue = "fx"; + } + + // Queueing + opt.old = opt.complete; + + opt.complete = function() { + if ( jQuery.isFunction( opt.old ) ) { + opt.old.call( this ); + } + + if ( opt.queue ) { + jQuery.dequeue( this, opt.queue ); + } + }; + + return opt; +}; + +jQuery.fn.extend( { + fadeTo: function( speed, to, easing, callback ) { + + // Show any hidden elements after setting opacity to 0 + return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() + + // Animate to the value specified + .end().animate( { opacity: to }, speed, easing, callback ); + }, + animate: function( prop, speed, easing, callback ) { + var empty = jQuery.isEmptyObject( prop ), + optall = jQuery.speed( speed, easing, callback ), + doAnimation = function() { + + // Operate on a copy of prop so per-property easing won't be lost + var anim = Animation( this, jQuery.extend( {}, prop ), optall ); + + // Empty animations, or finishing resolves immediately + if ( empty || dataPriv.get( this, "finish" ) ) { + anim.stop( true ); + } + }; + doAnimation.finish = doAnimation; + + return empty || optall.queue === false ? + this.each( doAnimation ) : + this.queue( optall.queue, doAnimation ); + }, + stop: function( type, clearQueue, gotoEnd ) { + var stopQueue = function( hooks ) { + var stop = hooks.stop; + delete hooks.stop; + stop( gotoEnd ); + }; + + if ( typeof type !== "string" ) { + gotoEnd = clearQueue; + clearQueue = type; + type = undefined; + } + if ( clearQueue && type !== false ) { + this.queue( type || "fx", [] ); + } + + return this.each( function() { + var dequeue = true, + index = type != null && type + "queueHooks", + timers = jQuery.timers, + data = dataPriv.get( this ); + + if ( index ) { + if ( data[ index ] && data[ index ].stop ) { + stopQueue( data[ index ] ); + } + } else { + for ( index in data ) { + if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { + stopQueue( data[ index ] ); + } + } + } + + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && + ( type == null || timers[ index ].queue === type ) ) { + + timers[ index ].anim.stop( gotoEnd ); + dequeue = false; + timers.splice( index, 1 ); + } + } + + // Start the next in the queue if the last step wasn't forced. + // Timers currently will call their complete callbacks, which + // will dequeue but only if they were gotoEnd. + if ( dequeue || !gotoEnd ) { + jQuery.dequeue( this, type ); + } + } ); + }, + finish: function( type ) { + if ( type !== false ) { + type = type || "fx"; + } + return this.each( function() { + var index, + data = dataPriv.get( this ), + queue = data[ type + "queue" ], + hooks = data[ type + "queueHooks" ], + timers = jQuery.timers, + length = queue ? queue.length : 0; + + // Enable finishing flag on private data + data.finish = true; + + // Empty the queue first + jQuery.queue( this, type, [] ); + + if ( hooks && hooks.stop ) { + hooks.stop.call( this, true ); + } + + // Look for any active animations, and finish them + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && timers[ index ].queue === type ) { + timers[ index ].anim.stop( true ); + timers.splice( index, 1 ); + } + } + + // Look for any animations in the old queue and finish them + for ( index = 0; index < length; index++ ) { + if ( queue[ index ] && queue[ index ].finish ) { + queue[ index ].finish.call( this ); + } + } + + // Turn off finishing flag + delete data.finish; + } ); + } +} ); + +jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) { + var cssFn = jQuery.fn[ name ]; + jQuery.fn[ name ] = function( speed, easing, callback ) { + return speed == null || typeof speed === "boolean" ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; +} ); + +// Generate shortcuts for custom animations +jQuery.each( { + slideDown: genFx( "show" ), + slideUp: genFx( "hide" ), + slideToggle: genFx( "toggle" ), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; +} ); + +jQuery.timers = []; +jQuery.fx.tick = function() { + var timer, + i = 0, + timers = jQuery.timers; + + fxNow = jQuery.now(); + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + + // Run the timer and safely remove it when done (allowing for external removal) + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + fxNow = undefined; +}; + +jQuery.fx.timer = function( timer ) { + jQuery.timers.push( timer ); + jQuery.fx.start(); +}; + +jQuery.fx.interval = 13; +jQuery.fx.start = function() { + if ( inProgress ) { + return; + } + + inProgress = true; + schedule(); +}; + +jQuery.fx.stop = function() { + inProgress = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + + // Default speed + _default: 400 +}; + + +// Based off of the plugin by Clint Helfers, with permission. +// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ +jQuery.fn.delay = function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = window.setTimeout( next, time ); + hooks.stop = function() { + window.clearTimeout( timeout ); + }; + } ); +}; + + +( function() { + var input = document.createElement( "input" ), + select = document.createElement( "select" ), + opt = select.appendChild( document.createElement( "option" ) ); + + input.type = "checkbox"; + + // Support: Android <=4.3 only + // Default value for a checkbox should be "on" + support.checkOn = input.value !== ""; + + // Support: IE <=11 only + // Must access selectedIndex to make default options select + support.optSelected = opt.selected; + + // Support: IE <=11 only + // An input loses its value after becoming a radio + input = document.createElement( "input" ); + input.value = "t"; + input.type = "radio"; + support.radioValue = input.value === "t"; +} )(); + + +var boolHook, + attrHandle = jQuery.expr.attrHandle; + +jQuery.fn.extend( { + attr: function( name, value ) { + return access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each( function() { + jQuery.removeAttr( this, name ); + } ); + } +} ); + +jQuery.extend( { + attr: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set attributes on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + // Attribute hooks are determined by the lowercase version + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + hooks = jQuery.attrHooks[ name.toLowerCase() ] || + ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); + } + + if ( value !== undefined ) { + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + } + + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + elem.setAttribute( name, value + "" ); + return value; + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + ret = jQuery.find.attr( elem, name ); + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? undefined : ret; + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !support.radioValue && value === "radio" && + nodeName( elem, "input" ) ) { + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + removeAttr: function( elem, value ) { + var name, + i = 0, + + // Attribute names can contain non-HTML whitespace characters + // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 + attrNames = value && value.match( rnothtmlwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( ( name = attrNames[ i++ ] ) ) { + elem.removeAttribute( name ); + } + } + } +} ); + +// Hooks for boolean attributes +boolHook = { + set: function( elem, value, name ) { + if ( value === false ) { + + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + elem.setAttribute( name, name ); + } + return name; + } +}; + +jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { + var getter = attrHandle[ name ] || jQuery.find.attr; + + attrHandle[ name ] = function( elem, name, isXML ) { + var ret, handle, + lowercaseName = name.toLowerCase(); + + if ( !isXML ) { + + // Avoid an infinite loop by temporarily removing this function from the getter + handle = attrHandle[ lowercaseName ]; + attrHandle[ lowercaseName ] = ret; + ret = getter( elem, name, isXML ) != null ? + lowercaseName : + null; + attrHandle[ lowercaseName ] = handle; + } + return ret; + }; +} ); + + + + +var rfocusable = /^(?:input|select|textarea|button)$/i, + rclickable = /^(?:a|area)$/i; + +jQuery.fn.extend( { + prop: function( name, value ) { + return access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + return this.each( function() { + delete this[ jQuery.propFix[ name ] || name ]; + } ); + } +} ); + +jQuery.extend( { + prop: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set properties on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + return ( elem[ name ] = value ); + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + return elem[ name ]; + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + + // Support: IE <=9 - 11 only + // elem.tabIndex doesn't always return the + // correct value when it hasn't been explicitly set + // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + // Use proper attribute retrieval(#12072) + var tabindex = jQuery.find.attr( elem, "tabindex" ); + + if ( tabindex ) { + return parseInt( tabindex, 10 ); + } + + if ( + rfocusable.test( elem.nodeName ) || + rclickable.test( elem.nodeName ) && + elem.href + ) { + return 0; + } + + return -1; + } + } + }, + + propFix: { + "for": "htmlFor", + "class": "className" + } +} ); + +// Support: IE <=11 only +// Accessing the selectedIndex property +// forces the browser to respect setting selected +// on the option +// The getter ensures a default option is selected +// when in an optgroup +// eslint rule "no-unused-expressions" is disabled for this code +// since it considers such accessions noop +if ( !support.optSelected ) { + jQuery.propHooks.selected = { + get: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent && parent.parentNode ) { + parent.parentNode.selectedIndex; + } + return null; + }, + set: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent ) { + parent.selectedIndex; + + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + } + }; +} + +jQuery.each( [ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" +], function() { + jQuery.propFix[ this.toLowerCase() ] = this; +} ); + + + + + // Strip and collapse whitespace according to HTML spec + // https://html.spec.whatwg.org/multipage/infrastructure.html#strip-and-collapse-whitespace + function stripAndCollapse( value ) { + var tokens = value.match( rnothtmlwhite ) || []; + return tokens.join( " " ); + } + + +function getClass( elem ) { + return elem.getAttribute && elem.getAttribute( "class" ) || ""; +} + +jQuery.fn.extend( { + addClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( jQuery.isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( typeof value === "string" && value ) { + classes = value.match( rnothtmlwhite ) || []; + + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + if ( cur.indexOf( " " + clazz + " " ) < 0 ) { + cur += clazz + " "; + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( jQuery.isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( !arguments.length ) { + return this.attr( "class", "" ); + } + + if ( typeof value === "string" && value ) { + classes = value.match( rnothtmlwhite ) || []; + + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + + // This expression is here for better compressibility (see addClass) + cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + + // Remove *all* instances + while ( cur.indexOf( " " + clazz + " " ) > -1 ) { + cur = cur.replace( " " + clazz + " ", " " ); + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value; + + if ( typeof stateVal === "boolean" && type === "string" ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + if ( jQuery.isFunction( value ) ) { + return this.each( function( i ) { + jQuery( this ).toggleClass( + value.call( this, i, getClass( this ), stateVal ), + stateVal + ); + } ); + } + + return this.each( function() { + var className, i, self, classNames; + + if ( type === "string" ) { + + // Toggle individual class names + i = 0; + self = jQuery( this ); + classNames = value.match( rnothtmlwhite ) || []; + + while ( ( className = classNames[ i++ ] ) ) { + + // Check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } + } + + // Toggle whole class name + } else if ( value === undefined || type === "boolean" ) { + className = getClass( this ); + if ( className ) { + + // Store className if set + dataPriv.set( this, "__className__", className ); + } + + // If the element has a class name or if we're passed `false`, + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + if ( this.setAttribute ) { + this.setAttribute( "class", + className || value === false ? + "" : + dataPriv.get( this, "__className__" ) || "" + ); + } + } + } ); + }, + + hasClass: function( selector ) { + var className, elem, + i = 0; + + className = " " + selector + " "; + while ( ( elem = this[ i++ ] ) ) { + if ( elem.nodeType === 1 && + ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { + return true; + } + } + + return false; + } +} ); + + + + +var rreturn = /\r/g; + +jQuery.fn.extend( { + val: function( value ) { + var hooks, ret, isFunction, + elem = this[ 0 ]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || + jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && + "get" in hooks && + ( ret = hooks.get( elem, "value" ) ) !== undefined + ) { + return ret; + } + + ret = elem.value; + + // Handle most common string cases + if ( typeof ret === "string" ) { + return ret.replace( rreturn, "" ); + } + + // Handle cases where value is null/undef or number + return ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each( function( i ) { + var val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + + } else if ( typeof val === "number" ) { + val += ""; + + } else if ( Array.isArray( val ) ) { + val = jQuery.map( val, function( value ) { + return value == null ? "" : value + ""; + } ); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + } ); + } +} ); + +jQuery.extend( { + valHooks: { + option: { + get: function( elem ) { + + var val = jQuery.find.attr( elem, "value" ); + return val != null ? + val : + + // Support: IE <=10 - 11 only + // option.text throws exceptions (#14686, #14858) + // Strip and collapse whitespace + // https://html.spec.whatwg.org/#strip-and-collapse-whitespace + stripAndCollapse( jQuery.text( elem ) ); + } + }, + select: { + get: function( elem ) { + var value, option, i, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one", + values = one ? null : [], + max = one ? index + 1 : options.length; + + if ( index < 0 ) { + i = max; + + } else { + i = one ? index : 0; + } + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Support: IE <=9 only + // IE8-9 doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + + // Don't return options that are disabled or in a disabled optgroup + !option.disabled && + ( !option.parentNode.disabled || + !nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + + /* eslint-disable no-cond-assign */ + + if ( option.selected = + jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 + ) { + optionSet = true; + } + + /* eslint-enable no-cond-assign */ + } + + // Force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } + } + } +} ); + +// Radios and checkboxes getter/setter +jQuery.each( [ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( Array.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); + } + } + }; + if ( !support.checkOn ) { + jQuery.valHooks[ this ].get = function( elem ) { + return elem.getAttribute( "value" ) === null ? "on" : elem.value; + }; + } +} ); + + + + +// Return jQuery for attributes-only inclusion + + +var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/; + +jQuery.extend( jQuery.event, { + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "." ) > -1 ) { + + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split( "." ); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf( ":" ) < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join( "." ); + event.rnamespace = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === ( elem.ownerDocument || document ) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && + dataPriv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( ( !special._default || + special._default.apply( eventPath.pop(), data ) === false ) && + acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name as the event. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + // Piggyback on a donor event to simulate a different one + // Used only for `focus(in | out)` events + simulate: function( type, elem, event ) { + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true + } + ); + + jQuery.event.trigger( e, null, elem ); + } + +} ); + +jQuery.fn.extend( { + + trigger: function( type, data ) { + return this.each( function() { + jQuery.event.trigger( type, data, this ); + } ); + }, + triggerHandler: function( type, data ) { + var elem = this[ 0 ]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +} ); + + +jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup contextmenu" ).split( " " ), + function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + return arguments.length > 0 ? + this.on( name, null, data, fn ) : + this.trigger( name ); + }; +} ); + +jQuery.fn.extend( { + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +} ); + + + + +support.focusin = "onfocusin" in window; + + +// Support: Firefox <=44 +// Firefox doesn't have focus(in | out) events +// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 +// +// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 +// focus(in | out) events fire after focus & blur events, +// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order +// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 +if ( !support.focusin ) { + jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + var doc = this.ownerDocument || this, + attaches = dataPriv.access( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this, + attaches = dataPriv.access( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + dataPriv.remove( doc, fix ); + + } else { + dataPriv.access( doc, fix, attaches ); + } + } + }; + } ); +} +var location = window.location; + +var nonce = jQuery.now(); + +var rquery = ( /\?/ ); + + + +// Cross-browser xml parsing +jQuery.parseXML = function( data ) { + var xml; + if ( !data || typeof data !== "string" ) { + return null; + } + + // Support: IE 9 - 11 only + // IE throws on parseFromString with invalid input. + try { + xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); + } catch ( e ) { + xml = undefined; + } + + if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; +}; + + +var + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, + rsubmittable = /^(?:input|select|textarea|keygen)/i; + +function buildParams( prefix, obj, traditional, add ) { + var name; + + if ( Array.isArray( obj ) ) { + + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + + // Item is non-scalar (array or object), encode its numeric index. + buildParams( + prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", + v, + traditional, + add + ); + } + } ); + + } else if ( !traditional && jQuery.type( obj ) === "object" ) { + + // Serialize object item. + for ( name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } + + } else { + + // Serialize scalar item. + add( prefix, obj ); + } +} + +// Serialize an array of form elements or a set of +// key/values into a query string +jQuery.param = function( a, traditional ) { + var prefix, + s = [], + add = function( key, valueOrFunction ) { + + // If value is a function, invoke it and use its return value + var value = jQuery.isFunction( valueOrFunction ) ? + valueOrFunction() : + valueOrFunction; + + s[ s.length ] = encodeURIComponent( key ) + "=" + + encodeURIComponent( value == null ? "" : value ); + }; + + // If an array was passed in, assume that it is an array of form elements. + if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + } ); + + } else { + + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ); +}; + +jQuery.fn.extend( { + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map( function() { + + // Can add propHook for "elements" to filter or add form elements + var elements = jQuery.prop( this, "elements" ); + return elements ? jQuery.makeArray( elements ) : this; + } ) + .filter( function() { + var type = this.type; + + // Use .is( ":disabled" ) so that fieldset[disabled] works + return this.name && !jQuery( this ).is( ":disabled" ) && + rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && + ( this.checked || !rcheckableType.test( type ) ); + } ) + .map( function( i, elem ) { + var val = jQuery( this ).val(); + + if ( val == null ) { + return null; + } + + if ( Array.isArray( val ) ) { + return jQuery.map( val, function( val ) { + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ); + } + + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ).get(); + } +} ); + + +var + r20 = /%20/g, + rhash = /#.*$/, + rantiCache = /([?&])_=[^&]*/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, + + // #7653, #8125, #8152: local protocol detection + rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression + allTypes = "*/".concat( "*" ), + + // Anchor tag for parsing the document origin + originAnchor = document.createElement( "a" ); + originAnchor.href = location.href; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + var dataType, + i = 0, + dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; + + if ( jQuery.isFunction( func ) ) { + + // For each dataType in the dataTypeExpression + while ( ( dataType = dataTypes[ i++ ] ) ) { + + // Prepend if requested + if ( dataType[ 0 ] === "+" ) { + dataType = dataType.slice( 1 ) || "*"; + ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); + + // Otherwise append + } else { + ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); + } + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { + + var inspected = {}, + seekingTransport = ( structure === transports ); + + function inspect( dataType ) { + var selected; + inspected[ dataType ] = true; + jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { + var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); + if ( typeof dataTypeOrTransport === "string" && + !seekingTransport && !inspected[ dataTypeOrTransport ] ) { + + options.dataTypes.unshift( dataTypeOrTransport ); + inspect( dataTypeOrTransport ); + return false; + } else if ( seekingTransport ) { + return !( selected = dataTypeOrTransport ); + } + } ); + return selected; + } + + return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes #9887 +function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } + + return target; +} + +/* Handles responses to an ajax request: + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes; + + // Remove auto dataType and get content-type in the process + while ( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +/* Chain conversions given the request and the original response + * Also sets the responseXXX fields on the jqXHR instance + */ +function ajaxConvert( s, response, jqXHR, isSuccess ) { + var conv2, current, conv, tmp, prev, + converters = {}, + + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(); + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + current = dataTypes.shift(); + + // Convert to each sequential dataType + while ( current ) { + + if ( s.responseFields[ current ] ) { + jqXHR[ s.responseFields[ current ] ] = response; + } + + // Apply the dataFilter if provided + if ( !prev && isSuccess && s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + prev = current; + current = dataTypes.shift(); + + if ( current ) { + + // There's only work to do if current dataType is non-auto + if ( current === "*" ) { + + current = prev; + + // Convert response if prev dataType is non-auto and differs from current + } else if ( prev !== "*" && prev !== current ) { + + // Seek a direct converter + conv = converters[ prev + " " + current ] || converters[ "* " + current ]; + + // If none found, seek a pair + if ( !conv ) { + for ( conv2 in converters ) { + + // If conv2 outputs current + tmp = conv2.split( " " ); + if ( tmp[ 1 ] === current ) { + + // If prev can be converted to accepted input + conv = converters[ prev + " " + tmp[ 0 ] ] || + converters[ "* " + tmp[ 0 ] ]; + if ( conv ) { + + // Condense equivalence converters + if ( conv === true ) { + conv = converters[ conv2 ]; + + // Otherwise, insert the intermediate dataType + } else if ( converters[ conv2 ] !== true ) { + current = tmp[ 0 ]; + dataTypes.unshift( tmp[ 1 ] ); + } + break; + } + } + } + } + + // Apply converter (if not an equivalence) + if ( conv !== true ) { + + // Unless errors are allowed to bubble, catch and return them + if ( conv && s.throws ) { + response = conv( response ); + } else { + try { + response = conv( response ); + } catch ( e ) { + return { + state: "parsererror", + error: conv ? e : "No conversion from " + prev + " to " + current + }; + } + } + } + } + } + } + + return { state: "success", data: response }; +} + +jQuery.extend( { + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {}, + + ajaxSettings: { + url: location.href, + type: "GET", + isLocal: rlocalProtocol.test( location.protocol ), + global: true, + processData: true, + async: true, + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + "*": allTypes, + text: "text/plain", + html: "text/html", + xml: "application/xml, text/xml", + json: "application/json, text/javascript" + }, + + contents: { + xml: /\bxml\b/, + html: /\bhtml/, + json: /\bjson\b/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText", + json: "responseJSON" + }, + + // Data converters + // Keys separate source (or catchall "*") and destination types with a single space + converters: { + + // Convert anything to text + "* text": String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": JSON.parse, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + url: true, + context: true + } + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + return settings ? + + // Building a settings object + ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : + + // Extending ajaxSettings + ajaxExtend( jQuery.ajaxSettings, target ); + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var transport, + + // URL without anti-cache param + cacheURL, + + // Response headers + responseHeadersString, + responseHeaders, + + // timeout handle + timeoutTimer, + + // Url cleanup var + urlAnchor, + + // Request state (becomes false upon send and true upon completion) + completed, + + // To know if global events are to be dispatched + fireGlobals, + + // Loop variable + i, + + // uncached part of the url + uncached, + + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + + // Callbacks context + callbackContext = s.context || s, + + // Context for global events is callbackContext if it is a DOM node or jQuery collection + globalEventContext = s.context && + ( callbackContext.nodeType || callbackContext.jquery ) ? + jQuery( callbackContext ) : + jQuery.event, + + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + + // Status-dependent callbacks + statusCode = s.statusCode || {}, + + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + + // Default abort message + strAbort = "canceled", + + // Fake xhr + jqXHR = { + readyState: 0, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( completed ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while ( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ]; + } + } + match = responseHeaders[ key.toLowerCase() ]; + } + return match == null ? null : match; + }, + + // Raw string + getAllResponseHeaders: function() { + return completed ? responseHeadersString : null; + }, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( completed == null ) { + name = requestHeadersNames[ name.toLowerCase() ] = + requestHeadersNames[ name.toLowerCase() ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( completed == null ) { + s.mimeType = type; + } + return this; + }, + + // Status-dependent callbacks + statusCode: function( map ) { + var code; + if ( map ) { + if ( completed ) { + + // Execute the appropriate callbacks + jqXHR.always( map[ jqXHR.status ] ); + } else { + + // Lazy-add the new callbacks in a way that preserves old ones + for ( code in map ) { + statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; + } + } + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + var finalText = statusText || strAbort; + if ( transport ) { + transport.abort( finalText ); + } + done( 0, finalText ); + return this; + } + }; + + // Attach deferreds + deferred.promise( jqXHR ); + + // Add protocol if not provided (prefilters might expect it) + // Handle falsy url in the settings object (#10093: consistency with old signature) + // We also use the url parameter if available + s.url = ( ( url || s.url || location.href ) + "" ) + .replace( rprotocol, location.protocol + "//" ); + + // Alias method option to type as per ticket #12004 + s.type = options.method || options.type || s.method || s.type; + + // Extract dataTypes list + s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; + + // A cross-domain request is in order when the origin doesn't match the current origin. + if ( s.crossDomain == null ) { + urlAnchor = document.createElement( "a" ); + + // Support: IE <=8 - 11, Edge 12 - 13 + // IE throws exception on accessing the href property if url is malformed, + // e.g. http://example.com:80x/ + try { + urlAnchor.href = s.url; + + // Support: IE <=8 - 11 only + // Anchor's host property isn't correctly set when s.url is relative + urlAnchor.href = urlAnchor.href; + s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== + urlAnchor.protocol + "//" + urlAnchor.host; + } catch ( e ) { + + // If there is an error parsing the URL, assume it is crossDomain, + // it can be rejected by the transport if it is invalid + s.crossDomain = true; + } + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // If request was aborted inside a prefilter, stop there + if ( completed ) { + return jqXHR; + } + + // We can fire global events as of now if asked to + // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) + fireGlobals = jQuery.event && s.global; + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Save the URL in case we're toying with the If-Modified-Since + // and/or If-None-Match header later on + // Remove hash to simplify url manipulation + cacheURL = s.url.replace( rhash, "" ); + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // Remember the hash so we can put it back + uncached = s.url.slice( cacheURL.length ); + + // If data is available, append data to url + if ( s.data ) { + cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; + + // #9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Add or update anti-cache param if needed + if ( s.cache === false ) { + cacheURL = cacheURL.replace( rantiCache, "$1" ); + uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached; + } + + // Put hash and anti-cache on the URL that will be requested (gh-1732) + s.url = cacheURL + uncached; + + // Change '%20' to '+' if this is encoded form body content (gh-2658) + } else if ( s.data && s.processData && + ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { + s.data = s.data.replace( r20, "+" ); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + if ( jQuery.lastModified[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); + } + if ( jQuery.etag[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + jqXHR.setRequestHeader( "Content-Type", s.contentType ); + } + + // Set the Accepts header for the server, depending on the dataType + jqXHR.setRequestHeader( + "Accept", + s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? + s.accepts[ s.dataTypes[ 0 ] ] + + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : + s.accepts[ "*" ] + ); + + // Check for headers option + for ( i in s.headers ) { + jqXHR.setRequestHeader( i, s.headers[ i ] ); + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && + ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { + + // Abort if not done already and return + return jqXHR.abort(); + } + + // Aborting is no longer a cancellation + strAbort = "abort"; + + // Install callbacks on deferreds + completeDeferred.add( s.complete ); + jqXHR.done( s.success ); + jqXHR.fail( s.error ); + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + jqXHR.readyState = 1; + + // Send global event + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); + } + + // If request was aborted inside ajaxSend, stop there + if ( completed ) { + return jqXHR; + } + + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = window.setTimeout( function() { + jqXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + completed = false; + transport.send( requestHeaders, done ); + } catch ( e ) { + + // Rethrow post-completion exceptions + if ( completed ) { + throw e; + } + + // Propagate others as results + done( -1, e ); + } + } + + // Callback for when everything is done + function done( status, nativeStatusText, responses, headers ) { + var isSuccess, success, error, response, modified, + statusText = nativeStatusText; + + // Ignore repeat invocations + if ( completed ) { + return; + } + + completed = true; + + // Clear timeout if it exists + if ( timeoutTimer ) { + window.clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jqXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jqXHR.readyState = status > 0 ? 4 : 0; + + // Determine if successful + isSuccess = status >= 200 && status < 300 || status === 304; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // Convert no matter what (that way responseXXX fields are always set) + response = ajaxConvert( s, response, jqXHR, isSuccess ); + + // If successful, handle type chaining + if ( isSuccess ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + modified = jqXHR.getResponseHeader( "Last-Modified" ); + if ( modified ) { + jQuery.lastModified[ cacheURL ] = modified; + } + modified = jqXHR.getResponseHeader( "etag" ); + if ( modified ) { + jQuery.etag[ cacheURL ] = modified; + } + } + + // if no content + if ( status === 204 || s.type === "HEAD" ) { + statusText = "nocontent"; + + // if not modified + } else if ( status === 304 ) { + statusText = "notmodified"; + + // If we have data, let's convert it + } else { + statusText = response.state; + success = response.data; + error = response.error; + isSuccess = !error; + } + } else { + + // Extract error from statusText and normalize for non-aborts + error = statusText; + if ( status || !statusText ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jqXHR.status = status; + jqXHR.statusText = ( nativeStatusText || statusText ) + ""; + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jqXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( fireGlobals ) { + globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", + [ jqXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); + + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); + + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + return jqXHR; + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + } +} ); + +jQuery.each( [ "get", "post" ], function( i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + + // Shift arguments if data argument was omitted + if ( jQuery.isFunction( data ) ) { + type = type || callback; + callback = data; + data = undefined; + } + + // The url can be an options object (which then must have .url) + return jQuery.ajax( jQuery.extend( { + url: url, + type: method, + dataType: type, + data: data, + success: callback + }, jQuery.isPlainObject( url ) && url ) ); + }; +} ); + + +jQuery._evalUrl = function( url ) { + return jQuery.ajax( { + url: url, + + // Make this explicit, since user can override this through ajaxSetup (#11264) + type: "GET", + dataType: "script", + cache: true, + async: false, + global: false, + "throws": true + } ); +}; + + +jQuery.fn.extend( { + wrapAll: function( html ) { + var wrap; + + if ( this[ 0 ] ) { + if ( jQuery.isFunction( html ) ) { + html = html.call( this[ 0 ] ); + } + + // The elements to wrap the target around + wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); + + if ( this[ 0 ].parentNode ) { + wrap.insertBefore( this[ 0 ] ); + } + + wrap.map( function() { + var elem = this; + + while ( elem.firstElementChild ) { + elem = elem.firstElementChild; + } + + return elem; + } ).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each( function( i ) { + jQuery( this ).wrapInner( html.call( this, i ) ); + } ); + } + + return this.each( function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + } ); + }, + + wrap: function( html ) { + var isFunction = jQuery.isFunction( html ); + + return this.each( function( i ) { + jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html ); + } ); + }, + + unwrap: function( selector ) { + this.parent( selector ).not( "body" ).each( function() { + jQuery( this ).replaceWith( this.childNodes ); + } ); + return this; + } +} ); + + +jQuery.expr.pseudos.hidden = function( elem ) { + return !jQuery.expr.pseudos.visible( elem ); +}; +jQuery.expr.pseudos.visible = function( elem ) { + return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); +}; + + + + +jQuery.ajaxSettings.xhr = function() { + try { + return new window.XMLHttpRequest(); + } catch ( e ) {} +}; + +var xhrSuccessStatus = { + + // File protocol always yields status code 0, assume 200 + 0: 200, + + // Support: IE <=9 only + // #1450: sometimes IE returns 1223 when it should be 204 + 1223: 204 + }, + xhrSupported = jQuery.ajaxSettings.xhr(); + +support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); +support.ajax = xhrSupported = !!xhrSupported; + +jQuery.ajaxTransport( function( options ) { + var callback, errorCallback; + + // Cross domain only allowed if supported through XMLHttpRequest + if ( support.cors || xhrSupported && !options.crossDomain ) { + return { + send: function( headers, complete ) { + var i, + xhr = options.xhr(); + + xhr.open( + options.type, + options.url, + options.async, + options.username, + options.password + ); + + // Apply custom fields if provided + if ( options.xhrFields ) { + for ( i in options.xhrFields ) { + xhr[ i ] = options.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( options.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( options.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Set headers + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + + // Callback + callback = function( type ) { + return function() { + if ( callback ) { + callback = errorCallback = xhr.onload = + xhr.onerror = xhr.onabort = xhr.onreadystatechange = null; + + if ( type === "abort" ) { + xhr.abort(); + } else if ( type === "error" ) { + + // Support: IE <=9 only + // On a manual native abort, IE9 throws + // errors on any property access that is not readyState + if ( typeof xhr.status !== "number" ) { + complete( 0, "error" ); + } else { + complete( + + // File: protocol always yields status 0; see #8605, #14207 + xhr.status, + xhr.statusText + ); + } + } else { + complete( + xhrSuccessStatus[ xhr.status ] || xhr.status, + xhr.statusText, + + // Support: IE <=9 only + // IE9 has no XHR2 but throws on binary (trac-11426) + // For XHR2 non-text, let the caller handle it (gh-2498) + ( xhr.responseType || "text" ) !== "text" || + typeof xhr.responseText !== "string" ? + { binary: xhr.response } : + { text: xhr.responseText }, + xhr.getAllResponseHeaders() + ); + } + } + }; + }; + + // Listen to events + xhr.onload = callback(); + errorCallback = xhr.onerror = callback( "error" ); + + // Support: IE 9 only + // Use onreadystatechange to replace onabort + // to handle uncaught aborts + if ( xhr.onabort !== undefined ) { + xhr.onabort = errorCallback; + } else { + xhr.onreadystatechange = function() { + + // Check readyState before timeout as it changes + if ( xhr.readyState === 4 ) { + + // Allow onerror to be called first, + // but that will not handle a native abort + // Also, save errorCallback to a variable + // as xhr.onerror cannot be accessed + window.setTimeout( function() { + if ( callback ) { + errorCallback(); + } + } ); + } + }; + } + + // Create the abort callback + callback = callback( "abort" ); + + try { + + // Do send the request (this may raise an exception) + xhr.send( options.hasContent && options.data || null ); + } catch ( e ) { + + // #14683: Only rethrow if this hasn't been notified as an error yet + if ( callback ) { + throw e; + } + } + }, + + abort: function() { + if ( callback ) { + callback(); + } + } + }; + } +} ); + + + + +// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) +jQuery.ajaxPrefilter( function( s ) { + if ( s.crossDomain ) { + s.contents.script = false; + } +} ); + +// Install script dataType +jQuery.ajaxSetup( { + accepts: { + script: "text/javascript, application/javascript, " + + "application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /\b(?:java|ecma)script\b/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +} ); + +// Handle cache's special case and crossDomain +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + } +} ); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function( s ) { + + // This transport only deals with cross domain requests + if ( s.crossDomain ) { + var script, callback; + return { + send: function( _, complete ) { + script = jQuery( " + + + + + + + + + + + + + + + + + + +
+ + + + + + + Slack Developer Kit for Python + + +
+ + +
+
+ + + + + +
+
About
+
+
+

About

+
+

Slack Developer Kit for Python

+

Access the Slack Platform from your Python app. Slack Developer Kit for Python lets you build on the Slack Web APIs pythonically.

+

Slack Developer Kit for Python is proudly maintained with 💖 by the Slack Developer Tools team

+ +
+
+ + +
+
+
+ + +
+
+ +
+

© 2019 Slack Technologies, Inc. and contributors

+
+ + + + + + + \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/auth.html b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/auth.html new file mode 100644 index 0000000000..e541ccb53c --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/auth.html @@ -0,0 +1,300 @@ + + + + + + + Tokens & Authentication — Slack Developer Kit for Python + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + Slack Developer Kit for Python + + +
+ + +
+
+ + + + + +
+
Tokens & Authentication
+
+
+

Tokens & Authentication

+
+

Handling tokens and other sensitive data

+

⚠️ Slack tokens are the keys to your—or your customers’—data.Keep them secret. Keep them safe.

+

One way to do that is to never explicitly hardcode them.

+

Try to avoid this when possible:

+
token = 'xoxb-abc-1232'
+
+
+

⚠️ Never share test tokens with other users or applications. Do not publish test tokens in public code repositories.

+

We recommend you pass tokens in as environment variables, or persist them in a database that is accessed at runtime. You can add a token to the environment by starting your app as:

+
SLACK_BOT_TOKEN="xoxb-abc-1232" python myapp.py
+
+
+

Then retrieve the key with:

+
import os
+SLACK_BOT_TOKEN = os.environ["SLACK_BOT_TOKEN"]
+
+
+

You can use the same technique for other kinds of sensitive data that ne’er-do-wells could use in nefarious ways, including

+
    +
  • Incoming webhook URLs
  • +
  • Slash command verification tokens
  • +
  • App client ids and client secrets
  • +
+

For additional information, please see our Safely Storing Credentials page.

+
+
+

Single-Workspace Apps

+

If you’re building an application for a single Slack workspace, there’s no need to build out the entire OAuth flow.

+

Once you’ve setup your features, click on the Install App to Team button found on the Install App page. +If you add new permission scopes or Slack app features after an app has been installed, you must reinstall the app to +your workspace for changes to take effect.

+

For additional information, see the Installing Apps of our Building Slack apps page.

+
+
+

The OAuth flow

+

Authentication for Slack’s APIs is done using OAuth, so you’ll want to read up on OAuth.

+

In order to implement OAuth in your app, you will need to include a web server. In this example, we’ll use Flask.

+

As mentioned above, we’re setting the app tokens and other configs in environment variables and pulling them into global variables.

+

Depending on what actions your app will need to perform, you’ll need different OAuth permission scopes. Review the available scopes here.

+
import os
+from flask import Flask, request
+from slackclient import SlackClient
+
+client_id = os.environ["SLACK_CLIENT_ID"]
+client_secret = os.environ["SLACK_CLIENT_SECRET"]
+oauth_scope = os.environ["SLACK_BOT_SCOPE"]
+
+app = Flask(__name__)
+
+
+

The OAuth initiation link:

+

To begin the OAuth flow, you’ll need to provide the user with a link to Slack’s OAuth page. +This directs the user to Slack’s OAuth acceptance page, where the user will review and accept +or refuse the permissions your app is requesting as defined by the requested scope(s).

+

For the best user experience, use the Add to Slack button to direct users to approve your application for access or Sign in with Slack to log users in.

+
@app.route("/begin_auth", methods=["GET"])
+def pre_install():
+  return '''
+      <a href="https://slack.com/oauth/authorize?scope={0}&client_id={1}">
+          Add to Slack
+      </a>
+  '''.format(oauth_scope, client_id)
+
+
+

The OAuth completion page

+

Once the user has agreed to the permissions you’ve requested on Slack’s OAuth +page, Slack will redirect the user to your auth completion page. Included in this +redirect is a code query string param which you’ll use to request access +tokens from the oauth.access endpoint.

+

Generally, Web API requests require a valid OAuth token, but there are a few endpoints +which do not require a token. oauth.access is one example of this. Since this +is the endpoint you’ll use to retrieve the tokens for later API requests, +an empty string "" is acceptable for this request.

+
@app.route("/finish_auth", methods=["GET", "POST"])
+def post_install():
+
+  # Retrieve the auth code from the request params
+  auth_code = request.args['code']
+
+  # An empty string is a valid token for this request
+  sc = SlackClient("")
+
+  # Request the auth tokens from Slack
+  auth_response = sc.api_call(
+    "oauth.access",
+    client_id=client_id,
+    client_secret=client_secret,
+    code=auth_code
+  )
+
+
+

A successful request to oauth.access will yield two tokens: A user +token and a bot token. The user token auth_response['access_token'] +is used to make requests on behalf of the authorizing user and the bot +token auth_response['bot']['bot_access_token'] is for making requests +on behalf of your app’s bot user.

+

If your Slack app includes a bot user, upon approval the JSON response will contain +an additional node containing an access token to be specifically used for your bot +user, within the context of the approving team.

+

When you use Web API methods on behalf of your bot user, you should use this bot +user access token instead of the top-level access token granted to your application.

+
# Save the bot token to an environmental variable or to your data store
+# for later use
+os.environ["SLACK_USER_TOKEN"] = auth_response['access_token']
+os.environ["SLACK_BOT_TOKEN"] = auth_response['bot']['bot_access_token']
+
+# Don't forget to let the user know that auth has succeeded!
+return "Auth complete!"
+
+
+

Once your user has completed the OAuth flow, you’ll be able to use the provided +tokens to make a variety of Web API calls on behalf of the user and your app’s bot user.

+

See the Web API usage section of this documentation for usage examples.

+
+
+ + +
+
+
+ + +
+
+ +
+

© 2019 Slack Technologies, Inc. and contributors

+
+ + + + + + + \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/basic_usage.html b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/basic_usage.html new file mode 100644 index 0000000000..63f6305762 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/basic_usage.html @@ -0,0 +1,545 @@ + + + + + + + Basic Usage — Slack Developer Kit for Python + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + Slack Developer Kit for Python + + +
+ + +
+
+ + + + + +
+
Basic Usage
+
+
+

Basic Usage

+

The Slack Web API allows you to build applications that interact with Slack in more complex ways than the integrations +we provide out of the box.

+

This package is a modular wrapper designed to make Slack Web API calls simpler and easier for your +app. Provided below are examples of how to interact with commonly used API endpoints, but this is by no means +a complete list. Review the full list of available methods here.

+

See Tokens & Authentication for API token handling best practices.

+
+
+

Sending a message

+

The primary use of Slack is sending messages. Whether you’re sending a message +to a user or to a channel, this method handles both.

+

To send a message to a channel, use the channel’s ID. For IMs, use the user’s ID.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call(
+  "chat.postMessage",
+  channel="C0XXXXXX",
+  text="Hello from Python! :tada:"
+)
+
+
+

There are some unique options specific to sending IMs, so be sure to read the channels +section of the chat.postMessage +page for a full list of formatting and authorship options.

+

Sending an ephemeral message, which is only visible to an assigned user in a specified channel, is nearly the same +as sending a regular message, but with an additional user parameter.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call(
+  "chat.postEphemeral",
+  channel="C0XXXXXX",
+  text="Hello from Python! :tada:",
+  user="U0XXXXXXX"
+)
+
+
+

See chat.postEphemeral for more info.

+
+
+
+

Customizing a message’s layout

+

The chat.postMessage method takes an optional blocks argument that allows you to customize the layout of a message. +Blocks for Web API methods are all specified in a single object literal, so just add additional keys for any optional argument.

+

To send a message to a channel, use the channel’s ID. For IMs, use the user’s ID.

+
sc.api_call(
+  "chat.postMessage",
+  channel="C0XXXXXX",
+  blocks=[
+    {
+        "type": "section",
+        "text": {
+            "type": "mrkdwn",
+            "text": "Danny Torrence left the following review for your property:"
+        }
+    },
+    {
+        "type": "section",
+        "text": {
+            "type": "mrkdwn",
+            "text": "<https://example.com|Overlook Hotel> \n :star: \n Doors had too many axe holes, guest in room " +
+            "237 was far too rowdy, whole place felt stuck in the 1920s."
+        },
+        "accessory": {
+            "type": "image",
+            "image_url": "https://images.pexels.com/photos/750319/pexels-photo-750319.jpeg",
+            "alt_text": "Haunted hotel image"
+        }
+    },
+    {
+        "type": "section",
+        "fields": [
+            {
+                "type": "mrkdwn",
+                "text": "*Average Rating*\n1.0"
+            }
+        ]
+    }
+  ]
+)
+
+
+

Note: You can use the `Block Kit Builder <https://api.slack.com/tools/block-kit-builder>`for a playground where you can prototype your message’s look and feel.

+
+
+
+

Replying to messages and creating threads

+

Threaded messages are just like regular messages, except thread replies are grouped together to provide greater context +to the user. You can reply to a thread or start a new threaded conversation by simply passing the original message’s ts +ID in the thread_ts attribute when posting a message. If you’re replying to a threaded message, you’ll pass the thread_ts +ID of the message you’re replying to.

+

A channel or DM conversation is a nearly linear timeline of messages exchanged between people, bots, and apps. +When one of these messages is replied to, it becomes the parent of a thread. By default, threaded replies do not +appear directly in the channel, instead relegated to a kind of forked timeline descending from the parent message.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call(
+  "chat.postMessage",
+  channel="C0XXXXXX",
+  text="Hello from Python! :tada:",
+  thread_ts="1476746830.000003"
+)
+
+
+

By default, reply_broadcast is set to False. To indicate your reply is germane to all members of a channel, +set the reply_broadcast boolean parameter to True.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call(
+  "chat.postMessage",
+  channel="C0XXXXXX",
+  text="Hello from Python! :tada:",
+  thread_ts="1476746830.000003",
+  reply_broadcast=True
+)
+
+
+

Note: While threaded messages may contain attachments and message buttons, when your reply is broadcast to the +channel, it’ll actually be a reference to your reply, not the reply itself. +So, when appearing in the channel, it won’t contain any attachments or message buttons. Also note that updates and +deletion of threaded replies works the same as regular messages.

+

See the Threading messages together +article for more information.

+
+
+
+

Updating the content of a message

+

Let’s say you have a bot which posts the status of a request. When that request +is updated, you’ll want to update the message to reflect it’s state. Or your user +might want to fix a typo or change some wording. This is how you’ll make those changes.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call(
+  "chat.update",
+  ts="1476746830.000003",
+  channel="C0XXXXXX",
+  text="Hello from Python! :tada:"
+)
+
+
+

See chat.update for formatting options +and some special considerations when calling this with a bot user.

+
+
+
+

Deleting a message

+

Sometimes you need to delete things.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call(
+  "chat.delete",
+  channel="C0XXXXXX",
+  ts="1476745373.000002"
+)
+
+
+

See chat.delete for more info.

+
+
+
+

Adding or removing an emoji reaction

+

You can quickly respond to any message on Slack with an emoji reaction. Reactions +can be used for any purpose: voting, checking off to-do items, showing excitement — and just for fun.

+

This method adds a reaction (emoji) to an item (file, file comment, channel message, group message, or direct message). One of file, file_comment, or the combination of channel and timestamp must be specified.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call(
+  "reactions.add",
+  channel="C0XXXXXXX",
+  name="thumbsup",
+  timestamp="1234567890.123456"
+)
+
+
+

Removing an emoji reaction is basically the same format, but you’ll use reactions.remove instead of reactions.add

+
sc.api_call(
+  "reactions.remove",
+  channel="C0XXXXXXX",
+  name="thumbsup",
+  timestamp="1234567890.123456"
+)
+
+
+

See reactions.add and reactions.remove for more info.

+
+
+
+

Getting a list of channels

+

At some point, you’ll want to find out what channels are available to your app. This is how you get that list.

+

Note: This call requires the channels:read scope.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call("channels.list")
+
+
+

Archived channels are included by default. You can exclude them by passing exclude_archived=1 to your request.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call(
+  "channels.list",
+  exclude_archived=1
+)
+
+
+

See channels.list for more info.

+
+
+
+

Getting a channel’s info

+

Once you have the ID for a specific channel, you can fetch information about that channel.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call(
+  "channels.info",
+  channel="C0XXXXXXX"
+)
+
+
+

See channels.info for more info.

+
+
+
+

Joining a channel

+

Channels are the social hub of most Slack teams. Here’s how you hop into one:

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call(
+  "channels.join",
+  channel="C0XXXXXXY"
+)
+
+
+

If you are already in the channel, the response is slightly different. +already_in_channel will be true, and a limited channel object will be returned. Bot users cannot join a channel on their own, they need to be invited by another user.

+

See channels.join for more info.

+
+
+
+

Leaving a channel

+

Maybe you’ve finished up all the business you had in a channel, or maybe you +joined one by accident. This is how you leave a channel.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call(
+  "channels.leave",
+  channel="C0XXXXXXX"
+)
+
+
+

See channels.leave for more info.

+
+
+
+

Get a list of team members

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call("users.list")
+
+
+

See users.list for more info.

+
+
+
+

Uploading files

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+with open('thinking_very_much.png') as file_content:
+    sc.api_call(
+        "files.upload",
+        channels="C3UKJTQAC",
+        file=file_content,
+        title="Test upload"
+    )
+
+
+

See files.upload for more info.

+
+
+
+

Web API Rate Limits

+

Slack allows applications to send no more than one message per second. We allow bursts over that +limit for short periods. However, if your app continues to exceed the limit over a longer period +of time it will be rate limited.

+

Here’s a very basic example of how one might deal with rate limited requests.

+

If you go over these limits, Slack will start returning a HTTP 429 Too Many Requests error, +a JSON object containing the number of calls you have been making, and a Retry-After header +containing the number of seconds until you can retry.

+
from slackclient import SlackClient
+import time
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+# Simple wrapper for sending a Slack message
+def send_slack_message(channel, message):
+  return sc.api_call(
+    "chat.postMessage",
+    channel=channel,
+    text=message
+  )
+
+# Make the API call and save results to `response`
+response = send_slack_message("C0XXXXXX", "Hello, from Python!")
+
+# Check to see if the message sent successfully.
+# If the message succeeded, `response["ok"]`` will be `True`
+if response["ok"]:
+  print("Message posted successfully: " + response["message"]["ts"])
+  # If the message failed, check for rate limit headers in the response
+elif response["ok"] is False and response["headers"]["Retry-After"]:
+  # The `Retry-After` header will tell you how long to wait before retrying
+  delay = int(response["headers"]["Retry-After"])
+  print("Rate limited. Retrying in " + str(delay) + " seconds")
+  time.sleep(delay)
+  send_slack_message(message, channel)
+
+
+

See the documentation on Rate Limiting for more info.

+
+
+ + +
+
+
+ + +
+
+ +
+

© 2019 Slack Technologies, Inc. and contributors

+
+ + + + + + + \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/changelog.html b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/changelog.html new file mode 100644 index 0000000000..f2b1d919e0 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/changelog.html @@ -0,0 +1,365 @@ + + + + + + + Changelog — Slack Developer Kit for Python + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + Slack Developer Kit for Python + + +
+ + +
+
+ + + + + +
+
Changelog
+
+
+

Changelog

+
+

v1.3.0 (2018-09-11)

+

## New Features +- Adds support for short lived tokens and automatic token refresh #347 (Thanks @roach!)

+

## Other +- update RTM rate limiting comment and error message #308 (Thanks @benoitlavigne!) +- Use logging instead of traceback #309 (Thanks @harlowja!) +- Remove Python 3.3 from test environments #346 (Thanks @roach!) +- Enforced linting when using VSCode. #347 (Thanks @roach!)

+
+
+

v1.2.1 (2018-03-26)

+
    +
  • Added rate limit handling for rtm connections (thanks @jayalane!)
  • +
+
+
+

v1.2.0 (2018-03-20)

+
    +
  • You can now tell the RTM client to automatically reconnect by passing auto_reconnect=True
  • +
+
+
+

v1.1.3 (2018-03-01)

+
    +
  • Fixed another API param encoding bug. It encodes things properly now.
  • +
+
+
+

v1.1.2 (2018-01-31)

+
    +
  • Fixed an encoding issue which was encoding some Web API params incorrectly (sorry)
  • +
+
+
+

v1.1.1 (2018-01-30)

+
+
    +
  • Adds HTTP response headers to api_call responses to expose things like rate limit info
  • +
  • Moves token into auth header rather than request params
  • +
+
+
+
+

v1.1.0 (2017-11-21)

+
+
    +
  • Aadds new SlackClientError and ResponseParseError types to describe errors - thanks @aoberoi!
  • +
  • Fix Build Error (#245) - thanks @stasfilin!
  • +
  • include email as user property (#173) - thanks @acaire!
  • +
  • Add http reply into slack login and slack connection error (#216) - thanks @harlowja!
  • +
  • Removed unused exception class (#233)
  • +
  • Fix rtm_send_message bug (#225) - thanks @kt5356!
  • +
  • Allow use of custom parameters on rtm_connect() (#210) - thanks @kamushadenes!
  • +
  • Fix link to rtm.connect docs (#223) - @sampart!
  • +
+
+
+
+

v1.0.9 (2017-08-31)

+
+
    +
  • Fixed rtm_send_message ID bug introduced in 1.0.8
  • +
+
+
+
+

v1.0.8 (2017-08-31)

+
+
    +
  • Added rtm.connect support
  • +
+
+
+
+

v1.0.7 (2017-08-02)

+
+
    +
  • Fixes an issue where connecting over RTM to large teams may result in “Websocket URL expired” errors
  • +
  • A load of packaging improvements
  • +
+
+
+
+

v1.0.6 (2017-06-12)

+
+
    +
  • Added proxy support (thanks @timfeirg!)
  • +
  • Tidied up docs (thanks @schlueter!)
  • +
  • Added tox settings for Python 3 testing (thanks @cclauss!)
  • +
+
+
+
+

v1.0.5 (2017-01-23)

+
+
    +
  • Allow RTM Channel.send_message to reply to a thread
  • +
  • Index users by ID instead of Name (non-breaking change)
  • +
  • Added timeout to api calls.
  • +
  • Fixed a typo about token access in auth.rst, thanks @kelvintaywl!
  • +
  • Added Message Threads to the docs
  • +
+
+
+
+

v1.0.4 (2016-12-15)

+
+
    +
  • fixed the ability to search for a user by ID
  • +
+
+
+
+

v1.0.3 (2016-12-13)

+
+
    +
  • fixed an issue causing RTM connections to fail for large teams
  • +
+
+
+
+

v1.0.2 (2016-09-22)

+
+
    +
  • removed unused ping counter
  • +
  • fixed contributor guidelines links
  • +
  • updated documentation
  • +
  • Fix bug preventing API calls requiring a file ID
  • +
  • Removes files from api_calls before JSON encoding, so the request is properly formatted
  • +
+
+
+
+

v1.0.1 (2016-03-25)

+
+
    +
  • fix for __eq__ comparison in channels using ‘#’ in channel name
  • +
  • added copyright info to the LICENSE file
  • +
+
+
+
+

v1.0.0 (2016-02-28)

+
+
    +
  • the api_call function now returns a decoded JSON object, rather than a JSON encoded string
  • +
  • some api_call calls now call actions on the parent server object: +- im.open +- mpim.open, groups.create, groups.createChild +- channels.create, channels.join`
  • +
+
+
+
+

v0.18.0 (2016-02-21)

+
+
    +
  • Moves to use semver for versioning
  • +
  • Adds support for private groups and MPDMs
  • +
  • Switches to use requests instead of urllib
  • +
  • Gets Travis CI integration working
  • +
  • Fixes some formatting issues so the code will work for python 2.6
  • +
  • Cleans up some unused imports, some PEP-8 fixes and a couple bad default args fixes
  • +
+
+
+
+

v0.17.0 (2016-02-15)

+
+
+
+
+ + +
+
+
+ + +
+
+ +
+

© 2019 Slack Technologies, Inc. and contributors

+
+ + + + + + + \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/conversations.html b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/conversations.html new file mode 100644 index 0000000000..574ef819e8 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/conversations.html @@ -0,0 +1,313 @@ + + + + + + + Conversations API — Slack Developer Kit for Python + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + Slack Developer Kit for Python + + +
+ + +
+
+ + + + + +
+
Conversations API
+
+
+

Conversations API

+

The Slack Conversations API provides your app with a unified interface to work with all the +channel-like things encountered in Slack; public channels, private channels, direct messages, group +direct messages, and our newest channel type, Shared Channels.

+

See Conversations API docs for more info.

+
+
+

Creating a direct message or multi-person direct message

+

This Conversations API method opens a multi-person direct message or just a 1:1 direct message.

+

Use conversations.create for public or private channels.

+

Provide 1 to 8 user IDs in the user parameter to open or resume a conversation. Providing only +1 ID will create a direct message. Providing more will create an mpim.

+

If there are no conversations already in progress including that exact set of members, a new +multi-person direct message conversation begins.

+

Subsequent calls to conversations.open with the same set of users will return the already +existing conversation.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call(
+  "conversations.open",
+  users=["W1234567890","U2345678901","U3456789012"]
+)
+
+
+

See conversations.open additional info.

+
+
+
+

Creating a public or private channel

+

Initiates a public or private channel-based conversation

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call(
+  "conversations.create",
+  name="myprivatechannel",
+  is_private=True
+)
+
+
+

See conversations.create additional info.

+
+
+
+

Getting information about a conversation

+

This Conversations API method returns information about a workspace conversation.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call(
+  "conversations.info",
+  channel="C0XXXXXX",
+)
+
+
+

See conversations.info for more info.

+
+
+
+

Getting a list of conversations

+

This Conversations API method returns a list of all channel-like conversations in a workspace. +The “channels” returned depend on what the calling token has access to and the directives placed +in the types parameter.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call("conversations.list")
+
+
+

Only public conversations are included by default. You may include additional conversations types +by passing types (as a string) into your list request. Additional conversation types include +public_channel and private_channel.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+# Note that `types` is a string
+sc.api_call(
+  "conversations.list",
+  types="public_channel, private_channel"
+)
+
+
+

See conversations.list for more info.

+
+
+
+

Leaving a conversation

+

Maybe you’ve finished up all the business you had in a conversation, or maybe you +joined one by accident. This is how you leave a conversation.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call(
+  "conversations.leave",
+  channel="C0XXXXXXX"
+)
+
+
+

See conversations.leave for more info.

+
+
+
+

Get conversation members

+

Get a list fo the members of a conversation

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.api_call("conversations.members",
+  channel="C0XXXXXXX"
+)
+
+
+

See users.list for more info.

+
+
+ + +
+
+
+ + +
+
+ +
+

© 2019 Slack Technologies, Inc. and contributors

+
+ + + + + + + \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/faq.html b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/faq.html new file mode 100644 index 0000000000..98d7916613 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/faq.html @@ -0,0 +1,230 @@ + + + + + + + Frequently Asked Questions — Slack Developer Kit for Python + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + Slack Developer Kit for Python + + +
+ + +
+
+ + + + + +
+
Frequently Asked Questions
+
+
+

Frequently Asked Questions

+
+

What even is Slack Developer Kit for Python and why should I care?

+

Slack Developer Kit for Python is a wrapper around commonly accessed parts of the Slack Platform. It provides basic mechanisms for +using the Slack Web API from within your Python app.

+

On the other hand, Slack Developer Kit for Python does not provide access to the Events bot-building API, but +[this adapter](https://github.com/slackapi/python-slack-events-api) does.

+
+
+

OMG I found a bug!

+

Well, poop. Take a deep breath, and then let us know on the Issue Tracker. If you’re feeling particularly ambitious, +why not submit a pull request with a bug fix?

+
+
+

Hey, there’s a feature missing!

+

There’s always something more that could be added! You can let us know in the Issue Tracker to start a discussion +around the proposed feature, that’s a good start. If you’re feeling particularly ambitious, why not write the feature +yourself, and submit a pull request! We love feedback and we love help and we don’t bite. Much.

+
+
+

I’d like to contribute…but how?

+

What an excellent question. First of all, please have a look at our general contributing guidelines. We’ll wait for +you here.

+

All done? Great! While we’re super excited to incorporate your new feature into Slack Developer Kit for Python, there are a +couple of things we want to make sure you’ve given thought to.

+
    +
  • Please write unit tests for your new code. But don’t just aim to increase the test coverage, rather, we expect you +to have written thoughtful tests that ensure your new feature will continue to work as expected, and to help future +contributors to ensure they don’t break it!
  • +
  • Please document your new feature. Think about concrete use cases for your feature, and add a section to the +appropriate document, including a complete sample program that demonstrates your feature. Don’t forget to update +the changelog in changelog.rst!
  • +
+

Including these two items with your pull request will totally make our day—and, more importantly, your future users’ days!

+

On that note…

+
+
+

How do I compile the documentation?

+

This project’s documentation is generated with Sphinx. If you are editing one of the many +reStructuredText files in the docs-src folder, you’ll need to rebuild the documentation. It is recommended to run +the following steps inside a virtualenv environment.

+
tox -e docs
+
+
+

Do be sure to add the docs folder and its contents to your pull request!

+
+
+ + +
+
+
+ + +
+
+ +
+

© 2019 Slack Technologies, Inc. and contributors

+
+ + + + + + + \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/genindex.html b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/genindex.html new file mode 100644 index 0000000000..615d99ec64 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/genindex.html @@ -0,0 +1,189 @@ + + + + + + + + Index — Slack Developer Kit for Python + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + Slack Developer Kit for Python + + +
+ + +
+
+ + + + + +
+
Index
+
+ +

Index

+ +
+ +
+ + +
+
+
+ + +
+
+ +
+

© 2019 Slack Technologies, Inc. and contributors

+
+ + + + + + + \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/index.html b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/index.html new file mode 100644 index 0000000000..e88e84bf18 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/index.html @@ -0,0 +1,211 @@ + + + + + + + Slack Developer Kit for Python — Slack Developer Kit for Python + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + Slack Developer Kit for Python + + +
+ + +
+
+ + + + + +
+
Slack Developer Kit for Python
+
+
+
+
+

Slack Developer Kit for Python

+

Whether you’re building a custom app for your team, or integrating a third party +service into your Slack workflows, Slack Developer Kit for Python allows you to leverage the flexibility +of Python to get your project up and running as quickly as possible.

+
+

Requirements and Installation

+

We recommend using PyPI to install Slack Developer Kit for Python

+
pip install slackclient
+
+
+

Of course, if you prefer doing things the hard way, you can always implement Slack Developer Kit for Python +by pulling down the source code directly into your project:

+
git clone https://github.com/slackapi/python-slackclient.git
+pip install -r requirements.txt
+
+
+
+
+

Getting Help

+

If you get stuck, we’re here to help. The following are the best ways to get assistance working through your issue:

+
    +
  • Use our Github Issue Tracker for reporting bugs or requesting features.
  • +
  • Visit the Bot Developer Hangout for getting help using Slack Developer Kit for Python or just generally bond with your fellow Slack developers.
  • +
+
+
+ + +
+
+
+ + +
+
+ +
+

© 2019 Slack Technologies, Inc. and contributors

+
+ + + + + + + \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/metadata.html b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/metadata.html new file mode 100644 index 0000000000..87e93ebaf6 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/metadata.html @@ -0,0 +1,182 @@ + + + + + + + <no title> — Slack Developer Kit for Python + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + Slack Developer Kit for Python + + +
+ + +
+
+ + + + + +
+
<no title>
+
+ + +
+
+
+ + +
+
+ +
+

© 2019 Slack Technologies, Inc. and contributors

+
+ + + + + + + \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/objects.inv b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/objects.inv new file mode 100644 index 0000000000..6fa1db8dfa --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/objects.inv @@ -0,0 +1,7 @@ +# Sphinx inventory version 2 +# Project: Slack Developer Kit for Python +# Version: 1.0 +# The remainder of this file is compressed using zlib. +x}N0 y +KCER!&4iqkIפc{{-Np:w!tMej;2LXjCR%V"ix+VyuK +@ ,P$TJr:"BGOE|6AHJ;M뿴tR;G$,hTOݑ e?72>@kiA[#( )_8!03qk`*ߚ !=h>T`jU9$3Utn[B^SR. s0 `a].b9fgrQy_kIhu#d6oM \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/real_time_messaging.html b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/real_time_messaging.html new file mode 100644 index 0000000000..6cc67a7386 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/real_time_messaging.html @@ -0,0 +1,290 @@ + + + + + + + Real Time Messaging (RTM) — Slack Developer Kit for Python + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + Slack Developer Kit for Python + + +
+ + +
+
+ + + + + +
+
Real Time Messaging (RTM)
+
+
+

Real Time Messaging (RTM)

+

The Real Time Messaging (RTM) API is a WebSocket-based API that allows you to +receive events from Slack in real time and send messages as users.

+

If you prefer events to be pushed to you instead, we recommend using the +HTTP-based Events API instead. +Most event types supported by the RTM API are also available +in the Events API.

+

See Tokens & Authentication for API token handling best practices.

+
+

Connecting to the RTM API

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+if sc.rtm_connect():
+  while sc.server.connected is True:
+        print sc.rtm_read()
+        time.sleep(1)
+else:
+    print "Connection Failed"
+
+
+

If you connect successfully the first event received will be a hello:

+
{
+  u'type': u'hello'
+}
+
+
+

If there was a problem connecting an error will be returned, including a descriptive error message:

+
{
+  u'type': u'error',
+    u'error': {
+    u'code': 1,
+    u'msg': u'Socket URL has expired'
+  }
+}
+
+
+
+
+

rtm.start vs rtm.connect

+

If you expect your app to be used on large teams, we recommend starting the RTM client with rtm.connect rather than the default connection method for this client, rtm.start. +rtm.connect provides a lighter initial connection payload, without the team’s channel and user information included. You’ll need to request channel and user info via +the Web API separately.

+

To do this, simply pass with_team_state=False into the rtm_connect call, like so:

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+if sc.rtm_connect(with_team_state=False):
+    while True:
+        print sc.rtm_read()
+        time.sleep(1)
+else:
+    print "Connection Failed"
+
+
+

Passing auto_reconnect=True will tell the websocket client to automatically reconnect if the connection gets dropped.

+

See the rtm.start docs and the rtm.connect docs +for more details.

+
+
+

RTM Events

+
{
+  u'type': u'message',
+  u'ts': u'1358878749.000002',
+  u'user': u'U023BECGF',
+  u'text': u'Hello'
+}
+
+
+

See RTM Events for a complete list of events.

+
+
+

Sending messages via the RTM API

+

You can send a message to Slack by sending JSON over the websocket connection.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.rtm_send_message("welcome-test", "test")
+
+
+

You can send a message to a private group or direct message channel in the same +way, but using a Group ID (C024BE91L) or DM channel ID (D024BE91L).

+

You can send a message in reply to a thread using the thread argument, and +optionally broadcast that message back to the channel by setting +reply_broadcast to True.

+
from slackclient import SlackClient
+
+slack_token = os.environ["SLACK_API_TOKEN"]
+sc = SlackClient(slack_token)
+
+sc.rtm_send_message("welcome-test", "test", "1482960137.003543", True)
+
+
+

See Threading messages +for more details on using threads.

+

The RTM API only supports posting messages with basic formatting. +It does not support attachments or other message formatting modes.

+
+
To post a more complex message as a user, see Web API usage.
+
+
+ + +
+
+
+ + +
+
+ +
+

© 2019 Slack Technologies, Inc. and contributors

+
+ + + + + + + \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/search.html b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/search.html new file mode 100644 index 0000000000..84d7cb9dc5 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/search.html @@ -0,0 +1,204 @@ + + + + + + + Search — Slack Developer Kit for Python + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + Slack Developer Kit for Python + + +
+ + +
+
+ + + + + +
+
Search
+
+

Search

+
+ +

+ Please activate JavaScript to enable the search + functionality. +

+
+

+ From here you can search these documents. Enter your search + words into the box below and click "search". Note that the search + function will automatically search for all of the words. Pages + containing fewer words won't appear in the result list. +

+
+ + + +
+ +
+ +
+ +
+
+
+ + +
+
+ +
+

© 2019 Slack Technologies, Inc. and contributors

+
+ + + + + + + \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/searchindex.js b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/searchindex.js new file mode 100644 index 0000000000..a6691c9095 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/docs/searchindex.js @@ -0,0 +1 @@ +Search.setIndex({docnames:["about","auth","basic_usage","changelog","conversations","faq","index","metadata","real_time_messaging"],envversion:{"sphinx.domains.c":1,"sphinx.domains.changeset":1,"sphinx.domains.cpp":1,"sphinx.domains.javascript":1,"sphinx.domains.math":2,"sphinx.domains.python":1,"sphinx.domains.rst":1,"sphinx.domains.std":1,sphinx:54},filenames:["about.rst","auth.rst","basic_usage.rst","changelog.rst","conversations.rst","faq.rst","index.rst","metadata.rst","real_time_messaging.rst"],objects:{},objnames:{},objtypes:{},terms:{"0cb4bcd6e887b428e27e8059b6278b86ee661aaa":3,"1046cc2375a85a22e94573e2aad954ba7287c886":3,"1920s":2,"7d01515cebc80918a29100b0e4793790eb83e7b9":3,"boolean":2,"break":[3,5],"case":5,"class":3,"default":[2,3,4,8],"function":3,"import":[1,2,3,4,8],"int":2,"long":2,"new":[1,2,3,4,5],"public":1,"return":[1,2,3,4,8],"short":[2,3],"super":5,"switch":3,"true":[2,3,4,8],"try":1,"while":[2,5,8],Added:3,But:5,For:[1,2],IDs:4,IMs:2,One:[1,2],The:[2,4,6,8],Then:1,There:[2,5],Use:[3,4,6],__eq__:3,__name__:1,aadd:3,abc:1,abil:3,abl:1,about:[2,3,5],abov:1,acair:3,accept:1,access:[0,1,3,4,5],access_token:1,accessori:2,accid:[2,4],action:[1,3],actual:2,adapt:5,add:[1,2,3,5],added:[3,5],addit:[1,2,4],after:[1,2],agre:1,agreement:0,aim:5,all:[2,4,5],allow:[2,3,6,8],alreadi:[2,4],already_in_channel:2,also:[2,8],alt_text:2,alwai:[5,6],ambiti:5,ani:2,anoth:[2,3],aoberoi:3,api:[0,1,3,5],api_cal:[1,2,3,4],app:[0,2,4,5,6,8],appear:2,applic:[1,2],appropri:5,approv:1,archiv:2,arg:[1,3],argument:[2,8],around:5,articl:2,assign:2,assist:6,attach:[2,8],attribut:2,auth:[1,3],auth_cod:1,auth_respons:1,authent:[2,3,8],author:1,authorship:2,auto_reconnect:[3,8],automat:[3,8],avail:[1,2,8],averag:2,avoid:1,axe:2,back:8,bad:3,base:[4,8],basic:[5,8],becom:2,been:[1,2],befor:[2,3],begin:[1,4],begin_auth:1,behalf:1,below:2,benoitlavign:3,best:[1,2,6,8],between:2,bite:5,block:2,bond:6,bot:[1,2,5,6],bot_access_token:1,both:2,box:2,breath:5,broadcast:[2,8],bug:[3,6],build:[0,1,2,3,5,6],builder:2,burst:2,busi:[2,4],button:[1,2],c024be91l:8,c0xxxxxx:[2,4],c0xxxxxxx:[2,4],c0xxxxxxy:2,c3ukjtqac:2,cach:3,call:[1,2,3,4,8],can:[1,2,3,5,6,8],cannot:2,caus:3,cclauss:3,chang:[1,2,3],changelog:5,channel:[3,8],channnel:3,chat:2,check:2,clean:3,click:1,client:[1,3,8],client_id:1,client_secret:1,clone:6,code:[0,1,3,5,6,8],com:[1,2,3,5,6],combin:2,command:1,comment:[2,3],commit:3,commonli:[2,5],comparison:3,compat:3,complet:[1,2,5,8],complex:[2,8],concret:5,conduct:0,config:1,configur:3,connect:3,consider:2,contain:[1,2],content:5,context:[1,2],continu:[2,5],contribut:0,contributor:[0,3,5],convers:2,copyright:3,could:[1,5],counter:3,coupl:[3,5],cours:6,coverag:5,creat:3,createchild:3,credenti:1,custom:[1,3,6],d024be91l:8,d45285d2f1025899dcd65e259624ee73771f94bb:3,dai:5,danni:2,databas:1,deal:2,decod:3,deep:5,def:[1,2],defin:1,delai:2,demonstr:5,depend:[1,4],descend:2,describ:3,descript:8,design:2,detail:8,differ:[1,2],direct:[1,2,8],directli:[2,6],discuss:5,doc:[3,4,5,8],document:[1,2,3],doe:[5,8],doesn:3,doing:6,don:[1,5],done:[1,5],door:2,down:6,drop:8,duplic:3,easier:2,edit:5,effect:1,elif:2,els:8,email:3,empti:1,encod:3,encount:4,endpoint:[1,2],enforc:3,ensur:5,entir:1,environ:[1,2,3,4,5,8],environment:1,ephemer:2,error:[2,3,8],event:5,exact:4,exampl:[1,2],exce:2,excel:5,except:[2,3],exchang:2,excit:[2,5],exclud:2,exclude_archiv:2,exist:4,expect:[5,8],experi:1,expir:[3,8],explicitli:1,expos:3,f7bb8889580cc34471ba1ddc05afc34d1a5efa23:3,fail:[2,3,8],fals:[2,8],far:2,featur:[1,3,6],feedback:5,feel:[2,5],fellow:6,felt:2,fetch:2,few:1,field:2,file:[3,5],file_com:2,file_cont:2,find:2,finish:[2,4],finish_auth:1,first:[5,8],fix:[2,3,5],flask:1,flexibl:6,folder:5,follow:[2,5,6],forget:[1,5],fork:2,format:[1,2,3,8],found:1,from:[0,1,2,3,4,5,8],full:2,fun:2,futur:5,gener:[1,5,6],german:2,get:[1,3,8],git:6,github:[3,5,6],given:5,global:1,good:5,grant:1,great:5,greater:2,group:[2,3,4,8],guest:2,guidelin:[3,5],had:[2,4],hand:5,handl:[2,3,8],hangout:6,hard:6,hardcod:1,harlowja:3,has:[1,4,8],haunt:2,have:[2,5],header:[2,3],hello:[2,8],help:5,here:[1,2,5,6],hole:2,hop:2,hotel:2,how:[2,4],howev:2,href:1,http:[1,2,3,5,6,8],hub:2,ids:1,imag:2,image_url:2,implement:[1,6],importantli:5,improv:3,includ:[1,2,3,4,5,8],incom:1,incorpor:5,incorrectli:3,increas:5,index:3,indic:2,info:[3,4,8],inform:[1,2,8],initi:[1,4,8],insid:5,instal:1,instead:[1,2,3,8],integr:[2,3,6],interact:2,interfac:4,intern:3,introduc:3,invit:2,is_priv:4,issu:[3,5,6],item:[2,5],its:[3,5],itself:2,jayalan:3,join:[3,4],jpeg:2,json:[1,2,3,8],just:[2,4,5,6],kamushaden:3,keep:1,kei:[1,2],kelvintaywl:3,kind:[1,2],kit:2,know:[1,5],kt5356:3,larg:[3,8],later:1,left:2,let:[0,1,2,5],level:1,leverag:6,licens:[0,3],lighter:8,like:[2,3,4,8],limit:3,linear:2,link:[1,3],lint:3,list:[3,8],liter:2,live:3,load:3,local:3,log:[1,3],login:3,longer:2,look:[2,5],love:5,mai:[2,3,4],maintain:0,make:[1,2,5],mani:[2,5],mayb:[2,4],mean:2,mechan:5,mention:1,messag:3,method:[1,2,4,8],might:2,mode:8,modular:2,more:[2,4,5,8],most:[2,8],move:3,mpdm:3,mpim:[3,4],mrkdwn:2,msg:8,much:5,must:[1,2],myapp:1,myprivatechannel:4,name:[2,3,4],nearli:2,need:[1,2,5,8],nefari:1,never:1,newest:4,node:1,non:3,note:[2,4,5],now:3,number:2,oauth_scop:1,object:[2,3],off:2,onc:[1,2],one:[1,2,4,5],onli:[2,4,8],open:[2,3,4],option:[2,8],order:1,origin:2,other:[3,5,8],our:[1,4,5,6],out:[1,2],over:[2,3,8],overlook:2,own:2,packag:[2,3],page:[1,2],param:[1,3],paramet:[2,3,4],parent:[2,3],part:5,parti:6,particularli:5,pass:[1,2,3,4,8],payload:8,peopl:2,pep:3,per:2,perform:1,period:2,permiss:1,persist:1,pexel:2,photo:2,ping:3,pip:6,place:[2,4],platform:[0,5],playground:2,pleas:[1,5],png:2,point:[2,3],poop:5,possibl:[1,6],post:[1,2,8],post_instal:1,postephemer:2,postmessag:2,practic:[2,8],pre_instal:1,prefer:[6,8],prevent:3,primari:2,print:[2,8],privat:[3,8],private_channel:4,problem:8,program:5,progress:4,project:[5,6],properli:3,properti:[2,3],propos:5,prototyp:2,proudli:0,provid:[1,2,4,5,8],proxi:3,public_channel:4,publish:1,pull:[1,5,6],purpos:2,push:8,pypi:6,python:[1,2,3],queri:1,quickli:[2,6],rate:3,rather:[3,5,8],read:[1,2],readm:3,rebuild:5,receiv:8,recommend:[1,5,6,8],reconnect:[3,8],redirect:1,refer:2,reflect:2,refresh:3,refus:1,regular:2,reinstal:1,releg:2,remov:3,repli:[3,8],reply_broadcast:[2,8],report:6,repositori:1,request:[1,2,3,4,5,6,8],requir:[1,2,3],respond:2,respons:[1,2,3],responseparseerror:3,restructuredtext:5,result:[2,3],resum:4,retri:2,retriev:1,review:[1,2],roach:3,room:2,rout:1,rowdi:2,rst:[3,5],rtm:3,rtm_connect:[3,8],rtm_read:8,rtm_send_messag:[3,8],run:[5,6],runtim:1,safe:1,sai:2,same:[1,2,4,8],sampart:3,sampl:5,save:[1,2],schlueter:3,scope:[1,2],search:3,second:2,secret:1,section:[1,2,5],see:[1,2,4,8],semver:3,send_messag:3,send_slack_messag:2,sent:2,separ:8,server:[1,3,8],servic:6,set:[1,2,3,4,8],setup:1,share:[1,4],should:1,show:2,sign:1,simpl:2,simpler:2,simpli:[2,8],sinc:1,singl:2,slack:[1,2,3,4,8],slack_api_token:[2,4,8],slack_bot_scop:1,slack_bot_token:1,slack_client_id:1,slack_client_secret:1,slack_token:[2,4,8],slack_user_token:1,slackapi:[3,5,6],slackclient:[1,2,3,4,6,8],slackclienterror:3,slash:1,sleep:[2,8],slightli:2,social:2,socket:8,some:[2,3],someth:5,sometim:2,sorri:3,sourc:6,special:2,specif:[1,2],specifi:2,sphinx:5,src:5,star:2,start:[1,2,5],stasfilin:3,state:2,statu:2,step:5,store:1,str:2,string:[1,3,4],stuck:[2,6],submit:5,subsequ:4,succeed:[1,2],success:1,successfulli:[2,8],support:[3,8],sure:[2,5],tada:2,take:[1,2,5],team:[0,1,3,6,8],techniqu:1,tell:[2,3,8],test:[1,2,3,5,8],text:[2,8],than:[2,3,8],thank:3,thei:[2,3,5],them:[1,2],thi:[1,2,4,5,8],thing:[2,3,4,5,6],think:5,thinking_very_much:2,third:6,those:2,thought:5,thread:[3,8],thread_t:2,through:6,thumbsup:2,tidi:3,time:2,timelin:2,timeout:3,timestamp:2,timfeirg:3,titl:2,togeth:2,token:[2,3,4,8],too:2,tool:[0,2],top:1,torrenc:2,total:5,tox:[3,5],traceback:3,tracker:[5,6],travi:3,two:[1,5],txt:6,type:[2,3,4,8],typo:[2,3],u023becgf:8,u0xxxxxxx:2,u2345678901:4,u3456789012:4,unifi:4,uniqu:2,unit:5,until:2,unus:3,updat:[3,5],upon:1,url:[1,3,8],urllib:3,usag:[1,8],use:[1,2,3,5],used:[1,2,8],user:[1,2,3,4,5,8],using:[1,3,5,6,8],valid:1,variabl:1,varieti:1,veri:2,verif:1,version:3,virtualenv:5,visibl:2,visit:6,vote:2,vscode:3,w1234567890:4,wai:[1,2,6,8],wait:[2,5],want:[1,2,5],web:[0,1,3,5,8],webhook:1,websocket:[3,8],welcom:8,well:[1,5],what:[1,2,4],when:[1,2,3],where:[1,2,3],whether:[2,6],which:[1,2,3],whole:2,with_team_st:8,within:[1,5],without:8,won:2,word:2,work:[2,3,4,5,6],workflow:6,workspac:4,wrapper:[2,5],write:5,written:5,xoxb:1,yield:1,you:[0,1,2,3,4,5,6,8],your:[0,1,2,4,5,6,8],yourself:5},titles:["About","Tokens & Authentication","Basic Usage","Changelog","Conversations API","Frequently Asked Questions","Slack Developer Kit for Python","<no title>","Real Time Messaging (RTM)"],titleterms:{"public":4,Adding:2,The:1,about:[0,4],api:[2,4,8],app:1,ask:5,authent:1,basic:2,bug:5,care:5,changelog:3,channel:[2,4],compil:5,connect:8,content:2,contribut:5,convers:4,creat:[2,4],custom:2,data:1,delet:2,develop:[0,5,6],direct:4,document:5,emoji:2,even:5,event:8,featur:5,file:2,flow:1,found:5,frequent:5,get:[2,4,6],handl:1,hei:5,help:6,how:5,info:2,inform:4,instal:6,join:2,kit:[0,5,6],layout:2,leav:[2,4],like:5,limit:2,list:[2,4],member:[2,4],messag:[2,4,8],miss:5,multi:4,oauth:1,omg:5,other:1,person:4,privat:4,python:[0,5,6],question:5,rate:2,reaction:2,real:8,remov:2,repli:2,requir:6,rtm:8,send:[2,8],sensit:1,should:5,singl:1,slack:[0,5,6],start:8,team:2,thread:2,time:8,token:1,updat:2,upload:2,usag:2,via:8,web:2,what:5,why:5,workspac:1}}) \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/requirements.txt b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/requirements.txt new file mode 100644 index 0000000000..cd8c47d3d7 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/requirements.txt @@ -0,0 +1,3 @@ +--index-url https://pypi.python.org/simple/ + +-e . diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/setup.cfg b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/setup.cfg new file mode 100644 index 0000000000..24cf69da18 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/setup.cfg @@ -0,0 +1,5 @@ +[metadata] +description-file = README.rst + +[bdist_wheel] +universal=1 \ No newline at end of file diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/setup.py b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/setup.py new file mode 100644 index 0000000000..c6e3402738 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/setup.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +from setuptools import setup, find_packages +import io +import os +import re + + +def read(*names, **kwargs): + with io.open( + os.path.join(os.path.dirname(__file__), *names), + encoding=kwargs.get("encoding", "utf8") + ) as fp: + return fp.read() + + +long_description = read('README.rst') + + +def find_version(*file_paths): + version_file = read(*file_paths) + version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) + if version_match: + return version_match.group(1) + raise RuntimeError("Unable to find version string.") + + +setup(name='slackclient', + version=find_version('slackclient', 'version.py'), + description='Slack API clients for Web API and RTM API', + long_description=long_description, + url='https://github.com/slackapi/python-slackclient', + author='Slack Technologies, Inc.', + author_email='opensource@slack.com', + license='MIT', + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Intended Audience :: Developers', + 'Topic :: Communications :: Chat', + 'Topic :: System :: Networking', + 'Topic :: Office/Business', + 'License :: OSI Approved :: MIT License', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + ], + keywords='slack slack-web slack-rtm chat chatbots bots chatops', + packages=find_packages(exclude=['docs', 'docs-src', 'tests']), + install_requires=[ + 'websocket-client >=0.35, <0.55.0', + 'requests >=2.11, <3.0a0', + 'six >=1.10, <2.0a0', + ]) diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/__init__.py b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/__init__.py new file mode 100644 index 0000000000..776c7ba3fe --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/__init__.py @@ -0,0 +1 @@ +from .client import SlackClient # noqa diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/channel.py b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/channel.py new file mode 100644 index 0000000000..ad6e8b9ce7 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/channel.py @@ -0,0 +1,46 @@ +class Channel(object): + ''' + A Channel represents a public or private Slack Channel instance + ''' + def __init__(self, server, name, channel_id, members=None): + self.server = server + self.name = name + self.id = channel_id + self.members = [] if members is None else members + + def __eq__(self, compare_str): + if self.name == compare_str or "#" + self.name == compare_str or self.id == compare_str: + return True + else: + return False + + def __hash__(self): + return hash(self.id) + + def __str__(self): + data = "" + for key in list(self.__dict__.keys()): + data += "{0} : {1}\n".format(key, str(self.__dict__[key])[:40]) + return data + + def __repr__(self): + return self.__str__() + + def send_message(self, message, thread=None, reply_broadcast=False): + ''' + Sends a message to a this Channel. + + Include the parent message's thread_ts value in `thread` + to send to a thread. + + :Args: + message (message) - the string you'd like to send to the channel + thread (str or None) - the parent message ID, if sending to a + thread + reply_broadcast (bool) - if messaging a thread, whether to + also send the message back to the channel + + :Returns: + None + ''' + self.server.rtm_send_message(self.id, message, thread, reply_broadcast) diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/client.py b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/client.py new file mode 100644 index 0000000000..0e3dfde5e7 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/client.py @@ -0,0 +1,295 @@ +#!/usr/bin/python +# mostly a proxy object to abstract how some of this works + +import json +import logging +import time + +from .server import Server +from .exceptions import ParseResponseError, TokenRefreshError + + +LOG = logging.getLogger(__name__) + + +class SlackClient(object): + """ + The SlackClient makes API Calls to the `Slack Web API `_ as well as + managing connections to the `Real-time Messaging API via websocket `_ + + It also manages some of the Client state for Channels that the associated token (User or Bot) + is associated with. + + For more information, check out the `Slack API Docs `_ + """ + + def __init__( + self, + token=None, + refresh_token=None, + token_update_callback=None, + client_id=None, + client_secret=None, + proxies=None, + **kwargs + ): + """ + Init: + :Args: + token (str): Your Slack Authentication token. You can find or generate a test token + `here `_ + Note: Be `careful with your token `_ + proxies (dict): Proxies to use when create websocket or api calls, + declare http and websocket proxies using {'http': 'http://127.0.0.1'}, + and https proxy using {'https': 'https://127.0.0.1:443'} + refresh_token (str): Your Slack app's refresh token. This token is used to + update your app's OAuth access token + client_id (str): Your app's Client ID + client_secret (srt): Your app's Client Secret (Used for OAuth requests) + refresh_callback (function): Your application's function for updating Slack + OAuth tokens inside your data store + """ + + self.client_id = client_id + self.client_secret = client_secret + self.refresh_token = refresh_token + self.token_update_callback = token_update_callback + self.token = token + self.access_token_expires_at = 0 + + if refresh_token: + if callable(token_update_callback): + self.server = Server( + connect=False, + proxies=proxies, + refresh_token=refresh_token, + client_id=client_id, + client_secret=client_secret, + token_update_callback=token_update_callback, + ) + else: + raise TokenRefreshError( + "Token refresh callback function is required when using refresh token." + ) + else: + # Slack app configs + self.server = Server(token=token, connect=False, proxies=proxies) + + def refresh_access_token(self): + """ + Refresh the client's OAUth access tokens + https://api.slack.com/docs/rotating-and-refreshing-credentials + """ + post_data = { + "refresh_token": self.refresh_token, + "grant_type": "refresh_token", + "client_id": self.client_id, + "client_secret": self.client_secret, + } + response = self.server.api_requester.post_http_request( + self.refresh_token, api_method="oauth.access", post_data=post_data + ) + response_json = json.loads(response.text) + + # If Slack returned an updated access token, update the client, otherwise + # raise TokenRefreshError exception with the error returned from the API + if response_json["ok"]: + # Update the client's access token and expiration timestamp + self.team_id = response_json["team_id"] + # TODO: Minimize the numer of places token is stored. + self.token = response_json["access_token"] + self.server.token = response_json["access_token"] + + # Update the token expiration timestamp + current_ts = int(time.time()) + expires_at = int(current_ts + response_json["expires_in"]) + self.access_token_expires_at = expires_at + # Call the developer's token update callback + update_args = { + "enterprise_id": response_json["enterprise_id"], + "team_id": response_json["team_id"], + "access_token": response_json["access_token"], + "expires_in": response_json["expires_in"], + } + self.token_update_callback(update_args) + else: + raise TokenRefreshError("Token refresh failed") + + def append_user_agent(self, name, version): + self.server.append_user_agent(name, version) + + def rtm_connect(self, with_team_state=True, **kwargs): + """ + Connects to the RTM Websocket + + :Args: + with_team_state (bool): Connect via `rtm.start` to pull workspace state information. + `False` connects via `rtm.connect`, which is lighter weight and better for very large + teams. + + :Returns: + False on exceptions + """ + + if self.refresh_token: + raise TokenRefreshError( + "Workspace tokens may not be used to connect to the RTM API." + ) + + try: + self.server.rtm_connect(use_rtm_start=with_team_state, **kwargs) + return self.server.connected + except Exception: + LOG.warn("Failed RTM connect", exc_info=True) + return False + + def api_call(self, method, timeout=None, **kwargs): + """ + Call the Slack Web API as documented here: https://api.slack.com/web + + :Args: + method (str): The API Method to call. See + `the full list here `_ + :Kwargs: + (optional) kwargs: any arguments passed here will be bundled and sent to the api + requester as post_data and will be passed along to the API. + + Example:: + + sc.api_call( + "channels.setPurpose", + channel="CABC12345", + purpose="Writing some code!" + ) + + :Returns: + str -- returns the text of the HTTP response. + + Examples:: + + u'{"ok":true,"purpose":"Testing bots"}' + or + u'{"ok":false,"error":"channel_not_found"}' + + See here for more information on responses: https://api.slack.com/web + """ + # Check for missing or expired access token before submitting the request + if method != "oauth.access" and self.refresh_token: + current_ts = int(time.time()) + token_is_expired = current_ts > self.access_token_expires_at + if token_is_expired or self.token is None: + self.refresh_access_token() + + response_body = self.server.api_call( + self.token, request=method, timeout=timeout, **kwargs + ) + + # Attempt to parse the response as JSON + try: + result = json.loads(response_body) + except ValueError as json_decode_error: + raise ParseResponseError(response_body, json_decode_error) + response_json = json.loads(response_body) + + if result.get("ok", False): + if method == "im.open": + self.server.attach_channel(kwargs["user"], result["channel"]["id"]) + elif method in ("mpim.open", "groups.create", "groups.createchild"): + self.server.parse_channel_data([result["group"]]) + elif method in ("channels.create", "channels.join"): + self.server.parse_channel_data([result["channel"]]) + else: + # if the API request returns an invalid_auth error, refresh the token and try again + if ( + self.refresh_token + and "error" in response_json + and response_json["error"] == "invalid_auth" + ): + self.refresh_access_token() + # If token refresh was successful, retry the original API request + return self.api_call(method, timeout, **kwargs) + return result + + def rtm_read(self): + """ + Reads from the RTM Websocket stream then calls `self.process_changes(item)` for each line + in the returned data. + + Multiple events may be returned, always returns a list [], which is empty if there are no + incoming messages. + + :Args: + None + + :Returns: + data (json) - The server response. For example:: + + [{u'presence': u'active', u'type': u'presence_change', u'user': u'UABC1234'}] + + :Raises: + SlackNotConnected if self.server is not defined. + """ + # in the future, this should handle some events internally i.e. channel + # creation + if self.server: + json_data = self.server.websocket_safe_read() + data = [] + if json_data != "": + for d in json_data.split("\n"): + data.append(json.loads(d)) + for item in data: + self.process_changes(item) + return data + else: + raise SlackNotConnected + + def rtm_send_message(self, channel, message, thread=None, reply_broadcast=None): + """ + Sends a message to a given channel. + + :Args: + channel (str) - the string identifier for a channel or channel name (e.g. 'C1234ABC', + 'bot-test' or '#bot-test') + message (message) - the string you'd like to send to the channel + thread (str or None) - the parent message ID, if sending to a + thread + reply_broadcast (bool) - if messaging a thread, whether to + also send the message back to the channel + + :Returns: + None + + """ + # The `channel` argument can be a channel name or an ID. At first its assumed to be a + # name and an attempt is made to find the ID in the workspace state cache. + # If that lookup fails, the argument is used as the channel ID. + found_channel = self.server.channels.find(channel) + channel_id = found_channel.id if found_channel else channel + return self.server.rtm_send_message( + channel_id, message, thread, reply_broadcast + ) + + def process_changes(self, data): + """ + Internal method which processes RTM events and modifies the local data store + accordingly. + + Stores new channels when joining a group (Multi-party DM), IM (DM) or channel. + + Stores user data on a team join event. + """ + if "type" in data.keys(): + if data["type"] in ("channel_created", "group_joined"): + channel = data["channel"] + self.server.attach_channel(channel["name"], channel["id"], []) + if data["type"] == "im_created": + channel = data["channel"] + self.server.attach_channel(channel["user"], channel["id"], []) + if data["type"] == "team_join": + user = data["user"] + self.server.parse_user_data([user]) + pass + + +class SlackNotConnected(Exception): + pass diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/exceptions.py b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/exceptions.py new file mode 100644 index 0000000000..d8674567ce --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/exceptions.py @@ -0,0 +1,29 @@ +class SlackClientError(Exception): + """ + Base exception for all errors raised by the SlackClient library + """ + def __init__(self, msg=None): + if msg is None: + # default error message + msg = "An error occurred in the SlackClient library" + super(SlackClientError, self).__init__(msg) + + +class ParseResponseError(SlackClientError, ValueError): + """ + Error raised when responses to Web API methods cannot be parsed as valid JSON + """ + def __init__(self, response_body, original_exception): + super(ParseResponseError, self).__init__( + "Slack API response body could not be parsed: {0}. Original exception: {1}".format( + response_body, original_exception + ) + ) + self.response_body = response_body + self.original_exception = original_exception + + +class TokenRefreshError(SlackClientError): + """ + This exception is rasied when a token related error occurs within the client + """ diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/im.py b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/im.py new file mode 100644 index 0000000000..b615925354 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/im.py @@ -0,0 +1,40 @@ +class Im(object): + ''' + IMs represent direct message channels between two users on Slack. + ''' + def __init__(self, server, user, im_id): + self.server = server + self.user = user + self.id = im_id + + def __eq__(self, compare_str): + if self.id == compare_str or self.user == compare_str: + return True + else: + return False + + def __hash__(self): + return hash(self.id) + + def __str__(self): + data = "" + for key in list(self.__dict__.keys()): + if key != "server": + data += "{0} : {1}\n".format(key, str(self.__dict__[key])[:40]) + return data + + def __repr__(self): + return self.__str__() + + def send_message(self, message): + ''' + Sends a message to a this IM (or DM depending on your preferred terminology). + + :Args: + message (message) - the string you'd like to send to the IM + + :Returns: + None + ''' + message_json = {"type": "message", "channel": self.id, "text": message} + self.server.send_to_websocket(message_json) diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/server.py b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/server.py new file mode 100644 index 0000000000..04e6537da7 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/slackclient/server.py @@ -0,0 +1,377 @@ +from .channel import Channel +from .exceptions import SlackClientError +from .slackrequest import SlackRequest +from .user import User +from .util import SearchList, SearchDict + +import json +import logging +import time +import random + +from requests.packages.urllib3.util.url import parse_url +from ssl import SSLError +from websocket import create_connection +from websocket._exceptions import WebSocketConnectionClosedException + + +class Server(object): + """ + The Server object owns the websocket connection and all attached channel information. + """ + + def __init__(self, token=None, connect=True, proxies=None, **kwargs): + # Slack app configs + self.token = token + + # api configs + self.proxies = proxies + + # HTTP Request handler + self.api_requester = SlackRequest(proxies=proxies) + + # Workspace metadata + self.username = None + self.domain = None + self.login_data = None + self.users = SearchDict() + self.channels = SearchList() + + # RTM configs + self.websocket = None + self.ws_url = None + self.connected = False + self.auto_reconnect = False + self.last_connected_at = 0 + self.reconnect_count = 0 + self.rtm_connect_retries = 0 + + # Connect to RTM on load + if connect: + self.rtm_connect() + + def __eq__(self, compare_str): + if compare_str == self.domain or compare_str == self.token: + return True + else: + return False + + def __hash__(self): + return hash(self.token) + + def __str__(self): + """ + Example Output:: + + username : None + domain : None + websocket : None + users : [] + login_data : None + api_requester : 0: + # Back off after the the first attempt + backoff_offset_multiplier = random.randint(1, 4) + retry_timeout = ( + backoff_offset_multiplier * recon_count * recon_count + ) + logging.debug("Reconnecting in %d seconds", retry_timeout) + + time.sleep(retry_timeout) + self.reconnect_count += 1 + else: + self.reconnect_count = 0 + + reply = self.api_requester.do( + self.token, connect_method, post_data=kwargs, timeout=timeout + ) + + if reply.status_code != 200: + if self.rtm_connect_retries < 5 and reply.status_code == 429: + self.rtm_connect_retries += 1 + retry_after = int(reply.headers.get("retry-after", 120)) + logging.debug( + "HTTP 429: Rate limited. Retrying in %d seconds", retry_after + ) + time.sleep(retry_after) + self.rtm_connect( + reconnect=reconnect, + timeout=timeout, + use_rtm_start=use_rtm_start, + **kwargs + ) + else: + raise SlackConnectionError( + "RTM connection attempt was rate limited 5 times." + ) + else: + self.rtm_connect_retries = 0 + login_data = reply.json() + if login_data["ok"]: + self.ws_url = login_data["url"] + self.connect_slack_websocket(self.ws_url) + if not reconnect: + self.parse_slack_login_data(login_data, use_rtm_start) + else: + raise SlackLoginError(reply=reply) + + def parse_slack_login_data(self, login_data, use_rtm_start): + self.login_data = login_data + self.domain = self.login_data["team"]["domain"] + self.username = self.login_data["self"]["name"] + + # if the connection was made via rtm.start, update the server's state + if use_rtm_start: + self.parse_channel_data(login_data["channels"]) + self.parse_channel_data(login_data["groups"]) + self.parse_user_data(login_data["users"]) + self.parse_channel_data(login_data["ims"]) + + def connect_slack_websocket(self, ws_url): + """Uses http proxy if available""" + if self.proxies and "http" in self.proxies: + parts = parse_url(self.proxies["http"]) + proxy_host, proxy_port = parts.host, parts.port + auth = parts.auth + proxy_auth = auth and auth.split(":") + else: + proxy_auth, proxy_port, proxy_host = None, None, None + + try: + self.websocket = create_connection( + ws_url, + http_proxy_host=proxy_host, + http_proxy_port=proxy_port, + http_proxy_auth=proxy_auth, + ) + self.connected = True + self.last_connected_at = time.time() + logging.debug("RTM connected") + self.websocket.sock.setblocking(0) + except Exception as e: + self.connected = False + raise SlackConnectionError(message=str(e)) + + def parse_channel_data(self, channel_data): + for channel in channel_data: + if "name" not in channel: + channel["name"] = channel["id"] + if "members" not in channel: + channel["members"] = [] + self.attach_channel(channel["name"], channel["id"], channel["members"]) + + def parse_user_data(self, user_data): + for user in user_data: + if "tz" not in user: + user["tz"] = "unknown" + if "real_name" not in user: + user["real_name"] = user["name"] + if "email" not in user["profile"]: + user["profile"]["email"] = "" + self.attach_user( + user["name"], + user["id"], + user["real_name"], + user["tz"], + user["profile"]["email"], + ) + + def send_to_websocket(self, data): + """ + Send a JSON message directly to the websocket. See + `RTM documentation =2.4.0,<2.6 +pytest-mock +responses diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/conftest.py b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/conftest.py new file mode 100644 index 0000000000..9b2571ad75 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/conftest.py @@ -0,0 +1,39 @@ +import pytest +import requests +from slackclient.channel import Channel +from slackclient.server import Server +from slackclient.client import SlackClient + + +# This is so that tests work on Travis for python 2.6, it's really hacky, but expedient +def get_unverified_post(): + requests_post = requests.post + + def unverified_post(*args, **kwargs): + # don't throw SSL errors plz + kwargs['verify'] = False + return requests_post(*args, **kwargs) + + return unverified_post + + +requests.post = get_unverified_post() + + +@pytest.fixture +def server(monkeypatch): + my_server = Server(token='xoxp-1234123412341234-12341234-1234', connect=False) + return my_server + + +@pytest.fixture +def slackclient(): + my_slackclient = SlackClient('xoxp-1234123412341234-12341234-1234') + return my_slackclient + + +@pytest.fixture +def channel(server): + my_channel = Channel(server, "somechannel", "C12341234", ["user"]) + return my_channel + diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/data/channel.created.json b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/data/channel.created.json new file mode 100644 index 0000000000..9ccbffaebc --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/data/channel.created.json @@ -0,0 +1,9 @@ +{ + "type": "channel_created", + "channel": { + "id": "C024BE91L", + "name": "fun", + "created": 1360782804, + "creator": "U024BE7LH" + } +} diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/data/im.created.json b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/data/im.created.json new file mode 100644 index 0000000000..8f51519f1e --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/data/im.created.json @@ -0,0 +1,9 @@ +{ + "type": "im_created", + "user": "U024BE7LH", + "channel": { + "id": "D024BE91L", + "user": "U123BL234", + "created": 1360782804 + } +} diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/data/rtm.start.json b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/data/rtm.start.json new file mode 100644 index 0000000000..a0696eda93 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/data/rtm.start.json @@ -0,0 +1,321 @@ +{ + "ok": true, + "self": { + "id": "U10CX1234", + "name": "fakeuser", + "prefs": { + "highlight_words": "", + "user_colors": "", + "color_names_in_list": true, + "growls_enabled": true, + "tz": "America\/Los_Angeles", + "push_dm_alert": true, + "push_mention_alert": true, + "push_everything": true, + "push_idle_wait": 2, + "push_sound": "b2.mp3", + "push_loud_channels": "", + "push_mention_channels": "", + "push_loud_channels_set": "", + "email_alerts": "instant", + "email_alerts_sleep_until": 0, + "email_misc": true, + "email_weekly": true, + "welcome_message_hidden": false, + "all_channels_loud": true, + "loud_channels": "", + "never_channels": "", + "loud_channels_set": "", + "show_member_presence": true, + "search_sort": "timestamp", + "expand_inline_imgs": true, + "expand_internal_inline_imgs": true, + "expand_snippets": false, + "posts_formatting_guide": true, + "seen_welcome_2": true, + "seen_ssb_prompt": false, + "search_only_my_channels": false, + "emoji_mode": "default", + "has_invited": false, + "has_uploaded": false, + "has_created_channel": false, + "search_exclude_channels": "", + "messages_theme": "default", + "webapp_spellcheck": true, + "no_joined_overlays": false, + "no_created_overlays": false, + "dropbox_enabled": false, + "seen_user_menu_tip_card": true, + "seen_team_menu_tip_card": true, + "seen_channel_menu_tip_card": true, + "seen_message_input_tip_card": true, + "seen_channels_tip_card": true, + "seen_domain_invite_reminder": false, + "seen_member_invite_reminder": false, + "seen_flexpane_tip_card": true, + "seen_search_input_tip_card": true, + "mute_sounds": false, + "arrow_history": false, + "tab_ui_return_selects": true, + "obey_inline_img_limit": true, + "new_msg_snd": "knock_brush.mp3", + "collapsible": false, + "collapsible_by_click": true, + "require_at": false, + "mac_ssb_bounce": "", + "mac_ssb_bullet": true, + "expand_non_media_attachments": true, + "show_typing": true, + "pagekeys_handled": true, + "last_snippet_type": "", + "display_real_names_override": 0, + "time24": false, + "enter_is_special_in_tbt": false, + "graphic_emoticons": false, + "convert_emoticons": true, + "autoplay_chat_sounds": true, + "ss_emojis": true, + "sidebar_behavior": "", + "mark_msgs_read_immediately": true, + "start_scroll_at_oldest": true, + "snippet_editor_wrap_long_lines": false, + "ls_disabled": false, + "sidebar_theme": "default", + "sidebar_theme_custom_values": "", + "f_key_search": false, + "k_key_omnibox": true, + "speak_growls": false, + "mac_speak_voice": "com.apple.speech.synthesis.voice.Alex", + "mac_speak_speed": 250, + "comma_key_prefs": false, + "at_channel_suppressed_channels": "", + "push_at_channel_suppressed_channels": "", + "prompted_for_email_disabling": false, + "full_text_extracts": false, + "no_text_in_notifications": false, + "muted_channels": "", + "no_macssb1_banner": true, + "no_winssb1_banner": false, + "privacy_policy_seen": true, + "search_exclude_bots": false, + "fuzzy_matching": false, + "load_lato_2": false, + "fuller_timestamps": false, + "last_seen_at_channel_warning": 0, + "enable_flexpane_rework": false, + "flex_resize_window": false, + "msg_preview": false, + "msg_preview_displaces": true, + "msg_preview_persistent": true, + "emoji_autocomplete_big": false, + "winssb_run_from_tray": true + }, + "created": 1421456475, + "manual_presence": "active" + }, + "team": { + "id": "T03CX4S34", + "name": "TESTteam, INC", + "email_domain": "", + "domain": "testteaminc", + "msg_edit_window_mins": -1, + "prefs": { + "default_channels": [ + "C01CX1234", + "C05BX1234" + ], + "msg_edit_window_mins": -1, + "allow_message_deletion": true, + "hide_referers": true, + "display_real_names": false, + "who_can_at_everyone": "regular", + "who_can_at_channel": "ra", + "warn_before_at_channel": "always", + "who_can_create_channels": "regular", + "who_can_archive_channels": "regular", + "who_can_create_groups": "ra", + "who_can_post_general": "ra", + "who_can_kick_channels": "admin", + "who_can_kick_groups": "regular", + "retention_type": 0, + "retention_duration": 0, + "group_retention_type": 0, + "group_retention_duration": 0, + "dm_retention_type": 0, + "dm_retention_duration": 0, + "require_at_for_mention": 0, + "compliance_export_start": 0 + }, + "icon": { + "image_34": "https:\/\/slack.global.ssl.fastly.net\/b3b7\/img\/avatars-teams\/ava_0025-34.png", + "image_44": "https:\/\/slack.global.ssl.fastly.net\/b3b7\/img\/avatars-teams\/ava_0025-44.png", + "image_68": "https:\/\/slack.global.ssl.fastly.net\/b3b7\/img\/avatars-teams\/ava_0025-68.png", + "image_88": "https:\/\/slack.global.ssl.fastly.net\/b3b7\/img\/avatars-teams\/ava_0025-88.png", + "image_102": "https:\/\/slack.global.ssl.fastly.net\/b3b7\/img\/avatars-teams\/ava_0025-102.png", + "image_132": "https:\/\/slack.global.ssl.fastly.net\/b3b7\/img\/avatars-teams\/ava_0025-132.png", + "image_default": true + }, + "over_storage_limit": false + }, + "latest_event_ts": "1426103085.000000", + "channels": [ + { + "id": "C01CX1234", + "name": "general", + "is_channel": true, + "created": 1421456475, + "creator": "U03CX4S38", + "is_archived": false, + "is_general": true, + "is_member": true, + "last_read": "0000000000.000000", + "latest": { + "type": "message", + "user": "U03CX4S38", + "text": "a", + "ts": "1425499421.000004" + }, + "unread_count": 0, + "unread_count_display": 0, + "members": [ + "U03CX4S38" + ], + "topic": { + "value": "", + "creator": "", + "last_set": 0 + }, + "purpose": { + "value": "This channel is for team-wide communication and announcements. All team members are in this channel.", + "creator": "", + "last_set": 0 + } + }, + { + "id": "C05BX1234", + "name": "random", + "is_channel": true, + "created": 1421456475, + "creator": "U03CX4S38", + "is_archived": false, + "is_general": false, + "is_member": true, + "last_read": "0000000000.000000", + "latest": null, + "unread_count": 0, + "unread_count_display": 0, + "members": [ + "U03CX4S38" + ], + "topic": { + "value": "", + "creator": "", + "last_set": 0 + }, + "purpose": { + "value": "A place for non-work banter, links, articles of interest, humor or anything else which you'd like concentrated in some place other than work-related channels.", + "creator": "", + "last_set": 0 + } + } + ], + "groups": [], + "ims": [ + { + "id": "D03CX4S3E", + "is_im": true, + "user": "USLACKBOT", + "created": 1421456475, + "last_read": "1425318850.000003", + "latest": { + "type": "message", + "user": "USLACKBOT", + "text": "To start, what is your first name?", + "ts": "1425318850.000003" + }, + "unread_count": 0, + "unread_count_display": 0, + "is_open": true + } + ], + "users": [ + { + "id": "U10CX1234", + "name": "fakeuser", + "deleted": false, + "status": null, + "color": "9f69e7", + "profile": { + "email": "fakeuser@example.com", + "image_24": "https:\/\/secure.gravatar.com\/avatar\/4f1bd7fd71e645fa19620504b4c0e3ba.jpg?s=24&d=https%3A%2F%2Fslack.global.ssl.fastly.net%2F3654%2Fimg%2Favatars%2Fava_0002-24.png", + "image_32": "https:\/\/secure.gravatar.com\/avatar\/4f1bd7fd71e645fa19620504b4c0e3ba.jpg?s=32&d=https%3A%2F%2Fslack.global.ssl.fastly.net%2F3654%2Fimg%2Favatars%2Fava_0002-32.png", + "image_48": "https:\/\/secure.gravatar.com\/avatar\/4f1bd7fd71e645fa19620504b4c0e3ba.jpg?s=48&d=https%3A%2F%2Fslack.global.ssl.fastly.net%2F272a%2Fimg%2Favatars%2Fava_0002-48.png", + "image_72": "https:\/\/secure.gravatar.com\/avatar\/4f1bd7fd71e645fa19620504b4c0e3ba.jpg?s=72&d=https%3A%2F%2Fslack.global.ssl.fastly.net%2F3654%2Fimg%2Favatars%2Fava_0002-72.png", + "image_192": "https:\/\/secure.gravatar.com\/avatar\/4f1bd7fd71e645fa19620504b4c0e3ba.jpg?s=192&d=https%3A%2F%2Fslack.global.ssl.fastly.net%2F3654%2Fimg%2Favatars%2Fava_0002.png" + }, + "is_admin": true, + "is_owner": true, + "is_primary_owner": true, + "is_restricted": false, + "is_ultra_restricted": false, + "is_bot": false, + "has_files": false, + "presence": "away" + }, + { + "id": "U10CX1235", + "name": "userwithoutemail", + "deleted": false, + "status": null, + "color": "9f69e7", + "profile": { + "image_24": "https:\/\/secure.gravatar.com\/avatar\/4f1bd7fd71e645fa19620504b4c0e3ba.jpg?s=24&d=https%3A%2F%2Fslack.global.ssl.fastly.net%2F3654%2Fimg%2Favatars%2Fava_0002-24.png", + "image_32": "https:\/\/secure.gravatar.com\/avatar\/4f1bd7fd71e645fa19620504b4c0e3ba.jpg?s=32&d=https%3A%2F%2Fslack.global.ssl.fastly.net%2F3654%2Fimg%2Favatars%2Fava_0002-32.png", + "image_48": "https:\/\/secure.gravatar.com\/avatar\/4f1bd7fd71e645fa19620504b4c0e3ba.jpg?s=48&d=https%3A%2F%2Fslack.global.ssl.fastly.net%2F272a%2Fimg%2Favatars%2Fava_0002-48.png", + "image_72": "https:\/\/secure.gravatar.com\/avatar\/4f1bd7fd71e645fa19620504b4c0e3ba.jpg?s=72&d=https%3A%2F%2Fslack.global.ssl.fastly.net%2F3654%2Fimg%2Favatars%2Fava_0002-72.png", + "image_192": "https:\/\/secure.gravatar.com\/avatar\/4f1bd7fd71e645fa19620504b4c0e3ba.jpg?s=192&d=https%3A%2F%2Fslack.global.ssl.fastly.net%2F3654%2Fimg%2Favatars%2Fava_0002.png" + }, + "is_admin": true, + "is_owner": true, + "is_primary_owner": true, + "is_restricted": false, + "is_ultra_restricted": false, + "is_bot": false, + "has_files": false, + "presence": "away" + }, + { + "id": "USLACKBOT", + "name": "slackbot", + "deleted": false, + "status": null, + "color": "757575", + "real_name": "Slack Bot", + "tz": null, + "tz_label": "Pacific Daylight Time", + "tz_offset": -25200, + "profile": { + "first_name": "Slack", + "last_name": "Bot", + "image_24": "https:\/\/slack-assets2.s3-us-west-2.amazonaws.com\/10068\/img\/slackbot_24.png", + "image_32": "https:\/\/slack-assets2.s3-us-west-2.amazonaws.com\/10068\/img\/slackbot_32.png", + "image_48": "https:\/\/slack-assets2.s3-us-west-2.amazonaws.com\/10068\/img\/slackbot_48.png", + "image_72": "https:\/\/slack-assets2.s3-us-west-2.amazonaws.com\/10068\/img\/slackbot_72.png", + "image_192": "https:\/\/slack-assets2.s3-us-west-2.amazonaws.com\/10068\/img\/slackbot_192.png", + "real_name": "Slack Bot", + "real_name_normalized": "Slack Bot", + "email": null + }, + "is_admin": false, + "is_owner": false, + "is_primary_owner": false, + "is_restricted": false, + "is_ultra_restricted": false, + "is_bot": false, + "presence": "active" + } + ], + "bots": [], + "cache_version": "v5-dog", + "url": "wss:\/\/cerberus-xxxx.lb.slack-msgs.com\/websocket\/ifkp3MKfNXd6ftbrEGllwcHn" +} diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/data/slack_logo.png b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/data/slack_logo.png new file mode 100644 index 0000000000..232a00cf13 Binary files /dev/null and b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/data/slack_logo.png differ diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/test_channel.py b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/test_channel.py new file mode 100644 index 0000000000..88ea5a8561 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/test_channel.py @@ -0,0 +1,47 @@ +from slackclient.channel import Channel + + +def test_channel(channel): + assert type(channel) == Channel + + +def test_channel_eq(channel): + channel = Channel( + 'test-server', + 'test-channel', + 'C12345678', + ) + assert channel == 'test-channel' + assert channel == '#test-channel' + assert channel == 'C12345678' + assert 'C12345678' in str(channel) + assert 'C12345678' in "%r" % channel + assert (channel == 'foo') is False + + +def test_channel_is_hashable(channel): + channel = Channel( + 'test-server', + 'test-channel', + 'C12345678', + ) + channel_map = {channel: channel.id} + assert channel_map[channel] == 'C12345678' + assert (channel_map[channel] == 'foo') is False + + +def test_channel_send_message(channel, mocker, monkeypatch): + mock_server = mocker.Mock() + monkeypatch.setattr(channel, 'server', mock_server) + channel.send_message('hi') + mock_server.rtm_send_message.assert_called_with(channel.id, 'hi', None, False) + + +def test_channel_send_message_to_thread(channel, mocker, monkeypatch): + mock_server = mocker.Mock() + monkeypatch.setattr(channel, 'server', mock_server) + channel.send_message('hi', thread='123456.789') + mock_server.rtm_send_message.assert_called_with(channel.id, 'hi', '123456.789', False) + + channel.send_message('hi', thread='123456.789', reply_broadcast=True) + mock_server.rtm_send_message.assert_called_with(channel.id, 'hi', '123456.789', True) diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/test_server.py b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/test_server.py new file mode 100644 index 0000000000..10e9183467 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/test_server.py @@ -0,0 +1,236 @@ +import json +import pytest +import responses +import time +import urllib3 + +from mock import patch + +from slackclient.user import User +from slackclient.server import Server, SlackConnectionError +from slackclient.channel import Channel + +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + +@pytest.fixture +def rtm_start_fixture(): + file_login_data = open('tests/data/rtm.start.json', 'r').read() + json_login_data = json.loads(file_login_data) + return json_login_data + + +def test_server(): + server = Server(token="valid_token", connect=False) + assert type(server) == Server + + # The server eqs to a string, either the token or workspace domain + assert server.token == "valid_token" + + +def test_server_connect(rtm_start_fixture): + with responses.RequestsMock() as rsps: + rsps.add( + responses.POST, + "https://slack.com/api/rtm.start", + status=200, + json=rtm_start_fixture + ) + + Server(token="token", connect=True) + + for call in rsps.calls: + assert call.request.url in [ + "https://slack.com/api/rtm.start" + ] + + +def test_api_call_for_empty_slack_responses(server): + with responses.RequestsMock() as rsps: + rsps.add( + responses.POST, + "https://slack.com/api/chat.postMessage", + status=429, + headers={"Retry-After": "1"}, + ) + + response_received = server.api_call("token", "chat.postMessage") + chat_postMessage_response = rsps.calls[0].response + + assert chat_postMessage_response.text == "" + expected_response = { + "headers": {"Content-Type": "text/plain", "Retry-After": "1"} + } + assert json.loads(response_received) == expected_response + + +def test_server_is_hashable(server): + server_map = {server: server.token} + assert server_map[server] == 'xoxp-1234123412341234-12341234-1234' + assert (server_map[server] == 'foo') is False + + +@patch('time.sleep', return_value=None) +def test_rate_limiting(patched_time_sleep, server): + # Testing for rate limit retry headers + with responses.RequestsMock() as rsps: + rsps.add( + responses.POST, + "https://slack.com/api/rtm.start", + status=429, + json={"ok": False}, + headers={'Retry-After': "1"} + ) + + with pytest.raises(SlackConnectionError) as e: + server.rtm_connect() + for call in rsps.calls: + assert call.response.status_code == 429 + assert e.message == "RTM connection attempt was rate limited 10 times." + + +def test_custom_agent(server): + server.append_user_agent("test agent", 1.0) + assert server.api_requester.custom_user_agent[0] == ['test agent', 1.0] + + +def test_server_parse_channel_data(server, rtm_start_fixture): + server.parse_channel_data(rtm_start_fixture["channels"]) + assert type(server.channels.find('general')) == Channel + + +def test_server_parse_user_data(server, rtm_start_fixture): + server.parse_user_data(rtm_start_fixture["users"]) + # Find user by Name + user_by_name = server.users.find('fakeuser') + assert type(user_by_name) == User + assert user_by_name == "fakeuser" + assert user_by_name != "someotheruser" + # Find user by ID + user_by_id = server.users.find('U10CX1234') + assert type(user_by_id) == User + assert user_by_id == "fakeuser" + assert user_by_id.email == 'fakeuser@example.com' + # Don't find invalid user + user_by_id = server.users.find('invaliduser') + assert user_by_id is None + + +def test_server_cant_connect(server): + with responses.RequestsMock() as rsps: + rsps.add( + responses.POST, + "https://slack.com/api/rtm.start", + status=403, + json={"ok": False} + ) + + with pytest.raises(SlackConnectionError) as e: + server.rtm_connect() + + +def test_reconnect_flag(server, rtm_start_fixture): + with responses.RequestsMock() as rsps: + rsps.add( + responses.POST, + "https://slack.com/api/rtm.start", + status=200, + json=rtm_start_fixture + ) + + server.rtm_connect(auto_reconnect=True) + assert server.auto_reconnect is True + + for call in rsps.calls: + assert call.request.url in [ + "https://slack.com/api/rtm.start" + ] + + +def test_rtm_reconnect(server, rtm_start_fixture): + with responses.RequestsMock() as rsps: + rsps.add( + responses.POST, + "https://slack.com/api/rtm.connect", + status=200, + json=rtm_start_fixture + ) + + server.rtm_connect(auto_reconnect=True, reconnect=True, use_rtm_start=False) + + for call in rsps.calls: + assert call.request.url in [ + "https://slack.com/api/rtm.connect" + ] + + +@patch('time.sleep', return_value=None) +def test_rtm_max_reconnect_timeout(patched_time_sleep, server, rtm_start_fixture): + with responses.RequestsMock() as rsps: + rsps.add( + responses.POST, + "https://slack.com/api/rtm.connect", + status=200, + json=rtm_start_fixture + ) + + server.reconnect_count = 4 + server.last_connected_at = time.time() + server.rtm_connect(auto_reconnect=True, reconnect=True, use_rtm_start=False) + + assert server.reconnect_count == 5 + + +def test_rtm_reconnect_timeout_recently_connected(server, rtm_start_fixture): + # If reconnected recently, server must wait to reconnect and increment the counter + with responses.RequestsMock() as rsps: + rsps.add( + responses.POST, + "https://slack.com/api/rtm.connect", + status=200, + json=rtm_start_fixture + ) + + server.reconnect_count = 0 + server.last_connected_at = time.time() + server.rtm_connect(auto_reconnect=True, reconnect=True, use_rtm_start=False) + + assert server.reconnect_count == 1 + for call in rsps.calls: + assert call.request.url in [ + "https://slack.com/api/rtm.connect" + ] + + +def test_rtm_reconnect_timeout_not_recently_connected(server, rtm_start_fixture): + # If reconnecting after 3 minutes since last reconnect, reset counter and connect without wait + with responses.RequestsMock() as rsps: + rsps.add( + responses.POST, + "https://slack.com/api/rtm.connect", + status=200, + json=rtm_start_fixture + ) + + server.reconnect_count = 1 + server.last_connected_at = time.time() - 180 + server.rtm_connect(auto_reconnect=True, reconnect=True, use_rtm_start=False) + + assert server.reconnect_count == 0 + for call in rsps.calls: + assert call.request.url in [ + "https://slack.com/api/rtm.connect" + ] + + +def test_max_rtm_reconnects(server, monkeypatch): + monkeypatch.setattr("time.sleep", None) + with pytest.raises(SlackConnectionError) as e: + server.reconnect_count = 5 + server.rtm_connect(auto_reconnect=True, reconnect=True, use_rtm_start=False) + assert e.message == "RTM connection failed, reached max reconnects." + + +@pytest.mark.xfail +def test_server_ping(server, monkeypatch): + monkeypatch.setattr("websocket.create_connection", lambda: True) + reply = server.ping() diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/test_slackclient.py b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/test_slackclient.py new file mode 100644 index 0000000000..7eaeacad56 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/test_slackclient.py @@ -0,0 +1,295 @@ +import json +import pytest +from requests.exceptions import ProxyError +import responses +from slackclient.exceptions import TokenRefreshError +from slackclient.channel import Channel +from slackclient.client import SlackClient +from slackclient.server import SlackConnectionError + + +@pytest.fixture +def channel_created_fixture(): + file_channel_created_data = open("tests/data/channel.created.json", "r").read() + json_channel_created_data = json.loads(file_channel_created_data) + return json_channel_created_data + + +@pytest.fixture +def im_created_fixture(): + file_channel_created_data = open("tests/data/im.created.json", "r").read() + json_channel_created_data = json.loads(file_channel_created_data) + return json_channel_created_data + + +def test_proxy(): + proxies = {"http": "some-bad-proxy", "https": "some-bad-proxy"} + client = SlackClient("xoxp-1234123412341234-12341234-1234", proxies=proxies) + server = client.server + + assert server.proxies == proxies + + with pytest.raises(ProxyError): + server.rtm_connect() + + with pytest.raises(SlackConnectionError): + server.connect_slack_websocket( + "wss://mpmulti-xw58.slack-msgs.com/websocket/bad-token" + ) + + api_requester = server.api_requester + assert api_requester.proxies == proxies + with pytest.raises(ProxyError): + api_requester.do("xoxp-1234123412341234-12341234-1234", request="channels.list") + + +def test_SlackClient(slackclient): + assert type(slackclient) == SlackClient + + +def test_custom_user_agent(slackclient): + slackclient.append_user_agent("customua", "1.0.0") + assert "customua" in slackclient.server.api_requester.get_user_agent() + + +def test_SlackClient_process_changes( + slackclient, channel_created_fixture, im_created_fixture +): + slackclient.process_changes(channel_created_fixture) + assert type(slackclient.server.channels.find("fun")) == Channel + slackclient.process_changes(im_created_fixture) + assert type(slackclient.server.channels.find("U123BL234")) == Channel + + +def test_api_not_ok(slackclient): + # Testing for rate limit retry headers + client = SlackClient("xoxp-1234123412341234-12341234-1234") + + with responses.RequestsMock() as rsps: + rsps.add( + responses.POST, + "https://slack.com/api/im.open", + status=200, + json={"ok": False, "error": "invalid_auth"}, + headers={}, + ) + + client.api_call("im.open", user="UXXXX") + + for call in rsps.calls: + assert call.response.status_code == 200 + assert call.request.url in ["https://slack.com/api/im.open"] + + +def test_im_open(slackclient): + with responses.RequestsMock() as rsps: + rsps.add( + responses.POST, + "https://slack.com/api/im.open", + status=200, + json={"ok": True, "channel": {"id": "CXXXXXX"}}, + headers={}, + ) + + slackclient.api_call("im.open", user="UXXXX") + + for call in rsps.calls: + assert call.response.status_code == 200 + assert call.request.url in ["https://slack.com/api/im.open"] + + +def test_channel_join(slackclient): + with responses.RequestsMock() as rsps: + rsps.add( + responses.POST, + "https://slack.com/api/channels.join", + status=200, + json={ + "ok": True, + "channel": { + "id": "CXXXX", + "name": "test", + "members": ("U0G9QF9C6", "U1QNSQB9U"), + }, + }, + ) + + slackclient.api_call("channels.join", channel="CXXXX") + + for call in rsps.calls: + assert call.response.status_code == 200 + assert call.request.url in ["https://slack.com/api/channels.join"] + response_json = call.response.json() + assert response_json["ok"] is True + + +def test_noncallable_refresh_callback(): + with pytest.raises(TokenRefreshError): + SlackClient( + client_id="12345", + client_secret="12345", + refresh_token="refresh_token", + token_update_callback="THIS IS A STRING, NOT A CALLABLE METHOD", + ) + + +def test_no_RTM_with_workspace_tokens(): + def token_update_callback(update_data): + return update_data + + with pytest.raises(TokenRefreshError): + sc = SlackClient( + client_id="12345", + client_secret="12345", + refresh_token="refresh_token", + token_update_callback=token_update_callback, + ) + + sc.rtm_connect() + + +def test_token_refresh_on_initial_api_request(): + # Client should fetch and append an access token on the first API request + + # When the token is refreshed, the client will call this callback + access_token = "xoxa-2-abcdef" + client_args = {} + + def token_update_callback(update_data): + client_args[update_data["team_id"]] = update_data + + sc = SlackClient( + client_id="12345", + client_secret="12345", + refresh_token="refresh_token", + token_update_callback=token_update_callback, + ) + + # The client starts out with an empty token + assert sc.token is None + + # Mock both the main API request and the token refresh request + with responses.RequestsMock() as rsps: + rsps.add( + responses.POST, + "https://slack.com/api/auth.test", + status=200, + json={"ok": True}, + ) + + rsps.add( + responses.POST, + "https://slack.com/api/oauth.access", + status=200, + json={ + "ok": True, + "access_token": access_token, + "token_type": "app", + "expires_in": 3600, + "team_id": "T2U81E2FP", + "enterprise_id": "T2U81ELK", + }, + ) + + # Calling the API for the first time will trigger a token refresh + sc.api_call("auth.test") + + # Store the calls in order + calls = {} + for index, call in enumerate(rsps.calls): + calls[index] = {"url": call.request.url} + + # After the initial call, the refresh method will update the client's token, + # then the callback will update client_args + assert sc.token == access_token + assert client_args["T2U81E2FP"]["access_token"] == access_token + + # Verify that the client first tried to call the API, refreshed the token, then retried + assert calls[0]["url"] == "https://slack.com/api/oauth.access" + assert calls[1]["url"] == "https://slack.com/api/auth.test" + + +def test_token_refresh_failed(): + # Client should raise TokenRefreshError is token refresh returns error + def token_update_callback(update_data): + return update_data + + sc = SlackClient( + client_id="12345", + client_secret="12345", + refresh_token="refresh_token", + token_update_callback=token_update_callback, + ) + + with pytest.raises(TokenRefreshError): + with responses.RequestsMock() as rsps: + rsps.add( + responses.POST, + "https://slack.com/api/channels.list", + status=200, + json={"ok": False, "error": "invalid_auth"}, + ) + + rsps.add( + responses.POST, + "https://slack.com/api/oauth.access", + status=200, + json={"ok": False, "error": "invalid_auth"}, + ) + + sc.api_call("channels.list") + + +def test_token_refresh_on_expired_token(): + # Client should fetch and append an access token on the first API request + + # When the token is refreshed, the client will call this callback + client_args = {} + + def token_update_callback(update_data): + client_args[update_data["team_id"]] = update_data + + sc = SlackClient( + client_id="12345", + client_secret="12345", + refresh_token="refresh_token", + token_update_callback=token_update_callback, + ) + + # Set the token TTL to some time in the past + sc.access_token_expires_at = 0 + + # Mock both the main API request and the token refresh request + with responses.RequestsMock() as rsps: + rsps.add( + responses.POST, + "https://slack.com/api/auth.test", + status=200, + json={"ok": True}, + ) + + rsps.add( + responses.POST, + "https://slack.com/api/oauth.access", + status=200, + json={ + "ok": True, + "access_token": "xoxa-2-abcdef", + "token_type": "app", + "expires_in": 3600, + "team_id": "T2U81E2FP", + "enterprise_id": "T2U81ELK", + }, + ) + + # Calling the API for the first time will trigger a token refresh + sc.api_call("auth.test") + + # Store the calls in order + calls = {} + for index, call in enumerate(rsps.calls): + calls[index] = {"url": call.request.url} + + # Verify that the client first fetches the token, then submits the request + assert calls[0]["url"] == "https://slack.com/api/oauth.access" + assert calls[1]["url"] == "https://slack.com/api/auth.test" diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/test_slackrequest.py b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/test_slackrequest.py new file mode 100644 index 0000000000..0c49915f88 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tests/test_slackrequest.py @@ -0,0 +1,114 @@ +from slackclient.slackrequest import SlackRequest +from slackclient.version import __version__ +import os + + +def test_http_headers(mocker): + requests = mocker.patch('slackclient.slackrequest.requests') + request = SlackRequest() + + request.do('xoxb-123', 'chat.postMessage', {'text': 'test', 'channel': '#general'}) + args, kwargs = requests.post.call_args + + assert kwargs['headers']['user-agent'] is not None + + +def test_custom_user_agent(mocker): + requests = mocker.patch('slackclient.slackrequest.requests') + request = SlackRequest() + + request.append_user_agent("fooagent1", "0.1") + request.append_user_agent("baragent/2", "0.2") + + request.do('xoxb-123', 'chat.postMessage', {'text': 'test', 'channel': '#general'}) + args, kwargs = requests.post.call_args + + # Verify user-agent includes both default and custom agent info + assert "slackclient/{}".format(__version__) in kwargs['headers']['user-agent'] + assert "fooagent1/0.1" in kwargs['headers']['user-agent'] + + # verify escaping of slashes in custom agent name + assert "baragent:2/0.2" in kwargs['headers']['user-agent'] + + +def test_auth_header(mocker): + requests = mocker.patch('slackclient.slackrequest.requests') + request = SlackRequest() + + request.do('xoxb-123', 'chat.postMessage', {'text': 'test', 'channel': '#general'}) + args, kwargs = requests.post.call_args + + assert "Bearer xoxb-123" in kwargs['headers']['Authorization'] + + +def test_token_override(mocker): + requests = mocker.patch('slackclient.slackrequest.requests') + request = SlackRequest() + + request.do('xoxb-123', 'chat.postMessage', + { + 'token': "newtoken", + 'text': 'test', + 'channel': '#general' + }) + args, kwargs = requests.post.call_args + + assert "Bearer newtoken" in kwargs['headers']['Authorization'] + + +def test_plural_field(mocker): + requests = mocker.patch('slackclient.slackrequest.requests') + request = SlackRequest() + + request.do('xoxb-123', 'conversations.open', {'users': ['U123', 'U234', 'U345']}) + args, kwargs = requests.post.call_args + + assert kwargs['data'] == {'users': 'U123,U234,U345'} + + request.do('xoxb-123', 'conversations.open', {'users': "U123,U234,U345"}) + args2, kwargs2 = requests.post.call_args + + assert kwargs2['data'] == {'users': 'U123,U234,U345'} + + +def test_post_file(mocker): + requests = mocker.patch('slackclient.slackrequest.requests') + request = SlackRequest() + + request.do('xoxb-123', + 'files.upload', + {'file': open(os.path.join('.', 'tests', 'data', 'slack_logo.png'), 'rb'), + 'filename': 'slack_logo.png'}) + args, kwargs = requests.post.call_args + + assert requests.post.call_count == 1 + assert 'https://slack.com/api/files.upload' == args[0] + assert {'filename': 'slack_logo.png'} == kwargs['data'] + assert kwargs['files'] is not None + + +def test_get_file(mocker): + requests = mocker.patch('slackclient.slackrequest.requests') + request = SlackRequest() + + request.do('xoxb-123', 'files.info', {'file': 'myFavoriteFileID'}) + args, kwargs = requests.post.call_args + + assert requests.post.call_count == 1 + assert 'https://slack.com/api/files.info' == args[0] + assert {'file': "myFavoriteFileID"} == kwargs['data'] + assert kwargs['files'] is None + + +def test_post_attachements(mocker): + requests = mocker.patch('slackclient.slackrequest.requests') + request = SlackRequest() + + request.do('xoxb-123', + 'chat.postMessage', + {'attachments': [{'title': 'hello'}]}) + args, kwargs = requests.post.call_args + + assert requests.post.call_count == 1 + assert 'https://slack.com/api/chat.postMessage' == args[0] + assert isinstance(kwargs["data"]["attachments"], str) diff --git a/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tox.ini b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tox.ini new file mode 100644 index 0000000000..488623a078 --- /dev/null +++ b/openpype/modules/slack/python2_vendor/python-slack-sdk-1/tox.ini @@ -0,0 +1,35 @@ +[tox] +; you probably don't have all of these python versions on your machine. when you invoke tox, you should pick an +; environment that you have (e.g. `tox -e py27,py36,flake8`). +; for quality analysis, use `tox -e flake8` or just `flake8 slackclient` +; to build the docs, use `tox -e docs` +envlist= + py{27,34,35,36}, + flake8, + docs + +[testenv] +deps = -rtest_requirements.txt +commands = + ; `--cov-report=html:cov_html`: suppress terminal output, html report in `cov_html/`, populate `.coverage/` + ; `--cov=slackclient`: name project + ; `{posargs:tests}`: tests located in `tests` by default unless otherwise overriden by tox positional args + py.test --cov-report=html:cov_html --cov=slackclient {posargs:tests} + ; `codecov` will run the `coverage` utility and then upload results in xml format + ; `coverage` utility has configuration in `.coveragerc` + ; CI systems use their own build matricies and virtualenvs and don't need tox. therefore tox shouldn't be used + ; to upload coverage to codecov + ; codecov -e TOXENV + +[testenv:flake8] +basepython = python +deps = flake8 +commands = flake8 slackclient + +[testenv:docs] +basepython = python +whitelist_externals = /bin/bash +deps = + Sphinx + sphinx_rtd_theme +commands = bash ./docs.sh diff --git a/openpype/modules/slack/slack_module.py b/openpype/modules/slack/slack_module.py new file mode 100644 index 0000000000..9dd5a3d02b --- /dev/null +++ b/openpype/modules/slack/slack_module.py @@ -0,0 +1,30 @@ +import os +from openpype.modules import ( + PypeModule, IPluginPaths, ILaunchHookPaths) + +SLACK_MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) + + +class SlackIntegrationModule(PypeModule, IPluginPaths, ILaunchHookPaths): + """Allows sending notification to Slack channels during publishing.""" + + name = "slack" + + def initialize(self, modules_settings): + slack_settings = modules_settings[self.name] + self.enabled = slack_settings["enabled"] + + def connect_with_modules(self, _enabled_modules): + """Nothing special.""" + return + + def get_launch_hook_paths(self): + """Implementation of `ILaunchHookPaths`.""" + return os.path.join(SLACK_MODULE_DIR, "launch_hooks") + + def get_plugin_paths(self): + """Deadline plugin paths.""" + current_dir = os.path.dirname(os.path.abspath(__file__)) + return { + "publish": [os.path.join(current_dir, "plugins", "publish")] + } diff --git a/openpype/modules/standalonepublish_action.py b/openpype/modules/standalonepublish_action.py index 78d87cb6c7..4f87f9704c 100644 --- a/openpype/modules/standalonepublish_action.py +++ b/openpype/modules/standalonepublish_action.py @@ -37,7 +37,7 @@ class StandAlonePublishAction(PypeModule, ITrayAction): args = get_pype_execute_args("standalonepublisher") kwargs = {} if platform.system().lower() == "darwin": - new_args = ["open", "-a", args.pop(0), "--args"] + new_args = ["open", "-na", args.pop(0), "--args"] new_args.extend(args) args = new_args diff --git a/openpype/modules/timers_manager/widget_user_idle.py b/openpype/modules/timers_manager/widget_user_idle.py index 8b614f6a13..25b4e56650 100644 --- a/openpype/modules/timers_manager/widget_user_idle.py +++ b/openpype/modules/timers_manager/widget_user_idle.py @@ -1,6 +1,5 @@ -from avalon import style from Qt import QtCore, QtGui, QtWidgets -from openpype import resources +from openpype import resources, style class WidgetUserIdle(QtWidgets.QWidget): diff --git a/openpype/plugin.py b/openpype/plugin.py index 8ade0f3825..45c9a08209 100644 --- a/openpype/plugin.py +++ b/openpype/plugin.py @@ -16,13 +16,59 @@ class PypeCreatorMixin: Mixin class must be used as first in inheritance order to override methods. """ + dynamic_subset_keys = [] + + @classmethod + def get_dynamic_data( + cls, variant, task_name, asset_id, project_name, host_name + ): + """Return dynamic data for current Creator plugin. + + By default return keys from `dynamic_subset_keys` attribute as mapping + to keep formatted template unchanged. + + ``` + dynamic_subset_keys = ["my_key"] + --- + output = { + "my_key": "{my_key}" + } + ``` + + Dynamic keys may override default Creator keys (family, task, asset, + ...) but do it wisely if you need. + + All of keys will be converted into 3 variants unchanged, capitalized + and all upper letters. Because of that are all keys lowered. + + This method can be modified to prefill some values just keep in mind it + is class method. + + Returns: + dict: Fill data for subset name template. + """ + dynamic_data = {} + for key in cls.dynamic_subset_keys: + key = key.lower() + dynamic_data[key] = "{" + key + "}" + return dynamic_data @classmethod def get_subset_name( cls, variant, task_name, asset_id, project_name, host_name=None ): + dynamic_data = cls.get_dynamic_data( + variant, task_name, asset_id, project_name, host_name + ) + return get_subset_name( - cls.family, variant, task_name, asset_id, project_name, host_name + cls.family, + variant, + task_name, + asset_id, + project_name, + host_name, + dynamic_data=dynamic_data ) diff --git a/openpype/plugins/publish/collect_otio_subset_resources.py b/openpype/plugins/publish/collect_otio_subset_resources.py index fa376eeac7..010430a303 100644 --- a/openpype/plugins/publish/collect_otio_subset_resources.py +++ b/openpype/plugins/publish/collect_otio_subset_resources.py @@ -40,6 +40,7 @@ class CollectOcioSubsetResources(pyblish.api.InstancePlugin): otio_clip = instance.data["otioClip"] otio_avalable_range = otio_clip.available_range() media_fps = otio_avalable_range.start_time.rate + available_duration = otio_avalable_range.duration.value # get available range trimmed with processed retimes retimed_attributes = editorial.get_media_range_with_retimes( @@ -68,6 +69,8 @@ class CollectOcioSubsetResources(pyblish.api.InstancePlugin): a_frame_start_h, (a_frame_end_h - a_frame_start_h + 1), media_fps ) + trimmed_duration = trimmed_media_range_h.duration.value + self.log.debug("trimmed_media_range_h: {}".format( trimmed_media_range_h)) self.log.debug("a_frame_start_h: {}".format( @@ -150,12 +153,18 @@ class CollectOcioSubsetResources(pyblish.api.InstancePlugin): repre = self._create_representation( frame_start, frame_end, collection=collection) else: + _trim = False dirname, filename = os.path.split(media_ref.target_url) self.staging_dir = dirname + if trimmed_duration < available_duration: + self.log.debug("Ready for Trimming") + instance.data["families"].append("trim") + instance.data["otioTrimmingRange"] = trimmed_media_range_h + _trim = True self.log.debug(filename) repre = self._create_representation( - frame_start, frame_end, file=filename) + frame_start, frame_end, file=filename, trim=_trim) if repre: # add representation to instance data @@ -196,7 +205,7 @@ class CollectOcioSubsetResources(pyblish.api.InstancePlugin): "frameStart": start, "frameEnd": end, }) - return representation_data + if kwargs.get("file"): file = kwargs.get("file") ext = os.path.splitext(file)[-1] @@ -207,4 +216,9 @@ class CollectOcioSubsetResources(pyblish.api.InstancePlugin): "frameStart": start, "frameEnd": end, }) - return representation_data + + if kwargs.get("trim") is True: + representation_data.update({ + "tags": ["trim"] + }) + return representation_data diff --git a/openpype/plugins/publish/collect_rendered_files.py b/openpype/plugins/publish/collect_rendered_files.py index edf9b50b92..2f55f2bdb5 100644 --- a/openpype/plugins/publish/collect_rendered_files.py +++ b/openpype/plugins/publish/collect_rendered_files.py @@ -87,11 +87,14 @@ class CollectRenderedFiles(pyblish.api.ContextPlugin): instance = self._context.create_instance( instance_data.get("subset") ) - self.log.info("Filling stagignDir...") + self.log.info("Filling stagingDir...") self._fill_staging_dir(instance_data, anatomy) instance.data.update(instance_data) + # stash render job id for later validation + instance.data["render_job_id"] = data.get("job").get("_id") + representations = [] for repre_data in instance_data.get("representations") or []: self._fill_staging_dir(repre_data, anatomy) diff --git a/openpype/plugins/publish/extract_otio_trimming_video.py b/openpype/plugins/publish/extract_otio_trimming_video.py new file mode 100644 index 0000000000..fdb7c4b096 --- /dev/null +++ b/openpype/plugins/publish/extract_otio_trimming_video.py @@ -0,0 +1,125 @@ +""" +Requires: + instance -> otioTrimmingRange + instance -> representations + +""" + +import os +from pyblish import api +import openpype +from copy import deepcopy + + +class ExtractOTIOTrimmingVideo(openpype.api.Extractor): + """ + Trimming video file longer then required lenght + + """ + order = api.ExtractorOrder + label = "Extract OTIO trim longer video" + families = ["trim"] + hosts = ["resolve", "hiero"] + + def process(self, instance): + self.staging_dir = self.staging_dir(instance) + otio_trim_range = instance.data["otioTrimmingRange"] + representations = instance.data["representations"] + self.log.debug("otio_trim_range: {}".format(otio_trim_range)) + self.log.debug("self.staging_dir: {}".format(self.staging_dir)) + + # get corresponding representation + for _repre in representations: + if "trim" not in _repre.get("tags", []): + continue + + input_file = _repre["files"] + input_file_path = os.path.normpath(os.path.join( + _repre["stagingDir"], input_file + )) + self.log.debug("input_file_path: {}".format(input_file_path)) + + # trim via ffmpeg + new_file = self._ffmpeg_trim_seqment( + input_file_path, otio_trim_range) + + # prepare new representation data + repre_data = deepcopy(_repre) + # remove tags as we dont need them + repre_data.pop("tags") + repre_data["stagingDir"] = self.staging_dir + repre_data["files"] = new_file + + # romove `trim` tagged representation + representations.remove(_repre) + representations.append(repre_data) + self.log.debug(repre_data) + + self.log.debug("representations: {}".format(representations)) + + def _ffmpeg_trim_seqment(self, input_file_path, otio_range): + """ + Trim seqment of video file. + + Using ffmpeg to trim video to desired length. + + Args: + input_file_path (str): path string + otio_range (opentime.TimeRange): range to trim to + + """ + # get rendering app path + ffmpeg_path = openpype.lib.get_ffmpeg_tool_path("ffmpeg") + + # create path to destination + output_path = self._get_ffmpeg_output(input_file_path) + + # start command list + command = ['"{}"'.format(ffmpeg_path)] + + video_path = input_file_path + frame_start = otio_range.start_time.value + input_fps = otio_range.start_time.rate + frame_duration = (otio_range.duration.value + 1) + sec_start = openpype.lib.frames_to_secons(frame_start, input_fps) + sec_duration = openpype.lib.frames_to_secons(frame_duration, input_fps) + + # form command for rendering gap files + command.extend([ + "-ss {}".format(sec_start), + "-t {}".format(sec_duration), + "-i \"{}\"".format(video_path), + "-c copy", + output_path + ]) + + # execute + self.log.debug("Executing: {}".format(" ".join(command))) + output = openpype.api.run_subprocess( + " ".join(command), logger=self.log + ) + self.log.debug("Output: {}".format(output)) + + return os.path.basename(output_path) + + def _get_ffmpeg_output(self, file_path): + """ + Returning ffmpeg output command arguments. + + Arguments" + file_path (str): path string + + Returns: + str: output_path is path + + """ + basename = os.path.basename(file_path) + name, ext = os.path.splitext(basename) + + output_file = "{}_{}{}".format( + name, + "trimmed", + ext + ) + # create path to destination + return os.path.join(self.staging_dir, output_file) diff --git a/openpype/plugins/publish/extract_review.py b/openpype/plugins/publish/extract_review.py index e1e24af3ea..42fb2a8f93 100644 --- a/openpype/plugins/publish/extract_review.py +++ b/openpype/plugins/publish/extract_review.py @@ -986,9 +986,21 @@ class ExtractReview(pyblish.api.InstancePlugin): output_width = output_def.get("width") or None output_height = output_def.get("height") or None + # Overscal color + overscan_color_value = "black" + overscan_color = output_def.get("overscan_color") + if overscan_color: + bg_red, bg_green, bg_blue, _ = overscan_color + overscan_color_value = "#{0:0>2X}{1:0>2X}{2:0>2X}".format( + bg_red, bg_green, bg_blue + ) + self.log.debug("Overscan color: `{}`".format(overscan_color_value)) + # Convert overscan value video filters overscan_crop = output_def.get("overscan_crop") - overscan = OverscanCrop(input_width, input_height, overscan_crop) + overscan = OverscanCrop( + input_width, input_height, overscan_crop, overscan_color_value + ) overscan_crop_filters = overscan.video_filters() # Add overscan filters to filters if are any and modify input # resolution by it's values @@ -1158,9 +1170,10 @@ class ExtractReview(pyblish.api.InstancePlugin): "scale={}x{}:flags=lanczos".format( width_scale, height_scale ), - "pad={}:{}:{}:{}:black".format( + "pad={}:{}:{}:{}:{}".format( output_width, output_height, - width_half_pad, height_half_pad + width_half_pad, height_half_pad, + overscan_color_value ), "setsar=1" ]) @@ -1707,12 +1720,15 @@ class OverscanCrop: item_regex = re.compile(r"([\+\-])?([0-9]+)(.+)?") relative_source_regex = re.compile(r"%([\+\-])") - def __init__(self, input_width, input_height, string_value): + def __init__( + self, input_width, input_height, string_value, overscal_color=None + ): # Make sure that is not None string_value = string_value or "" self.input_width = input_width self.input_height = input_height + self.overscal_color = overscal_color width, height = self._convert_string_to_values(string_value) self._width_value = width @@ -1767,16 +1783,22 @@ class OverscanCrop: elif width >= self.input_width and height >= self.input_height: output.append( - "pad={}:{}:(iw-ow)/2:(ih-oh)/2".format(width, height) + "pad={}:{}:(iw-ow)/2:(ih-oh)/2:{}".format( + width, height, self.overscal_color + ) ) elif width > self.input_width and height < self.input_height: output.append("crop=iw:{}".format(height)) - output.append("pad={}:ih:(iw-ow)/2:(ih-oh)/2".format(width)) + output.append("pad={}:ih:(iw-ow)/2:(ih-oh)/2:{}".format( + width, self.overscal_color + )) elif width < self.input_width and height > self.input_height: output.append("crop={}:ih".format(width)) - output.append("pad=iw:{}:(iw-ow)/2:(ih-oh)/2".format(height)) + output.append("pad=iw:{}:(iw-ow)/2:(ih-oh)/2:{}".format( + height, self.overscal_color + )) return output diff --git a/openpype/plugins/publish/integrate_ftrack_component_overwrite.py b/openpype/plugins/publish/integrate_ftrack_component_overwrite.py deleted file mode 100644 index 047fd8462c..0000000000 --- a/openpype/plugins/publish/integrate_ftrack_component_overwrite.py +++ /dev/null @@ -1,21 +0,0 @@ -import pyblish.api - - -class IntegrateFtrackComponentOverwrite(pyblish.api.InstancePlugin): - """ - Set `component_overwrite` to True on all instances `ftrackComponentsList` - """ - - order = pyblish.api.IntegratorOrder + 0.49 - label = 'Overwrite ftrack created versions' - families = ["clip"] - optional = True - active = False - - def process(self, instance): - component_list = instance.data['ftrackComponentsList'] - - for cl in component_list: - cl['component_overwrite'] = True - self.log.debug('Component {} overwriting'.format( - cl['component_data']['name'])) diff --git a/openpype/plugins/publish/validate_editorial_asset_name.py b/openpype/plugins/publish/validate_editorial_asset_name.py new file mode 100644 index 0000000000..ccea42dc37 --- /dev/null +++ b/openpype/plugins/publish/validate_editorial_asset_name.py @@ -0,0 +1,112 @@ +import pyblish.api +from avalon import io +from pprint import pformat + + +class ValidateEditorialAssetName(pyblish.api.ContextPlugin): + """ Validating if editorial's asset names are not already created in db. + + Checking variations of names with different size of caps or with + or without underscores. + """ + + order = pyblish.api.ValidatorOrder + label = "Validate Asset Name" + + def process(self, context): + + asset_and_parents = self.get_parents(context) + + if not io.Session: + io.install() + + db_assets = list(io.find( + {"type": "asset"}, {"name": 1, "data.parents": 1})) + self.log.debug("__ db_assets: {}".format(db_assets)) + + asset_db_docs = { + str(e["name"]): e["data"]["parents"] for e in db_assets} + + self.log.debug("__ project_entities: {}".format( + pformat(asset_db_docs))) + + assets_missing_name = {} + assets_wrong_parent = {} + for asset in asset_and_parents.keys(): + if asset not in asset_db_docs.keys(): + # add to some nonexistent list for next layer of check + assets_missing_name.update({asset: asset_and_parents[asset]}) + continue + + if asset_and_parents[asset] != asset_db_docs[asset]: + # add to some nonexistent list for next layer of check + assets_wrong_parent.update({ + asset: { + "required": asset_and_parents[asset], + "already_in_db": asset_db_docs[asset] + } + }) + continue + + self.log.info("correct asset: {}".format(asset)) + + if assets_missing_name: + wrong_names = {} + self.log.debug( + ">> assets_missing_name: {}".format(assets_missing_name)) + for asset in assets_missing_name.keys(): + _asset = asset.lower().replace("_", "") + if _asset in [a.lower().replace("_", "") + for a in asset_db_docs.keys()]: + wrong_names.update({ + "required_name": asset, + "used_variants_in_db": [ + a for a in asset_db_docs.keys() + if a.lower().replace("_", "") == _asset + ] + }) + + if wrong_names: + self.log.debug( + ">> wrong_names: {}".format(wrong_names)) + raise Exception( + "Some already existing asset name variants `{}`".format( + wrong_names)) + + if assets_wrong_parent: + self.log.debug( + ">> assets_wrong_parent: {}".format(assets_wrong_parent)) + raise Exception( + "Wrong parents on assets `{}`".format(assets_wrong_parent)) + + def _get_all_assets(self, input_dict): + """ Returns asset names in list. + + List contains all asset names including parents + """ + for key in input_dict.keys(): + # check if child key is available + if input_dict[key].get("childs"): + # loop deeper + self._get_all_assets( + input_dict[key]["childs"]) + else: + self.all_testing_assets.append(key) + + def get_parents(self, context): + return_dict = {} + for instance in context: + asset = instance.data["asset"] + families = instance.data.get("families", []) + [ + instance.data["family"] + ] + # filter out non-shot families + if "shot" not in families: + continue + + parents = instance.data["parents"] + + return_dict.update({ + asset: [p["entity_name"] for p in parents] + }) + return return_dict diff --git a/openpype/pype_commands.py b/openpype/pype_commands.py index f86ece6799..7c47d8c613 100644 --- a/openpype/pype_commands.py +++ b/openpype/pype_commands.py @@ -46,16 +46,18 @@ class PypeCommands: standalonepublish.main() @staticmethod - def publish(paths): + def publish(paths, targets=None): """Start headless publishing. Publish use json from passed paths argument. Args: paths (list): Paths to jsons. + targets (string): What module should be targeted + (to choose validator for example) Raises: - RuntimeError: When there is no pathto process. + RuntimeError: When there is no path to process. """ if not any(paths): raise RuntimeError("No publish paths specified") @@ -82,6 +84,10 @@ class PypeCommands: pyblish.api.register_target("filesequence") pyblish.api.register_host("shell") + if targets: + for target in targets: + pyblish.api.register_target(target) + os.environ["OPENPYPE_PUBLISH_DATA"] = os.pathsep.join(paths) log.info("Running publish ...") diff --git a/openpype/settings/defaults/project_anatomy/imageio.json b/openpype/settings/defaults/project_anatomy/imageio.json index ff16c22663..fcebc876f5 100644 --- a/openpype/settings/defaults/project_anatomy/imageio.json +++ b/openpype/settings/defaults/project_anatomy/imageio.json @@ -78,6 +78,10 @@ { "name": "colorspace", "value": "linear" + }, + { + "name": "create_directories", + "value": "True" } ] }, @@ -114,6 +118,10 @@ { "name": "colorspace", "value": "linear" + }, + { + "name": "create_directories", + "value": "True" } ] } diff --git a/openpype/settings/defaults/project_settings/deadline.json b/openpype/settings/defaults/project_settings/deadline.json index 03f3e19a64..2cc345d5ad 100644 --- a/openpype/settings/defaults/project_settings/deadline.json +++ b/openpype/settings/defaults/project_settings/deadline.json @@ -1,5 +1,12 @@ { "publish": { + "ValidateExpectedFiles": { + "enabled": true, + "active": true, + "families": ["render"], + "targets": ["deadline"], + "allow_user_override": true + }, "MayaSubmitDeadline": { "enabled": true, "optional": false, diff --git a/openpype/settings/defaults/project_settings/ftrack.json b/openpype/settings/defaults/project_settings/ftrack.json index b964ce07c3..88f4e1e2e7 100644 --- a/openpype/settings/defaults/project_settings/ftrack.json +++ b/openpype/settings/defaults/project_settings/ftrack.json @@ -200,6 +200,88 @@ } }, "publish": { + "CollectFtrackFamily": { + "enabled": true, + "profiles": [ + { + "hosts": [ + "standalonepublisher" + ], + "families": [], + "tasks": [], + "add_ftrack_family": true, + "advanced_filtering": [] + }, + { + "hosts": [ + "standalonepublisher" + ], + "families": [ + "matchmove", + "shot" + ], + "tasks": [], + "add_ftrack_family": false, + "advanced_filtering": [] + }, + { + "hosts": [ + "standalonepublisher" + ], + "families": [ + "review", + "plate" + ], + "tasks": [], + "add_ftrack_family": false, + "advanced_filtering": [ + { + "families": [ + "clip", + "review" + ], + "add_ftrack_family": true + } + ] + }, + { + "hosts": [ + "maya" + ], + "families": [ + "model", + "setdress", + "animation", + "look", + "rig", + "camera" + ], + "tasks": [], + "add_ftrack_family": true, + "advanced_filtering": [] + }, + { + "hosts": [ + "tvpaint" + ], + "families": [ + "renderPass" + ], + "tasks": [], + "add_ftrack_family": false, + "advanced_filtering": [] + }, + { + "hosts": [ + "tvpaint" + ], + "families": [], + "tasks": [], + "add_ftrack_family": true, + "advanced_filtering": [] + } + ] + }, "IntegrateFtrackNote": { "enabled": true, "note_with_intent_template": "{intent}: {comment}", diff --git a/openpype/settings/defaults/project_settings/global.json b/openpype/settings/defaults/project_settings/global.json index 5f779fccfa..037fa63a29 100644 --- a/openpype/settings/defaults/project_settings/global.json +++ b/openpype/settings/defaults/project_settings/global.json @@ -56,6 +56,12 @@ ] }, "overscan_crop": "", + "overscan_color": [ + 0, + 0, + 0, + 255 + ], "width": 0, "height": 0, "bg_color": [ @@ -215,6 +221,28 @@ "hosts": [], "tasks": [], "template": "{family}{Task}{Variant}" + }, + { + "families": [ + "renderLayer", + "renderPass" + ], + "hosts": [ + "tvpaint" + ], + "tasks": [], + "template": "{family}{Task}_{Render_layer}_{Render_pass}" + }, + { + "families": [ + "review", + "workfile" + ], + "hosts": [ + "tvpaint" + ], + "tasks": [], + "template": "{family}{Task}" } ] }, diff --git a/openpype/settings/defaults/project_settings/harmony.json b/openpype/settings/defaults/project_settings/harmony.json index 0c7a35c058..3cc175ae72 100644 --- a/openpype/settings/defaults/project_settings/harmony.json +++ b/openpype/settings/defaults/project_settings/harmony.json @@ -5,6 +5,11 @@ ".*" ] }, + "ValidateContainers": { + "enabled": true, + "optional": true, + "active": true + }, "ValidateSceneSettings": { "enabled": true, "optional": true, diff --git a/openpype/settings/defaults/project_settings/hiero.json b/openpype/settings/defaults/project_settings/hiero.json index 44b27fc16f..1dff3aac51 100644 --- a/openpype/settings/defaults/project_settings/hiero.json +++ b/openpype/settings/defaults/project_settings/hiero.json @@ -34,7 +34,8 @@ "jpeg", "png", "h264", - "mov" + "mov", + "mp4" ], "clip_name_template": "{asset}_{subset}_{representation}" } diff --git a/openpype/settings/defaults/project_settings/houdini.json b/openpype/settings/defaults/project_settings/houdini.json new file mode 100644 index 0000000000..811a446e59 --- /dev/null +++ b/openpype/settings/defaults/project_settings/houdini.json @@ -0,0 +1,9 @@ +{ + "publish": { + "ValidateContainers": { + "enabled": true, + "optional": true, + "active": true + } + } +} \ No newline at end of file diff --git a/openpype/settings/defaults/project_settings/maya.json b/openpype/settings/defaults/project_settings/maya.json index ba685ae502..284a1a0040 100644 --- a/openpype/settings/defaults/project_settings/maya.json +++ b/openpype/settings/defaults/project_settings/maya.json @@ -127,6 +127,11 @@ "CollectMayaRender": { "sync_workfile_version": false }, + "ValidateContainers": { + "enabled": true, + "optional": true, + "active": true + }, "ValidateShaderName": { "enabled": false, "regex": "(?P.*)_(.*)_SHD" diff --git a/openpype/settings/defaults/project_settings/nuke.json b/openpype/settings/defaults/project_settings/nuke.json index 13e1924b36..71bf46d5b3 100644 --- a/openpype/settings/defaults/project_settings/nuke.json +++ b/openpype/settings/defaults/project_settings/nuke.json @@ -13,13 +13,19 @@ "fpath_template": "{work}/renders/nuke/{subset}/{subset}.{frame}.{ext}" }, "CreateWritePrerender": { - "fpath_template": "{work}/prerenders/nuke/{subset}/{subset}.{frame}.{ext}" + "fpath_template": "{work}/prerenders/nuke/{subset}/{subset}.{frame}.{ext}", + "use_range_limit": true } }, "publish": { "PreCollectNukeInstances": { "sync_workfile_version": true }, + "ValidateContainers": { + "enabled": true, + "optional": true, + "active": true + }, "ValidateKnobs": { "enabled": false, "knobs": { @@ -43,11 +49,6 @@ "optional": true, "active": true }, - "ValidateNukeWriteBoundingBox": { - "enabled": true, - "optional": true, - "active": true - }, "ExtractThumbnail": { "enabled": true, "nodes": { diff --git a/openpype/settings/defaults/project_settings/photoshop.json b/openpype/settings/defaults/project_settings/photoshop.json index b306a757a6..4c36e4bd49 100644 --- a/openpype/settings/defaults/project_settings/photoshop.json +++ b/openpype/settings/defaults/project_settings/photoshop.json @@ -7,6 +7,11 @@ } }, "publish": { + "ValidateContainers": { + "enabled": true, + "optional": true, + "active": true + }, "ExtractImage": { "formats": [ "png", diff --git a/openpype/settings/defaults/project_settings/slack.json b/openpype/settings/defaults/project_settings/slack.json new file mode 100644 index 0000000000..e70ef77fd2 --- /dev/null +++ b/openpype/settings/defaults/project_settings/slack.json @@ -0,0 +1,17 @@ +{ + "token": "", + "publish": { + "CollectSlackFamilies": { + "enabled": true, + "optional": true, + "profiles": [ + { + "families": [], + "tasks": [], + "hosts": [], + "channel_messages": [] + } + ] + } + } +} \ No newline at end of file diff --git a/openpype/settings/defaults/project_settings/standalonepublisher.json b/openpype/settings/defaults/project_settings/standalonepublisher.json index 9d40d2ded6..443203951d 100644 --- a/openpype/settings/defaults/project_settings/standalonepublisher.json +++ b/openpype/settings/defaults/project_settings/standalonepublisher.json @@ -100,6 +100,29 @@ ], "help": "Script exported from matchmoving application" }, + "create_render": { + "name": "render", + "label": "Render", + "family": "render", + "icon": "image", + "defaults": [ + "Animation", + "Lighting", + "Lookdev", + "Compositing" + ], + "help": "Rendered images or video files" + }, + "create_mov_batch": { + "name": "mov_batch", + "label": "Batch Mov", + "family": "render_mov_batch", + "icon": "image", + "defaults": [ + "Main" + ], + "help": "Process multiple Mov files and publish them for layout and comp." + }, "__dynamic_keys_labels__": { "create_workfile": "Workfile", "create_model": "Model", @@ -109,14 +132,36 @@ "create_camera": "Camera", "create_editorial": "Editorial", "create_image": "Image", - "create_matchmove": "Matchmove" + "create_matchmove": "Matchmove", + "create_render": "Render", + "create_mov_batch": "Batch Mov" } }, "publish": { + "ValidateSceneSettings": { + "enabled": true, + "optional": true, + "active": true, + "check_extensions": [ + "exr", + "dpx", + "jpg", + "jpeg", + "png", + "tiff", + "tga", + "gif", + "svg" + ], + "families": [ + "render" + ], + "skip_timelines_check": [] + }, "ExtractThumbnailSP": { "ffmpeg_args": { "input": [ - "-gamma 2.2" + "-apply_trc gamma22" ], "output": [] } diff --git a/openpype/settings/defaults/project_settings/tvpaint.json b/openpype/settings/defaults/project_settings/tvpaint.json index b4f3b315ec..763802a73f 100644 --- a/openpype/settings/defaults/project_settings/tvpaint.json +++ b/openpype/settings/defaults/project_settings/tvpaint.json @@ -1,5 +1,13 @@ { "publish": { + "ExtractSequence": { + "review_bg": [ + 255, + 255, + 255, + 255 + ] + }, "ValidateProjectSettings": { "enabled": true, "optional": true, diff --git a/openpype/settings/defaults/system_settings/applications.json b/openpype/settings/defaults/system_settings/applications.json index 020924db67..72cd010cf2 100644 --- a/openpype/settings/defaults/system_settings/applications.json +++ b/openpype/settings/defaults/system_settings/applications.json @@ -1101,16 +1101,6 @@ "variants": { "4-26": { "use_python_2": false, - "executables": { - "windows": [], - "darwin": [], - "linux": [] - }, - "arguments": { - "windows": [], - "darwin": [], - "linux": [] - }, "environment": {} } } diff --git a/openpype/settings/defaults/system_settings/modules.json b/openpype/settings/defaults/system_settings/modules.json index 31da9e9e7b..1b74b4695c 100644 --- a/openpype/settings/defaults/system_settings/modules.json +++ b/openpype/settings/defaults/system_settings/modules.json @@ -167,5 +167,8 @@ }, "project_manager": { "enabled": true + }, + "slack": { + "enabled": false } } \ No newline at end of file diff --git a/openpype/settings/entities/__init__.py b/openpype/settings/entities/__init__.py index f64ca1e98d..94eb819f2b 100644 --- a/openpype/settings/entities/__init__.py +++ b/openpype/settings/entities/__init__.py @@ -101,6 +101,7 @@ from .color_entity import ColorEntity from .enum_entity import ( BaseEnumEntity, EnumEntity, + HostsEnumEntity, AppsEnumEntity, ToolsEnumEntity, TaskTypeEnumEntity, @@ -153,6 +154,7 @@ __all__ = ( "BaseEnumEntity", "EnumEntity", + "HostsEnumEntity", "AppsEnumEntity", "ToolsEnumEntity", "TaskTypeEnumEntity", diff --git a/openpype/settings/entities/base_entity.py b/openpype/settings/entities/base_entity.py index c6bff1ff47..1b0dd372fa 100644 --- a/openpype/settings/entities/base_entity.py +++ b/openpype/settings/entities/base_entity.py @@ -279,6 +279,11 @@ class BaseItemEntity(BaseEntity): self, "Dynamic entity can't require restart." ) + @abstractproperty + def root_key(self): + """Root is represented as this dictionary key.""" + pass + @abstractmethod def set_override_state(self, state): """Set override state and trigger it on children. @@ -866,6 +871,10 @@ class ItemEntity(BaseItemEntity): """Call save on root item.""" self.root_item.save() + @property + def root_key(self): + return self.root_item.root_key + def schema_validations(self): if not self.label and self.use_label_wrap: reason = ( diff --git a/openpype/settings/entities/color_entity.py b/openpype/settings/entities/color_entity.py index 7a1b1d9848..dfaa75e761 100644 --- a/openpype/settings/entities/color_entity.py +++ b/openpype/settings/entities/color_entity.py @@ -12,6 +12,17 @@ class ColorEntity(InputEntity): def _item_initalization(self): self.valid_value_types = (list, ) self.value_on_not_set = [0, 0, 0, 255] + self.use_alpha = self.schema_data.get("use_alpha", True) + + def set_override_state(self, *args, **kwargs): + super(ColorEntity, self).set_override_state(*args, **kwargs) + value = self._current_value + if ( + not self.use_alpha + and isinstance(value, list) + and len(value) == 4 + ): + value[3] = 255 def convert_to_valid_type(self, value): """Conversion to valid type. @@ -51,4 +62,8 @@ class ColorEntity(InputEntity): ).format(value) raise BaseInvalidValueType(reason, self.path) new_value.append(item) + + # Make sure + if not self.use_alpha: + new_value[3] = 255 return new_value diff --git a/openpype/settings/entities/dict_mutable_keys_entity.py b/openpype/settings/entities/dict_mutable_keys_entity.py index 4b221720c3..3c2645e3e5 100644 --- a/openpype/settings/entities/dict_mutable_keys_entity.py +++ b/openpype/settings/entities/dict_mutable_keys_entity.py @@ -467,7 +467,7 @@ class DictMutableKeysEntity(EndpointEntity): if self.store_as_list: output = [] for key, child_entity in self.children_by_key.items(): - output.append(key, child_entity.value) + output.append([key, child_entity.value]) return output output = {} diff --git a/openpype/settings/entities/enum_entity.py b/openpype/settings/entities/enum_entity.py index 5df365508c..63e0afeb47 100644 --- a/openpype/settings/entities/enum_entity.py +++ b/openpype/settings/entities/enum_entity.py @@ -101,6 +101,78 @@ class EnumEntity(BaseEnumEntity): super(EnumEntity, self).schema_validations() +class HostsEnumEntity(BaseEnumEntity): + """Enumeration of host names. + + Enum items are hardcoded in definition of the entity. + + Hosts enum can have defined empty value as valid option which is + represented by empty string. Schema key to set this option is + `use_empty_value` (true/false). And to set label of empty value set + `empty_label` (string). + + Enum can have single and multiselection. + + NOTE: + Host name is not the same as application name. Host name defines + implementation instead of application name. + """ + schema_types = ["hosts-enum"] + + def _item_initalization(self): + self.multiselection = self.schema_data.get("multiselection", True) + self.use_empty_value = self.schema_data.get( + "use_empty_value", not self.multiselection + ) + custom_labels = self.schema_data.get("custom_labels") or {} + + host_names = [ + "aftereffects", + "blender", + "celaction", + "fusion", + "harmony", + "hiero", + "houdini", + "maya", + "nuke", + "photoshop", + "resolve", + "tvpaint", + "unreal" + ] + if self.use_empty_value: + host_names.insert(0, "") + # Add default label for empty value if not available + if "" not in custom_labels: + custom_labels[""] = "< without host >" + + # These are hardcoded there is not list of available host in OpenPype + enum_items = [] + valid_keys = set() + for key in host_names: + label = custom_labels.get(key, key) + valid_keys.add(key) + enum_items.append({key: label}) + + self.enum_items = enum_items + self.valid_keys = valid_keys + + if self.multiselection: + self.valid_value_types = (list, ) + self.value_on_not_set = [] + else: + for key in valid_keys: + if self.value_on_not_set is NOT_SET: + self.value_on_not_set = key + break + + self.valid_value_types = (STRING_TYPE, ) + + # GUI attribute + self.placeholder = self.schema_data.get("placeholder") + + class AppsEnumEntity(BaseEnumEntity): schema_types = ["apps-enum"] @@ -116,7 +188,7 @@ class AppsEnumEntity(BaseEnumEntity): system_settings_entity = self.get_entity_from_path("system_settings") valid_keys = set() - enum_items = [] + enum_items_list = [] applications_entity = system_settings_entity["applications"] for group_name, app_group in applications_entity.items(): enabled_entity = app_group.get("enabled") @@ -149,8 +221,12 @@ class AppsEnumEntity(BaseEnumEntity): full_label = variant_label full_name = "/".join((group_name, variant_name)) - enum_items.append({full_name: full_label}) + enum_items_list.append((full_name, full_label)) valid_keys.add(full_name) + + enum_items = [] + for key, value in sorted(enum_items_list, key=lambda item: item[1]): + enum_items.append({key: value}) return enum_items, valid_keys def set_override_state(self, *args, **kwargs): @@ -179,7 +255,7 @@ class ToolsEnumEntity(BaseEnumEntity): system_settings_entity = self.get_entity_from_path("system_settings") valid_keys = set() - enum_items = [] + enum_items_list = [] tool_groups_entity = system_settings_entity["tools"]["tool_groups"] for group_name, tool_group in tool_groups_entity.items(): # Try to get group label from entity @@ -204,8 +280,12 @@ class ToolsEnumEntity(BaseEnumEntity): else: tool_label = tool_name - enum_items.append({tool_name: tool_label}) + enum_items_list.append((tool_name, tool_label)) valid_keys.add(tool_name) + + enum_items = [] + for key, value in sorted(enum_items_list, key=lambda item: item[1]): + enum_items.append({key: value}) return enum_items, valid_keys def set_override_state(self, *args, **kwargs): diff --git a/openpype/settings/entities/root_entities.py b/openpype/settings/entities/root_entities.py index 401d3980c9..5ed78fd401 100644 --- a/openpype/settings/entities/root_entities.py +++ b/openpype/settings/entities/root_entities.py @@ -189,11 +189,10 @@ class RootEntity(BaseItemEntity): if not KEY_REGEX.match(key): raise InvalidKeySymbols(self.path, key) + @abstractmethod def get_entity_from_path(self, path): - """Return system settings entity.""" - raise NotImplementedError(( - "Method `get_entity_from_path` not available for \"{}\"" - ).format(self.__class__.__name__)) + """Return entity matching passed path.""" + pass def create_schema_object(self, schema_data, *args, **kwargs): """Create entity by entered schema data. @@ -491,6 +490,8 @@ class SystemSettings(RootEntity): schema_data (dict): Pass schema data to entity. This is for development and debugging purposes. """ + root_key = SYSTEM_SETTINGS_KEY + def __init__( self, set_studio_state=True, reset=True, schema_data=None ): @@ -503,6 +504,18 @@ class SystemSettings(RootEntity): if set_studio_state: self.set_studio_state() + def get_entity_from_path(self, path): + """Return system settings entity.""" + path_parts = path.split("/") + first_part = path_parts[0] + output = self + if first_part == self.root_key: + path_parts.pop(0) + + for path_part in path_parts: + output = output[path_part] + return output + def _reset_values(self): default_value = get_default_settings()[SYSTEM_SETTINGS_KEY] for key, child_obj in self.non_gui_children.items(): @@ -600,6 +613,8 @@ class ProjectSettings(RootEntity): schema_data (dict): Pass schema data to entity. This is for development and debugging purposes. """ + root_key = PROJECT_SETTINGS_KEY + def __init__( self, project_name=None, diff --git a/openpype/settings/entities/schemas/README.md b/openpype/settings/entities/schemas/README.md index 6c31b61f59..bbd53fa46b 100644 --- a/openpype/settings/entities/schemas/README.md +++ b/openpype/settings/entities/schemas/README.md @@ -272,6 +272,25 @@ } ``` +### hosts-enum +- enumeration of available hosts +- multiselection can be allowed with setting key `"multiselection"` to `True` (Default: `False`) +- it is possible to add empty value (represented with empty string) with setting `"use_empty_value"` to `True` (Default: `False`) +- it is possible to set `"custom_labels"` for host names where key `""` is empty value (Default: `{}`) +``` +{ + "key": "host", + "label": "Host name", + "type": "hosts-enum", + "multiselection": false, + "use_empty_value": true, + "custom_labels": { + "": "N/A", + "nuke": "Nuke" + } +} +``` + ## Inputs for setting value using Pure inputs - these inputs also have required `"key"` - attribute `"label"` is required in few conditions diff --git a/openpype/settings/entities/schemas/projects_schema/schema_main.json b/openpype/settings/entities/schemas/projects_schema/schema_main.json index 64c5a7f366..4a8a9d496e 100644 --- a/openpype/settings/entities/schemas/projects_schema/schema_main.json +++ b/openpype/settings/entities/schemas/projects_schema/schema_main.json @@ -66,6 +66,10 @@ "type": "schema", "name": "schema_project_deadline" }, + { + "type": "schema", + "name": "schema_project_slack" + }, { "type": "schema", "name": "schema_project_maya" @@ -78,6 +82,10 @@ "type": "schema", "name": "schema_project_hiero" }, + { + "type": "schema", + "name": "schema_project_houdini" + }, { "type": "schema", "name": "schema_project_blender" diff --git a/openpype/settings/entities/schemas/projects_schema/schema_project_deadline.json b/openpype/settings/entities/schemas/projects_schema/schema_project_deadline.json index d47a6917da..f6a8127951 100644 --- a/openpype/settings/entities/schemas/projects_schema/schema_project_deadline.json +++ b/openpype/settings/entities/schemas/projects_schema/schema_project_deadline.json @@ -11,6 +11,47 @@ "key": "publish", "label": "Publish plugins", "children": [ + { + "type": "dict", + "collapsible": true, + "key": "ValidateExpectedFiles", + "label": "Validate Expected Files", + "checkbox_key": "enabled", + "children": [ + { + "type": "boolean", + "key": "enabled", + "label": "Enabled" + }, + { + "type": "boolean", + "key": "active", + "label": "Active" + }, + { + "type": "label", + "label": "Validate if all expected files were rendered" + }, + { + "type": "boolean", + "key": "allow_user_override", + "object_type": "text", + "label": "Allow user change frame range" + }, + { + "type": "list", + "key": "families", + "object_type": "text", + "label": "Trigger on families" + }, + { + "type": "list", + "key": "targets", + "object_type": "text", + "label": "Trigger for plugins" + } + ] + }, { "type": "dict", "collapsible": true, diff --git a/openpype/settings/entities/schemas/projects_schema/schema_project_ftrack.json b/openpype/settings/entities/schemas/projects_schema/schema_project_ftrack.json index aae2bb2539..a94ebc8888 100644 --- a/openpype/settings/entities/schemas/projects_schema/schema_project_ftrack.json +++ b/openpype/settings/entities/schemas/projects_schema/schema_project_ftrack.json @@ -604,6 +604,82 @@ "key": "publish", "label": "Publish plugins", "children": [ + { + "type": "dict", + "collapsible": true, + "checkbox_key": "enabled", + "key": "CollectFtrackFamily", + "label": "Collect Ftrack Family", + "is_group": true, + "children": [ + { + "type": "boolean", + "key": "enabled", + "label": "Enabled" + }, + { + "type": "list", + "collapsible": true, + "key": "profiles", + "label": "Profiles", + "use_label_wrap": true, + "object_type": { + "type": "dict", + "children": [ + { + "key": "hosts", + "label": "Host names", + "type": "list", + "object_type": "text" + }, + { + "key": "families", + "label": "Families", + "type": "list", + "object_type": "text" + }, + { + "key": "tasks", + "label": "Task names", + "type": "list", + "object_type": "text" + }, + { + "type": "separator" + }, + { + "key": "add_ftrack_family", + "label": "Add Ftrack Family", + "type": "boolean" + }, + { + "type": "list", + "collapsible": true, + "key": "advanced_filtering", + "label": "Advanced adding if additional families present", + "use_label_wrap": true, + "object_type": { + "type": "dict", + "children": [ + { + "key": "families", + "label": "Additional Families", + "type": "list", + "object_type": "text" + }, + { + "key": "add_ftrack_family", + "label": "Add Ftrack Family", + "type": "boolean" + } + ] + } + } + ] + } + } + ] + }, { "type": "dict", "collapsible": true, diff --git a/openpype/settings/entities/schemas/projects_schema/schema_project_harmony.json b/openpype/settings/entities/schemas/projects_schema/schema_project_harmony.json index 8b5d638cd8..ce6246a8de 100644 --- a/openpype/settings/entities/schemas/projects_schema/schema_project_harmony.json +++ b/openpype/settings/entities/schemas/projects_schema/schema_project_harmony.json @@ -25,6 +25,16 @@ } ] }, + { + "type": "schema_template", + "name": "template_publish_plugin", + "template_data": [ + { + "key": "ValidateContainers", + "label": "ValidateContainers" + } + ] + }, { "type": "dict", "collapsible": true, diff --git a/openpype/settings/entities/schemas/projects_schema/schema_project_houdini.json b/openpype/settings/entities/schemas/projects_schema/schema_project_houdini.json new file mode 100644 index 0000000000..c6de257a61 --- /dev/null +++ b/openpype/settings/entities/schemas/projects_schema/schema_project_houdini.json @@ -0,0 +1,27 @@ +{ + "type": "dict", + "collapsible": true, + "key": "houdini", + "label": "Houdini", + "is_file": true, + "children": [ + { + "type": "dict", + "collapsible": true, + "key": "publish", + "label": "Publish plugins", + "children": [ + { + "type": "schema_template", + "name": "template_publish_plugin", + "template_data": [ + { + "key": "ValidateContainers", + "label": "ValidateContainers" + } + ] + } + ] + } + ] +} diff --git a/openpype/settings/entities/schemas/projects_schema/schema_project_nuke.json b/openpype/settings/entities/schemas/projects_schema/schema_project_nuke.json index f709e84651..01a954f283 100644 --- a/openpype/settings/entities/schemas/projects_schema/schema_project_nuke.json +++ b/openpype/settings/entities/schemas/projects_schema/schema_project_nuke.json @@ -77,6 +77,11 @@ "type": "text", "key": "fpath_template", "label": "Path template" + }, + { + "type": "boolean", + "key": "use_range_limit", + "label": "Use Frame range limit by default" } ] } diff --git a/openpype/settings/entities/schemas/projects_schema/schema_project_photoshop.json b/openpype/settings/entities/schemas/projects_schema/schema_project_photoshop.json index 4eb6c26dbb..3b65f08ac4 100644 --- a/openpype/settings/entities/schemas/projects_schema/schema_project_photoshop.json +++ b/openpype/settings/entities/schemas/projects_schema/schema_project_photoshop.json @@ -33,6 +33,16 @@ "key": "publish", "label": "Publish plugins", "children": [ + { + "type": "schema_template", + "name": "template_publish_plugin", + "template_data": [ + { + "key": "ValidateContainers", + "label": "ValidateContainers" + } + ] + }, { "type": "dict", "collapsible": true, @@ -50,7 +60,7 @@ "object_type": "text" } ] - } + } ] }, { diff --git a/openpype/settings/entities/schemas/projects_schema/schema_project_slack.json b/openpype/settings/entities/schemas/projects_schema/schema_project_slack.json new file mode 100644 index 0000000000..170de7c8a2 --- /dev/null +++ b/openpype/settings/entities/schemas/projects_schema/schema_project_slack.json @@ -0,0 +1,106 @@ +{ + "type": "dict", + "key": "slack", + "label": "Slack", + "collapsible": true, + "is_file": true, + "children": [ + { + "type": "text", + "key": "token", + "label": "Auth Token" + }, + { + "type": "dict", + "collapsible": true, + "key": "publish", + "label": "Publish plugins", + "children": [ + { + "type": "label", + "label": "Fill combination of families, task names and hosts when to send notification" + }, + { + "type": "dict", + "key": "CollectSlackFamilies", + "label": "Notification to Slack", + "use_label_wrap": true, + "checkbox_key": "enabled", + "children": [ + { + "type": "boolean", + "key": "enabled", + "label": "Enabled" + }, + { + "type": "boolean", + "key": "optional", + "label": "Optional" + }, + { + "type": "list", + "collapsible": true, + "key": "profiles", + "label": "Profiles", + "use_label_wrap": true, + "object_type": { + "type": "dict", + "children": [ + { + "key": "families", + "label": "Families", + "type": "list", + "object_type": "text" + }, + { + "key": "tasks", + "label": "Task names", + "type": "list", + "object_type": "text" + }, + { + "type": "hosts-enum", + "key": "hosts", + "label": "Host names", + "multiselection": true + }, + { + "type": "separator" + }, + { + "key": "channel_messages", + "label": "Messages to channels", + "type": "list", + "use_label_wrap": true, + "object_type": { + "type": "dict", + "children": [ + { + "type": "list", + "object_type": "text", + "key": "channels", + "label": "Channels" + }, + { + "type": "boolean", + "key": "upload_thumbnail", + "label": "Upload thumbnail" + }, + { + "type": "text", + "multiline": true, + "key": "message", + "label": "Message" + } + ] + } + } + ] + } + } + ] + } + ] + } + ] +} diff --git a/openpype/settings/entities/schemas/projects_schema/schema_project_standalonepublisher.json b/openpype/settings/entities/schemas/projects_schema/schema_project_standalonepublisher.json index 28755ad268..0ef7612805 100644 --- a/openpype/settings/entities/schemas/projects_schema/schema_project_standalonepublisher.json +++ b/openpype/settings/entities/schemas/projects_schema/schema_project_standalonepublisher.json @@ -56,6 +56,52 @@ "key": "publish", "label": "Publish plugins", "children": [ + { + "type": "dict", + "collapsible": true, + "key": "ValidateSceneSettings", + "label": "Validate Scene Settings", + "checkbox_key": "enabled", + "children": [ + { + "type": "boolean", + "key": "enabled", + "label": "Enabled" + }, + { + "type": "boolean", + "key": "optional", + "label": "Optional" + }, + { + "type": "boolean", + "key": "active", + "label": "Active" + }, + { + "type": "label", + "label": "Validate if frame range in DB matches number of published files" + }, + { + "type": "list", + "key": "check_extensions", + "object_type": "text", + "label": "Check Frame Range for Extensions" + }, + { + "key": "families", + "label": "Families", + "type": "list", + "object_type": "text" + }, + { + "type": "list", + "key": "skip_timelines_check", + "object_type": "text", + "label": "Skip Frame Range check for Tasks" + } + ] + }, { "type": "dict", "collapsible": true, diff --git a/openpype/settings/entities/schemas/projects_schema/schema_project_tvpaint.json b/openpype/settings/entities/schemas/projects_schema/schema_project_tvpaint.json index 6f90bb4263..67aa4b0a06 100644 --- a/openpype/settings/entities/schemas/projects_schema/schema_project_tvpaint.json +++ b/openpype/settings/entities/schemas/projects_schema/schema_project_tvpaint.json @@ -11,6 +11,25 @@ "key": "publish", "label": "Publish plugins", "children": [ + { + "type": "dict", + "collapsible": true, + "key": "ExtractSequence", + "label": "ExtractSequence", + "is_group": true, + "children": [ + { + "type": "label", + "label": "Review BG color is used for whole scene review and for thumbnails." + }, + { + "type": "color", + "key": "review_bg", + "label": "Review BG color", + "use_alpha": false + } + ] + }, { "type": "schema_template", "name": "template_publish_plugin", diff --git a/openpype/settings/entities/schemas/projects_schema/schemas/schema_anatomy_imageio.json b/openpype/settings/entities/schemas/projects_schema/schemas/schema_anatomy_imageio.json index 3c589f9492..2b2eab8868 100644 --- a/openpype/settings/entities/schemas/projects_schema/schemas/schema_anatomy_imageio.json +++ b/openpype/settings/entities/schemas/projects_schema/schemas/schema_anatomy_imageio.json @@ -3,7 +3,6 @@ "key": "imageio", "label": "Color Management and Output Formats", "is_file": true, - "is_group": true, "children": [ { "key": "hiero", @@ -15,6 +14,7 @@ "type": "dict", "label": "Workfile", "collapsible": false, + "is_group": true, "children": [ { "type": "form", @@ -89,6 +89,7 @@ "type": "dict", "label": "Colorspace on Inputs by regex detection", "collapsible": true, + "is_group": true, "children": [ { "type": "list", @@ -123,6 +124,7 @@ "type": "dict", "label": "Viewer", "collapsible": false, + "is_group": true, "children": [ { "type": "text", @@ -136,6 +138,7 @@ "type": "dict", "label": "Workfile", "collapsible": false, + "is_group": true, "children": [ { "type": "form", @@ -233,6 +236,7 @@ "type": "dict", "label": "Nodes", "collapsible": true, + "is_group": true, "children": [ { "key": "requiredNodes", @@ -335,6 +339,7 @@ "type": "dict", "label": "Colorspace on Inputs by regex detection", "collapsible": true, + "is_group": true, "children": [ { "type": "list", diff --git a/openpype/settings/entities/schemas/projects_schema/schemas/schema_global_publish.json b/openpype/settings/entities/schemas/projects_schema/schemas/schema_global_publish.json index 0c89575d74..496635287f 100644 --- a/openpype/settings/entities/schemas/projects_schema/schemas/schema_global_publish.json +++ b/openpype/settings/entities/schemas/projects_schema/schemas/schema_global_publish.json @@ -90,10 +90,10 @@ "object_type": "text" }, { + "type": "hosts-enum", "key": "hosts", "label": "Hosts", - "type": "list", - "object_type": "text" + "multiselection": true }, { "type": "splitter" @@ -182,6 +182,16 @@ "key": "overscan_crop", "label": "Overscan crop" }, + { + "type": "label", + "label": "Overscan color is used when input aspect ratio is not same as output aspect ratio." + }, + { + "type": "color", + "label": "Overscan color", + "key": "overscan_color", + "use_alpha": false + }, { "type": "label", "label": "Width and Height must be both set to higher value than 0 else source resolution is used." @@ -348,10 +358,10 @@ "object_type": "text" }, { + "type": "hosts-enum", "key": "hosts", "label": "Hosts", - "type": "list", - "object_type": "text" + "multiselection": true }, { "type": "splitter" @@ -482,10 +492,10 @@ "object_type": "text" }, { + "type": "hosts-enum", "key": "hosts", "label": "Hosts", - "type": "list", - "object_type": "text" + "multiselection": true }, { "key": "tasks", diff --git a/openpype/settings/entities/schemas/projects_schema/schemas/schema_global_tools.json b/openpype/settings/entities/schemas/projects_schema/schemas/schema_global_tools.json index 224389d42e..8c92a45a56 100644 --- a/openpype/settings/entities/schemas/projects_schema/schemas/schema_global_tools.json +++ b/openpype/settings/entities/schemas/projects_schema/schemas/schema_global_tools.json @@ -35,10 +35,10 @@ "object_type": "text" }, { + "type": "hosts-enum", "key": "hosts", "label": "Hosts", - "type": "list", - "object_type": "text" + "multiselection": true }, { "key": "tasks", @@ -75,10 +75,10 @@ "type": "dict", "children": [ { + "type": "hosts-enum", "key": "hosts", "label": "Hosts", - "type": "list", - "object_type": "text" + "multiselection": true }, { "key": "tasks", diff --git a/openpype/settings/entities/schemas/projects_schema/schemas/schema_maya_publish.json b/openpype/settings/entities/schemas/projects_schema/schemas/schema_maya_publish.json index 0abcdd2965..5ca7059ee5 100644 --- a/openpype/settings/entities/schemas/projects_schema/schemas/schema_maya_publish.json +++ b/openpype/settings/entities/schemas/projects_schema/schemas/schema_maya_publish.json @@ -28,7 +28,16 @@ "type": "label", "label": "Validators" }, - + { + "type": "schema_template", + "name": "template_publish_plugin", + "template_data": [ + { + "key": "ValidateContainers", + "label": "ValidateContainers" + } + ] + }, { "type": "dict", "collapsible": true, diff --git a/openpype/settings/entities/schemas/projects_schema/schemas/schema_nuke_publish.json b/openpype/settings/entities/schemas/projects_schema/schemas/schema_nuke_publish.json index 087e6c13a9..782179cfd1 100644 --- a/openpype/settings/entities/schemas/projects_schema/schemas/schema_nuke_publish.json +++ b/openpype/settings/entities/schemas/projects_schema/schemas/schema_nuke_publish.json @@ -29,6 +29,16 @@ "type": "label", "label": "Validators" }, + { + "type": "schema_template", + "name": "template_publish_plugin", + "template_data": [ + { + "key": "ValidateContainers", + "label": "ValidateContainers" + } + ] + }, { "type": "dict", "collapsible": true, @@ -64,10 +74,6 @@ { "key": "ValidateScript", "label": "Validate script settings" - }, - { - "key": "ValidateNukeWriteBoundingBox", - "label": "Validate and Write Bounding Box" } ] }, diff --git a/openpype/settings/entities/schemas/system_schema/host_settings/schema_unreal.json b/openpype/settings/entities/schemas/system_schema/host_settings/schema_unreal.json index df5ec0e6fa..133d6c9eaf 100644 --- a/openpype/settings/entities/schemas/system_schema/host_settings/schema_unreal.json +++ b/openpype/settings/entities/schemas/system_schema/host_settings/schema_unreal.json @@ -30,7 +30,12 @@ "children": [ { "type": "schema_template", - "name": "template_host_variant_items" + "name": "template_host_variant_items", + "skip_paths": [ + "executables", + "separator", + "arguments" + ] } ] } diff --git a/openpype/settings/entities/schemas/system_schema/host_settings/template_host_unchangables.json b/openpype/settings/entities/schemas/system_schema/host_settings/template_host_unchangables.json index e8b2a70076..c4d8d89209 100644 --- a/openpype/settings/entities/schemas/system_schema/host_settings/template_host_unchangables.json +++ b/openpype/settings/entities/schemas/system_schema/host_settings/template_host_unchangables.json @@ -14,25 +14,11 @@ "roles": ["developer"] }, { - "type": "enum", + "type": "hosts-enum", "key": "host_name", "label": "Host implementation", - "enum_items": [ - { "": "< without host >" }, - { "aftereffects": "aftereffects" }, - { "blender": "blender" }, - { "celaction": "celaction" }, - { "fusion": "fusion" }, - { "harmony": "harmony" }, - { "hiero": "hiero" }, - { "houdini": "houdini" }, - { "maya": "maya" }, - { "nuke": "nuke" }, - { "photoshop": "photoshop" }, - { "resolve": "resolve" }, - { "tvpaint": "tvpaint" }, - { "unreal": "unreal" } - ], + "multiselection": false, + "use_empty_value": true, "roles": ["developer"] } ] diff --git a/openpype/settings/entities/schemas/system_schema/host_settings/template_host_variant_items.json b/openpype/settings/entities/schemas/system_schema/host_settings/template_host_variant_items.json index ab4d2374a3..409efb006e 100644 --- a/openpype/settings/entities/schemas/system_schema/host_settings/template_host_variant_items.json +++ b/openpype/settings/entities/schemas/system_schema/host_settings/template_host_variant_items.json @@ -14,6 +14,7 @@ "placeholder": "Executable path" }, { + "key": "separator", "type":"separator" }, { diff --git a/openpype/settings/entities/schemas/system_schema/schema_modules.json b/openpype/settings/entities/schemas/system_schema/schema_modules.json index d6527f368d..7d734ff4fd 100644 --- a/openpype/settings/entities/schemas/system_schema/schema_modules.json +++ b/openpype/settings/entities/schemas/system_schema/schema_modules.json @@ -82,7 +82,8 @@ "label": "Workspace name" } ] - }, { + }, + { "type": "dict", "key": "sync_server", "label": "Site Sync", @@ -114,7 +115,8 @@ } } ] - },{ + }, + { "type": "dict", "key": "deadline", "label": "Deadline", @@ -206,6 +208,21 @@ "label": "Enabled" } ] + }, + { + "type": "dict", + "key": "slack", + "label": "Slack Notifications", + "collapsible": true, + "require_restart": true, + "checkbox_key": "enabled", + "children": [ + { + "type": "boolean", + "key": "enabled", + "label": "Enabled" + } + ] } ] } diff --git a/openpype/settings/handlers.py b/openpype/settings/handlers.py index 65ec7291d3..288fc76801 100644 --- a/openpype/settings/handlers.py +++ b/openpype/settings/handlers.py @@ -590,16 +590,21 @@ class MongoSettingsHandler(SettingsHandler): attributes[key] = value project_doc_config = project_doc.get("config") or {} + app_names = set() - if "apps" in project_doc_config: - for app_item in project_doc_config.pop("apps"): + if not project_doc_config or "apps" not in project_doc_config: + set_applications = False + else: + set_applications = True + for app_item in project_doc_config["apps"]: if not app_item: continue app_name = app_item.get("name") if app_name: app_names.add(app_name) - attributes["applications"] = list(app_names) + if set_applications: + attributes["applications"] = list(app_names) output = {"attributes": attributes} for key in self.anatomy_keys: diff --git a/openpype/settings/lib.py b/openpype/settings/lib.py index f61166fa69..4a3e66de33 100644 --- a/openpype/settings/lib.py +++ b/openpype/settings/lib.py @@ -532,7 +532,11 @@ def apply_local_settings_on_system_settings(system_settings, local_settings): variants = system_settings["applications"][app_group_name]["variants"] for app_name, app_value in value.items(): - if not app_value or app_name not in variants: + if ( + not app_value + or app_name not in variants + or "executables" not in variants[app_name] + ): continue executable = app_value.get("executable") diff --git a/openpype/style/style.css b/openpype/style/style.css index aa71105320..c57b9a8da6 100644 --- a/openpype/style/style.css +++ b/openpype/style/style.css @@ -22,6 +22,7 @@ Enabled vs Disabled logic in most of stylesheets font-size: 9pt; font-family: "Spartan"; font-weight: 450; + outline: none; } QWidget { @@ -96,6 +97,29 @@ QToolButton:disabled { background: {color:bg-buttons-disabled}; } +QToolButton[popupMode="1"] { + /* make way for the popup button */ + padding-right: 20px; + border: 1px solid {color:bg-buttons}; +} + +QToolButton::menu-button { + width: 16px; + /* Set border only of left side. */ + border: 1px solid transparent; + border-left: 1px solid {color:bg-buttons}; +} + +QToolButton::menu-arrow { + /* Offset arrow a little bit to center. */ + left: 1px; top: 1px; +} + +QToolButton::menu-arrow:open { + /* Don't offset arrow on open. */ + left: 0px; top: 0px; +} + /* QMenu */ QMenu { border: 1px solid #555555; @@ -145,7 +169,6 @@ QComboBox:disabled { QComboBox QAbstractItemView { border: 1px solid {color:border}; background: {color:bg-inputs}; - outline: none; } QComboBox QAbstractItemView::item:selected { @@ -313,6 +336,8 @@ QAbstractItemView { border-radius: 0.2em; background: {color:bg-view}; alternate-background-color: {color:bg-view-alternate}; + /* Mac shows selection color on branches. */ + selection-background-color: transparent; } QAbstractItemView:disabled{ @@ -344,30 +369,35 @@ QAbstractItemView::item:selected:hover { background: {color:bg-view-selection-hover}; } +/* Row colors (alternate colors) are from left - right */ +QAbstractItemView:branch { + background: transparent; +} + QAbstractItemView::branch:open:has-children:!has-siblings, QAbstractItemView::branch:open:has-children:has-siblings { border-image: none; image: url(:/openpype/images/branch_open.png); - background: {color:bg-view}; + background: transparent; } QAbstractItemView::branch:open:has-children:!has-siblings:hover, QAbstractItemView::branch:open:has-children:has-siblings:hover { border-image: none; image: url(:/openpype/images//branch_open_on.png); - /* background: {color:bg-view-hover}; */ + background: transparent; } QAbstractItemView::branch:has-children:!has-siblings:closed, QAbstractItemView::branch:closed:has-children:has-siblings { border-image: none; image: url(:/openpype/images//branch_closed.png); - background: {color:bg-view}; + background: transparent; } QAbstractItemView::branch:has-children:!has-siblings:closed:hover, QAbstractItemView::branch:closed:has-children:has-siblings:hover { border-image: none; image: url(:/openpype/images//branch_closed_on.png); - /* background: {color:bg-view-hover}; */ + background: transparent; } /* Progress bar */ @@ -538,7 +568,6 @@ QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { #CompleterView { border: 1px solid {color:border}; background: {color:bg-inputs}; - outline: none; } #CompleterView::item { @@ -576,9 +605,6 @@ QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { } /* Standalone publisher */ -#ComponentList { - outline: none; -} #ComponentItem { background: transparent; diff --git a/openpype/tools/launcher/lib.py b/openpype/tools/launcher/lib.py index b4e6a0c3e9..65d40cd0df 100644 --- a/openpype/tools/launcher/lib.py +++ b/openpype/tools/launcher/lib.py @@ -15,7 +15,7 @@ provides a bridge between the file-based project inventory and configuration. """ import os -from Qt import QtGui +from Qt import QtGui, QtCore from avalon.vendor import qtawesome from openpype.api import resources @@ -23,6 +23,51 @@ ICON_CACHE = {} NOT_FOUND = type("NotFound", (object, ), {}) +class ProjectHandler(QtCore.QObject): + """Handler of project model and current project in Launcher tool. + + Helps to organize two separate widgets handling current project selection. + + It is easier to trigger project change callbacks from one place than from + multiple differect places without proper handling or sequence changes. + + Args: + dbcon(AvalonMongoDB): Mongo connection with Session. + model(ProjectModel): Object of projects model which is shared across + all widgets using projects. Arg dbcon should be used as source for + the model. + """ + # Project list will be refreshed each 10000 msecs + # - this is not part of helper implementation but should be used by widgets + # that may require reshing of projects + refresh_interval = 10000 + + # Signal emmited when project has changed + project_changed = QtCore.Signal(str) + + def __init__(self, dbcon, model): + super(ProjectHandler, self).__init__() + # Store project model for usage + self.model = model + # Store dbcon + self.dbcon = dbcon + + self.current_project = dbcon.Session.get("AVALON_PROJECT") + + def set_project(self, project_name): + # Change current project of this handler + self.current_project = project_name + # Change session project to take effect for other widgets using the + # dbcon object. + self.dbcon.Session["AVALON_PROJECT"] = project_name + + # Trigger change signal when everything is updated to new project + self.project_changed.emit(project_name) + + def refresh_model(self): + self.model.refresh() + + def get_action_icon(action): icon_name = action.icon if not icon_name: diff --git a/openpype/tools/launcher/models.py b/openpype/tools/launcher/models.py index 25b6dcdbf0..846a07e081 100644 --- a/openpype/tools/launcher/models.py +++ b/openpype/tools/launcher/models.py @@ -325,19 +325,59 @@ class ProjectModel(QtGui.QStandardItemModel): self.hide_invisible = False self.project_icon = qtawesome.icon("fa.map", color="white") + self._project_names = set() def refresh(self): - self.clear() - self.beginResetModel() - + project_names = set() for project_doc in self.get_projects(): - item = QtGui.QStandardItem(self.project_icon, project_doc["name"]) - self.appendRow(item) + project_names.add(project_doc["name"]) - self.endResetModel() + origin_project_names = set(self._project_names) + self._project_names = project_names + + project_names_to_remove = origin_project_names - project_names + if project_names_to_remove: + row_counts = {} + continuous = None + for row in range(self.rowCount()): + index = self.index(row, 0) + index_name = index.data(QtCore.Qt.DisplayRole) + if index_name in project_names_to_remove: + if continuous is None: + continuous = row + row_counts[continuous] = 0 + row_counts[continuous] += 1 + else: + continuous = None + + for row in reversed(sorted(row_counts.keys())): + count = row_counts[row] + self.removeRows(row, count) + + continuous = None + row_counts = {} + for idx, project_name in enumerate(sorted(project_names)): + if project_name in origin_project_names: + continuous = None + continue + + if continuous is None: + continuous = idx + row_counts[continuous] = [] + + row_counts[continuous].append(project_name) + + for row in reversed(sorted(row_counts.keys())): + items = [] + for project_name in row_counts[row]: + item = QtGui.QStandardItem(self.project_icon, project_name) + items.append(item) + + self.invisibleRootItem().insertRows(row, items) def get_projects(self): project_docs = [] + for project_doc in sorted( self.dbcon.projects(), key=lambda x: x["name"] ): diff --git a/openpype/tools/launcher/widgets.py b/openpype/tools/launcher/widgets.py index 22b08d7d15..048210115c 100644 --- a/openpype/tools/launcher/widgets.py +++ b/openpype/tools/launcher/widgets.py @@ -20,22 +20,15 @@ from .constants import ( class ProjectBar(QtWidgets.QWidget): - project_changed = QtCore.Signal(int) - - def __init__(self, dbcon, parent=None): + def __init__(self, project_handler, parent=None): super(ProjectBar, self).__init__(parent) - self.dbcon = dbcon - - model = ProjectModel(dbcon) - model.hide_invisible = True - project_combobox = QtWidgets.QComboBox(self) # Change delegate so stylysheets are applied project_delegate = QtWidgets.QStyledItemDelegate(project_combobox) project_combobox.setItemDelegate(project_delegate) - project_combobox.setModel(model) + project_combobox.setModel(project_handler.model) project_combobox.setRootModelIndex(QtCore.QModelIndex()) layout = QtWidgets.QHBoxLayout(self) @@ -47,21 +40,43 @@ class ProjectBar(QtWidgets.QWidget): QtWidgets.QSizePolicy.Maximum ) - self.model = model + refresh_timer = QtCore.QTimer() + refresh_timer.setInterval(project_handler.refresh_interval) + + self.project_handler = project_handler self.project_delegate = project_delegate self.project_combobox = project_combobox - - # Initialize - self.refresh() + self.refresh_timer = refresh_timer # Signals - self.project_combobox.currentIndexChanged.connect(self.project_changed) + refresh_timer.timeout.connect(self._on_refresh_timeout) + self.project_combobox.currentIndexChanged.connect(self.on_index_change) + project_handler.project_changed.connect(self._on_project_change) # Set current project by default if it's set. - project_name = self.dbcon.Session.get("AVALON_PROJECT") + project_name = project_handler.current_project if project_name: self.set_project(project_name) + def showEvent(self, event): + if not self.refresh_timer.isActive(): + self.refresh_timer.start() + super(ProjectBar, self).showEvent(event) + + def _on_refresh_timeout(self): + if not self.isVisible(): + # Stop timer if widget is not visible + self.refresh_timer.stop() + + elif self.isActiveWindow(): + # Refresh projects if window is active + self.project_handler.refresh_model() + + def _on_project_change(self, project_name): + if self.get_current_project() == project_name: + return + self.set_project(project_name) + def get_current_project(self): return self.project_combobox.currentText() @@ -69,27 +84,18 @@ class ProjectBar(QtWidgets.QWidget): index = self.project_combobox.findText(project_name) if index < 0: # Try refresh combobox model - self.project_combobox.blockSignals(True) - self.model.refresh() - self.project_combobox.blockSignals(False) - + self.project_handler.refresh_model() index = self.project_combobox.findText(project_name) if index >= 0: self.project_combobox.setCurrentIndex(index) - def refresh(self): - prev_project_name = self.get_current_project() + def on_index_change(self, idx): + if not self.isVisible(): + return - # Refresh without signals - self.project_combobox.blockSignals(True) - - self.model.refresh() - self.set_project(prev_project_name) - - self.project_combobox.blockSignals(False) - - self.project_changed.emit(self.project_combobox.currentIndex()) + project_name = self.get_current_project() + self.project_handler.set_project(project_name) class ActionBar(QtWidgets.QWidget): diff --git a/openpype/tools/launcher/window.py b/openpype/tools/launcher/window.py index af749814b7..979aab42cf 100644 --- a/openpype/tools/launcher/window.py +++ b/openpype/tools/launcher/window.py @@ -12,7 +12,7 @@ from avalon.tools import lib as tools_lib from avalon.tools.widgets import AssetWidget from avalon.vendor import qtawesome from .models import ProjectModel -from .lib import get_action_label +from .lib import get_action_label, ProjectHandler from .widgets import ( ProjectBar, ActionBar, @@ -89,37 +89,49 @@ class ProjectIconView(QtWidgets.QListView): class ProjectsPanel(QtWidgets.QWidget): """Projects Page""" - - project_clicked = QtCore.Signal(str) - - def __init__(self, dbcon, parent=None): + def __init__(self, project_handler, parent=None): super(ProjectsPanel, self).__init__(parent=parent) layout = QtWidgets.QVBoxLayout(self) - self.dbcon = dbcon - self.dbcon.install() - view = ProjectIconView(parent=self) view.setSelectionMode(QtWidgets.QListView.NoSelection) flick = FlickCharm(parent=self) flick.activateOn(view) - model = ProjectModel(self.dbcon) - model.hide_invisible = True - model.refresh() - view.setModel(model) + + view.setModel(project_handler.model) layout.addWidget(view) + refresh_timer = QtCore.QTimer() + refresh_timer.setInterval(project_handler.refresh_interval) + + refresh_timer.timeout.connect(self._on_refresh_timeout) view.clicked.connect(self.on_clicked) - self.model = model self.view = view + self.refresh_timer = refresh_timer + self.project_handler = project_handler def on_clicked(self, index): if index.isValid(): project_name = index.data(QtCore.Qt.DisplayRole) - self.project_clicked.emit(project_name) + self.project_handler.set_project(project_name) + + def showEvent(self, event): + self.project_handler.refresh_model() + if not self.refresh_timer.isActive(): + self.refresh_timer.start() + super(ProjectsPanel, self).showEvent(event) + + def _on_refresh_timeout(self): + if not self.isVisible(): + # Stop timer if widget is not visible + self.refresh_timer.stop() + + elif self.isActiveWindow(): + # Refresh projects if window is active + self.project_handler.refresh_model() class AssetsPanel(QtWidgets.QWidget): @@ -127,7 +139,7 @@ class AssetsPanel(QtWidgets.QWidget): back_clicked = QtCore.Signal() session_changed = QtCore.Signal() - def __init__(self, dbcon, parent=None): + def __init__(self, project_handler, dbcon, parent=None): super(AssetsPanel, self).__init__(parent=parent) self.dbcon = dbcon @@ -142,7 +154,7 @@ class AssetsPanel(QtWidgets.QWidget): btn_back = QtWidgets.QPushButton(project_bar_widget) btn_back.setIcon(btn_back_icon) - project_bar = ProjectBar(self.dbcon, project_bar_widget) + project_bar = ProjectBar(project_handler, project_bar_widget) layout.addWidget(btn_back) layout.addWidget(project_bar) @@ -185,24 +197,19 @@ class AssetsPanel(QtWidgets.QWidget): layout.addWidget(body) # signals - project_bar.project_changed.connect(self.on_project_changed) + project_handler.project_changed.connect(self.on_project_changed) assets_widget.selection_changed.connect(self.on_asset_changed) assets_widget.refreshed.connect(self.on_asset_changed) tasks_widget.task_changed.connect(self.on_task_change) btn_back.clicked.connect(self.back_clicked) + self.project_handler = project_handler self.project_bar = project_bar self.assets_widget = assets_widget self.tasks_widget = tasks_widget self._btn_back = btn_back - # Force initial refresh for the assets since we might not be - # trigging a Project switch if we click the project that was set - # prior to launching the Launcher - # todo: remove this behavior when AVALON_PROJECT is not required - assets_widget.refresh() - def showEvent(self, event): super(AssetsPanel, self).showEvent(event) @@ -211,19 +218,7 @@ class AssetsPanel(QtWidgets.QWidget): btn_size = self.project_bar.height() self._btn_back.setFixedSize(QtCore.QSize(btn_size, btn_size)) - def set_project(self, project): - before = self.project_bar.get_current_project() - if before == project: - self.assets_widget.refresh() - return - - self.project_bar.set_project(project) - self.on_project_changed() - def on_project_changed(self): - project_name = self.project_bar.get_current_project() - self.dbcon.Session["AVALON_PROJECT"] = project_name - self.session_changed.emit() self.assets_widget.refresh() @@ -232,11 +227,8 @@ class AssetsPanel(QtWidgets.QWidget): """Callback on asset selection changed This updates the task view. - """ - print("Asset changed..") - asset_name = None asset_silo = None @@ -276,6 +268,8 @@ class AssetsPanel(QtWidgets.QWidget): class LauncherWindow(QtWidgets.QDialog): """Launcher interface""" + # Refresh actions each 10000msecs + actions_refresh_timeout = 10000 def __init__(self, parent=None): super(LauncherWindow, self).__init__(parent) @@ -298,8 +292,12 @@ class LauncherWindow(QtWidgets.QDialog): self.windowFlags() | QtCore.Qt.WindowMinimizeButtonHint ) - project_panel = ProjectsPanel(self.dbcon) - asset_panel = AssetsPanel(self.dbcon) + project_model = ProjectModel(self.dbcon) + project_model.hide_invisible = True + project_handler = ProjectHandler(self.dbcon, project_model) + + project_panel = ProjectsPanel(project_handler) + asset_panel = AssetsPanel(project_handler, self.dbcon) page_slider = SlidePageWidget() page_slider.addWidget(project_panel) @@ -344,6 +342,12 @@ class LauncherWindow(QtWidgets.QDialog): layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) + actions_refresh_timer = QtCore.QTimer() + actions_refresh_timer.setInterval(self.actions_refresh_timeout) + + self.actions_refresh_timer = actions_refresh_timer + self.project_handler = project_handler + self.message_label = message_label self.project_panel = project_panel self.asset_panel = asset_panel @@ -353,23 +357,21 @@ class LauncherWindow(QtWidgets.QDialog): self._page = 0 # signals + actions_refresh_timer.timeout.connect(self._on_action_timer) actions_bar.action_clicked.connect(self.on_action_clicked) action_history.trigger_history.connect(self.on_history_action) - project_panel.project_clicked.connect(self.on_project_clicked) + project_handler.project_changed.connect(self.on_project_change) asset_panel.back_clicked.connect(self.on_back_clicked) asset_panel.session_changed.connect(self.on_session_changed) - # todo: Simplify this callback connection - asset_panel.project_bar.project_changed.connect( - self.on_project_changed - ) - self.resize(520, 740) def showEvent(self, event): - super().showEvent(event) - # TODO implement refresh/reset which will trigger updating - self.discover_actions() + if not self.actions_refresh_timer.isActive(): + self.actions_refresh_timer.start() + self.discover_actions() + + super(LauncherWindow, self).showEvent(event) def set_page(self, page): current = self.page_slider.currentIndex() @@ -385,13 +387,6 @@ class LauncherWindow(QtWidgets.QDialog): QtCore.QTimer.singleShot(5000, lambda: self.message_label.setText("")) self.log.debug(message) - def on_project_changed(self): - project_name = self.asset_panel.project_bar.get_current_project() - self.dbcon.Session["AVALON_PROJECT"] = project_name - - # Update the Action plug-ins available for the current project - self.discover_actions() - def on_session_changed(self): self.filter_actions() @@ -402,17 +397,23 @@ class LauncherWindow(QtWidgets.QDialog): def filter_actions(self): self.actions_bar.filter_actions() - def on_project_clicked(self, project_name): - self.dbcon.Session["AVALON_PROJECT"] = project_name - # Refresh projects - self.asset_panel.set_project(project_name) + def _on_action_timer(self): + if not self.isVisible(): + # Stop timer if widget is not visible + self.actions_refresh_timer.stop() + + elif self.isActiveWindow(): + # Refresh projects if window is active + self.discover_actions() + + def on_project_change(self, project_name): + # Update the Action plug-ins available for the current project self.set_page(1) self.discover_actions() def on_back_clicked(self): - self.dbcon.Session["AVALON_PROJECT"] = None + self.project_handler.set_project(None) self.set_page(0) - self.project_panel.model.refresh() # Refresh projects self.discover_actions() def on_action_clicked(self, action): diff --git a/openpype/tools/project_manager/__init__.py b/openpype/tools/project_manager/__init__.py index 62fa8af8aa..1c5bfdcbd5 100644 --- a/openpype/tools/project_manager/__init__.py +++ b/openpype/tools/project_manager/__init__.py @@ -1,3 +1,24 @@ +"""Project Manager tool + +Purpose of the tool is to be able create and modify hierarchy under project +ready for OpenPype pipeline usage. Tool also give ability to create new +projects. + +# Brief info +Project hierarchy consist of two types "asset" and "task". Assets can be +children of Project or other Asset. Task can be children of Asset. + +It is not possible to have duplicated Asset name across whole project. +It is not possible to have duplicated Task name under one Asset. + +Asset can't be moved or renamed if has or it's children has published content. + +Deleted assets are not deleted from database but their type is changed to +"archived_asset". + +Tool allows to modify Asset attributes like frame start/end, fps, etc. +""" + from .project_manager import ( ProjectManagerWindow, main diff --git a/openpype/tools/project_manager/project_manager/constants.py b/openpype/tools/project_manager/project_manager/constants.py index 6fb4b991ed..67dea79e59 100644 --- a/openpype/tools/project_manager/project_manager/constants.py +++ b/openpype/tools/project_manager/project_manager/constants.py @@ -2,12 +2,21 @@ import re from Qt import QtCore +# Item identifier (unique ID - uuid4 is used) IDENTIFIER_ROLE = QtCore.Qt.UserRole + 1 +# Item has duplicated name (Asset and Task items) DUPLICATED_ROLE = QtCore.Qt.UserRole + 2 +# It is possible to move and rename items +# - that is disabled if e.g. Asset has published content HIERARCHY_CHANGE_ABLE_ROLE = QtCore.Qt.UserRole + 3 +# Item is marked for deletion +# - item will be deleted after hitting save REMOVED_ROLE = QtCore.Qt.UserRole + 4 +# Item type in string ITEM_TYPE_ROLE = QtCore.Qt.UserRole + 5 +# Item has opened editor (per column) EDITOR_OPENED_ROLE = QtCore.Qt.UserRole + 6 +# Allowed symbols for any name NAME_ALLOWED_SYMBOLS = "a-zA-Z0-9_" NAME_REGEX = re.compile("^[" + NAME_ALLOWED_SYMBOLS + "]*$") diff --git a/openpype/tools/project_manager/project_manager/delegates.py b/openpype/tools/project_manager/project_manager/delegates.py index 51edff028f..842352cba1 100644 --- a/openpype/tools/project_manager/project_manager/delegates.py +++ b/openpype/tools/project_manager/project_manager/delegates.py @@ -8,6 +8,10 @@ from .multiselection_combobox import MultiSelectionComboBox class ResizeEditorDelegate(QtWidgets.QStyledItemDelegate): + """Implementation of private method from QStyledItemDelegate. + + Force editor to resize into item size. + """ @staticmethod def _q_smart_min_size(editor): min_size_hint = editor.minimumSizeHint() @@ -67,6 +71,16 @@ class ResizeEditorDelegate(QtWidgets.QStyledItemDelegate): class NumberDelegate(QtWidgets.QStyledItemDelegate): + """Delegate for number attributes. + + Editor correspond passed arguments. + + Args: + minimum(int, float): Minimum possible value. + maximum(int, float): Maximum possible value. + decimals(int): How many decimal points can be used. Float will be used + as value if is higher than 0. + """ def __init__(self, minimum, maximum, decimals, *args, **kwargs): super(NumberDelegate, self).__init__(*args, **kwargs) self.minimum = minimum @@ -80,10 +94,13 @@ class NumberDelegate(QtWidgets.QStyledItemDelegate): editor = QtWidgets.QSpinBox(parent) editor.setObjectName("NumberEditor") + # Set min/max editor.setMinimum(self.minimum) editor.setMaximum(self.maximum) + # Hide spinbox buttons editor.setButtonSymbols(QtWidgets.QSpinBox.NoButtons) + # Try to set value from item value = index.data(QtCore.Qt.EditRole) if value is not None: try: @@ -98,6 +115,8 @@ class NumberDelegate(QtWidgets.QStyledItemDelegate): class NameDelegate(QtWidgets.QStyledItemDelegate): + """Specific delegate for "name" key.""" + def createEditor(self, parent, option, index): editor = NameTextEdit(parent) editor.setObjectName("NameEditor") @@ -108,11 +127,26 @@ class NameDelegate(QtWidgets.QStyledItemDelegate): class TypeDelegate(QtWidgets.QStyledItemDelegate): + """Specific delegate for "type" key. + + It is expected that will be used only for TaskItem which has modifiable + type. Type values are defined with cached project document. + + Args: + project_doc_cache(ProjectDocCache): Project cache shared across all + delegates (kind of a struct pointer). + """ + def __init__(self, project_doc_cache, *args, **kwargs): self._project_doc_cache = project_doc_cache super(TypeDelegate, self).__init__(*args, **kwargs) def createEditor(self, parent, option, index): + """Editor is using filtrable combobox. + + Editor should not be possible to create new items or set values that + are not in this method. + """ editor = FilterComboBox(parent) editor.setObjectName("TypeEditor") editor.style().polish(editor) @@ -136,6 +170,18 @@ class TypeDelegate(QtWidgets.QStyledItemDelegate): class ToolsDelegate(QtWidgets.QStyledItemDelegate): + """Specific delegate for "tools_env" key. + + Expected that editor will be used only on AssetItem which is the only item + that can have `tools_env` (except project). + + Delegate requires tools cache which is shared across all ToolsDelegate + objects. + + Args: + tools_cache (ToolsCache): Possible values of tools. + """ + def __init__(self, tools_cache, *args, **kwargs): self._tools_cache = tools_cache super(ToolsDelegate, self).__init__(*args, **kwargs) diff --git a/openpype/tools/project_manager/project_manager/model.py b/openpype/tools/project_manager/project_manager/model.py index 5000729adf..7ee43a6b61 100644 --- a/openpype/tools/project_manager/project_manager/model.py +++ b/openpype/tools/project_manager/project_manager/model.py @@ -1,7 +1,6 @@ import collections import copy import json -from queue import Queue from uuid import uuid4 from .constants import ( @@ -21,7 +20,11 @@ from Qt import QtCore, QtGui class ProjectModel(QtGui.QStandardItemModel): - project_changed = QtCore.Signal() + """Load possible projects to modify from MongoDB. + + Mongo collection must contain project document with "type" "project" and + matching "name" value with name of collection. + """ def __init__(self, dbcon, *args, **kwargs): self.dbcon = dbcon @@ -31,6 +34,7 @@ class ProjectModel(QtGui.QStandardItemModel): super(ProjectModel, self).__init__(*args, **kwargs) def refresh(self): + """Reload projects.""" self.dbcon.Session["AVALON_PROJECT"] = None project_items = [] @@ -63,6 +67,12 @@ class ProjectModel(QtGui.QStandardItemModel): class HierarchySelectionModel(QtCore.QItemSelectionModel): + """Selection model with defined allowed multiselection columns. + + This model allows to select multiple rows and enter one of their + editors to edit value of all selected rows. + """ + def __init__(self, multiselection_columns, *args, **kwargs): super(HierarchySelectionModel, self).__init__(*args, **kwargs) self.multiselection_columns = multiselection_columns @@ -78,6 +88,21 @@ class HierarchySelectionModel(QtCore.QItemSelectionModel): class HierarchyModel(QtCore.QAbstractItemModel): + """Main model for hierarchy modification and value changes. + + Main part of ProjectManager. + + Model should be able to load existing entities, create new, handle their + validations like name duplication and validate if is possible to save it's + data. + + Args: + dbcon (AvalonMongoDB): Connection to MongoDB with set AVALON_PROJECT in + it's Session to current project. + """ + + # Definition of all possible columns with their labels in default order + # - order is important as column names are used as keys for column indexes _columns_def = [ ("name", "Name"), ("type", "Type"), @@ -93,6 +118,8 @@ class HierarchyModel(QtCore.QAbstractItemModel): ("pixelAspect", "Pixel aspect"), ("tools_env", "Tools") ] + # Columns allowing multiselection in edit mode + # - gives ability to set all of keys below on multiple items at once multiselection_columns = { "frameStart", "frameEnd", @@ -141,13 +168,19 @@ class HierarchyModel(QtCore.QAbstractItemModel): return self._items_by_id def _reset_root_item(self): + """Removes all previous content related to model.""" self._root_item = RootItem(self) def refresh_project(self): + """Reload project data and discard unsaved changes.""" self.set_project(self._current_project, True) @property def project_item(self): + """Access to current project item. + + Model can have 0-1 ProjectItems at once. + """ output = None for row in range(self._root_item.rowCount()): item = self._root_item.child(row) @@ -157,25 +190,44 @@ class HierarchyModel(QtCore.QAbstractItemModel): return output def set_project(self, project_name, force=False): + """Change project and discard unsaved changes. + + Args: + project_name(str): New project name. Or None if just clearing + content. + force(bool): Force to change project even if project name is same + as current project. + """ if self._current_project == project_name and not force: return + # Reset attributes + self._items_by_id.clear() + self._asset_items_by_name.clear() + self.clear() self._current_project = project_name + + # Skip if project is None if not project_name: return + # Find project'd document project_doc = self.dbcon.database[project_name].find_one( {"type": "project"}, ProjectItem.query_projection ) + # Skip if project document does not exist + # - this shouldn't happen using only UI elements if not project_doc: return + # Create project item project_item = ProjectItem(project_doc) self.add_item(project_item) + # Query all assets of the project asset_docs = self.dbcon.database[project_name].find( {"type": "asset"}, AssetItem.query_projection @@ -185,7 +237,8 @@ class HierarchyModel(QtCore.QAbstractItemModel): for asset_doc in asset_docs } - # Prepare booleans if asset item can be modified (name or hierarchy) + # Check if asset have published content and prepare booleans + # if asset item can be modified (name and hierarchy change) # - the same must be applied to all it's parents asset_ids = list(asset_docs_by_id.keys()) result = [] @@ -214,18 +267,19 @@ class HierarchyModel(QtCore.QAbstractItemModel): count = item["count"] asset_modifiable[asset_id] = count < 1 + # Store assets by their visual parent to be able create their hierarchy asset_docs_by_parent_id = collections.defaultdict(list) for asset_doc in asset_docs_by_id.values(): parent_id = asset_doc["data"].get("visualParent") asset_docs_by_parent_id[parent_id].append(asset_doc) - appending_queue = Queue() - appending_queue.put((None, project_item)) + appending_queue = collections.deque() + appending_queue.append((None, project_item)) asset_items_by_id = {} non_modifiable_items = set() - while not appending_queue.empty(): - parent_id, parent_item = appending_queue.get() + while appending_queue: + parent_id, parent_item = appending_queue.popleft() asset_docs = asset_docs_by_parent_id.get(parent_id) or [] new_items = [] @@ -242,19 +296,19 @@ class HierarchyModel(QtCore.QAbstractItemModel): asset_items_by_id[asset_id] = new_item # Add item to appending queue - appending_queue.put((asset_id, new_item)) + appending_queue.append((asset_id, new_item)) if new_items: self.add_items(new_items, parent_item) # Handle Asset's that are not modifiable # - pass the information to all it's parents - non_modifiable_queue = Queue() + non_modifiable_queue = collections.deque() for item_id in non_modifiable_items: - non_modifiable_queue.put(item_id) + non_modifiable_queue.append(item_id) - while not non_modifiable_queue.empty(): - item_id = non_modifiable_queue.get() + while non_modifiable_queue: + item_id = non_modifiable_queue.popleft() item = self._items_by_id[item_id] item.setData(False, HIERARCHY_CHANGE_ABLE_ROLE) @@ -264,7 +318,7 @@ class HierarchyModel(QtCore.QAbstractItemModel): and parent.id not in non_modifiable_items ): non_modifiable_items.add(parent.id) - non_modifiable_queue.put(parent.id) + non_modifiable_queue.append(parent.id) # Add task items for asset_id, asset_item in asset_items_by_id.items(): @@ -282,9 +336,11 @@ class HierarchyModel(QtCore.QAbstractItemModel): self.add_items(task_items, asset_item) + # Emit that project was successfully changed self.project_changed.emit() def rowCount(self, parent=None): + """Number of rows for passed parent.""" if parent is None or not parent.isValid(): parent_item = self._root_item else: @@ -292,9 +348,15 @@ class HierarchyModel(QtCore.QAbstractItemModel): return parent_item.rowCount() def columnCount(self, *args, **kwargs): + """Number of columns is static for this model.""" return self.columns_len def data(self, index, role): + """Access data for passed index and it's role. + + Model is using principles implemented in BaseItem so converts passed + index column into key and ask item to return value for passed role. + """ if not index.isValid(): return None @@ -305,18 +367,24 @@ class HierarchyModel(QtCore.QAbstractItemModel): return item.data(role, key) def setData(self, index, value, role=QtCore.Qt.EditRole): + """Store data to passed index under role. + + Pass values to corresponding item and behave by it's result. + """ if not index.isValid(): return False item = index.internalPointer() column = index.column() key = self.columns[column] + # Capture asset name changes for duplcated asset names validation. if ( key == "name" and role in (QtCore.Qt.EditRole, QtCore.Qt.DisplayRole) ): self._rename_asset(item, value) + # Pass values to item and by result emi dataChanged signal or not result = item.setData(value, role, key) if result: self.dataChanged.emit(index, index, [role]) @@ -324,6 +392,7 @@ class HierarchyModel(QtCore.QAbstractItemModel): return result def headerData(self, section, orientation, role): + """Header labels.""" if role == QtCore.Qt.DisplayRole: if section < self.columnCount(): return self.column_labels[section] @@ -333,6 +402,7 @@ class HierarchyModel(QtCore.QAbstractItemModel): ) def flags(self, index): + """Index flags are defined by corresponding item.""" item = index.internalPointer() if item is None: return QtCore.Qt.NoItemFlags @@ -341,6 +411,11 @@ class HierarchyModel(QtCore.QAbstractItemModel): return item.flags(key) def parent(self, index=None): + """Parent for passed index as QModelIndex. + + Args: + index(QModelIndex): Parent index. Root item is used if not passed. + """ if not index.isValid(): return QtCore.QModelIndex() @@ -354,7 +429,13 @@ class HierarchyModel(QtCore.QAbstractItemModel): return self.createIndex(parent_item.row(), 0, parent_item) def index(self, row, column, parent=None): - """Return index for row/column under parent""" + """Return index for row/column under parent. + + Args: + row(int): Row number. + column(int): Column number. + parent(QModelIndex): Parent index. Root item is used if not passed. + """ parent_item = None if parent is not None and parent.isValid(): parent_item = parent.internalPointer() @@ -362,11 +443,31 @@ class HierarchyModel(QtCore.QAbstractItemModel): return self.index_from_item(row, column, parent_item) def index_for_item(self, item, column=0): + """Index for passed item. + + This is for cases that index operations are required on specific item. + + Args: + item(BaseItem): Item from model that will be converted to + corresponding QModelIndex. + column(int): Which column will be part of returned index. By + default is used column 0. + """ return self.index_from_item( item.row(), column, item.parent() ) def index_from_item(self, row, column, parent=None): + """Index for passed row, column and parent item. + + Same implementation as `index` method but "parent" is one of + BaseItem objects instead of QModelIndex. + + Args: + row(int): Row number. + column(int): Column number. + parent(BaseItem): Parent item. Root item is used if not passed. + """ if parent is None: parent = self._root_item @@ -377,15 +478,26 @@ class HierarchyModel(QtCore.QAbstractItemModel): return QtCore.QModelIndex() def add_new_asset(self, source_index): + """Create new asset item in hierarchy. + + Args: + source_index(QModelIndex): Parent under which new asset will be + added. + """ item_id = source_index.data(IDENTIFIER_ROLE) item = self.items_by_id[item_id] + if isinstance(item, TaskItem): + item = item.parent() + if isinstance(item, (RootItem, ProjectItem)): name = "ep" new_row = None - else: + elif isinstance(item, AssetItem): name = None new_row = item.rowCount() + else: + return asset_data = {} if name: @@ -402,6 +514,13 @@ class HierarchyModel(QtCore.QAbstractItemModel): return result def add_new_task(self, parent_index): + """Create new TaskItem under passed parent index or it's parent. + + Args: + parent_index(QModelIndex): Index of parent AssetItem under which + will be task added. If index represents TaskItem it's parent is + used as parent. + """ item_id = parent_index.data(IDENTIFIER_ROLE) item = self.items_by_id[item_id] @@ -417,6 +536,18 @@ class HierarchyModel(QtCore.QAbstractItemModel): return self.add_item(new_child, parent) def add_items(self, items, parent=None, start_row=None): + """Add new items with definition of QAbstractItemModel. + + Trigger `beginInsertRows` and `endInsertRows` to trigger proper + callbacks in view or proxy model. + + Args: + items(list[BaseItem]): List of item that will be inserted in model. + parent(RootItem, ProjectItem, AssetItem): Parent of items under + which will be items added. Root item is used if not passed. + start_row(int): Define to which row will be items added. Next + available row of parent is used if not passed. + """ if parent is None: parent = self._root_item @@ -456,12 +587,25 @@ class HierarchyModel(QtCore.QAbstractItemModel): return indexes def add_item(self, item, parent=None, row=None): + """Add single item into model.""" result = self.add_items([item], parent, row) if result: return result[0] return None def remove_delete_flag(self, item_ids, with_children=True): + """Remove deletion flag from items with matching ids. + + The flag is also removed from all parents of passed children as it + wouldn't make sense to not to do so. + + Children of passed item ids are by default also unset for deletion. + + Args: + list(uuid4): Ids of model items where remove flag should be unset. + with_children(bool): Unset remove flag also on all children of + passed items. + """ items_by_id = {} for item_id in item_ids: if item_id in items_by_id: @@ -508,9 +652,11 @@ class HierarchyModel(QtCore.QAbstractItemModel): self._validate_asset_duplicity(name) def delete_index(self, index): + """Delete item of the index from model.""" return self.delete_indexes([index]) def delete_indexes(self, indexes): + """Delete items from model.""" items_by_id = {} processed_ids = set() for index in indexes: @@ -533,12 +679,26 @@ class HierarchyModel(QtCore.QAbstractItemModel): self._remove_item(item) def _remove_item(self, item): + """Remove item from model or mark item for deletion. + + Deleted items are using definition of QAbstractItemModel which call + `beginRemoveRows` and `endRemoveRows` to trigger proper view and proxy + model callbacks. + + Item is not just removed but is checked if can be removed from model or + just mark it for deletion for save. + + First of all will find all related children and based on their + attributes define if can be removed. + """ + # Skip if item is already marked for deletion is_removed = item.data(REMOVED_ROLE) if is_removed: return parent = item.parent() + # Find all descendants and store them by parent id all_descendants = collections.defaultdict(dict) all_descendants[parent.id][item.id] = item @@ -571,6 +731,8 @@ class HierarchyModel(QtCore.QAbstractItemModel): if isinstance(cur_item, AssetItem): self._rename_asset(cur_item, None) + # Process tasks as last because their logic is based on parent + # - tasks may be processed before parent check all asset children for task_item in task_children: _fill_children(_all_descendants, task_item, cur_item) return remove_item @@ -596,21 +758,29 @@ class HierarchyModel(QtCore.QAbstractItemModel): if not all_without_children: continue - parent_item = self._items_by_id[parent_id] + # Row ranges of items to remove + # - store tuples of row "start", "end" (can be the same) row_ranges = [] + # Predefine start, end variables start_row = end_row = None chilren_by_row = {} + parent_item = self._items_by_id[parent_id] for row in range(parent_item.rowCount()): child_item = parent_item.child(row) child_id = child_item.id + # Not sure if this can happend + # TODO validate this line it seems dangerous as start/end + # row is not changed if child_id not in children: continue chilren_by_row[row] = child_item children.pop(child_item.id) - remove_item = child_item.data(REMOVED_ROLE) - if not remove_item or not child_item.is_new: + removed_mark = child_item.data(REMOVED_ROLE) + if not removed_mark or not child_item.is_new: + # Skip row sequence store child for later processing + # and store current start/end row range modified_children.append(child_item) if end_row is not None: row_ranges.append((start_row, end_row)) @@ -624,11 +794,12 @@ class HierarchyModel(QtCore.QAbstractItemModel): if end_row is not None: row_ranges.append((start_row, end_row)) - parent_index = None - for start, end in row_ranges: - if parent_index is None: - parent_index = self.index_for_item(parent_item) + if not row_ranges: + continue + # Remove items from model + parent_index = self.index_for_item(parent_item) + for start, end in row_ranges: self.beginRemoveRows(parent_index, start, end) for idx in range(start, end + 1): @@ -641,6 +812,8 @@ class HierarchyModel(QtCore.QAbstractItemModel): self.endRemoveRows() + # Trigger data change to repaint items + # - `BackgroundRole` is random role without any specific reason for item in modified_children: s_index = self.index_for_item(item) e_index = self.index_for_item(item, column=self.columns_len - 1) @@ -1054,12 +1227,32 @@ class HierarchyModel(QtCore.QAbstractItemModel): self.index_moved.emit(new_index) def move_vertical(self, indexes, direction): + """Move item vertically in model to matching parent if possible. + + If passed indexes contain items that has parent<->child relation at any + hierarchy level only the top parent is actually moved. + + Example (items marked with star are passed in `indexes`): + - shots* + - ep01 + - ep01_sh0010* + - ep01_sh0020* + In this case only `shots` item will be moved vertically and + both "ep01_sh0010" "ep01_sh0020" will stay as children of "ep01". + + Args: + indexes(list[QModelIndex]): Indexes that should be moved + vertically. + direction(int): Which way will be moved -1 or 1 to determine. + """ if not indexes: return + # Convert single index to list of indexes if isinstance(indexes, QtCore.QModelIndex): indexes = [indexes] + # Just process single index if len(indexes) == 1: self._move_vertical_single(indexes[0], direction) return @@ -1094,6 +1287,7 @@ class HierarchyModel(QtCore.QAbstractItemModel): self._move_vertical_single(index, direction) def child_removed(self, child): + """Callback for removed child.""" self._items_by_id.pop(child.id, None) def column_name(self, column): @@ -1103,11 +1297,19 @@ class HierarchyModel(QtCore.QAbstractItemModel): return None def clear(self): + """Reset model.""" self.beginResetModel() self._reset_root_item() self.endResetModel() def save(self): + """Save all changes from current project manager session. + + Will create new asset documents, update existing and asset documents + marked for deletion are removed from mongo if has published content or + their type is changed to `archived_asset` to not loose their data. + """ + # Check if all items are valid before save all_valid = True for item in self._items_by_id.values(): if not item.is_valid: @@ -1117,6 +1319,7 @@ class HierarchyModel(QtCore.QAbstractItemModel): if not all_valid: return + # Check project item and do not save without it project_item = None for _project_item in self._root_item.children(): project_item = _project_item @@ -1127,18 +1330,21 @@ class HierarchyModel(QtCore.QAbstractItemModel): project_name = project_item.name project_col = self.dbcon.database[project_name] - to_process = Queue() - to_process.put(project_item) + # Process asset items per one hierarchical level. + # - new assets are inserted per one parent + # - update and delete data are stored and processed at once at the end + to_process = collections.deque() + to_process.append(project_item) bulk_writes = [] - while not to_process.empty(): - parent = to_process.get() + while to_process: + parent = to_process.popleft() insert_list = [] for item in parent.children(): if not isinstance(item, AssetItem): continue - to_process.put(item) + to_process.append(item) if item.is_new: insert_list.append(item) @@ -1247,6 +1453,14 @@ class HierarchyModel(QtCore.QAbstractItemModel): class BaseItem: + """Base item for HierarchyModel. + + Is not meant to be used as real item but as superclass for all items used + in HierarchyModel. + + TODO cleanup some attributes and methods related only to AssetItem and + TaskItem. + """ columns = [] # Use `set` for faster result editable_columns = set() @@ -1274,6 +1488,10 @@ class BaseItem: self._data[key] = value def name_icon(self): + """Icon shown next to name. + + Item must imlpement this method to change it. + """ return None @property @@ -1292,6 +1510,7 @@ class BaseItem: self._children.insert(row, item) def _get_global_data(self, role): + """Global data getter without column specification.""" if role == ITEM_TYPE_ROLE: return self.item_type @@ -1419,6 +1638,7 @@ class BaseItem: class RootItem(BaseItem): + """Invisible root item used as base item for model.""" item_type = "root" def __init__(self, model): @@ -1433,6 +1653,10 @@ class RootItem(BaseItem): class ProjectItem(BaseItem): + """Item representing project document in Mongo. + + Item is used only to read it's data. It is not possible to modify them. + """ item_type = "project" columns = { @@ -1476,21 +1700,32 @@ class ProjectItem(BaseItem): @property def project_id(self): + """Project Mongo ID.""" return self._mongo_id @property def asset_id(self): + """Should not be implemented. + + TODO Remove this method from ProjectItem. + """ return None @property def name(self): + """Project name""" return self._data["name"] def child_parents(self): + """Used by children AssetItems for filling `data.parents` key.""" return [] @classmethod def data_from_doc(cls, project_doc): + """Convert document data into item data. + + Project data are used as default value for it's children. + """ data = { "name": project_doc["name"], "type": project_doc["type"] @@ -1505,10 +1740,17 @@ class ProjectItem(BaseItem): return data def flags(self, *args, **kwargs): + """Project is enabled and selectable.""" return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable class AssetItem(BaseItem): + """Item represent asset document. + + Item have ability to set all required and optional data for OpenPype + workflow. Some of them are not modifiable in specific cases e.g. when asset + has published content it is not possible to change it's name or parent. + """ item_type = "asset" columns = { @@ -1591,34 +1833,57 @@ class AssetItem(BaseItem): @property def project_id(self): + """Access to project "parent" id which is always set.""" if self._project_id is None: self._project_id = self.parent().project_id return self._project_id @property def asset_id(self): + """Property access to mongo id.""" return self.mongo_id @property def is_new(self): + """Item was created during current project manager session.""" return self.asset_id is None @property def is_valid(self): + """Item is invalid for saving.""" if self._is_duplicated or not self._data["name"]: return False return True @property def name(self): + """Asset name. + + Returns: + str: If name is set. + None: If name is not yet set in that case is AssetItem marked as + invalid. + """ return self._data["name"] def child_parents(self): + """Chilren AssetItem can use this method to get it's parent names. + + This is used for `data.parents` key on document. + """ parents = self.parent().child_parents() parents.append(self.name) return parents def to_doc(self): + """Convert item to Mongo document matching asset schema. + + Method does no validate if item is valid or children are valid. + + Returns: + dict: Document with all related data about asset item also + contains task children. + """ tasks = {} for item in self.children(): if isinstance(item, TaskItem): @@ -1653,6 +1918,22 @@ class AssetItem(BaseItem): return doc def update_data(self): + """Changes dictionary ready for Mongo's update. + + Method should be used on save. There is not other usage of this method. + + # Example + ```python + { + "$set": { + "name": "new_name" + } + } + ``` + + Returns: + dict: May be empty if item was not changed. + """ if not self.mongo_id: return {} @@ -1689,6 +1970,8 @@ class AssetItem(BaseItem): @classmethod def data_from_doc(cls, asset_doc): + """Convert asset document from Mongo to item data.""" + # Minimum required data for cases that it is new AssetItem withoud doc data = { "name": None, "type": "asset" @@ -1708,6 +1991,7 @@ class AssetItem(BaseItem): return data def name_icon(self): + """Icon shown next to name.""" if self.__class__._name_icons is None: self.__class__._name_icons = ResourceCache.get_icons()["asset"] @@ -1722,6 +2006,7 @@ class AssetItem(BaseItem): return self.__class__._name_icons[icon_type] def _get_global_data(self, role): + """Global data getter without column specification.""" if role == HIERARCHY_CHANGE_ABLE_ROLE: return self._hierarchy_changes_enabled @@ -1751,6 +2036,8 @@ class AssetItem(BaseItem): return super(AssetItem, self).data(role, key) def setData(self, value, role, key=None): + # Store information that column has opened editor + # - DisplayRole for the column will return empty string if role == EDITOR_OPENED_ROLE: if key not in self._edited_columns: return False @@ -1761,12 +2048,15 @@ class AssetItem(BaseItem): self._removed = value return True + # This can be set only on project load (or save) if role == HIERARCHY_CHANGE_ABLE_ROLE: if self._hierarchy_changes_enabled == value: return False self._hierarchy_changes_enabled = value return True + # Do not allow to change name if item is marked to not be able do any + # hierarchical changes. if ( role == QtCore.Qt.EditRole and key == "name" @@ -1814,6 +2104,8 @@ class AssetItem(BaseItem): _item.setData(False, DUPLICATED_ROLE) def _rename_task(self, item): + # Skip processing if item is marked for removing + # - item is not in any of attributes below if item.data(REMOVED_ROLE): return @@ -1845,9 +2137,22 @@ class AssetItem(BaseItem): self._task_name_by_item_id[item_id] = new_name def on_task_name_change(self, task_item): + """Method called from TaskItem children on name change. + + Helps to handle duplicated task name validations. + """ + self._rename_task(task_item) def on_task_remove_state_change(self, task_item): + """Method called from children TaskItem to handle name duplications. + + Method is called when TaskItem children is marked for deletion or + deletion was reversed. + + Name is removed/added to task item mapping attribute and removed/added + to `_task_items_by_name` used for determination of duplicated tasks. + """ is_removed = task_item.data(REMOVED_ROLE) item_id = task_item.data(IDENTIFIER_ROLE) if is_removed: @@ -1874,18 +2179,35 @@ class AssetItem(BaseItem): _item.setData(True, DUPLICATED_ROLE) def add_child(self, item, row=None): + """Add new children. + + Args: + item(AssetItem, TaskItem): New added item. + row(int): Optionally can be passed on which row (index) should be + children added. + """ if item in self._children: return super(AssetItem, self).add_child(item, row) + # Call inner method for checking task name duplications if isinstance(item, TaskItem): self._add_task(item) def remove_child(self, item): + """Remove one of children from AssetItem children. + + Skipped if item is not children of item. + + Args: + item(AssetItem, TaskItem): Child item. + """ if item not in self._children: return + # Call inner method to remove task from registered task name + # validations. if isinstance(item, TaskItem): self._remove_task(item) @@ -1893,6 +2215,16 @@ class AssetItem(BaseItem): class TaskItem(BaseItem): + """Item representing Task item on Asset document. + + Always should be AssetItem children and never should have any other + childrens. + + It's name value should be validated with it's parent which only knows if + has same name as other sibling under same parent. + """ + + # String representation of item item_type = "task" columns = { @@ -1921,10 +2253,12 @@ class TaskItem(BaseItem): @property def is_new(self): + """Task was created during current project manager session.""" return self._is_new @property def is_valid(self): + """Task valid for saving.""" if self._is_duplicated or not self._data["type"]: return False if not self.data(QtCore.Qt.EditRole, "name"): @@ -1932,6 +2266,7 @@ class TaskItem(BaseItem): return True def name_icon(self): + """Icon shown next to name.""" if self.__class__._name_icons is None: self.__class__._name_icons = ResourceCache.get_icons()["task"] @@ -1946,9 +2281,11 @@ class TaskItem(BaseItem): return self.__class__._name_icons[icon_type] def add_child(self, item, row=None): + """Reimplement `add_child` to avoid adding items under task.""" raise AssertionError("BUG: Can't add children to Task") def _get_global_data(self, role): + """Global data getter without column specification.""" if role == REMOVED_ROLE: return self._removed @@ -1967,6 +2304,12 @@ class TaskItem(BaseItem): return super(TaskItem, self)._get_global_data(role) def to_doc_data(self): + """Data for Asset document. + + Returns: + dict: May be empty if task is marked as removed or with single key + dict with name as key and task data as value. + """ if self._removed: return {} data = copy.deepcopy(self._data) @@ -1982,6 +2325,7 @@ class TaskItem(BaseItem): return False return self._edited_columns[key] + # Return empty string if column is edited if role == QtCore.Qt.DisplayRole and self._edited_columns.get(key): return "" @@ -1989,6 +2333,7 @@ class TaskItem(BaseItem): if key == "type": return self._data["type"] + # Always require task type filled if key == "name": if not self._data["type"]: if role == QtCore.Qt.DisplayRole: @@ -2001,6 +2346,8 @@ class TaskItem(BaseItem): return super(TaskItem, self).data(role, key) def setData(self, value, role, key=None): + # Store information that item on a column is edited + # - DisplayRole will return empty string in that case if role == EDITOR_OPENED_ROLE: if key not in self._edited_columns: return False @@ -2008,12 +2355,14 @@ class TaskItem(BaseItem): return True if role == REMOVED_ROLE: + # Skip value change if is same as already set value if value == self._removed: return False self._removed = value self.parent().on_task_remove_state_change(self) return True + # Convert empty string to None on EditRole if ( role == QtCore.Qt.EditRole and key == "name" @@ -2024,6 +2373,7 @@ class TaskItem(BaseItem): result = super(TaskItem, self).setData(value, role, key) if role == QtCore.Qt.EditRole: + # Trigger task name change of parent AssetItem if ( key == "name" or (key == "type" and not self._data["name"]) diff --git a/openpype/tools/project_manager/project_manager/view.py b/openpype/tools/project_manager/project_manager/view.py index 4d75af3405..74f5a06b71 100644 --- a/openpype/tools/project_manager/project_manager/view.py +++ b/openpype/tools/project_manager/project_manager/view.py @@ -92,19 +92,16 @@ class HierarchyView(QtWidgets.QTreeView): "stretch": QtWidgets.QHeaderView.ResizeToContents }, "name": { - "stretch": QtWidgets.QHeaderView.Stretch + "stretch": QtWidgets.QHeaderView.Interactive, + "width": 260 }, "type": { "stretch": QtWidgets.QHeaderView.Interactive, - "width": 100 + "width": 140 }, "tools_env": { "stretch": QtWidgets.QHeaderView.Interactive, - "width": 140 - }, - "pixelAspect": { - "stretch": QtWidgets.QHeaderView.Interactive, - "width": 80 + "width": 200 } } persistent_columns = { @@ -180,13 +177,14 @@ class HierarchyView(QtWidgets.QTreeView): def header_init(self): header = self.header() - header.setStretchLastSection(False) default_behavior = self.columns_sizes["default"] widths_by_idx = {} for idx in range(header.count()): key = self._source_model.columns[idx] behavior = self.columns_sizes.get(key, default_behavior) + if behavior is None: + continue logical_index = header.logicalIndex(idx) stretch = behavior["stretch"] header.setSectionResizeMode(logical_index, stretch) diff --git a/openpype/tools/project_manager/project_manager/window.py b/openpype/tools/project_manager/project_manager/window.py index 37092bc4a9..7c71f4b451 100644 --- a/openpype/tools/project_manager/project_manager/window.py +++ b/openpype/tools/project_manager/project_manager/window.py @@ -19,6 +19,8 @@ from avalon.api import AvalonMongoDB class ProjectManagerWindow(QtWidgets.QWidget): + """Main widget of Project Manager tool.""" + def __init__(self, parent=None): super(ProjectManagerWindow, self).__init__(parent) diff --git a/openpype/tools/pyblish_pype/window.py b/openpype/tools/pyblish_pype/window.py index df1d8687d5..536f793216 100644 --- a/openpype/tools/pyblish_pype/window.py +++ b/openpype/tools/pyblish_pype/window.py @@ -234,16 +234,19 @@ class Window(QtWidgets.QDialog): footer_button_stop = QtWidgets.QPushButton( awesome["stop"], footer_widget ) + footer_button_stop.setToolTip("Stop publishing") footer_button_reset = QtWidgets.QPushButton( awesome["refresh"], footer_widget ) + footer_button_reset.setToolTip("Restart publishing") footer_button_validate = QtWidgets.QPushButton( awesome["flask"], footer_widget ) + footer_button_validate.setToolTip("Run validations") footer_button_play = QtWidgets.QPushButton( awesome["play"], footer_widget ) - + footer_button_play.setToolTip("Publish") layout = QtWidgets.QHBoxLayout() layout.setContentsMargins(5, 5, 5, 5) layout.addWidget(footer_info, 0) diff --git a/openpype/tools/settings/local_settings/apps_widget.py b/openpype/tools/settings/local_settings/apps_widget.py index 5f4e5dd1c5..e6a4132955 100644 --- a/openpype/tools/settings/local_settings/apps_widget.py +++ b/openpype/tools/settings/local_settings/apps_widget.py @@ -121,6 +121,9 @@ class AppGroupWidget(QtWidgets.QWidget): widgets_by_variant_name = {} for variant_name, variant_entity in valid_variants.items(): + if "executables" not in variant_entity: + continue + variant_widget = AppVariantWidget( group_label, variant_name, variant_entity, content_widget ) @@ -193,8 +196,12 @@ class LocalApplicationsWidgets(QtWidgets.QWidget): # Create App group specific widget and store it by the key group_widget = AppGroupWidget(entity, self) - self.widgets_by_group_name[key] = group_widget - self.content_layout.addWidget(group_widget) + if group_widget.widgets_by_variant_name: + self.widgets_by_group_name[key] = group_widget + self.content_layout.addWidget(group_widget) + else: + group_widget.setVisible(False) + group_widget.deleteLater() def update_local_settings(self, value): if not value: diff --git a/openpype/tools/settings/local_settings/window.py b/openpype/tools/settings/local_settings/window.py index 69562d0b1f..9e8fd89b23 100644 --- a/openpype/tools/settings/local_settings/window.py +++ b/openpype/tools/settings/local_settings/window.py @@ -168,9 +168,6 @@ class LocalSettingsWindow(QtWidgets.QWidget): scroll_widget = QtWidgets.QScrollArea(self) scroll_widget.setObjectName("GroupWidget") - settings_widget = LocalSettingsWidget(scroll_widget) - - scroll_widget.setWidget(settings_widget) scroll_widget.setWidgetResizable(True) footer = QtWidgets.QWidget(self) @@ -191,7 +188,12 @@ class LocalSettingsWindow(QtWidgets.QWidget): save_btn.clicked.connect(self._on_save_clicked) reset_btn.clicked.connect(self._on_reset_clicked) - self.settings_widget = settings_widget + # Do not create local settings widget in init phase as it's using + # settings objects that must be OK to be able create this widget + # - we want to show dialog if anything goes wrong + # - without reseting nothing is shown + self._settings_widget = None + self._scroll_widget = scroll_widget self.reset_btn = reset_btn self.save_btn = save_btn @@ -203,13 +205,53 @@ class LocalSettingsWindow(QtWidgets.QWidget): def reset(self): if self._reset_on_show: self._reset_on_show = False - value = get_local_settings() - self.settings_widget.update_local_settings(value) + + error_msg = None + try: + # Create settings widget if is not created yet + if self._settings_widget is None: + self._settings_widget = LocalSettingsWidget( + self._scroll_widget + ) + self._scroll_widget.setWidget(self._settings_widget) + + value = get_local_settings() + self._settings_widget.update_local_settings(value) + + except Exception as exc: + error_msg = str(exc) + + crashed = error_msg is not None + # Enable/Disable save button if crashed or not + self.save_btn.setEnabled(not crashed) + # Show/Hide settings widget if crashed or not + if self._settings_widget: + self._settings_widget.setVisible(not crashed) + + if not crashed: + return + + # Show message with error + title = "Something went wrong" + msg = ( + "Bug: Loading of settings failed." + " Please contact your project manager or OpenPype team." + "\n\nError message:\n{}" + ).format(error_msg) + + dialog = QtWidgets.QMessageBox( + QtWidgets.QMessageBox.Critical, + title, + msg, + QtWidgets.QMessageBox.Ok, + self + ) + dialog.exec_() def _on_reset_clicked(self): self.reset() def _on_save_clicked(self): - value = self.settings_widget.settings_value() + value = self._settings_widget.settings_value() save_local_settings(value) self.reset() diff --git a/openpype/tools/settings/settings/base.py b/openpype/tools/settings/settings/base.py index 03f920b7dc..eb5f82ab9a 100644 --- a/openpype/tools/settings/settings/base.py +++ b/openpype/tools/settings/settings/base.py @@ -1,3 +1,5 @@ +import json + from Qt import QtWidgets, QtGui, QtCore from openpype.tools.settings import CHILD_OFFSET from .widgets import ExpandingWidget @@ -125,6 +127,117 @@ class BaseWidget(QtWidgets.QWidget): actions_mapping[action] = remove_from_project_override menu.addAction(action) + def _copy_value_actions(self, menu): + def copy_value(): + mime_data = QtCore.QMimeData() + + if self.entity.is_dynamic_item or self.entity.is_in_dynamic_item: + entity_path = None + else: + entity_path = "/".join( + [self.entity.root_key, self.entity.path] + ) + + value = self.entity.value + # Copy for settings tool + settings_data = { + "root_key": self.entity.root_key, + "value": value, + "path": entity_path + } + settings_encoded_data = QtCore.QByteArray() + settings_stream = QtCore.QDataStream( + settings_encoded_data, QtCore.QIODevice.WriteOnly + ) + settings_stream.writeQString(json.dumps(settings_data)) + mime_data.setData( + "application/copy_settings_value", settings_encoded_data + ) + + # Copy as json + json_encoded_data = None + if isinstance(value, (dict, list)): + json_encoded_data = QtCore.QByteArray() + json_stream = QtCore.QDataStream( + json_encoded_data, QtCore.QIODevice.WriteOnly + ) + json_stream.writeQString(json.dumps(value)) + + mime_data.setData("application/json", json_encoded_data) + + # Copy as text + if json_encoded_data is None: + # Store value as string + mime_data.setText(str(value)) + else: + # Store data as json string + mime_data.setText(json.dumps(value, indent=4)) + + QtWidgets.QApplication.clipboard().setMimeData(mime_data) + + action = QtWidgets.QAction("Copy", menu) + return [(action, copy_value)] + + def _paste_value_actions(self, menu): + output = [] + # Allow paste of value only if were copied from this UI + mime_data = QtWidgets.QApplication.clipboard().mimeData() + mime_value = mime_data.data("application/copy_settings_value") + # Skip if there is nothing to do + if not mime_value: + return output + + settings_stream = QtCore.QDataStream( + mime_value, QtCore.QIODevice.ReadOnly + ) + mime_data_value_str = settings_stream.readQString() + mime_data_value = json.loads(mime_data_value_str) + + value = mime_data_value["value"] + path = mime_data_value["path"] + root_key = mime_data_value["root_key"] + + # Try to find matching entity to be able paste values to same spot + # - entity can't by dynamic or in dynamic item + # - must be in same root entity as source copy + # Can't copy system settings <-> project settings + matching_entity = None + if path and root_key == self.entity.root_key: + try: + matching_entity = self.entity.get_entity_from_path(path) + except Exception: + pass + + def _set_entity_value(_entity, _value): + try: + _entity.set(_value) + except Exception: + dialog = QtWidgets.QMessageBox(self) + dialog.setWindowTitle("Value does not match settings schema") + dialog.setIcon(QtWidgets.QMessageBox.Warning) + dialog.setText(( + "Pasted value does not seem to match schema of destination" + " settings entity." + )) + dialog.exec_() + + # Simple paste value method + def paste_value(): + _set_entity_value(self.entity, value) + + action = QtWidgets.QAction("Paste", menu) + output.append((action, paste_value)) + + # Paste value to matchin entity + def paste_value_to_path(): + _set_entity_value(matching_entity, value) + + if matching_entity is not None: + action = QtWidgets.QAction("Paste to same place", menu) + output.append((action, paste_value_to_path)) + + return output + def show_actions_menu(self, event=None): if event and event.button() != QtCore.Qt.RightButton: return @@ -144,6 +257,15 @@ class BaseWidget(QtWidgets.QWidget): self._add_to_project_override_action(menu, actions_mapping) self._remove_from_project_override_action(menu, actions_mapping) + ui_actions = [] + ui_actions.extend(self._copy_value_actions(menu)) + ui_actions.extend(self._paste_value_actions(menu)) + if ui_actions: + menu.addSeparator() + for action, callback in ui_actions: + menu.addAction(action) + actions_mapping[action] = callback + if not actions_mapping: action = QtWidgets.QAction("< No action >") actions_mapping[action] = None diff --git a/openpype/tools/settings/settings/categories.py b/openpype/tools/settings/settings/categories.py index 34ab4c464a..392c749211 100644 --- a/openpype/tools/settings/settings/categories.py +++ b/openpype/tools/settings/settings/categories.py @@ -183,6 +183,12 @@ class SettingsCategoryWidget(QtWidgets.QWidget): footer_widget = QtWidgets.QWidget(configurations_widget) footer_layout = QtWidgets.QHBoxLayout(footer_widget) + refresh_icon = qtawesome.icon("fa.refresh", color="white") + refresh_btn = QtWidgets.QPushButton(footer_widget) + refresh_btn.setIcon(refresh_icon) + + footer_layout.addWidget(refresh_btn, 0) + if self.user_role == "developer": self._add_developer_ui(footer_layout) @@ -205,8 +211,10 @@ class SettingsCategoryWidget(QtWidgets.QWidget): main_layout.addWidget(configurations_widget, 1) save_btn.clicked.connect(self._save) + refresh_btn.clicked.connect(self._on_refresh) self.save_btn = save_btn + self.refresh_btn = refresh_btn self.require_restart_label = require_restart_label self.scroll_widget = scroll_widget self.content_layout = content_layout @@ -220,10 +228,6 @@ class SettingsCategoryWidget(QtWidgets.QWidget): return def _add_developer_ui(self, footer_layout): - refresh_icon = qtawesome.icon("fa.refresh", color="white") - refresh_button = QtWidgets.QPushButton() - refresh_button.setIcon(refresh_icon) - modify_defaults_widget = QtWidgets.QWidget() modify_defaults_checkbox = QtWidgets.QCheckBox(modify_defaults_widget) modify_defaults_checkbox.setChecked(self._hide_studio_overrides) @@ -235,10 +239,8 @@ class SettingsCategoryWidget(QtWidgets.QWidget): modify_defaults_layout.addWidget(label_widget) modify_defaults_layout.addWidget(modify_defaults_checkbox) - footer_layout.addWidget(refresh_button, 0) footer_layout.addWidget(modify_defaults_widget, 0) - refresh_button.clicked.connect(self._on_refresh) modify_defaults_checkbox.stateChanged.connect( self._on_modify_defaults ) diff --git a/openpype/tools/settings/settings/color_widget.py b/openpype/tools/settings/settings/color_widget.py index fa0cd2c989..b38b46f3cb 100644 --- a/openpype/tools/settings/settings/color_widget.py +++ b/openpype/tools/settings/settings/color_widget.py @@ -25,7 +25,9 @@ class ColorWidget(InputWidget): self._dialog.open() return - dialog = ColorDialog(self.input_field.color(), self) + dialog = ColorDialog( + self.input_field.color(), self.entity.use_alpha, self + ) self._dialog = dialog dialog.open() @@ -120,12 +122,12 @@ class ColorViewer(QtWidgets.QWidget): class ColorDialog(QtWidgets.QDialog): - def __init__(self, color=None, parent=None): + def __init__(self, color=None, use_alpha=True, parent=None): super(ColorDialog, self).__init__(parent) self.setWindowTitle("Color picker dialog") - picker_widget = ColorPickerWidget(color, self) + picker_widget = ColorPickerWidget(color, use_alpha, self) footer_widget = QtWidgets.QWidget(self) diff --git a/openpype/tools/settings/settings/list_item_widget.py b/openpype/tools/settings/settings/list_item_widget.py index e1990d0bf6..82ca541132 100644 --- a/openpype/tools/settings/settings/list_item_widget.py +++ b/openpype/tools/settings/settings/list_item_widget.py @@ -100,7 +100,6 @@ class ListItem(QtWidgets.QWidget): self.input_field = self.create_ui_for_entity( self.category_widget, self.entity, self ) - self.input_field.set_entity_value() spacer_widget = QtWidgets.QWidget(self) spacer_widget.setAttribute(QtCore.Qt.WA_TranslucentBackground) @@ -337,6 +336,12 @@ class ListWidget(InputWidget): self.content_layout.insertWidget(row + 1, item_widget) self.input_fields.insert(row, item_widget) + # Change to entity value after item is added to `input_fields` + # - may cause recursion error as setting a value may cause input field + # change which will trigger this validation if entity is already + # added as widget here which won't because is not in input_fields + item_widget.input_field.set_entity_value() + if previous_field: previous_field.order_changed() diff --git a/openpype/tools/tray/pype_info_widget.py b/openpype/tools/tray/pype_info_widget.py index f95a31f7c2..2965463c37 100644 --- a/openpype/tools/tray/pype_info_widget.py +++ b/openpype/tools/tray/pype_info_widget.py @@ -28,6 +28,8 @@ class EnvironmentsView(QtWidgets.QTreeView): def __init__(self, parent=None): super(EnvironmentsView, self).__init__(parent) + self._scroll_enabled = False + model = QtGui.QStandardItemModel() env = os.environ.copy() @@ -112,8 +114,11 @@ class EnvironmentsView(QtWidgets.QTreeView): else: return super(EnvironmentsView, self).keyPressEvent(event) + def set_scroll_enabled(self, value): + self._scroll_enabled = value + def wheelEvent(self, event): - if not self.hasFocus(): + if not self._scroll_enabled: event.ignore() return return super(EnvironmentsView, self).wheelEvent(event) @@ -200,9 +205,13 @@ class CollapsibleWidget(QtWidgets.QWidget): class PypeInfoWidget(QtWidgets.QWidget): + _resized = QtCore.Signal() + def __init__(self, parent=None): super(PypeInfoWidget, self).__init__(parent) + self._scroll_at_bottom = False + self.setStyleSheet(style.load_stylesheet()) icon = QtGui.QIcon(resources.pype_icon_filepath()) @@ -219,11 +228,39 @@ class PypeInfoWidget(QtWidgets.QWidget): main_layout.addWidget(scroll_area, 1) main_layout.addWidget(self._create_btns_section(), 0) + scroll_area.verticalScrollBar().valueChanged.connect( + self._on_area_scroll + ) + self._resized.connect(self._on_resize) self.resize(740, 540) self.scroll_area = scroll_area self.info_widget = info_widget + def _on_area_scroll(self, value): + vertical_bar = self.scroll_area.verticalScrollBar() + self._scroll_at_bottom = vertical_bar.maximum() == vertical_bar.value() + self.info_widget.set_scroll_enabled(self._scroll_at_bottom) + + def _on_resize(self): + if not self._scroll_at_bottom: + return + vertical_bar = self.scroll_area.verticalScrollBar() + vertical_bar.setValue(vertical_bar.maximum()) + + def resizeEvent(self, event): + super(PypeInfoWidget, self).resizeEvent(event) + self._resized.emit() + self.info_widget.set_content_height( + self.scroll_area.height() + ) + + def showEvent(self, event): + super(PypeInfoWidget, self).showEvent(event) + self.info_widget.set_content_height( + self.scroll_area.height() + ) + def _create_btns_section(self): btns_widget = QtWidgets.QWidget(self) btns_layout = QtWidgets.QHBoxLayout(btns_widget) @@ -282,6 +319,8 @@ class PypeInfoSubWidget(QtWidgets.QWidget): def __init__(self, parent=None): super(PypeInfoSubWidget, self).__init__(parent) + self.env_view = None + main_layout = QtWidgets.QVBoxLayout(self) main_layout.setContentsMargins(0, 0, 0, 0) main_layout.setAlignment(QtCore.Qt.AlignTop) @@ -293,6 +332,14 @@ class PypeInfoSubWidget(QtWidgets.QWidget): main_layout.addWidget(self._create_separator(), 0) main_layout.addWidget(self._create_environ_widget(), 1) + def set_content_height(self, height): + if self.env_view: + self.env_view.setMinimumHeight(height) + + def set_scroll_enabled(self, value): + if self.env_view: + self.env_view.set_scroll_enabled(value) + def _create_separator(self): separator_widget = QtWidgets.QWidget(self) separator_widget.setObjectName("Separator") @@ -369,9 +416,10 @@ class PypeInfoSubWidget(QtWidgets.QWidget): env_view = EnvironmentsView(env_widget) env_view.setMinimumHeight(300) - env_widget.set_content_widget(env_view) + self.env_view = env_view + return env_widget def _create_openpype_info_widget(self): diff --git a/openpype/tools/workfiles/app.py b/openpype/tools/workfiles/app.py index c79e55a143..d567e26d74 100644 --- a/openpype/tools/workfiles/app.py +++ b/openpype/tools/workfiles/app.py @@ -944,10 +944,8 @@ class Window(QtWidgets.QMainWindow): split_widget.addWidget(tasks_widget) split_widget.addWidget(files_widget) split_widget.addWidget(side_panel) - split_widget.setStretchFactor(0, 1) - split_widget.setStretchFactor(1, 1) - split_widget.setStretchFactor(2, 3) - split_widget.setStretchFactor(3, 1) + split_widget.setSizes([255, 160, 455, 175]) + body_layout.addWidget(split_widget) # Add top margin for tasks to align it visually with files as @@ -976,7 +974,7 @@ class Window(QtWidgets.QMainWindow): # Force focus on the open button by default, required for Houdini. files_widget.btn_open.setFocus() - self.resize(1000, 600) + self.resize(1200, 600) def keyPressEvent(self, event): """Custom keyPressEvent. diff --git a/openpype/version.py b/openpype/version.py index 6bcc8dcfb8..fcd3b2afca 100644 --- a/openpype/version.py +++ b/openpype/version.py @@ -1,3 +1,3 @@ # -*- coding: utf-8 -*- """Package declaring Pype version.""" -__version__ = "3.0.0" +__version__ = "3.2.0-nightly.4" diff --git a/openpype/widgets/color_widgets/color_inputs.py b/openpype/widgets/color_widgets/color_inputs.py index eda8c618f1..6f5d4baa02 100644 --- a/openpype/widgets/color_widgets/color_inputs.py +++ b/openpype/widgets/color_widgets/color_inputs.py @@ -4,35 +4,6 @@ from Qt import QtWidgets, QtCore, QtGui from .color_view import draw_checkerboard_tile -slide_style = """ -QSlider::groove:horizontal { - background: qlineargradient( - x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #000, stop: 1 #fff - ); - height: 8px; - border-radius: 4px; -} - -QSlider::handle:horizontal { - background: qlineargradient( - x1:0, y1:0, x2:1, y2:1, stop:0 #ddd, stop:1 #bbb - ); - border: 1px solid #777; - width: 8px; - margin-top: -1px; - margin-bottom: -1px; - border-radius: 4px; -} - -QSlider::handle:horizontal:hover { - background: qlineargradient( - x1:0, y1:0, x2:1, y2:1, stop:0 #eee, stop:1 #ddd - ); - border: 1px solid #444;ff - border-radius: 4px; -}""" - - class AlphaSlider(QtWidgets.QSlider): def __init__(self, *args, **kwargs): super(AlphaSlider, self).__init__(*args, **kwargs) @@ -80,7 +51,7 @@ class AlphaSlider(QtWidgets.QSlider): painter.fillRect(event.rect(), QtCore.Qt.transparent) - painter.setRenderHint(QtGui.QPainter.SmoothPixmapTransform) + painter.setRenderHint(QtGui.QPainter.HighQualityAntialiasing) rect = self.style().subControlRect( QtWidgets.QStyle.CC_Slider, opt, @@ -135,19 +106,8 @@ class AlphaSlider(QtWidgets.QSlider): painter.save() - gradient = QtGui.QRadialGradient() - radius = handle_rect.height() / 2 - center_x = handle_rect.width() / 2 + handle_rect.x() - center_y = handle_rect.height() - gradient.setCenter(center_x, center_y) - gradient.setCenterRadius(radius) - gradient.setFocalPoint(center_x, center_y) - - gradient.setColorAt(0.9, QtGui.QColor(127, 127, 127)) - gradient.setColorAt(1, QtCore.Qt.transparent) - painter.setPen(QtCore.Qt.NoPen) - painter.setBrush(gradient) + painter.setBrush(QtGui.QColor(127, 127, 127)) painter.drawEllipse(handle_rect) painter.restore() diff --git a/openpype/widgets/color_widgets/color_picker_widget.py b/openpype/widgets/color_widgets/color_picker_widget.py index 81ec1f87aa..228d35a77c 100644 --- a/openpype/widgets/color_widgets/color_picker_widget.py +++ b/openpype/widgets/color_widgets/color_picker_widget.py @@ -17,19 +17,12 @@ from .color_inputs import ( class ColorPickerWidget(QtWidgets.QWidget): color_changed = QtCore.Signal(QtGui.QColor) - def __init__(self, color=None, parent=None): + def __init__(self, color=None, use_alpha=True, parent=None): super(ColorPickerWidget, self).__init__(parent) # Color triangle color_triangle = QtColorTriangle(self) - alpha_slider_proxy = QtWidgets.QWidget(self) - alpha_slider = AlphaSlider(QtCore.Qt.Horizontal, alpha_slider_proxy) - - alpha_slider_layout = QtWidgets.QHBoxLayout(alpha_slider_proxy) - alpha_slider_layout.setContentsMargins(5, 5, 5, 5) - alpha_slider_layout.addWidget(alpha_slider, 1) - # Eye picked widget pick_widget = PickScreenColorWidget() pick_widget.setMaximumHeight(50) @@ -47,8 +40,6 @@ class ColorPickerWidget(QtWidgets.QWidget): color_view = ColorViewer(self) color_view.setMaximumHeight(50) - alpha_inputs = AlphaInputs(self) - color_inputs_color = QtGui.QColor() col_inputs_by_label = [ ("HEX", HEXInputs(color_inputs_color, self)), @@ -58,6 +49,7 @@ class ColorPickerWidget(QtWidgets.QWidget): ] layout = QtWidgets.QGridLayout(self) + empty_col = 1 label_col = empty_col + 1 input_col = label_col + 1 @@ -65,6 +57,9 @@ class ColorPickerWidget(QtWidgets.QWidget): empty_widget.setFixedWidth(10) layout.addWidget(empty_widget, 0, empty_col) + layout.setColumnStretch(0, 1) + layout.setColumnStretch(input_col, 1) + row = 0 layout.addWidget(btn_pick_color, row, label_col) layout.addWidget(color_view, row, input_col) @@ -84,20 +79,41 @@ class ColorPickerWidget(QtWidgets.QWidget): layout.setRowStretch(row, 1) row += 1 - layout.addWidget(alpha_slider_proxy, row, 0) + alpha_label = None + alpha_slider_proxy = None + alpha_slider = None + alpha_inputs = None + if not use_alpha: + color.setAlpha(255) + else: + alpha_inputs = AlphaInputs(self) + alpha_label = QtWidgets.QLabel("Alpha", self) + alpha_slider_proxy = QtWidgets.QWidget(self) + alpha_slider = AlphaSlider( + QtCore.Qt.Horizontal, alpha_slider_proxy + ) + + alpha_slider_layout = QtWidgets.QHBoxLayout(alpha_slider_proxy) + alpha_slider_layout.setContentsMargins(5, 5, 5, 5) + alpha_slider_layout.addWidget(alpha_slider, 1) + + layout.addWidget(alpha_slider_proxy, row, 0) + + layout.addWidget(alpha_label, row, label_col) + layout.addWidget(alpha_inputs, row, input_col) + + row += 1 - layout.addWidget(QtWidgets.QLabel("Alpha", self), row, label_col) - layout.addWidget(alpha_inputs, row, input_col) - row += 1 layout.setRowStretch(row, 1) color_view.set_color(color_triangle.cur_color) color_triangle.color_changed.connect(self.triangle_color_changed) - alpha_slider.valueChanged.connect(self._on_alpha_slider_change) pick_widget.color_selected.connect(self.on_color_change) - alpha_inputs.alpha_changed.connect(self._on_alpha_inputs_changed) btn_pick_color.released.connect(self.pick_color) + if alpha_slider: + alpha_slider.valueChanged.connect(self._on_alpha_slider_change) + alpha_inputs.alpha_changed.connect(self._on_alpha_inputs_changed) self.color_input_fields = color_input_fields self.color_inputs_color = color_inputs_color @@ -131,7 +147,8 @@ class ColorPickerWidget(QtWidgets.QWidget): return self.color_view.color() def set_color(self, color): - self.alpha_inputs.set_alpha(color.alpha()) + if self.alpha_inputs: + self.alpha_inputs.set_alpha(color.alpha()) self.on_color_change(color) def pick_color(self): @@ -163,10 +180,10 @@ class ColorPickerWidget(QtWidgets.QWidget): def alpha_changed(self, value): self.color_view.set_alpha(value) - if self.alpha_slider.value() != value: + if self.alpha_slider and self.alpha_slider.value() != value: self.alpha_slider.setValue(value) - if self.alpha_inputs.alpha_value != value: + if self.alpha_inputs and self.alpha_inputs.alpha_value != value: self.alpha_inputs.set_alpha(value) def _on_alpha_inputs_changed(self, value): diff --git a/openpype/widgets/color_widgets/color_triangle.py b/openpype/widgets/color_widgets/color_triangle.py index d4db175d84..f4a86c4fa5 100644 --- a/openpype/widgets/color_widgets/color_triangle.py +++ b/openpype/widgets/color_widgets/color_triangle.py @@ -241,7 +241,11 @@ class QtColorTriangle(QtWidgets.QWidget): # Blit the static generated background with the hue gradient onto # the double buffer. - buf = QtGui.QImage(self.bg_image.copy()) + buf = QtGui.QImage( + self.bg_image.width(), + self.bg_image.height(), + QtGui.QImage.Format_RGB32 + ) # Draw the trigon # Find the color with only the hue, and max value and saturation @@ -254,9 +258,21 @@ class QtColorTriangle(QtWidgets.QWidget): ) # Slow step: convert the image to a pixmap - pix = QtGui.QPixmap.fromImage(buf) + pix = self.bg_image.copy() pix_painter = QtGui.QPainter(pix) - pix_painter.setRenderHint(QtGui.QPainter.Antialiasing) + + pix_painter.setRenderHint(QtGui.QPainter.HighQualityAntialiasing) + + trigon_path = QtGui.QPainterPath() + trigon_path.moveTo(self.point_a) + trigon_path.lineTo(self.point_b) + trigon_path.lineTo(self.point_c) + trigon_path.closeSubpath() + pix_painter.setClipPath(trigon_path) + + pix_painter.drawImage(0, 0, buf) + + pix_painter.setClipping(False) # Draw an outline of the triangle pix_painter.setPen(self._triangle_outline_pen) @@ -724,27 +740,37 @@ class QtColorTriangle(QtWidgets.QWidget): lx = leftX[y] rx = rightX[y] + # if the xdist is 0, don't draw anything. + xdist = rx - lx + if xdist == 0.0: + continue + lxi = int(floor(lx)) rxi = int(floor(rx)) rc = rightColors[y] lc = leftColors[y] - # if the xdist is 0, don't draw anything. - xdist = rx - lx - if xdist != 0.0: - r = lc.r - g = lc.g - b = lc.b - rdelta = (rc.r - r) / xdist - gdelta = (rc.g - g) / xdist - bdelta = (rc.b - b) / xdist + r = lc.r + g = lc.g + b = lc.b + rdelta = (rc.r - r) / xdist + gdelta = (rc.g - g) / xdist + bdelta = (rc.b - b) / xdist - # Inner loop 2. Draws the line from left to right. - for x in range(lxi, rxi + 1): - buf.setPixel(x, y, QtGui.qRgb(int(r), int(g), int(b))) - r += rdelta - g += gdelta - b += bdelta + # Draw 2 more pixels on left side for smoothing + for x in range(lxi - 2, lxi): + buf.setPixel(x, y, QtGui.qRgb(int(r), int(g), int(b))) + + # Inner loop 2. Draws the line from left to right. + for x in range(lxi, rxi): + buf.setPixel(x, y, QtGui.qRgb(int(r), int(g), int(b))) + r += rdelta + g += gdelta + b += bdelta + + # Draw 2 more pixels on right side for smoothing + for x in range(rxi, rxi + 3): + buf.setPixel(x, y, QtGui.qRgb(int(r), int(g), int(b))) def _radius_at(self, pos, rect): mousexdist = pos.x() - float(rect.center().x()) diff --git a/openpype/widgets/color_widgets/color_view.py b/openpype/widgets/color_widgets/color_view.py index 8644281a1d..b5fce28894 100644 --- a/openpype/widgets/color_widgets/color_view.py +++ b/openpype/widgets/color_widgets/color_view.py @@ -5,6 +5,8 @@ def draw_checkerboard_tile(piece_size=None, color_1=None, color_2=None): if piece_size is None: piece_size = 7 + # Make sure piece size is not float + piece_size = int(piece_size) if color_1 is None: color_1 = QtGui.QColor(188, 188, 188) diff --git a/poetry.lock b/poetry.lock index 0951427449..30dbe50c19 100644 --- a/poetry.lock +++ b/poetry.lock @@ -11,7 +11,7 @@ develop = false type = "git" url = "https://github.com/pypeclub/acre.git" reference = "master" -resolved_reference = "9bf19573acb9328a3e5f5de96c619060177795cf" +resolved_reference = "68784b7eb5b7bb5f409b61ab31d4403878a3e1b7" [[package]] name = "aiohttp" @@ -307,7 +307,7 @@ trio = ["trio (>=0.14.0)", "sniffio (>=1.1)"] [[package]] name = "docutils" -version = "0.17.1" +version = "0.16" description = "Docutils -- Python Documentation Utilities" category = "dev" optional = false @@ -398,7 +398,7 @@ typing-extensions = {version = ">=3.7.4.0", markers = "python_version < \"3.8\"" [[package]] name = "google-api-core" -version = "1.29.0" +version = "1.30.0" description = "Google API client core library" category = "main" optional = false @@ -436,7 +436,7 @@ uritemplate = ">=3.0.0,<4dev" [[package]] name = "google-auth" -version = "1.30.1" +version = "1.31.0" description = "Google Authentication Library" category = "main" optional = false @@ -449,7 +449,7 @@ rsa = {version = ">=3.1.4,<5", markers = "python_version >= \"3.6\""} six = ">=1.9.0" [package.extras] -aiohttp = ["aiohttp (>=3.6.2,<4.0.0dev)"] +aiohttp = ["requests (>=2.20.0,<3.0.0dev)", "aiohttp (>=3.6.2,<4.0.0dev)"] pyopenssl = ["pyopenssl (>=20.0.0)"] reauth = ["pyu2f (>=0.1.5)"] @@ -509,7 +509,7 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" [[package]] name = "importlib-metadata" -version = "4.4.0" +version = "4.5.0" description = "Read metadata from Python packages" category = "main" optional = false @@ -759,7 +759,7 @@ python-versions = "*" [[package]] name = "protobuf" -version = "3.17.2" +version = "3.17.3" description = "Protocol Buffers" category = "main" optional = false @@ -904,7 +904,7 @@ six = "*" [[package]] name = "pyobjc-core" -version = "7.2" +version = "7.3" description = "Python<->ObjC Interoperability Module" category = "main" optional = false @@ -912,26 +912,26 @@ python-versions = ">=3.6" [[package]] name = "pyobjc-framework-cocoa" -version = "7.2" +version = "7.3" description = "Wrappers for the Cocoa frameworks on macOS" category = "main" optional = false python-versions = ">=3.6" [package.dependencies] -pyobjc-core = ">=7.2" +pyobjc-core = ">=7.3" [[package]] name = "pyobjc-framework-quartz" -version = "7.2" +version = "7.3" description = "Wrappers for the Quartz frameworks on macOS" category = "main" optional = false python-versions = ">=3.6" [package.dependencies] -pyobjc-core = ">=7.2" -pyobjc-framework-Cocoa = ">=7.2" +pyobjc-core = ">=7.3" +pyobjc-framework-Cocoa = ">=7.3" [[package]] name = "pyparsing" @@ -1161,6 +1161,18 @@ category = "main" optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*" +[[package]] +name = "slack-sdk" +version = "3.6.0" +description = "The Slack API Platform SDK for Python" +category = "main" +optional = false +python-versions = ">=3.6.0" + +[package.extras] +optional = ["aiodns (>1.0)", "aiohttp (>=3.7.3,<4)", "boto3 (<=2)", "SQLAlchemy (>=1,<2)", "websockets (>=9.1,<10)", "websocket-client (>=0.57,<1)"] +testing = ["pytest (>=5.4,<6)", "pytest-asyncio (<1)", "Flask-Sockets (>=0.2,<1)", "pytest-cov (>=2,<3)", "codecov (>=2,<3)", "flake8 (>=3,<4)", "black (==21.5b1)", "psutil (>=5,<6)", "databases (>=0.3)"] + [[package]] name = "smmap" version = "4.0.0" @@ -1230,13 +1242,14 @@ sphinx = "*" [[package]] name = "sphinx-rtd-theme" -version = "0.5.1" +version = "0.5.2" description = "Read the Docs theme for Sphinx" category = "dev" optional = false python-versions = "*" [package.dependencies] +docutils = "<0.17" sphinx = "*" [package.extras] @@ -1453,7 +1466,7 @@ testing = ["pytest (>=4.6)", "pytest-checkdocs (>=1.2.3)", "pytest-flake8", "pyt [metadata] lock-version = "1.1" python-versions = "3.7.*" -content-hash = "abfb3fda5422d9119fb942e66d82fad5c7fae46d0ed240876c3a61333e15febe" +content-hash = "8875d530ae66f9763b5b0cb84d9d35edc184ef5c141b63d38bf1ff5a1226e556" [metadata.files] acre = [] @@ -1714,8 +1727,8 @@ dnspython = [ {file = "dnspython-2.1.0.zip", hash = "sha256:e4a87f0b573201a0f3727fa18a516b055fd1107e0e5477cded4a2de497df1dd4"}, ] docutils = [ - {file = "docutils-0.17.1-py2.py3-none-any.whl", hash = "sha256:cf316c8370a737a022b72b56874f6602acf974a37a9fba42ec2876387549fc61"}, - {file = "docutils-0.17.1.tar.gz", hash = "sha256:686577d2e4c32380bb50cbb22f575ed742d58168cee37e99117a854bcd88f125"}, + {file = "docutils-0.16-py2.py3-none-any.whl", hash = "sha256:0c5b78adfbf7762415433f5515cd5c9e762339e23369dbe8000d84a4bf4ab3af"}, + {file = "docutils-0.16.tar.gz", hash = "sha256:c2de3a60e9e7d07be26b7f2b00ca0309c207e06c100f9cc2a94931fc75a478fc"}, ] enlighten = [ {file = "enlighten-1.10.1-py2.py3-none-any.whl", hash = "sha256:3d6c3eec8cf3eb626ee7b65eddc1b3e904d01f4547a2b9fe7f1da8892a0297e8"}, @@ -1744,16 +1757,16 @@ gitpython = [ {file = "GitPython-3.1.17.tar.gz", hash = "sha256:ee24bdc93dce357630764db659edaf6b8d664d4ff5447ccfeedd2dc5c253f41e"}, ] google-api-core = [ - {file = "google-api-core-1.29.0.tar.gz", hash = "sha256:dbe885011111a9afd9ea9a347db6a9c608e82e5c7648c1f7fabf2b4079a579b5"}, - {file = "google_api_core-1.29.0-py2.py3-none-any.whl", hash = "sha256:f83118319d2a28806ec3399671cbe4af5351bd0dac54c40a0395da6162ebe324"}, + {file = "google-api-core-1.30.0.tar.gz", hash = "sha256:0724d354d394b3d763bc10dfee05807813c5210f0bd9b8e2ddf6b6925603411c"}, + {file = "google_api_core-1.30.0-py2.py3-none-any.whl", hash = "sha256:92cd9e9f366e84bfcf2524e34d2dc244906c645e731962617ba620da1620a1e0"}, ] google-api-python-client = [ {file = "google-api-python-client-1.12.8.tar.gz", hash = "sha256:f3b9684442eec2cfe9f9bb48e796ef919456b82142c7528c5fd527e5224f08bb"}, {file = "google_api_python_client-1.12.8-py2.py3-none-any.whl", hash = "sha256:3c4c4ca46b5c21196bec7ee93453443e477d82cbfa79234d1ce0645f81170eaf"}, ] google-auth = [ - {file = "google-auth-1.30.1.tar.gz", hash = "sha256:044d81b1e58012f8ebc71cc134e191c1fa312f543f1fbc99973afe28c25e3228"}, - {file = "google_auth-1.30.1-py2.py3-none-any.whl", hash = "sha256:b3ca7a8ff9ab3bdefee3ad5aefb11fc6485423767eee016f5942d8e606ca23fb"}, + {file = "google-auth-1.31.0.tar.gz", hash = "sha256:154f7889c5d679a6f626f36adb12afbd4dbb0a9a04ec575d989d6ba79c4fd65e"}, + {file = "google_auth-1.31.0-py2.py3-none-any.whl", hash = "sha256:6d47c79b5d09fbc7e8355fd9594cc4cf65fdde5d401c63951eaac4baa1ba2ae1"}, ] google-auth-httplib2 = [ {file = "google-auth-httplib2-0.1.0.tar.gz", hash = "sha256:a07c39fd632becacd3f07718dfd6021bf396978f03ad3ce4321d060015cc30ac"}, @@ -1776,8 +1789,8 @@ imagesize = [ {file = "imagesize-1.2.0.tar.gz", hash = "sha256:b1f6b5a4eab1f73479a50fb79fcf729514a900c341d8503d62a62dbc4127a2b1"}, ] importlib-metadata = [ - {file = "importlib_metadata-4.4.0-py3-none-any.whl", hash = "sha256:960d52ba7c21377c990412aca380bf3642d734c2eaab78a2c39319f67c6a5786"}, - {file = "importlib_metadata-4.4.0.tar.gz", hash = "sha256:e592faad8de1bda9fe920cf41e15261e7131bcf266c30306eec00e8e225c1dd5"}, + {file = "importlib_metadata-4.5.0-py3-none-any.whl", hash = "sha256:833b26fb89d5de469b24a390e9df088d4e52e4ba33b01dc5e0e4f41b81a16c00"}, + {file = "importlib_metadata-4.5.0.tar.gz", hash = "sha256:b142cc1dd1342f31ff04bb7d022492b09920cb64fed867cd3ea6f80fe3ebd139"}, ] iniconfig = [ {file = "iniconfig-1.1.1-py2.py3-none-any.whl", hash = "sha256:011e24c64b7f47f6ebd835bb12a743f2fbe9a26d4cecaa7f53bc4f35ee9da8b3"}, @@ -1963,6 +1976,7 @@ pillow = [ {file = "Pillow-8.2.0-pp37-pypy37_pp73-manylinux2010_i686.whl", hash = "sha256:aac00e4bc94d1b7813fe882c28990c1bc2f9d0e1aa765a5f2b516e8a6a16a9e4"}, {file = "Pillow-8.2.0-pp37-pypy37_pp73-manylinux2010_x86_64.whl", hash = "sha256:22fd0f42ad15dfdde6c581347eaa4adb9a6fc4b865f90b23378aa7914895e120"}, {file = "Pillow-8.2.0-pp37-pypy37_pp73-win32.whl", hash = "sha256:e98eca29a05913e82177b3ba3d198b1728e164869c613d76d0de4bde6768a50e"}, + {file = "Pillow-8.2.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:8b56553c0345ad6dcb2e9b433ae47d67f95fc23fe28a0bde15a120f25257e291"}, {file = "Pillow-8.2.0.tar.gz", hash = "sha256:a787ab10d7bb5494e5f76536ac460741788f1fbce851068d73a87ca7c35fc3e1"}, ] pluggy = [ @@ -1974,29 +1988,29 @@ prefixed = [ {file = "prefixed-0.3.2.tar.gz", hash = "sha256:ca48277ba5fa8346dd4b760847da930c7b84416387c39e93affef086add2c029"}, ] protobuf = [ - {file = "protobuf-3.17.2-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:c49e673436e24e925022c090a98905cfe88d056cb5dde67a8e20ae339acd8140"}, - {file = "protobuf-3.17.2-cp27-cp27mu-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:4e62be28dcaab52c7e8e8e3fb9a7005dec6374e698f3b22d79276d95c13151e5"}, - {file = "protobuf-3.17.2-cp35-cp35m-macosx_10_9_intel.whl", hash = "sha256:c2038dec269b65683f16057886c09ca7526471793029bdd43259282e1e0fb668"}, - {file = "protobuf-3.17.2-cp35-cp35m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:b667ddbb77ff619fdbd18be75445d4448ee68493c9bddd1b4d0b177025e2f6f6"}, - {file = "protobuf-3.17.2-cp35-cp35m-win32.whl", hash = "sha256:993814b0199f22523a227696a8e20d2cd4b9cda60c76d2fb3969ce0c77eb9e0f"}, - {file = "protobuf-3.17.2-cp35-cp35m-win_amd64.whl", hash = "sha256:38b2c6e2204731cfebdb2452ffb7addf0367172b35cff8ccda338ccea9e7c87a"}, - {file = "protobuf-3.17.2-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:42239d47f213f1ce12ddca62c0c70856efbac09797d715e5d606b3fbc3f16c44"}, - {file = "protobuf-3.17.2-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:4da073b6c1a83e4ff1294156844f21343c5094e295c194d8ecc94703c7a6f42a"}, - {file = "protobuf-3.17.2-cp36-cp36m-win32.whl", hash = "sha256:c303ce92c60d069237cfbd41790fde3d00066ca9500fac464454e20c2f12250c"}, - {file = "protobuf-3.17.2-cp36-cp36m-win_amd64.whl", hash = "sha256:751d71dc6559dd794d309811d8dcf179d6a128b38a1655ae7137530f33895cb4"}, - {file = "protobuf-3.17.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:f3f057ad59cd4d5ea2b1bb88d36c6f009b8043007cf03d96cbd3b9c06859d4fa"}, - {file = "protobuf-3.17.2-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:c5b512c1982f8b427a302db094cf79f8f235284014d01b23fba461aa2c1459a0"}, - {file = "protobuf-3.17.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:9dc01ddc3b195c4538942790c4b195cf17b52d3785a60c1f6f25b794f51e2071"}, - {file = "protobuf-3.17.2-cp37-cp37m-win32.whl", hash = "sha256:45cc0197e9f9192693c8a4dbcba8c9227a53a2720fc3826dfe791113d9ff5e5e"}, - {file = "protobuf-3.17.2-cp37-cp37m-win_amd64.whl", hash = "sha256:816fe5e8b73c29adb13a57e1653da15f24cbb90e86ea92e6f08abe6d8c0cbdb4"}, - {file = "protobuf-3.17.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:557e16884d7276caf92c1fb188fe6dfbec47891d3507d4982db1e3d89ffd22de"}, - {file = "protobuf-3.17.2-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:89613ec119fdcad992f65d7a5bfe3170c17edc839982d0089fc0c9242fb8e517"}, - {file = "protobuf-3.17.2-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:744f5c9a3b9e7538c4c70f2b0e46f86858b684f5d17bf78643a19a6c21c7936f"}, - {file = "protobuf-3.17.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:1e08da38d56b74962d9cb05d86ca5f25d2e5b78f05fd00db7900cad3faa6de00"}, - {file = "protobuf-3.17.2-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:6388e7f300010ea7ac77113c7491c5622645d2447fdf701cbfe026b832d728cd"}, - {file = "protobuf-3.17.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:0b5a73fa43efda0df0191c162680ec40cef45463fa8ff69fbeaeeddda4c760f5"}, - {file = "protobuf-3.17.2-py2.py3-none-any.whl", hash = "sha256:50c657a54592c1bec7b24521fdbbbd2f7b51325ba23ab505ed03e8ebf3a5aeff"}, - {file = "protobuf-3.17.2.tar.gz", hash = "sha256:5a3450acf046716e4a4f02a3f7adfb7b86f1b5b3ae392cec759915e79538d40d"}, + {file = "protobuf-3.17.3-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:ab6bb0e270c6c58e7ff4345b3a803cc59dbee19ddf77a4719c5b635f1d547aa8"}, + {file = "protobuf-3.17.3-cp27-cp27mu-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:13ee7be3c2d9a5d2b42a1030976f760f28755fcf5863c55b1460fd205e6cd637"}, + {file = "protobuf-3.17.3-cp35-cp35m-macosx_10_9_intel.whl", hash = "sha256:1556a1049ccec58c7855a78d27e5c6e70e95103b32de9142bae0576e9200a1b0"}, + {file = "protobuf-3.17.3-cp35-cp35m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:f0e59430ee953184a703a324b8ec52f571c6c4259d496a19d1cabcdc19dabc62"}, + {file = "protobuf-3.17.3-cp35-cp35m-win32.whl", hash = "sha256:a981222367fb4210a10a929ad5983ae93bd5a050a0824fc35d6371c07b78caf6"}, + {file = "protobuf-3.17.3-cp35-cp35m-win_amd64.whl", hash = "sha256:6d847c59963c03fd7a0cd7c488cadfa10cda4fff34d8bc8cba92935a91b7a037"}, + {file = "protobuf-3.17.3-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:145ce0af55c4259ca74993ddab3479c78af064002ec8227beb3d944405123c71"}, + {file = "protobuf-3.17.3-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:6ce4d8bf0321e7b2d4395e253f8002a1a5ffbcfd7bcc0a6ba46712c07d47d0b4"}, + {file = "protobuf-3.17.3-cp36-cp36m-win32.whl", hash = "sha256:7a4c97961e9e5b03a56f9a6c82742ed55375c4a25f2692b625d4087d02ed31b9"}, + {file = "protobuf-3.17.3-cp36-cp36m-win_amd64.whl", hash = "sha256:a22b3a0dbac6544dacbafd4c5f6a29e389a50e3b193e2c70dae6bbf7930f651d"}, + {file = "protobuf-3.17.3-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:ffea251f5cd3c0b9b43c7a7a912777e0bc86263436a87c2555242a348817221b"}, + {file = "protobuf-3.17.3-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:9b7a5c1022e0fa0dbde7fd03682d07d14624ad870ae52054849d8960f04bc764"}, + {file = "protobuf-3.17.3-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:8727ee027157516e2c311f218ebf2260a18088ffb2d29473e82add217d196b1c"}, + {file = "protobuf-3.17.3-cp37-cp37m-win32.whl", hash = "sha256:14c1c9377a7ffbeaccd4722ab0aa900091f52b516ad89c4b0c3bb0a4af903ba5"}, + {file = "protobuf-3.17.3-cp37-cp37m-win_amd64.whl", hash = "sha256:c56c050a947186ba51de4f94ab441d7f04fcd44c56df6e922369cc2e1a92d683"}, + {file = "protobuf-3.17.3-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:2ae692bb6d1992afb6b74348e7bb648a75bb0d3565a3f5eea5bec8f62bd06d87"}, + {file = "protobuf-3.17.3-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:99938f2a2d7ca6563c0ade0c5ca8982264c484fdecf418bd68e880a7ab5730b1"}, + {file = "protobuf-3.17.3-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:6902a1e4b7a319ec611a7345ff81b6b004b36b0d2196ce7a748b3493da3d226d"}, + {file = "protobuf-3.17.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:4ffbd23640bb7403574f7aff8368e2aeb2ec9a5c6306580be48ac59a6bac8bde"}, + {file = "protobuf-3.17.3-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:26010f693b675ff5a1d0e1bdb17689b8b716a18709113288fead438703d45539"}, + {file = "protobuf-3.17.3-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:e76d9686e088fece2450dbc7ee905f9be904e427341d289acbe9ad00b78ebd47"}, + {file = "protobuf-3.17.3-py2.py3-none-any.whl", hash = "sha256:2bfb815216a9cd9faec52b16fd2bfa68437a44b67c56bee59bc3926522ecb04e"}, + {file = "protobuf-3.17.3.tar.gz", hash = "sha256:72804ea5eaa9c22a090d2803813e280fb273b62d5ae497aaf3553d141c4fdd7b"}, ] py = [ {file = "py-1.10.0-py2.py3-none-any.whl", hash = "sha256:3b80836aa6d1feeaa108e046da6423ab8f6ceda6468545ae8d02d9d58d18818a"}, @@ -2136,28 +2150,28 @@ pynput = [ {file = "pynput-1.7.3.tar.gz", hash = "sha256:4e50b1a0ab86847e87e58f6d1993688b9a44f9f4c88d4712315ea8eb552ef828"}, ] pyobjc-core = [ - {file = "pyobjc-core-7.2.tar.gz", hash = "sha256:9e9ec482d80ea030cdb1613d05a247f31eedabe6666d884d42dd890cc5fb0e05"}, - {file = "pyobjc_core-7.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:94b4d9de9d228db52dd35012096d63bdf8c1ace58ea3be1d5f6f39313cd502f2"}, - {file = "pyobjc_core-7.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:971cbd7189ae1aa03ef0d16124aa5bcd053779e0e6b6011a41c3dbd5b4ea7e88"}, - {file = "pyobjc_core-7.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:9d93b20394008373d6d2856d49aaff26f4b97ff42d924a14516c8a82313ec8c0"}, - {file = "pyobjc_core-7.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:860183540d1be792c26426018139ac8ba75e85f675c59ba080ccdc52d8e74c7a"}, - {file = "pyobjc_core-7.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:ffe61d3c2a404354daf2d895e34e38c5044453353581b3c396bf5365de26250c"}, + {file = "pyobjc-core-7.3.tar.gz", hash = "sha256:5081aedf8bb40aac1a8ad95adac9e44e148a882686ded614adf46bb67fd67574"}, + {file = "pyobjc_core-7.3-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:4e93ad769a20b908778fe950f62a843a6d8f0fa71996e5f3cc9fab5ae7d17771"}, + {file = "pyobjc_core-7.3-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:9f63fd37bbf3785af4ddb2f86cad5ca81c62cfc7d1c0099637ca18343c3656c1"}, + {file = "pyobjc_core-7.3-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:e9b1311f72f2e170742a7ee3a8149f52c35158dc024a21e88d6f1e52ba5d718b"}, + {file = "pyobjc_core-7.3-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:8d5e12a0729dfd1d998a861998b422d0a3e41923d75ea229bacf31372c831d7b"}, + {file = "pyobjc_core-7.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:efdee8c4884405e0c0186c57f87d7bfaa0abc1f50b18e865db3caea3a1f329b9"}, ] pyobjc-framework-cocoa = [ - {file = "pyobjc-framework-Cocoa-7.2.tar.gz", hash = "sha256:c8b23f03dc3f4436d36c0fd006a8a084835c4f6015187df7c3aa5de8ecd5c653"}, - {file = "pyobjc_framework_Cocoa-7.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:8e5dd5daa0096755937ec24c345a4b07c3fa131a457f99e0fdeeb01979178ec7"}, - {file = "pyobjc_framework_Cocoa-7.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:828d183947fc7746953fd0c9b1092cc423745ba0b49719e7b7d1e1614aaa20ec"}, - {file = "pyobjc_framework_Cocoa-7.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:7e4c6d7baa0c2ab5ea5efb8836ad0b3b3976cffcfc6195c1f195e826c6eb5744"}, - {file = "pyobjc_framework_Cocoa-7.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:c9a9d1d49cc5a810773c88d6de821e60c8cc41d01113cf1b9e7662938f5f7d66"}, - {file = "pyobjc_framework_Cocoa-7.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:506c2cd09f421eac92b9008a0142174c3d1d70ecd4b0e3fa2b924767995fd14e"}, + {file = "pyobjc-framework-Cocoa-7.3.tar.gz", hash = "sha256:b18d05e7a795a3455ad191c3e43d6bfa673c2a4fd480bb1ccf57191051b80b7e"}, + {file = "pyobjc_framework_Cocoa-7.3-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:9edffdfa6dd1f71f21b531c3e61fdd3e4d5d3bf6c5a528c98e88828cd60bac11"}, + {file = "pyobjc_framework_Cocoa-7.3-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:35a6340437a4e0109a302150b7d1f6baf57004ccf74834f9e6062fcafe2fd8d7"}, + {file = "pyobjc_framework_Cocoa-7.3-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:7c3886f2608ab3ed02482f8b2ebf9f782b324c559e84b52cfd92dba8a1109872"}, + {file = "pyobjc_framework_Cocoa-7.3-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:2e8e7a1a82cca21d9bfac9115baf065305f3da577bf240085964dfb9c9fff337"}, + {file = "pyobjc_framework_Cocoa-7.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:6c15f43077c9a2ba1853eb402ff7a9515df9e584315bc2fcb779d4c95ef46dc5"}, ] pyobjc-framework-quartz = [ - {file = "pyobjc-framework-Quartz-7.2.tar.gz", hash = "sha256:ea554e5697bc6747a4ce793c0b0036da16622b44ff75196d6124603008922afa"}, - {file = "pyobjc_framework_Quartz-7.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:dc61fe61d26f797e4335f3ffc891bcef64624c728c2603e3307b3910580b2cb8"}, - {file = "pyobjc_framework_Quartz-7.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:ad8103cc38923f2708904db11a0992ea960125ce6adf7b4c7a77d8fdafd412c4"}, - {file = "pyobjc_framework_Quartz-7.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:4549d17ca41f0bf62792d5bc4b4293ba9a6cc560014b3e18ba22c65e4a5030d2"}, - {file = "pyobjc_framework_Quartz-7.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:da16e4f1e13cb7b02e30fa538cbb3a356e4a694bbc2bb26d2bd100ca12a54ff6"}, - {file = "pyobjc_framework_Quartz-7.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:c1f6471177a39535cd0358ae29b8f3d31fe778a21deb74105c448c4e726619d7"}, + {file = "pyobjc-framework-Quartz-7.3.tar.gz", hash = "sha256:98812844c34262def980bdf60923a875cd43428a8375b6fd53bd2cd800eccf0b"}, + {file = "pyobjc_framework_Quartz-7.3-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:1ef18f5a16511ded65980bf4f5983ea5d35c88224dbad1b3112abd29c60413ea"}, + {file = "pyobjc_framework_Quartz-7.3-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:3b41eec8d4b10c7c7e011e2f9051367f5499ef315ba52dfbae573c3a2e05469c"}, + {file = "pyobjc_framework_Quartz-7.3-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:2c65456ed045dfe1711d0298734e5a3ad670f8c770f7eb3b19979256c388bdd2"}, + {file = "pyobjc_framework_Quartz-7.3-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:8ddbca6b466584c3dc0e5b701b1c2a9b5d97ddc1d79a949927499ebb1be1f210"}, + {file = "pyobjc_framework_Quartz-7.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:7aba3cd966a0768dd58a35680742820f0c5ac596a9cd11014e2057818e65b0af"}, ] pyparsing = [ {file = "pyparsing-2.4.7-py2.py3-none-any.whl", hash = "sha256:ef9d7589ef3c200abe66653d3f1ab1033c3c419ae9b9bdb1240a85b024efc88b"}, @@ -2269,6 +2283,10 @@ six = [ {file = "six-1.16.0-py2.py3-none-any.whl", hash = "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254"}, {file = "six-1.16.0.tar.gz", hash = "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926"}, ] +slack-sdk = [ + {file = "slack_sdk-3.6.0-py2.py3-none-any.whl", hash = "sha256:e1b257923a1ef88b8620dd3abff94dc5b3eee16ef37975d101ba9e60123ac3af"}, + {file = "slack_sdk-3.6.0.tar.gz", hash = "sha256:195f044e02a2844579a7a26818ce323e85dde8de224730c859644918d793399e"}, +] smmap = [ {file = "smmap-4.0.0-py2.py3-none-any.whl", hash = "sha256:a9a7479e4c572e2e775c404dcd3080c8dc49f39918c2cf74913d30c4c478e3c2"}, {file = "smmap-4.0.0.tar.gz", hash = "sha256:7e65386bd122d45405ddf795637b7f7d2b532e7e401d46bbe3fb49b9986d5182"}, @@ -2290,8 +2308,8 @@ sphinx-qt-documentation = [ {file = "sphinx_qt_documentation-0.3.tar.gz", hash = "sha256:f09a0c9d9e989172ba3e282b92bf55613bb23ad47315ec5b0d38536b343ac6c8"}, ] sphinx-rtd-theme = [ - {file = "sphinx_rtd_theme-0.5.1-py2.py3-none-any.whl", hash = "sha256:fa6bebd5ab9a73da8e102509a86f3fcc36dec04a0b52ea80e5a033b2aba00113"}, - {file = "sphinx_rtd_theme-0.5.1.tar.gz", hash = "sha256:eda689eda0c7301a80cf122dad28b1861e5605cbf455558f3775e1e8200e83a5"}, + {file = "sphinx_rtd_theme-0.5.2-py2.py3-none-any.whl", hash = "sha256:4a05bdbe8b1446d77a01e20a23ebc6777c74f43237035e76be89699308987d6f"}, + {file = "sphinx_rtd_theme-0.5.2.tar.gz", hash = "sha256:32bd3b5d13dc8186d7a42fc816a23d32e83a4827d7d9882948e7b837c232da5a"}, ] sphinxcontrib-applehelp = [ {file = "sphinxcontrib-applehelp-1.0.2.tar.gz", hash = "sha256:a072735ec80e7675e3f432fcae8610ecf509c5f1869d17e2eecff44389cdbc58"}, diff --git a/pyproject.toml b/pyproject.toml index 7bde62a848..e376986606 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -62,6 +62,7 @@ jinxed = [ ] python3-xlib = { version="*", markers = "sys_platform == 'linux'"} enlighten = "^1.9.0" +slack-sdk = "^3.6.0" [tool.poetry.dev-dependencies] flake8 = "^3.7" @@ -84,6 +85,8 @@ sphinx-qt-documentation = "*" recommonmark = "*" wheel = "*" enlighten = "*" # cool terminal progress bars +toml = "^0.10.2" # for parsing pyproject.toml + [tool.poetry.urls] "Bug Tracker" = "https://github.com/pypeclub/openpype/issues" diff --git a/repos/avalon-core b/repos/avalon-core index efde026e5a..d8be0bdb37 160000 --- a/repos/avalon-core +++ b/repos/avalon-core @@ -1 +1 @@ -Subproject commit efde026e5aad72dac0e69848005419e2c4f067f2 +Subproject commit d8be0bdb37961e32243f1de0eb9696e86acf7443 diff --git a/setup.py b/setup.py index 927dd28afd..55098cb0b4 100644 --- a/setup.py +++ b/setup.py @@ -46,10 +46,16 @@ install_requires = [ "httplib2", # Harmony implementation "filecmp", - "dns" + "dns", + # Python defaults (cx_Freeze skip them by default) + "dbm" ] includes = [] +# WARNING: As of cx_freeze there is a bug? +# when this is empty, its hooks will not kick in +# and won't clean platform irrelevant modules +# like dbm mentioned above. excludes = [ "openpype" ] diff --git a/tools/ci_tools.py b/tools/ci_tools.py index 28a735222b..436551c243 100644 --- a/tools/ci_tools.py +++ b/tools/ci_tools.py @@ -58,7 +58,7 @@ def file_regex_replace(filename, regex, version): def bump_file_versions(version): - filename = "./openpypeCItest/version.py" + filename = "./openpype/version.py" regex = "(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-((0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(\+([0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*))?" file_regex_replace(filename, regex, version) @@ -92,6 +92,24 @@ def calculate_next_nightly(token="nightly"): next_tag = last_pre_v.bump_prerelease(token=token).__str__() return next_tag +def finalize_latest_nightly(): + last_prerelease, last_pre_tag = get_last_version("CI") + last_pre_v = VersionInfo.parse(last_prerelease) + last_pre_v_finalized = last_pre_v.finalize_version() + # print(last_pre_v_finalized) + + return last_pre_v_finalized.__str__() + +def finalize_prerelease(prerelease): + + if "/" in prerelease: + prerelease = prerelease.split("/")[-1] + + prerelease_v = VersionInfo.parse(prerelease) + prerelease_v_finalized = prerelease_v.finalize_version() + + return prerelease_v_finalized.__str__() + def main(): usage = "usage: %prog [options] arg" @@ -102,12 +120,22 @@ def main(): parser.add_option("-b", "--bump", dest="bump", action="store_true", help="Return if there is something to bump") - parser.add_option("-v", "--version", - dest="version", action="store", - help="work with explicit version") + parser.add_option("-r", "--release-latest", + dest="releaselatest", action="store_true", + help="finalize latest prerelease to a release") parser.add_option("-p", "--prerelease", dest="prerelease", action="store", help="define prerelease token") + parser.add_option("-f", "--finalize", + dest="finalize", action="store", + help="define prerelease token") + parser.add_option("-v", "--version", + dest="version", action="store", + help="work with explicit version") + parser.add_option("-l", "--lastversion", + dest="lastversion", action="store", + help="work with explicit version") + (options, args) = parser.parse_args() @@ -124,6 +152,25 @@ def main(): print(next_tag_v) bump_file_versions(next_tag_v) + if options.finalize: + new_release = finalize_prerelease(options.finalize) + print(new_release) + bump_file_versions(new_release) + + if options.lastversion: + last_release, last_release_tag = get_last_version(options.lastversion) + print(last_release_tag) + + if options.releaselatest: + new_release = finalize_latest_nightly() + last_release, last_release_tag = get_last_version("release") + + if VersionInfo.parse(new_release) > VersionInfo.parse(last_release): + print(new_release) + bump_file_versions(new_release) + else: + print("skip") + if options.prerelease: current_prerelease = VersionInfo.parse(options.prerelease) new_prerelease = current_prerelease.bump_prerelease().__str__() diff --git a/vendor/deadline/custom/plugins/GlobalJobPreLoad.py b/vendor/deadline/custom/plugins/GlobalJobPreLoad.py index 5e64605271..41df9d4dc9 100644 --- a/vendor/deadline/custom/plugins/GlobalJobPreLoad.py +++ b/vendor/deadline/custom/plugins/GlobalJobPreLoad.py @@ -9,6 +9,10 @@ from Deadline.Scripting import RepositoryUtils, FileUtils def inject_openpype_environment(deadlinePlugin): + """ Pull env vars from OpenPype and push them to rendering process. + + Used for correct paths, configuration from OpenPype etc. + """ job = deadlinePlugin.GetJob() job = RepositoryUtils.GetJob(job.JobId, True) # invalidates cache @@ -73,6 +77,21 @@ def inject_openpype_environment(deadlinePlugin): raise +def inject_render_job_id(deadlinePlugin): + """Inject dependency ids to publish process as env var for validation.""" + print("inject_render_job_id start") + job = deadlinePlugin.GetJob() + job = RepositoryUtils.GetJob(job.JobId, True) # invalidates cache + + dependency_ids = job.JobDependencyIDs + print("dependency_ids {}".format(dependency_ids)) + render_job_ids = ",".join(dependency_ids) + + deadlinePlugin.SetProcessEnvironmentVariable("RENDER_JOB_IDS", + render_job_ids) + print("inject_render_job_id end") + + def pype_command_line(executable, arguments, workingDirectory): """Remap paths in comand line argument string. @@ -156,8 +175,7 @@ def __main__(deadlinePlugin): "render and publish.") if openpype_publish_job == '1': - print("Publish job, skipping inject.") - return + inject_render_job_id(deadlinePlugin) elif openpype_render_job == '1': inject_openpype_environment(deadlinePlugin) else: diff --git a/website/docs/admin_hosts_aftereffects.md b/website/docs/admin_hosts_aftereffects.md index dc43820465..e3a09058da 100644 --- a/website/docs/admin_hosts_aftereffects.md +++ b/website/docs/admin_hosts_aftereffects.md @@ -14,7 +14,7 @@ All of them are Project based, eg. each project could have different configurati Location: Settings > Project > AfterEffects -![Harmony Project Settings](assets/admin_hosts_aftereffects_settings.png) +![AfterEffects Project Settings](assets/admin_hosts_aftereffects_settings.png) ## Publish plugins diff --git a/website/docs/admin_hosts_tvpaint.md b/website/docs/admin_hosts_tvpaint.md new file mode 100644 index 0000000000..a99cd19010 --- /dev/null +++ b/website/docs/admin_hosts_tvpaint.md @@ -0,0 +1,30 @@ +--- +id: admin_hosts_tvpaint +title: TVPaint +sidebar_label: TVPaint +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +## Subset name templates +Definition of possibile subset name templates in TVPaint integration. + +### [Render Layer](artist_hosts_tvpaint#render-layer) +Render layer has additional keys for subset name template. It is possible to use **render_layer** and **render_pass**. + +- Key **render_layer** is alias for variant (user's input). +- For key **render_pass** is used predefined value `"Beauty"` (ATM value can't be changed). + +### [Render pass](artist_hosts_tvpaint#render-pass) +Render pass has additional keys for subset name template. It is possible to use **render_layer** and **render_pass**. +- Key **render_layer** is filled with value of **render_pass** from `renderLayer` group. +- Key **render_pass** is alias for variant (user's input). + +:::important Render Layer/Pass templates +It is recommended to use same subset name template for both **renderLayer** and **renderPass** families. +- Example template: `"{family}{Task}_{Render_layer}_{Render_pass}"` +::: + +### [Review](artist_hosts_tvpaint#review) and [Workfile](artist_hosts_tvpaint#workfile) +Families **review** and **workfile** are not manually created but are automatically generated during publishing. That's why it is recommended to not use **variant** key in their subset name template. diff --git a/website/docs/artist_hosts_tvpaint.md b/website/docs/artist_hosts_tvpaint.md index 19cb615158..2e831e64d8 100644 --- a/website/docs/artist_hosts_tvpaint.md +++ b/website/docs/artist_hosts_tvpaint.md @@ -45,7 +45,7 @@ In TVPaint you can find the Tools in OpenPype menu extension. The OpenPype Tools ## Create -In TVPaint you can create and publish **[Reviews](#review)**, **[Render Passes](#render-pass)**, and **[Render Layers](#render-layer)**. +In TVPaint you can create and publish **[Reviews](#review)**, **[Workfile](#workfile)**, **[Render Passes](#render-pass)** and **[Render Layers](#render-layer)**. You have the possibility to organize your layers by using `Color group`. @@ -67,26 +67,13 @@ OpenPype specifically never tries to guess what you want to publish from the sce When you want to publish `review` or `render layer` or `render pass`, open the `Creator` through the Tools menu `Create` button. -### Review +### Review +`Review` renders the whole file as is and sends the resulting QuickTime to Ftrack. +- Is automatically created during publishing. -
-
- -`Review` renders the whole file as is and sends the resulting QuickTime to Ftrack. - -To create reviewable quicktime of your animation: - -- select `Review` in the `Creator` -- press `Create` -- When you run [publish](#publish), file will be rendered and converted to quicktime.` - -
-
- -![createreview](assets/tvp_create_review.png) - -
-
+### Workfile +`Workfile` stores the source workfile as is during publishing (e.g. for backup). +- Is automatically created during publishing. ### Render Layer diff --git a/website/docs/assets/ftrack/ftrack-collect-advanced.png b/website/docs/assets/ftrack/ftrack-collect-advanced.png new file mode 100644 index 0000000000..5249685c86 Binary files /dev/null and b/website/docs/assets/ftrack/ftrack-collect-advanced.png differ diff --git a/website/docs/assets/ftrack/ftrack-collect-main.png b/website/docs/assets/ftrack/ftrack-collect-main.png new file mode 100644 index 0000000000..7c75cd6269 Binary files /dev/null and b/website/docs/assets/ftrack/ftrack-collect-main.png differ diff --git a/website/docs/assets/slack_project.png b/website/docs/assets/slack_project.png new file mode 100644 index 0000000000..417cdab2de Binary files /dev/null and b/website/docs/assets/slack_project.png differ diff --git a/website/docs/assets/slack_system.png b/website/docs/assets/slack_system.png new file mode 100644 index 0000000000..31183206c9 Binary files /dev/null and b/website/docs/assets/slack_system.png differ diff --git a/website/docs/assets/slack_token.png b/website/docs/assets/slack_token.png new file mode 100644 index 0000000000..b88b35deb3 Binary files /dev/null and b/website/docs/assets/slack_token.png differ diff --git a/website/docs/assets/tvp_create_review.png b/website/docs/assets/tvp_create_review.png deleted file mode 100644 index d6e9f63428..0000000000 Binary files a/website/docs/assets/tvp_create_review.png and /dev/null differ diff --git a/website/docs/module_ftrack.md b/website/docs/module_ftrack.md index bd0dbaef4f..c3b9fd6bc2 100644 --- a/website/docs/module_ftrack.md +++ b/website/docs/module_ftrack.md @@ -196,7 +196,7 @@ Is used to remove value from `Avalon/Mongo Id` Custom Attribute when entity is c ### Sync status from Task to Parent -List of parent boject types where this is triggered ("Shot", "Asset build", etc. Skipped if it is empty) +List of parent object types where this is triggered ("Shot", "Asset build", etc. Skipped if it is empty) ### Sync status from Version to Task @@ -214,3 +214,29 @@ This is usefull for example if first version publish doesn't contain any actual ### Update status on next task Change status on next task by task types order when task status state changed to "Done". All tasks with the same Task mapping of next task status changes From → To. Some status can be ignored. + +## Publish plugins + +### Collect Ftrack Family + +Reviews uploads to Ftrack could be configured by combination of hosts, families and task names. +(Currently implemented only in Standalone Publisher, Maya.) + +#### Profiles + +Profiles are used to select when to add Ftrack family to the instance. One or multiple profiles could be configured, Families, Task names (regex available), Host names combination is needed. + +Eg. If I want review created and uploaded to Ftrack for render published from Maya , setting is: + +Host names: 'Maya' +Families: 'render' +Add Ftrack Family: enabled + +![Collect Ftrack Family](assets/ftrack/ftrack-collect-main.png) + +#### Advanced adding if additional families present + +In special cases adding 'ftrack' based on main family ('Families' set higher) is not enough. +(For example upload to Ftrack for 'plate' main family should only happen if 'review' is contained in instance 'families', not added in other cases. ) + +![Collect Ftrack Family](assets/ftrack/ftrack-collect-advanced.png) \ No newline at end of file diff --git a/website/docs/module_slack.md b/website/docs/module_slack.md new file mode 100644 index 0000000000..f71fcc2bb7 --- /dev/null +++ b/website/docs/module_slack.md @@ -0,0 +1,76 @@ +--- +id: module_slack +title: Slack Integration Administration +sidebar_label: Slack +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + + +This module allows configuring profiles(when to trigger, for which combination of task, host and family) +and templates(could contain {} placeholder) to send notification to Slack channel(s) +whenever configured asset type is published. + + +## App installation + +Slack application must be installed to company's Slack first. + +Please locate `openpype/modules/slack/manifest.yml` file in deployed OpenPype installation and follow instruction at +https://api.slack.com/reference/manifests#using and follow "Creating apps with manifests". + + +## System Settings + +To use notifications, *Slack Notifications* needs to be enabled globally in **OpenPype Settings/System/Modules/Slack Notifications**. + +![Configure module](assets/slack_system.png) + + +## Project Settings + +### Token +Most important for module to work is to fill authentication token +```Project settings > Slack > Publish plugins > Token``` + +This token should be available after installation of the app in the Slack dashboard. +It is possible to create multiple tokens and configure different scopes for them. + +![Get token](assets/slack_token.png) + +### Profiles +Profiles are used to select when to trigger notification. One or multiple profiles +could be configured, `Families`, `Task names` (regex available), `Host names` combination is needed. + +Eg. If I want to be notified when render is published from Maya, setting is: + +- family: 'render' +- host: 'Maya' + +### Messages to channels + +#### Channels +Multiple messages could be delivered to one or multiple channels, by default app allows Slack bot +to send messages to 'public' channels (eg. bot doesn't need to join the channel first). + +![Configure module](assets/slack_project.png) + +#### Upload thumbnail +Integration can upload 'thumbnail' file (if present in an instance), for that bot must be +manually added to target channel by Slack admin! +(In target channel write: ```/invite @OpenPypeNotifier``) + +#### Message +Message content can use Templating (see [Available template keys](admin_settings_project_anatomy#available-template-keys)). + +Few keys also have Capitalized and UPPERCASE format. Values will be modified accordingly ({Asset} >> "Asset", {FAMILY} >> "RENDER"). + +**Available keys:** +- asset +- subset +- task +- username +- app +- family +- version diff --git a/website/docs/project_settings/assets/global_extract_review_output_defs.png b/website/docs/project_settings/assets/global_extract_review_output_defs.png index ce3c00ca40..f4c1661b11 100644 Binary files a/website/docs/project_settings/assets/global_extract_review_output_defs.png and b/website/docs/project_settings/assets/global_extract_review_output_defs.png differ diff --git a/website/docs/project_settings/assets/global_tools_creator_subset_template.png b/website/docs/project_settings/assets/global_tools_creator_subset_template.png new file mode 100644 index 0000000000..c4e863c4e0 Binary files /dev/null and b/website/docs/project_settings/assets/global_tools_creator_subset_template.png differ diff --git a/website/docs/project_settings/settings_project_global.md b/website/docs/project_settings/settings_project_global.md index 5d23dd75e6..e6336c36e2 100644 --- a/website/docs/project_settings/settings_project_global.md +++ b/website/docs/project_settings/settings_project_global.md @@ -112,6 +112,10 @@ Profile may generate multiple outputs from a single input. Each output must defi | "-10% -200px" | 1800px 800px | | "-10% -0px" | 1800px 1000px | +- **`Overscan color`** + - Color of empty area caused by different aspect ratio of input and output. + - By default is set to black color. + - **`Letter Box`** - **Enabled** - Enable letter boxes - **Ratio** - Ratio of letter boxes @@ -124,6 +128,14 @@ Profile may generate multiple outputs from a single input. Each output must defi ![global_extract_review_letter_box_settings](assets/global_extract_review_letter_box_settings.png) ![global_extract_review_letter_box](assets/global_extract_review_letter_box.png) +- **`Background color`** + - Background color can be used for inputs with possible transparency (e.g. png sequence). + - Input's without possible alpha channel are ignored all the time (e.g. mov). + - Background color slows down rendering process. + - set alpha to `0` to not use this option at all (in most of cases background stays black) + - other than `0` alpha will draw color as background + + ### IntegrateAssetNew Saves information for all published subsets into DB, published assets are available for other hosts, tools and tasks after. @@ -160,6 +172,39 @@ Applicable context filters: ## Tools Settings for OpenPype tools. +## Creator +Settings related to [Creator tool](artist_tools.md#details). + +### Subset name profiles +![global_tools_creator_subset_template](assets/global_tools_creator_subset_template.png) + +Subset name helps to identify published content. More specific name helps with organization and avoid mixing of published content. Subset name is defined using one of templates defined in **Subset name profiles settings**. The template is filled with context information at the time of creation. + +Usage of template is defined by profile filtering using creator's family, host and task name. Profile without filters is used as default template and it is recommend to set default template. If default template is not available `"{family}{Task}"` is used. + +**Formatting keys** + +All templates can contain text and formatting keys **family**, **task** and **variant** e.g. `"MyStudio_{family}_{task}"` (example - not recommended in production). + +|Key|Description| +|---|---| +|family|Creators family| +|task|Task under which is creation triggered| +|variant|User input in creator tool| + +**Formatting keys have 3 variants with different letter capitalization.** + +|Task|Key variant|Description|Result| +|---|---|---|---| +|`bgAnim`|`{task}`|Keep original value as is.|`bgAnim`| +|`bgAnim`|`{Task}`|Capitalize first letter of value.|`BgAnim`| +|`bgAnim`|`{TASK}`|Each letter which be capitalized.|`BGANIM`| + +Template may look like `"{family}{Task}{Variant}"`. + +Some creators may have other keys as their context may require more information or more specific values. Make sure you've read documentation of host you're using. + + ## Workfiles All settings related to Workfile tool. diff --git a/website/sidebars.js b/website/sidebars.js index 0b831bccb3..d38973e40f 100644 --- a/website/sidebars.js +++ b/website/sidebars.js @@ -78,7 +78,8 @@ module.exports = { "module_site_sync", "module_deadline", "module_muster", - "module_clockify" + "module_clockify", + "module_slack" ], }, { @@ -89,7 +90,8 @@ module.exports = { "admin_hosts_maya", "admin_hosts_resolve", "admin_hosts_harmony", - "admin_hosts_aftereffects" + "admin_hosts_aftereffects", + "admin_hosts_tvpaint" ], }, { diff --git a/website/src/pages/index.js b/website/src/pages/index.js index 8eb6e84c24..6a233ddb66 100644 --- a/website/src/pages/index.js +++ b/website/src/pages/index.js @@ -351,6 +351,11 @@ function Home() { DaVinci Resolve (Beta) + + + Slack (Beta) + +

In development by us or a community of avalon core developers.

diff --git a/website/static/img/app_slack.png b/website/static/img/app_slack.png new file mode 100644 index 0000000000..20c9a465b8 Binary files /dev/null and b/website/static/img/app_slack.png differ diff --git a/website/yarn.lock b/website/yarn.lock index f1527f5b76..2d5ec103d4 100644 --- a/website/yarn.lock +++ b/website/yarn.lock @@ -5834,9 +5834,9 @@ normalize-range@^0.1.2: integrity sha1-LRDAa9/TEuqXd2laTShDlFa3WUI= normalize-url@^4.1.0, normalize-url@^4.5.0: - version "4.5.0" - resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-4.5.0.tgz#453354087e6ca96957bd8f5baf753f5982142129" - integrity sha512-2s47yzUxdexf1OhyRi4Em83iQk0aPvwTddtFz4hnSSw9dCEsLEGf6SwIO8ss/19S9iBb5sJaOuTvTGDeZI00BQ== + version "4.5.1" + resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-4.5.1.tgz#0dd90cf1288ee1d1313b87081c9a5932ee48518a" + integrity sha512-9UZCFRHQdNrfTpGg8+1INIg93B6zE0aXMVFkw1WFwvO4SlZywU6aLg5Of0Ap/PgcbSw4LNxvMWXMeugwMCX0AA== npm-run-path@^2.0.0: version "2.0.2"