From 3d133ac333121b29e95bb95eb05f65a3a5b72047 Mon Sep 17 00:00:00 2001 From: faroukbmiled Date: Sat, 28 Mar 2026 23:57:15 +0100 Subject: [PATCH] modded scinsta with additional features and fixes for recent instagram version --- .clangd | 10 + .github/FUNDING.yml | 2 + .github/ISSUE_TEMPLATE/1-bug.yaml | 94 ++ .github/ISSUE_TEMPLATE/2-feat.yaml | 39 + .github/ISSUE_TEMPLATE/config.yml | 8 + .github/workflows/auto-assign-issue.yml | 17 + .github/workflows/auto-assign-pr.yml | 18 + .github/workflows/buildapp.yml | 138 ++ .github/workflows/buildtweak.yml | 95 ++ .github/workflows/delete-workflow-runs.yml | 70 + .gitignore | 38 + .gitmodules | 3 + .vscode/settings.json | 19 + .vscode/snippets.code-snippets | 27 + .vscode/tasks.json | 59 + LICENSE | 674 +++++++++ Makefile | 22 + README.md | 148 ++ RELEASE_CHECKLIST.md | 14 + SCInsta.plist | 14 + build-dev.sh | 28 + build.sh | 120 ++ control | 10 + modules/JGProgressHUD/JGProgressHUD-Defines.h | 78 ++ modules/JGProgressHUD/JGProgressHUD.h | 310 +++++ modules/JGProgressHUD/JGProgressHUD.m | 1234 +++++++++++++++++ .../JGProgressHUD/JGProgressHUDAnimation.h | 43 + .../JGProgressHUD/JGProgressHUDAnimation.m | 48 + .../JGProgressHUDErrorIndicatorView.h | 24 + .../JGProgressHUDErrorIndicatorView.m | 57 + .../JGProgressHUDFadeAnimation.h | 33 + .../JGProgressHUDFadeAnimation.m | 56 + .../JGProgressHUDFadeZoomAnimation.h | 40 + .../JGProgressHUDFadeZoomAnimation.m | 77 + .../JGProgressHUDImageIndicatorView.h | 28 + .../JGProgressHUDImageIndicatorView.m | 42 + .../JGProgressHUDIndeterminateIndicatorView.h | 25 + .../JGProgressHUDIndeterminateIndicatorView.m | 63 + .../JGProgressHUDIndicatorView.h | 61 + .../JGProgressHUDIndicatorView.m | 103 ++ .../JGProgressHUDPieIndicatorView.h | 35 + .../JGProgressHUDPieIndicatorView.m | 171 +++ .../JGProgressHUDRingIndicatorView.h | 50 + .../JGProgressHUDRingIndicatorView.m | 194 +++ modules/JGProgressHUD/JGProgressHUDShadow.h | 37 + modules/JGProgressHUD/JGProgressHUDShadow.m | 30 + .../JGProgressHUDSuccessIndicatorView.h | 24 + .../JGProgressHUDSuccessIndicatorView.m | 56 + src/Downloader/Download.h | 41 + src/Downloader/Download.m | 261 ++++ src/Downloader/Manager.h | 32 + src/Downloader/Manager.m | 75 + src/Features/Confirm/CallConfirm.x | 25 + src/Features/Confirm/ChangeThemeConfirm.x | 35 + src/Features/Confirm/DMAudioMsgConfirm.x | 38 + src/Features/Confirm/FollowConfirm.x | 103 ++ src/Features/Confirm/FollowRequestConfirm.xm | 22 + src/Features/Confirm/LikeConfirm.x | 150 ++ src/Features/Confirm/PostCommentConfirm.x | 13 + src/Features/Confirm/ShhConfirm.x | 33 + src/Features/Confirm/StickerInteractConfirm.x | 13 + .../Experimental/EnableAllTextEffects.xm_ | 35 + .../Experimental/EnableHomecomingUI.x_ | 26 + src/Features/Feed/DisableFeedAutoplay.x | 10 + src/Features/Feed/HideFeedItems.xm | 334 +++++ src/Features/Feed/HideStoryTray.x | 15 + src/Features/Feed/HideThreads.x | 15 + src/Features/General/CopyDescription.x | 50 + src/Features/General/DetailedColorPicker.xm | 87 ++ src/Features/General/DisableScrollingReels.x | 36 + src/Features/General/HideExploreGrid.xm | 31 + src/Features/General/HideFriendsMap.x | 33 + src/Features/General/HideMetaAI.xm | 572 ++++++++ src/Features/General/HideTrendingSearches.x | 16 + src/Features/General/Navigation.xm | 100 ++ src/Features/General/NoRecentSearches.x | 50 + src/Features/General/NoSuggestedChats.x | 19 + src/Features/General/NoSuggestedUsers.x | 263 ++++ src/Features/General/NotesCustomization.x | 293 ++++ src/Features/General/SCSettingsMenuEntry.x | 58 + src/Features/General/TeenAppIcons.x | 38 + src/Features/Media/MediaDownload.xm | 703 ++++++++++ src/Features/Reels/HideReelsHeader.x | 13 + src/Features/Reels/ReelsPlayback.xm | 72 + .../DisableInstantsCreation.x | 58 + .../StoriesAndMessages/DisableStorySeen.x | 245 ++++ .../StoriesAndMessages/DisableTypingStatus.x | 9 + .../StoriesAndMessages/KeepDeletedMessages.x | 22 + src/Features/StoriesAndMessages/SeenButtons.x | 96 ++ .../StoriesAndMessages/VisualMsgModifier.x | 21 + src/InstagramHeaders.h | 616 ++++++++ src/QuickLook.h | 10 + src/QuickLook.m | 29 + src/Settings/SCISetting.h | 105 ++ src/Settings/SCISetting.m | 245 ++++ src/Settings/SCISettingsViewController.h | 17 + src/Settings/SCISettingsViewController.m | 356 +++++ src/Settings/SCISymbol.h | 21 + src/Settings/SCISymbol.m | 87 ++ src/Settings/TweakSettings.h | 17 + src/Settings/TweakSettings.m | 520 +++++++ src/Tweak.h | 7 + src/Tweak.x | 718 ++++++++++ src/Utils.h | 83 ++ src/Utils.m | 338 +++++ 105 files changed, 11916 insertions(+) create mode 100644 .clangd create mode 100644 .github/FUNDING.yml create mode 100755 .github/ISSUE_TEMPLATE/1-bug.yaml create mode 100755 .github/ISSUE_TEMPLATE/2-feat.yaml create mode 100755 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/workflows/auto-assign-issue.yml create mode 100644 .github/workflows/auto-assign-pr.yml create mode 100644 .github/workflows/buildapp.yml create mode 100644 .github/workflows/buildtweak.yml create mode 100644 .github/workflows/delete-workflow-runs.yml create mode 100644 .gitignore create mode 100644 .gitmodules create mode 100644 .vscode/settings.json create mode 100644 .vscode/snippets.code-snippets create mode 100644 .vscode/tasks.json create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 RELEASE_CHECKLIST.md create mode 100644 SCInsta.plist create mode 100755 build-dev.sh create mode 100755 build.sh create mode 100644 control create mode 100644 modules/JGProgressHUD/JGProgressHUD-Defines.h create mode 100644 modules/JGProgressHUD/JGProgressHUD.h create mode 100755 modules/JGProgressHUD/JGProgressHUD.m create mode 100644 modules/JGProgressHUD/JGProgressHUDAnimation.h create mode 100755 modules/JGProgressHUD/JGProgressHUDAnimation.m create mode 100644 modules/JGProgressHUD/JGProgressHUDErrorIndicatorView.h create mode 100644 modules/JGProgressHUD/JGProgressHUDErrorIndicatorView.m create mode 100644 modules/JGProgressHUD/JGProgressHUDFadeAnimation.h create mode 100755 modules/JGProgressHUD/JGProgressHUDFadeAnimation.m create mode 100644 modules/JGProgressHUD/JGProgressHUDFadeZoomAnimation.h create mode 100755 modules/JGProgressHUD/JGProgressHUDFadeZoomAnimation.m create mode 100644 modules/JGProgressHUD/JGProgressHUDImageIndicatorView.h create mode 100644 modules/JGProgressHUD/JGProgressHUDImageIndicatorView.m create mode 100644 modules/JGProgressHUD/JGProgressHUDIndeterminateIndicatorView.h create mode 100644 modules/JGProgressHUD/JGProgressHUDIndeterminateIndicatorView.m create mode 100644 modules/JGProgressHUD/JGProgressHUDIndicatorView.h create mode 100755 modules/JGProgressHUD/JGProgressHUDIndicatorView.m create mode 100644 modules/JGProgressHUD/JGProgressHUDPieIndicatorView.h create mode 100755 modules/JGProgressHUD/JGProgressHUDPieIndicatorView.m create mode 100644 modules/JGProgressHUD/JGProgressHUDRingIndicatorView.h create mode 100755 modules/JGProgressHUD/JGProgressHUDRingIndicatorView.m create mode 100644 modules/JGProgressHUD/JGProgressHUDShadow.h create mode 100644 modules/JGProgressHUD/JGProgressHUDShadow.m create mode 100644 modules/JGProgressHUD/JGProgressHUDSuccessIndicatorView.h create mode 100644 modules/JGProgressHUD/JGProgressHUDSuccessIndicatorView.m create mode 100644 src/Downloader/Download.h create mode 100644 src/Downloader/Download.m create mode 100644 src/Downloader/Manager.h create mode 100644 src/Downloader/Manager.m create mode 100644 src/Features/Confirm/CallConfirm.x create mode 100644 src/Features/Confirm/ChangeThemeConfirm.x create mode 100644 src/Features/Confirm/DMAudioMsgConfirm.x create mode 100644 src/Features/Confirm/FollowConfirm.x create mode 100644 src/Features/Confirm/FollowRequestConfirm.xm create mode 100644 src/Features/Confirm/LikeConfirm.x create mode 100644 src/Features/Confirm/PostCommentConfirm.x create mode 100644 src/Features/Confirm/ShhConfirm.x create mode 100644 src/Features/Confirm/StickerInteractConfirm.x create mode 100644 src/Features/Experimental/EnableAllTextEffects.xm_ create mode 100644 src/Features/Experimental/EnableHomecomingUI.x_ create mode 100644 src/Features/Feed/DisableFeedAutoplay.x create mode 100644 src/Features/Feed/HideFeedItems.xm create mode 100644 src/Features/Feed/HideStoryTray.x create mode 100644 src/Features/Feed/HideThreads.x create mode 100644 src/Features/General/CopyDescription.x create mode 100644 src/Features/General/DetailedColorPicker.xm create mode 100644 src/Features/General/DisableScrollingReels.x create mode 100644 src/Features/General/HideExploreGrid.xm create mode 100644 src/Features/General/HideFriendsMap.x create mode 100644 src/Features/General/HideMetaAI.xm create mode 100644 src/Features/General/HideTrendingSearches.x create mode 100644 src/Features/General/Navigation.xm create mode 100644 src/Features/General/NoRecentSearches.x create mode 100644 src/Features/General/NoSuggestedChats.x create mode 100644 src/Features/General/NoSuggestedUsers.x create mode 100644 src/Features/General/NotesCustomization.x create mode 100644 src/Features/General/SCSettingsMenuEntry.x create mode 100644 src/Features/General/TeenAppIcons.x create mode 100644 src/Features/Media/MediaDownload.xm create mode 100644 src/Features/Reels/HideReelsHeader.x create mode 100644 src/Features/Reels/ReelsPlayback.xm create mode 100644 src/Features/StoriesAndMessages/DisableInstantsCreation.x create mode 100644 src/Features/StoriesAndMessages/DisableStorySeen.x create mode 100644 src/Features/StoriesAndMessages/DisableTypingStatus.x create mode 100644 src/Features/StoriesAndMessages/KeepDeletedMessages.x create mode 100644 src/Features/StoriesAndMessages/SeenButtons.x create mode 100644 src/Features/StoriesAndMessages/VisualMsgModifier.x create mode 100644 src/InstagramHeaders.h create mode 100644 src/QuickLook.h create mode 100644 src/QuickLook.m create mode 100644 src/Settings/SCISetting.h create mode 100644 src/Settings/SCISetting.m create mode 100644 src/Settings/SCISettingsViewController.h create mode 100644 src/Settings/SCISettingsViewController.m create mode 100644 src/Settings/SCISymbol.h create mode 100644 src/Settings/SCISymbol.m create mode 100644 src/Settings/TweakSettings.h create mode 100644 src/Settings/TweakSettings.m create mode 100644 src/Tweak.h create mode 100644 src/Tweak.x create mode 100644 src/Utils.h create mode 100644 src/Utils.m diff --git a/.clangd b/.clangd new file mode 100644 index 0000000..2ede5e4 --- /dev/null +++ b/.clangd @@ -0,0 +1,10 @@ +CompileFlags: + Add: [ + "-isysroot", + "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk", + "-fmodules", + "-fcxx-modules", + "-fobjc-arc", + "-I/opt/theos/include", + "-I/opt/theos/vendor/include" + ] \ No newline at end of file diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..6d46d01 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,2 @@ +ko_fi: SoCuul +github: SoCuul diff --git a/.github/ISSUE_TEMPLATE/1-bug.yaml b/.github/ISSUE_TEMPLATE/1-bug.yaml new file mode 100755 index 0000000..9a88a9b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/1-bug.yaml @@ -0,0 +1,94 @@ +name: 🐛 Bug Report +description: "Notice something isn't working quite right? Help improve the tweak by reporting issues that you experience." +title: 'bug: ' +labels: + - bug +assignees: + - SoCuul +body: + - type: markdown + attributes: + value: | +
+ + >[!TIP] + > If you are looking for support with the tweak, make sure to visit the [SCInsta discussions page](https://github.com/SoCuul/SCInsta/discussions) to get help. + - type: checkboxes + id: before-start + attributes: + label: Before creating a bug report... + description: 'Please make sure you have done the following steps:' + options: + - label: >- + I have read through the + [FAQ](https://github.com/SoCuul/SCInsta/wiki/FAQ) + required: true + - label: I have made sure this issue has not already been reported previously + required: true + - label: >- + I have made sure this issue is present in the latest version of + SCInsta + required: true + - label: >- + I am confident that this bug presents unintended behaviour within + the tweak + required: true + - type: textarea + id: description + attributes: + label: Description + description: A clear and concise description of the problem + placeholder: >- + Provide as much information about the issue you are experiencing as + possible! + validations: + required: true + - type: textarea + id: reproduction + attributes: + label: Minimal Reproduction + description: Provide steps and relevant information to reproduce the problem + placeholder: >- + If possible, providing screenshots & videos are extremely helpful when + trying to fix an issue + validations: + required: true + - type: markdown + attributes: + value: '---' + - type: input + id: info-scinsta-version + attributes: + label: SCInsta Version + description: This can be found at the bottom of the tweak settings + placeholder: e.g. v0.7.0 + validations: + required: true + - type: input + id: info-instagram-version + attributes: + label: Instagram Version + description: This can be found as well at the bottom of the tweak settings + placeholder: e.g. 382.0.0 + validations: + required: true + - type: dropdown + id: info-install-type + attributes: + label: Install Type + description: The method used to use to install SCInsta + options: + - Sideloaded + - TrollStore + - Jailbroken (Rootless) + - Jailbroken (Rootful) + validations: + required: true + - type: textarea + id: info-device-info + attributes: + label: Device Info + description: Details about the phone running the tweak + value: |- + Model: [e.g. iPhone 15 Pro] + iOS Version: [e.g. 18.4] diff --git a/.github/ISSUE_TEMPLATE/2-feat.yaml b/.github/ISSUE_TEMPLATE/2-feat.yaml new file mode 100755 index 0000000..a65714b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/2-feat.yaml @@ -0,0 +1,39 @@ +name: ✨ Feature Request +description: Have an idea for a new feature/enhancement? Let us know! +title: 'feat: ' +labels: + - enhancement +assignees: + - SoCuul +body: + - type: checkboxes + id: before-start + attributes: + label: Before creating a feature request... + description: 'Please make sure you have done the following steps:' + options: + - label: >- + I have read through the + [FAQ](https://github.com/SoCuul/SCInsta/wiki/FAQ) + required: true + - label: I have made sure this feature has not already been already suggested + required: true + - type: textarea + id: description + attributes: + label: Description + description: A clear and concise description of the problem or missing functionality + validations: + required: true + - type: textarea + id: solution + attributes: + label: Describe the solution you'd like + description: If you have a solution in mind, please describe it + validations: + required: true + - type: textarea + id: alternatives + attributes: + label: Describe alternatives you've considered + description: Have you considered any alternative solutions or workarounds? diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100755 index 0000000..df9474b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: '💬 Browse Q&A' + url: https://github.com/SoCuul/SCInsta/wiki/FAQ + about: Find answers to the most commonly asked questions + - name: '❓ Need Help?' + url: https://github.com/SoCuul/SCInsta/discussions + about: Visit the SCInsta discussions form to get support diff --git a/.github/workflows/auto-assign-issue.yml b/.github/workflows/auto-assign-issue.yml new file mode 100644 index 0000000..b5f656a --- /dev/null +++ b/.github/workflows/auto-assign-issue.yml @@ -0,0 +1,17 @@ +name: Issue assignment + +on: + issues: + types: [opened] + +jobs: + auto-assign: + runs-on: ubuntu-latest + permissions: + issues: write + steps: + - name: 'Auto-assign issue' + uses: pozil/auto-assign-issue@v1 + with: + assignees: faroukbmiled + allowNoAssignees: true diff --git a/.github/workflows/auto-assign-pr.yml b/.github/workflows/auto-assign-pr.yml new file mode 100644 index 0000000..6d91e9c --- /dev/null +++ b/.github/workflows/auto-assign-pr.yml @@ -0,0 +1,18 @@ +name: PR assignment + +on: + pull_request: + types: [opened, reopened] + +jobs: + auto-assign: + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write + steps: + - name: 'Auto-assign PR' + uses: pozil/auto-assign-issue@v1 + with: + assignees: faroukbmiled + allowNoAssignees: true diff --git a/.github/workflows/buildapp.yml b/.github/workflows/buildapp.yml new file mode 100644 index 0000000..56e583e --- /dev/null +++ b/.github/workflows/buildapp.yml @@ -0,0 +1,138 @@ +# Inspired heavily by the following workflows +# https://github.com/arichornlover/uYouEnhanced/blob/main/.github/workflows/buildapp.yml +# https://github.com/ISnackable/YTCubePlus/blob/main/.github/workflows/Build.yml +# https://github.com/BandarHL/BHTwitter/actions/workflows/build.yml + +name: Build and Package SCInsta + +on: + workflow_dispatch: + inputs: + decrypted_instagram_url: + description: "The direct URL to the decrypted Instagram IPA" + default: "" + required: true + type: string + upload_artifact: + description: "Upload Artifact" + default: true + required: false + type: boolean + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +jobs: + build: + name: Build SCInsta + runs-on: macos-latest + permissions: + contents: write + + steps: + - name: Checkout Main + uses: actions/checkout@v4 + with: + path: main + submodules: recursive + + - name: Install Dependencies + run: brew install ldid dpkg make + + - name: Set PATH environment variable + run: echo "$(brew --prefix make)/libexec/gnubin" >> $GITHUB_PATH + + - name: Setup Theos + uses: actions/checkout@v4 + with: + repository: theos/theos + ref: master + path: ${{ github.workspace }}/theos + submodules: recursive + + - name: SDK Caching + id: SDK + uses: actions/cache@v4 + env: + cache-name: iPhoneOS16.2.sdk + with: + path: ${{ github.workspace }}/theos/sdks/ + key: ${{ env.cache-name }} + restore-keys: ${{ env.cache-name }} + + - name: Download iOS SDK + if: steps.SDK.outputs.cache-hit != 'true' + run: | + git clone --quiet -n --depth=1 --filter=tree:0 https://github.com/xybp888/iOS-SDKs/ + cd iOS-SDKs + git sparse-checkout set --no-cone iPhoneOS16.2.sdk + git checkout + mv *.sdk $THEOS/sdks + env: + THEOS: ${{ github.workspace }}/theos + + - name: Prepare Instagram IPA + run: | + cd main + + mkdir -p packages + wget "$Instagram_URL" --no-verbose -O packages/com.burbn.instagram.ipa + + ls -la packages + + env: + THEOS: ${{ github.workspace }}/theos + Instagram_URL: ${{ inputs.decrypted_instagram_url }} + + - name: Get SCInsta Version + id: scinsta_version + run: | + SCINSTA_VERSION=$(awk '/Version:/ {print $2}' main/control) + + echo "SCINSTA_VERSION=${SCINSTA_VERSION}" >> "$GITHUB_ENV" + echo "version=${SCINSTA_VERSION}" >> "$GITHUB_OUTPUT" + + - name: Build SCInsta tweak for sideloading (as IPA) + run: | + pip install --force-reinstall https://github.com/asdfzxcvbn/pyzule-rw/archive/main.zip + + cd main + curl -Lo ipapatch https://github.com/asdfzxcvbn/ipapatch/releases/download/v2.1.3/ipapatch.macos-arm64 + chmod +x ipapatch + export PATH=.:$PATH + ls -la + + ./build.sh sideload + ls -la packages + + env: + THEOS: ${{ github.workspace }}/theos + + - name: Rename IPA to include version info + run: | + cd main/packages + mv "$(ls -t | head -n1)" "SCInsta_sideloaded_v${SCINSTA_VERSION}.ipa" + + - name: Pass package name to upload action + id: package_name + run: | + echo "package=$(ls -t main/packages | head -n1)" >> "$GITHUB_OUTPUT" + + - name: Upload Artifact + if: ${{ inputs.upload_artifact }} + uses: actions/upload-artifact@v4 + with: + name: SCInsta_sideloaded_v${{ steps.scinsta_version.outputs.version }} + path: ${{ github.workspace }}/main/packages/${{ steps.package_name.outputs.package }} + if-no-files-found: error + + - name: Create Release + uses: softprops/action-gh-release@v2.0.6 + with: + name: SCInsta_sideloaded_v${{ steps.scinsta_version.outputs.version }} + files: ${{ github.workspace }}/main/packages/SCInsta_sideloaded_v*.ipa + draft: true + + - name: Output Release URL + run: | + echo "::notice::Release available at: https://github.com/${{ github.repository }}/releases" diff --git a/.github/workflows/buildtweak.yml b/.github/workflows/buildtweak.yml new file mode 100644 index 0000000..b08ce0a --- /dev/null +++ b/.github/workflows/buildtweak.yml @@ -0,0 +1,95 @@ +name: Build SCInsta tweak for Rootless + +on: + push: + branches: + - 'main' + - 'dev' + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +jobs: + build: + name: Build SCInsta Rootless + runs-on: macos-latest + permissions: + contents: write + + steps: + - name: Checkout Main + uses: actions/checkout@v4 + with: + path: main + + - name: Install Dependencies + run: brew install ldid dpkg make + + - name: Set PATH environment variable + run: echo "$(brew --prefix make)/libexec/gnubin" >> $GITHUB_PATH + + - name: Setup Theos + uses: actions/checkout@v4 + with: + repository: theos/theos + ref: master + path: ${{ github.workspace }}/theos + submodules: recursive + + - name: SDK Caching + id: SDK + uses: actions/cache@v4 + env: + cache-name: iPhoneOS16.2.sdk + with: + path: ${{ github.workspace }}/theos/sdks/ + key: ${{ env.cache-name }} + restore-keys: ${{ env.cache-name }} + + - name: Download iOS SDK + if: steps.SDK.outputs.cache-hit != 'true' + run: | + git clone --quiet -n --depth=1 --filter=tree:0 https://github.com/xybp888/iOS-SDKs/ + cd iOS-SDKs + git sparse-checkout set --no-cone iPhoneOS16.2.sdk + git checkout + mv *.sdk $THEOS/sdks + env: + THEOS: ${{ github.workspace }}/theos + + - name: Get SCInsta Version + id: scinsta_version + run: | + SCINSTA_VERSION=$(awk '/Version:/ {print $2}' main/control) + + echo "SCINSTA_VERSION=${SCINSTA_VERSION}" >> "$GITHUB_ENV" + echo "version=${SCINSTA_VERSION}" >> "$GITHUB_OUTPUT" + + - name: Build SCInsta tweak for Rootless + run: | + cd main + ls -la + + ./build.sh rootless + ls -la packages + + env: + THEOS: ${{ github.workspace }}/theos + + - name: Rename deb to include version info + run: | + cd main/packages + mv "$(ls -t | head -n1)" "com.socuul.scinsta_${SCINSTA_VERSION}+debug-rootless.deb" + + - name: Pass package name to upload action + id: package_name + run: | + echo "package=$(ls -t main/packages | head -n1)" >> "$GITHUB_OUTPUT" + + - name: Upload Artifact + uses: actions/upload-artifact@v4 + with: + name: ${{ steps.package_name.outputs.package }} + path: ${{ github.workspace }}/main/packages/${{ steps.package_name.outputs.package }} + if-no-files-found: error diff --git a/.github/workflows/delete-workflow-runs.yml b/.github/workflows/delete-workflow-runs.yml new file mode 100644 index 0000000..3550d80 --- /dev/null +++ b/.github/workflows/delete-workflow-runs.yml @@ -0,0 +1,70 @@ +name: Delete old workflow runs +on: + workflow_dispatch: + inputs: + days: + description: 'Days-worth of runs to keep for each workflow' + required: true + default: '7' + minimum_runs: + description: 'Minimum runs to keep for each workflow' + required: true + default: '5' + delete_workflow_pattern: + description: 'Name or filename of the workflow (if not set, all workflows are targeted)' + required: false + default: 'Build and Package SCInsta' + delete_workflow_by_state_pattern: + description: 'Filter workflows by state: active, deleted, disabled_fork, disabled_inactivity, disabled_manually' + required: true + default: "ALL" + type: choice + options: + - "ALL" + - active + - deleted + - disabled_inactivity + - disabled_manually + delete_run_by_conclusion_pattern: + description: 'Remove runs based on conclusion: action_required, cancelled, failure, skipped, success' + required: true + default: "ALL" + type: choice + options: + - "ALL" + - "Unsuccessful: action_required,cancelled,failure,skipped" + - action_required + - cancelled + - failure + - skipped + - success + dry_run: + description: 'Logs simulated changes, no deletions are performed' + required: false + +# schedule: +# - cron: '0 0 * * *' + +jobs: + del_runs: + runs-on: ubuntu-latest + permissions: + actions: write + contents: read + steps: + - name: Delete workflow runs + uses: Mattraks/delete-workflow-runs@v2 + with: + token: ${{ github.token }} + repository: ${{ github.repository }} + retain_days: ${{ github.event.inputs.days }} + keep_minimum_runs: ${{ github.event.inputs.minimum_runs }} + delete_workflow_pattern: ${{ github.event.inputs.delete_workflow_pattern }} + delete_workflow_by_state_pattern: ${{ github.event.inputs.delete_workflow_by_state_pattern }} + delete_run_by_conclusion_pattern: >- + ${{ + startsWith(github.event.inputs.delete_run_by_conclusion_pattern, 'Unsuccessful:') + && 'action_required,cancelled,failure,skipped' + || github.event.inputs.delete_run_by_conclusion_pattern + }} + dry_run: ${{ github.event.inputs.dry_run }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e84d7db --- /dev/null +++ b/.gitignore @@ -0,0 +1,38 @@ +.DS_Store +.AppleDouble +.LSOverride +Icon +._* +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk +*.icloud + +*.deb +.debmake +_ +obj +.theos +packages + +.pyzule* +.cyan* +.ipapatch* +dumps +livecontainer + +src/**/wip.x +src/**/wip.xm + +.claude +CLAUDE.md +upstream-scinsta diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..3974061 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "modules/FLEXing"] + path = modules/FLEXing + url = https://github.com/SoCuul/FLEXing diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..c293d2d --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,19 @@ +{ + "editor.tabSize": 4, + "editor.insertSpaces": true, + "editor.trimAutoWhitespace": true, + "editor.formatOnSave": false, + "files.associations": { + "*.x": "logos", + "*.xi": "logos", + "*.xm": "logos", + "*.xmi": "logos", + "*.m": "objective-c", + "*.h": "objective-c" + }, + + "search.exclude": { + "modules/": true, + "dumps/": true + } +} \ No newline at end of file diff --git a/.vscode/snippets.code-snippets b/.vscode/snippets.code-snippets new file mode 100644 index 0000000..d02a432 --- /dev/null +++ b/.vscode/snippets.code-snippets @@ -0,0 +1,27 @@ +{ + "SCIUtils: Bool Pref": { + "prefix": "scibool", + "body": [ + "if ([SCIUtils getBoolPref:@\"${1:key}\"]) $0" + ] + }, + "SCIUtils: String Pref": { + "prefix": "scistring", + "body": [ + "if ([[SCIUtils getStringPref:@\"${1:key}\"] isEqualToString:@\"${2:string}\"]) $0" + ] + }, + + "SCIUtils: Log": { + "prefix": "scilog", + "body": [ + "SCILog($0);" + ] + }, + "SCIUtils: Log Id": { + "prefix": "scilogid", + "body": [ + "SCILogId(@\"${1:prefix}\", $0);" + ] + } +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..ff607cf --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,59 @@ +{ + // See https://go.microsoft.com/fwlink/?LinkId=733558 + // for the documentation about the tasks.json format + "version": "2.0.0", + "tasks": [ + { + "label": "Compile tweak and deploy to LiveContainer", + "type": "shell", + "command": "./build-dev.sh", + "group": { + "kind": "build", + "isDefault": true + }, + "presentation": { + "reveal": "always", + "panel": "dedicated", + "clear": true + }, + "icon": { + "color": "terminal.ansiCyan", + "id": "run-all" + } + }, + { + "label": "Build SCInsta and deploy with IPA", + "type": "shell", + "command": "./build-dev.sh true", + "group": { + "kind": "build", + }, + "presentation": { + "reveal": "always", + "panel": "dedicated", + "clear": true + }, + "icon": { + "id": "package" + } + }, + { + "label": "Launch pymobiledevice3 device tunnel (for quick dev builds)", + "type": "shell", + "command": "sudo pymobiledevice3 remote tunneld", + "group": { + "kind": "build", + }, + "presentation": { + "reveal": "silent", + "panel": "dedicated", + "clear": true + }, + "icon": { + "color": "terminal.ansiYellow", + "id": "debug-connected" + } + } + ] + } + \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..0986509 --- /dev/null +++ b/Makefile @@ -0,0 +1,22 @@ +TARGET := iphone:clang:16.2 +INSTALL_TARGET_PROCESSES = Instagram +ARCHS = arm64 + +include $(THEOS)/makefiles/common.mk + +TWEAK_NAME = SCInsta + +$(TWEAK_NAME)_FILES = $(shell find src -type f \( -iname \*.x -o -iname \*.xm -o -iname \*.m \)) $(wildcard modules/JGProgressHUD/*.m) +$(TWEAK_NAME)_FRAMEWORKS = UIKit Foundation CoreGraphics Photos CoreServices SystemConfiguration SafariServices Security QuartzCore +$(TWEAK_NAME)_PRIVATE_FRAMEWORKS = Preferences +$(TWEAK_NAME)_CFLAGS = -fobjc-arc -Wno-unsupported-availability-guard -Wno-unused-value -Wno-deprecated-declarations -Wno-nullability-completeness -Wno-unused-function -Wno-incompatible-pointer-types +$(TWEAK_NAME)_LOGOSFLAGS = --c warnings=none + +CCFLAGS += -std=c++11 + +include $(THEOS_MAKE_PATH)/tweak.mk + +# Build FLEXing for sideloading (not building in dev-mode) +ifdef SIDELOAD + $(TWEAK_NAME)_SUBPROJECTS += modules/flexing +endif \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..287f117 --- /dev/null +++ b/README.md @@ -0,0 +1,148 @@ +# SCInsta +A feature-rich tweak for Instagram on iOS!\ +`Version v1.1.1` | `Tested on Instagram 418.2.0` + +--- + +> [!NOTE] +> ⚙️  To modify SCInsta's settings, check out [this section below](https://github.com/SoCuul/SCInsta#Opening-Tweak-Settings) for help\ +> ❓  If you have any questions or need help with the tweak, visit the [Discussions](https://github.com/SoCuul/SCInsta/discussions) tab +> +> ✨  If you have a feature request, [click here](https://github.com/SoCuul/SCInsta/issues/new/choose)\ +> 🐛  If you have a bug report, [click here](https://github.com/SoCuul/SCInsta/issues/new/choose) +> + +--- + +# Installation +>[!IMPORTANT] +> Which type of device are you planning on installing this tweak on? +> - Jailbroken/TrollStore device -> [Download pre-built tweak](https://github.com/SoCuul/SCInsta/releases/latest) +> - Standard iOS device -> [Visit the wiki to create an IPA file](https://github.com/SoCuul/SCInsta/wiki/Building-IPA) + +# Features +### General +- Hide ads +- Hide Meta AI +- Copy description +- Do not save recent searches +- Use detailed (native) color picker +- Enable liquid glass buttons +- Enable teen app icons +- IG Notes: + - Hide notes tray + - Hide friends map + - Enable note theming + - Custom note themes +- Focus/Distractions + - No suggested users + - No suggested chats + - Hide trending searches + - Hide explore posts grid + +### Feed +- Hide stories tray +- Hide entire feed +- No suggested posts +- No suggested for you (accounts) +- No suggested reels +- No suggested threads posts +- Disable video autoplay + +### Reels +- Modify tap controls +- Always show progress scrubber +- Disable auto-unmuting reels +- Confirm reel refresh +- Hide reels header +- Hide reels blend button +- Disable scrolling reels +- Prevent doom scrolling (limit maximum viewable reels) + +### Saving +- Download feed posts +- Download reels +- Download stories +- Save profile picture +- *Customize finger count for long-press* +- *Customize hold time for long-press* + +### Stories and messages +- Keep deleted messages +- Manually mark messages as seen +- Disable typing status +- Unlimited replay of direct stories +- Disable view-once limitations +- Disable screenshot detection +- Disable story seen receipt +- Disable instants creation + +### Navigation +- Modify tab bar icon order +- Modify swiping between tabs +- Hiding tabs + - Hide feed tab + - Hide explore tab + - Hide reels tab + - Hide create tab + +### Confirm actions +- Confirm like: Posts/Stories +- Confirm like: Reels +- Confirm follow +- Confirm repost +- Confirm call +- Confirm voice messages +- Confirm follow requests +- Confirm shh mode (disappearing messages) +- Confirm posting comment +- Confirm changing direct message theme +- Confirm sticker interaction + +### Optimization +- Automatically clears unneeded cache folders, reducing the size of your Instagram installation + +# Opening Tweak Settings + +| | | +|:-------------------------------------------:|:-------------------------------------------:| +| | | + +# Building from source +### Prerequisites +- XCode + Command-Line Developer Tools +- [Homebrew](https://brew.sh/#install) +- [CMake](https://formulae.brew.sh/formula/cmake#default) (`brew install cmake`) +- [Theos](https://theos.dev/docs/installation) +- [cyan](https://github.com/asdfzxcvbn/pyzule-rw?tab=readme-ov-file#install-instructions) **\*only required for sideloading** +- [ipapatch](https://github.com/asdfzxcvbn/ipapatch/releases/latest) **\*only required for sideloading** + +### Setup +1. Install iOS 16.2 frameworks for theos + 1. [Click to download iOS SDKs](https://github.com/xybp888/iOS-SDKs/archive/refs/heads/master.zip) + 2. Unzip, then copy the `iPhoneOS16.2.sdk` folder into `~/theos/sdks` +2. Clone SCInsta repo from GitHub: `git clone --recurse-submodules https://github.com/SoCuul/SCInsta` +3. **For sideloading**: Download a decrypted Instagram IPA from a trusted source, making sure to rename it to `com.burbn.instagram.ipa`. + Then create a folder called `packages` inside of the `SCInsta` folder, and move the Instagram IPA file into it. + +### Run build script +```sh +$ chmod +x build.sh +$ ./build.sh +``` + +# Contributing +Contributions to this tweak are greatly appreciated. Feel free to create a pull request if you would like to contribute. + +If you do not have the technical knowledge to contribute to the codebase, improvements to the documentation are always welcome! + +# Support the project +SCInsta takes a lot of time to develop, as the Instagram app is ever-changing and difficult to keep up with. Additionally, I'm still a student which doesn't leave me much time to work on this tweak. + +If you'd like to support my work, you can donate to my [ko-fi page](https://ko-fi.com/socuul)!\ +There's many other ways to support this project however, by simply sharing a link to this tweak with others who would like it! + +Seeing people use this tweak is what keeps me motivated to keep working on it ❤️ + +# Credits +- Huge thanks to [@BandarHL](https://github.com/BandarHL) for creating the original BHInstagram project, which SCInsta is based upon. diff --git a/RELEASE_CHECKLIST.md b/RELEASE_CHECKLIST.md new file mode 100644 index 0000000..798e499 --- /dev/null +++ b/RELEASE_CHECKLIST.md @@ -0,0 +1,14 @@ +# New Version - Release Checklist + +### Before git pushing +- [ ] Update version string in `control` +- [ ] Update version string in `src/Tweak.x` +- [ ] Update version string at top of `README.md` +- [ ] Update compatible Instagram app version at top of `README.md` +- [ ] Update features list in `README.md` +- [ ] (Optional) Update screenshots + +### Creating new release +- [ ] Ensure new tag is created with proper format +- [ ] Make sure to include full changelog in release notes +- [ ] Include rootful & rootless deb files in release \ No newline at end of file diff --git a/SCInsta.plist b/SCInsta.plist new file mode 100644 index 0000000..45c93f6 --- /dev/null +++ b/SCInsta.plist @@ -0,0 +1,14 @@ + + + + + + Filter + + Bundles + + com.burbn.instagram + + + + \ No newline at end of file diff --git a/build-dev.sh b/build-dev.sh new file mode 100755 index 0000000..8c45998 --- /dev/null +++ b/build-dev.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash + +set -e + +echo 'Note: This script is meant to be used while developing the tweak.' +echo ' This does not build "libflex" or "FLEXing", they must be built manually and moved to ./packages' +echo + +if [ "$1" == "true" ]; +then + _scinsta_dev_before + + # Build tweak and package into ipa + ./build.sh sideload --dev + + _scinsta_dev_after +else + _scinsta_devquick_before + + # Built tweak and deploy to live container + make clean + make DEV=1 + + # Change framework locations to @rpath + install_name_tool -change "/Library/Frameworks/CydiaSubstrate.framework/CydiaSubstrate" "@rpath/CydiaSubstrate.framework/CydiaSubstrate" ".theos/obj/debug/SCInsta.dylib" 2>/dev/null || true + + _scinsta_devquick_after +fi \ No newline at end of file diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..fbeaef9 --- /dev/null +++ b/build.sh @@ -0,0 +1,120 @@ +#!/usr/bin/env bash + +set -e + +CMAKE_OSX_ARCHITECTURES="arm64e;arm64" +CMAKE_OSX_SYSROOT="iphoneos" + +# Building modes +if [ "$1" == "sideload" ]; +then + + # FLEXing is only needed for sideload builds + if [ -z "$(ls -A modules/FLEXing 2>/dev/null)" ]; then + echo -e '\033[1m\033[0;31mFLEXing submodule not found.\nPlease run the following command to checkout submodules:\n\n\033[0m git submodule update --init --recursive' + exit 1 + fi + + # Check if building with dev mode + if [ "$2" == "--dev" ]; + then + # Cache pre-built FLEX libs + mkdir -p "packages/cache" + cp -f ".theos/obj/debug/FLEXing.dylib" "packages/cache/FLEXing.dylib" 2>/dev/null || true + cp -f ".theos/obj/debug/libflex.dylib" "packages/cache/libflex.dylib" 2>/dev/null || true + + if [[ ! -f "packages/cache/FLEXing.dylib" || ! -f "packages/cache/libflex.dylib" ]]; then + echo -e '\033[1m\033[0;33mCould not find cached pre-built FLEX libs, building prerequisite binaries\033[0m' + echo + + ./build.sh sideload --buildonly + ./build-dev.sh true + exit + fi + + MAKEARGS='DEV=1' + FLEXPATH='packages/cache/FLEXing.dylib packages/cache/libflex.dylib' + COMPRESSION=0 + else + # Clear cached FLEX libs + rm -rf "packages/cache" + + MAKEARGS='SIDELOAD=1' + FLEXPATH='.theos/obj/debug/FLEXing.dylib .theos/obj/debug/libflex.dylib' + COMPRESSION=9 + fi + + # Clean build artifacts + make clean + rm -rf .theos + + # Check for decrypted instagram ipa + ipaFile="$(find ./packages/*com.burbn.instagram*.ipa -type f -exec basename {} \;)" + if [ -z "${ipaFile}" ]; then + echo -e '\033[1m\033[0;31m./packages/com.burbn.instagram.ipa not found.\nPlease put a decrypted Instagram IPA in its path.\033[0m' + exit 1 + fi + + echo -e '\033[1m\033[32mBuilding SCInsta tweak for sideloading (as IPA)\033[0m' + + make $MAKEARGS + + # Only build libs (for future use in dev build mode) + if [ "$2" == "--buildonly" ]; + then + exit + fi + + SCINSTAPATH=".theos/obj/debug/SCInsta.dylib" + if [ "$2" == "--devquick" ]; + then + # Exclude SCInsta.dylib from ipa for livecontainer quick builds + SCINSTAPATH="" + fi + + # Create IPA File + echo -e '\033[1m\033[32mCreating the IPA file...\033[0m' + rm -f packages/SCInsta-sideloaded.ipa + cyan -i "packages/${ipaFile}" -o packages/SCInsta-sideloaded.ipa -f $SCINSTAPATH $FLEXPATH -c $COMPRESSION -m 15.0 -du + + # Patch IPA for sideloading + ipapatch --input "packages/SCInsta-sideloaded.ipa" --inplace --noconfirm + + echo -e "\033[1m\033[32mDone, we hope you enjoy SCInsta!\033[0m\n\nYou can find the ipa file at: $(pwd)/packages" + +elif [ "$1" == "rootless" ]; +then + + # Clean build artifacts + make clean + rm -rf .theos + + echo -e '\033[1m\033[32mBuilding SCInsta tweak for rootless\033[0m' + + export THEOS_PACKAGE_SCHEME=rootless + make package + + echo -e "\033[1m\033[32mDone, we hope you enjoy SCInsta!\033[0m\n\nYou can find the deb file at: $(pwd)/packages" + +elif [ "$1" == "rootful" ]; +then + + # Clean build artifacts + make clean + rm -rf .theos + + echo -e '\033[1m\033[32mBuilding SCInsta tweak for rootful\033[0m' + + unset THEOS_PACKAGE_SCHEME + make package + + echo -e "\033[1m\033[32mDone, we hope you enjoy SCInsta!\033[0m\n\nYou can find the deb file at: $(pwd)/packages" + +else + echo '+--------------------+' + echo '|SCInsta Build Script|' + echo '+--------------------+' + echo + echo 'Usage: ./build.sh ' + exit 1 +fi \ No newline at end of file diff --git a/control b/control new file mode 100644 index 0000000..46ef400 --- /dev/null +++ b/control @@ -0,0 +1,10 @@ +Package: com.socuul.scinsta +Name: SCInsta +Version: 1.1.2 +Architecture: iphoneos-arm +Description: A feature-rich tweak for Instagram on iOS! +Homepage: https://github.com/SoCuul/SCInsta +Maintainer: SoCuul +Author: SoCuul +Section: Tweaks +Depends: mobilesubstrate \ No newline at end of file diff --git a/modules/JGProgressHUD/JGProgressHUD-Defines.h b/modules/JGProgressHUD/JGProgressHUD-Defines.h new file mode 100644 index 0000000..d777bf6 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUD-Defines.h @@ -0,0 +1,78 @@ +// +// JGProgressHUD-Defines.h +// JGProgressHUD +// +// Created by Jonas Gessner on 28.04.15. +// Copyright (c) 2015 Jonas Gessner. All rights reserved. +// + +#import + +/** + Positions of the HUD. + */ +typedef NS_ENUM(NSUInteger, JGProgressHUDPosition) { + /** Center position. */ + JGProgressHUDPositionCenter = 0, + /** Top left position. */ + JGProgressHUDPositionTopLeft, + /** Top center position. */ + JGProgressHUDPositionTopCenter, + /** Top right position. */ + JGProgressHUDPositionTopRight, + /** Center left position. */ + JGProgressHUDPositionCenterLeft, + /** Center right position. */ + JGProgressHUDPositionCenterRight, + /** Bottom left position. */ + JGProgressHUDPositionBottomLeft, + /** Bottom center position. */ + JGProgressHUDPositionBottomCenter, + /** Bottom right position. */ + JGProgressHUDPositionBottomRight +}; + +/** + Appearance styles of the HUD. + */ +typedef NS_ENUM(NSUInteger, JGProgressHUDStyle) { + /** Extra light HUD with dark elements. */ + JGProgressHUDStyleExtraLight = 0, + /** Light HUD with dark elemets. */ + JGProgressHUDStyleLight, + /** Dark HUD with light elements. */ + JGProgressHUDStyleDark, +}; + +#if TARGET_OS_IOS +/** + Interaction types. + */ +typedef NS_ENUM(NSUInteger, JGProgressHUDInteractionType) { + /** Block all touches. No interaction behin the HUD is possible. */ + JGProgressHUDInteractionTypeBlockAllTouches = 0, + /** Block touches on the HUD view. */ + JGProgressHUDInteractionTypeBlockTouchesOnHUDView, + /** Block no touches. */ + JGProgressHUDInteractionTypeBlockNoTouches +}; +#endif + +/** + Parallax Modes. + */ +typedef NS_ENUM(NSUInteger, JGProgressHUDParallaxMode) { + /** Follows the device setting for parallax. If "Reduce Motion" is enabled, no parallax effect is added to the HUD, if "Reduce Motion" is disabled the HUD will have a parallax effect. This behaviour is only supported on iOS 8 and higher. */ + JGProgressHUDParallaxModeDevice = 0, + /** Always adds a parallax effect to the HUD. Parallax is only supported on iOS 7 and higher. */ + JGProgressHUDParallaxModeAlwaysOn, + /** Never adds a parallax effect to the HUD. */ + JGProgressHUDParallaxModeAlwaysOff +}; + +#ifndef fequal +/** + Macro for safe floating point comparison (for internal use in JGProgressHUD). + */ +#define fequal(a,b) (fabs((a) - (b)) < FLT_EPSILON) +#endif diff --git a/modules/JGProgressHUD/JGProgressHUD.h b/modules/JGProgressHUD/JGProgressHUD.h new file mode 100644 index 0000000..3169c8d --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUD.h @@ -0,0 +1,310 @@ +// +// JGProgressHUD.h +// JGProgressHUD +// +// Created by Jonas Gessner on 20.7.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "JGProgressHUD-Defines.h" +#import "JGProgressHUDShadow.h" +#import "JGProgressHUDAnimation.h" +#import "JGProgressHUDFadeAnimation.h" +#import "JGProgressHUDFadeZoomAnimation.h" +#import "JGProgressHUDIndicatorView.h" +#import "JGProgressHUDErrorIndicatorView.h" +#import "JGProgressHUDSuccessIndicatorView.h" +#import "JGProgressHUDRingIndicatorView.h" +#import "JGProgressHUDPieIndicatorView.h" +#import "JGProgressHUDIndeterminateIndicatorView.h" +#pragma clang diagnostic pop + +@protocol JGProgressHUDDelegate; + +/** + A HUD to indicate progress, success, error, warnings or other notifications to the user. + @discussion @c JGProgressHUD respects its @c layoutMargins when positioning the HUD view. Additionally, on iOS 11 if @c insetsLayoutMarginsFromSafeArea is set to @c YES (default) the @c layoutMargins additionally contain the @c safeAreaInsets. + @note Remember to call every method from the main thread! UIKit => main thread! + @attention You may not add JGProgressHUD to a view which has an alpha value < 1.0 or to a view which is a subview of a view with an alpha value < 1.0. + */ +@interface JGProgressHUD : UIView + +/** + Designated initializer. + @param style The appearance style of the HUD. + */ +- (instancetype __nonnull)initWithStyle:(JGProgressHUDStyle)style; + +/** + Convenience initializer. + @param style The appearance style of the HUD. + */ ++ (instancetype __nonnull)progressHUDWithStyle:(JGProgressHUDStyle)style; + +/** + Convenience initializer. The HUD will dynamically change its style based on whether dark mode is enabled or not. When dark mode is on, the style will be JGProgressHUDStyleDark, when dark mode is off the style will be JGProgressHUDStyleExtraLight. + */ +- (instancetype __nonnull)initWithAutomaticStyle; + +/** + Convenience initializer. The HUD will dynamically change its style based on whether dark mode is enabled or not. When dark mode is on, the style will be JGProgressHUDStyleDark, when dark mode is off the style will be JGProgressHUDStyleExtraLight. + */ ++ (instancetype __nonnull)progressHUDWithAutomaticStyle; + +/** + The appearance style of the HUD. + @b Default: JGProgressHUDStyleExtraLight. + */ +@property (nonatomic, assign) JGProgressHUDStyle style; + +/** The view in which the HUD is presented. */ +@property (nonatomic, weak, readonly, nullable) UIView *targetView; + +/** + The delegate of the HUD. + @sa JGProgressHUDDelegate. + */ +@property (nonatomic, weak, nullable) id delegate; + +/** The actual HUD view visible on screen. You may add animations to this view. */ +@property (nonatomic, strong, readonly, nonnull) UIView *HUDView; + +/** + The content view inside the @c HUDView. If you want to add additional views to the HUD you should add them as subview to the @c contentView. + */ +@property (nonatomic, strong, readonly, nonnull) UIView *contentView; + +/** + The label used to present text on the HUD. Set the @c text or @c attributedText property of this label to change the displayed text. You may not change the label's @c frame or @c bounds. + */ +@property (nonatomic, strong, readonly, nonnull) UILabel *textLabel; + +/** + The label used to present detail text on the HUD. Set the @c text or @c attributedText property of this label to change the displayed text. You may not change the label's @c frame or @c bounds. + */ +@property (nonatomic, strong, readonly, nonnull) UILabel *detailTextLabel; + +/** + The indicator view. You can assign a custom subclass of @c JGProgressHUDIndicatorView to this property or one of the default indicator views (if you do so, you should assign it before showing the HUD). This value is optional. + @b Default: JGProgressHUDIndeterminateIndicatorView. + */ +@property (nonatomic, strong, nullable) JGProgressHUDIndicatorView *indicatorView; + +/** + The shadow cast by the @c HUDView. This value is optional. Setting this to @c nil means no shadow is cast by the HUD. + @b Default: nil. + */ +@property (nonatomic, strong, nullable) JGProgressHUDShadow *shadow; + +/** + The position of the HUD inside the hosting view's frame, or inside the specified frame. + @b Default: JGProgressHUDPositionCenter + */ +@property (nonatomic, assign) JGProgressHUDPosition position; + +/** + The animation used for showing and dismissing the HUD. + @b Default: JGProgressHUDFadeAnimation. + */ +@property (nonatomic, strong, nonnull) JGProgressHUDAnimation *animation; + +#if TARGET_OS_IOS +/** + Interaction type of the HUD. Determines whether touches should be let through to the views behind the HUD. + @sa JGProgressHUDInteractionType. + @b Default: JGProgressHUDInteractionTypeBlockAllTouches. + */ +@property (nonatomic, assign) JGProgressHUDInteractionType interactionType; +#endif + +/** + Parallax mode for the HUD. This setting determines whether the HUD should have a parallax (@c UIDeviceMotion) effect. This effect is controlled by device motion on iOS and remote touchpad panning gestures on tvOS. + @sa JGProgressHUDParallaxMode. + @b Default: JGProgressHUDParallaxModeDevice. + */ +@property (nonatomic, assign) JGProgressHUDParallaxMode parallaxMode; + +#if TARGET_OS_TV +/** + When this property is set to @c YES the HUD will try to become focused, which prevents interactions with the @c targetView. If set to @c NO the HUD will not become focused and interactions with @c targetView remain possible. Default: @c YES. + */ +@property (nonatomic, assign) BOOL wantsFocus; +#endif + +/** + If the HUD should always have the same width and height. + @b Default: NO. + */ +@property (nonatomic, assign) BOOL square; + +/** + Internally @c JGProgressHUD uses an @c UIVisualEffectView with a @c UIBlurEffect. A second @c UIVisualEffectView can be added on top of that with a @c UIVibrancyEffect which amplifies and adjusts the color of content layered behind the view, allowing content placed inside the contentView to become more vivid. This flag sets whether the @c UIVibrancyEffect should be used. Using the vibrancy effect can sometimes, depending on the contents of the display, result in a weird look (especially on iOS < 9.3). + @b Default: NO. + */ +@property (nonatomic, assign) BOOL vibrancyEnabled; + +/** + The radius used for rounding the four corners of the HUD view. + @b Default: 10.0. + */ +@property (nonatomic, assign) CGFloat cornerRadius; + +/** + Insets the contents of the HUD. + @b Default: (20, 20, 20, 20). + */ +@property (nonatomic, assign) UIEdgeInsets contentInsets; + +/** + @return Whether the HUD is visible on screen. + */ +@property (nonatomic, assign, readonly, getter = isVisible) BOOL visible; + +/** + The progress to display using the @c progressIndicatorView. A change of this property is not animated. Use the @c setProgress:animated: method for an animated progress change. + @b Default: 0.0. + */ +@property (nonatomic, assign) float progress; + +/** + Adjusts the current progress shown by the receiver, optionally animating the change. + + The current progress is represented by a floating-point value between 0.0 and 1.0, inclusive, where 1.0 indicates the completion of the task. The default value is 0.0. Values less than 0.0 and greater than 1.0 are pinned to those limits. + @param progress The new progress value. + @param animated YES if the change should be animated, NO if the change should happen immediately. + */ +- (void)setProgress:(float)progress animated:(BOOL)animated; + +/** + Specifies a minimum time that the HUD will be on-screen. Useful to prevent the HUD from flashing quickly on the screen when indeterminate tasks complete more quickly than expected. + @b Default: 0.0. + */ +@property (nonatomic, assign) NSTimeInterval minimumDisplayTime; + +/** + Determines whether Voice Over announcements should be made upon displaying the HUD (if Voice Over is active). + @b Default: YES + */ +@property (nonatomic, assign) BOOL voiceOverEnabled; + +#if TARGET_OS_IOS +/** + A block to be invoked when the HUD view is tapped. + @note The interaction type of the HUD must be @c JGProgressHUDInteractionTypeBlockTouchesOnHUDView or @c JGProgressHUDInteractionTypeBlockAllTouches, otherwise this block won't be fired. + */ +@property (nonatomic, copy, nullable) void (^tapOnHUDViewBlock)(JGProgressHUD *__nonnull HUD); + +/** + A block to be invoked when the area outside of the HUD view is tapped. + @note The interaction type of the HUD must be @c JGProgressHUDInteractionTypeBlockAllTouches, otherwise this block won't be fired. + */ +@property (nonatomic, copy, nullable) void (^tapOutsideBlock)(JGProgressHUD *__nonnull HUD); +#endif + +/** + Shows the HUD animated. You should preferably show the HUD in a UIViewController's view. The HUD will be repositioned in response to rotation and keyboard show/hide notifications. + @param view The view to show the HUD in. The frame of the @c view will be used to calculate the position of the HUD. + */ +- (void)showInView:(UIView *__nonnull)view; + +/** + Shows the HUD. You should preferably show the HUD in a UIViewController's view. The HUD will be repositioned in response to rotation and keyboard show/hide notifications. + @param view The view to show the HUD in. The frame of the @c view will be used to calculate the position of the HUD. + @param animated If the HUD should show with an animation. + */ +- (void)showInView:(UIView *__nonnull)view animated:(BOOL)animated; + +/** + Shows the HUD after a delay. You should preferably show the HUD in a UIViewController's view. The HUD will be repositioned in response to rotation and keyboard show/hide notifications. + You may call @c dismiss to stop the HUD from appearing before the delay has passed. + @param view The view to show the HUD in. The frame of the @c view will be used to calculate the position of the HUD. + @param animated If the HUD should show with an animation. + @param delay The delay until the HUD will be shown. + */ +- (void)showInView:(UIView *__nonnull)view animated:(BOOL)animated afterDelay:(NSTimeInterval)delay; + +/** Dismisses the HUD animated. If the HUD is currently not visible this method does nothing. */ +- (void)dismiss; + +/** + Dismisses the HUD. If the HUD is currently not visible this method does nothing. + @param animated If the HUD should dismiss with an animation. + */ +- (void)dismissAnimated:(BOOL)animated; + +/** + Dismisses the HUD animated after a delay. If the HUD is currently not visible this method does nothing. + @param delay The delay until the HUD will be dismissed. + */ +- (void)dismissAfterDelay:(NSTimeInterval)delay; + +/** + Dismisses the HUD after a delay. If the HUD is currently not visible this method does nothing. + @param delay The delay until the HUD will be dismissed. + @param animated If the HUD should dismiss with an animation. + */ +- (void)dismissAfterDelay:(NSTimeInterval)delay animated:(BOOL)animated; + +/** + Dismisses the HUD after a delay and runs a block upon completion. If the HUD is currently not visible this method does nothing. + @param delay The delay until the HUD will be dismissed. + @param animated If the HUD should dismiss with an animation. + @param dismissCompletion The block to execute after the HUD was dismissed. + */ +- (void)dismissAfterDelay:(NSTimeInterval)delay animated:(BOOL)animated completion:(void (^_Nullable)(void))dismissCompletion; + +/** + Schedules the given block to be executed when this HUD disapears. If the HUD is currently not visible this method does nothing. + @param dismissCompletion The block to execute after the HUD was dismissed. Multiple calls to this method cause the different blocks to be executed in FIFO order. + */ +- (void)performAfterDismiss:(void (^_Nonnull)(void))dismissCompletion; + +@end + +@interface JGProgressHUD (HUDManagement) + +/** + @param view The view to return all visible progress HUDs for. + @return All visible progress HUDs in the view. + */ ++ (NSArray *__nonnull)allProgressHUDsInView:(UIView *__nonnull)view; + +/** + @param view The view to return all visible progress HUDs for. + @return All visible progress HUDs in the view and its subviews. + */ ++ (NSArray *__nonnull)allProgressHUDsInViewHierarchy:(UIView *__nonnull)view; + +@end + +@protocol JGProgressHUDDelegate + +@optional + +/** + Called before the HUD will appear. + @param view The view in which the HUD is presented. + */ +- (void)progressHUD:(JGProgressHUD *__nonnull)progressHUD willPresentInView:(UIView *__nonnull)view; + +/** + Called after the HUD appeared. + @param view The view in which the HUD is presented. + */ +- (void)progressHUD:(JGProgressHUD *__nonnull)progressHUD didPresentInView:(UIView *__nonnull)view; + +/** + Called before the HUD will disappear. + @param view The view in which the HUD is presented and will be dismissed from. + */ +- (void)progressHUD:(JGProgressHUD *__nonnull)progressHUD willDismissFromView:(UIView *__nonnull)view; + +/** + Called after the HUD has disappeared. + @param view The view in which the HUD was presented and was be dismissed from. + */ +- (void)progressHUD:(JGProgressHUD *__nonnull)progressHUD didDismissFromView:(UIView *__nonnull)view; + +@end diff --git a/modules/JGProgressHUD/JGProgressHUD.m b/modules/JGProgressHUD/JGProgressHUD.m new file mode 100755 index 0000000..d397ee0 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUD.m @@ -0,0 +1,1234 @@ +// +// JGProgressHUD.m +// JGProgressHUD +// +// Created by Jonas Gessner on 20.7.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#import "JGProgressHUD.h" +#import +#import "JGProgressHUDFadeAnimation.h" +#import "JGProgressHUDIndeterminateIndicatorView.h" + +#if !__has_feature(objc_arc) +#error "JGProgressHUD requires ARC!" +#endif + +static inline CGRect JGProgressHUD_CGRectIntegral(CGRect rect) { + CGFloat scale = [[UIScreen mainScreen] scale]; + + return (CGRect){{((CGFloat)floor(rect.origin.x*scale))/scale, ((CGFloat)floor(rect.origin.y*scale))/scale}, {((CGFloat)ceil(rect.size.width*scale))/scale, ((CGFloat)ceil(rect.size.height*scale))/scale}}; +} + +API_AVAILABLE(ios(12.0), tvos(10.0)) +static inline JGProgressHUDStyle JGProgressHUDStyleFromUIUserInterfaceStyle(UIUserInterfaceStyle uiStyle) { + if (uiStyle == UIUserInterfaceStyleDark) { + return JGProgressHUDStyleDark; + } + else { + return JGProgressHUDStyleExtraLight; + } +} + +@interface JGProgressHUD () { + BOOL _transitioning; + BOOL _updateAfterAppear; + + BOOL _dismissAfterTransitionFinished; + BOOL _dismissAfterTransitionFinishedWithAnimation; + + CFAbsoluteTime _displayTimestamp; + dispatch_block_t __nullable _displayBlock; + + BOOL _effectiveIndicatorViewNeedsUpdate; + + UIView *__nonnull _blurViewContainer; + UIView *__nonnull _shadowView; + CAShapeLayer *__nonnull _shadowMaskLayer; + + NSMutableArray *_dismissActions; + + BOOL _automaticStyle; +} + +// In 'beta' +/** + Setting this to @c YES makes the text and indicator views bigger. + @b Default: NO. + */ +@property (nonatomic, assign) BOOL thick; + +@property (nonatomic, strong, readonly, nonnull) UIVisualEffectView *blurView; +@property (nonatomic, strong, readonly, nonnull) UIVisualEffectView *vibrancyView; + +@property (nonatomic, strong, readonly, nonnull) JGProgressHUDIndicatorView *effectiveIndicatorView; + +@end + +@interface JGProgressHUDAnimation (Private) + +@property (nonatomic, weak, nullable) JGProgressHUD *progressHUD; + +@end + +@implementation JGProgressHUD + +@synthesize HUDView = _HUDView; +@synthesize blurView = _blurView; +@synthesize vibrancyView = _vibrancyView; +@synthesize textLabel = _textLabel; +@synthesize detailTextLabel = _detailTextLabel; +@synthesize indicatorView = _indicatorView; +@synthesize animation = _animation; +@synthesize contentView = _contentView; + +@dynamic visible; + +#pragma mark - Keyboard + +static CGRect keyboardFrame = (CGRect){{0.0, 0.0}, {0.0, 0.0}}; + +#if TARGET_OS_IOS ++ (void)keyboardFrameWillChange:(NSNotification *)notification { + keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; + if (CGRectIsEmpty(keyboardFrame)) { + keyboardFrame = [notification.userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue]; + } +} + ++ (void)keyboardFrameDidChange:(NSNotification *)notification { + keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]; +} + ++ (void)keyboardDidHide { + keyboardFrame = CGRectZero; +} + ++ (void)load { + @autoreleasepool { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil]; + + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameDidChange:) name:UIKeyboardDidChangeFrameNotification object:nil]; + + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide) name:UIKeyboardDidHideNotification object:nil]; + } +} +#endif + ++ (CGRect)currentKeyboardFrame { + return keyboardFrame; +} + +#pragma mark - Initializers + +- (instancetype)init { + return [self initWithAutomaticStyle]; +} + +- (instancetype)initWithFrame:(CGRect __unused)frame { + return [self initWithAutomaticStyle]; +} + +/* + Basic architecture: + + * self covers the entire target view. + * self.HUDView is a subview of self and has the size and position of the visible HUD. The layer has rounded corners set with self.cornerRadius. The layer does not clip to bounds. + * _shadowView is a subview of self.HUDView and always covers the entire HUDView. The corners are also rounded in the same way as self.HUDView. It draws its shadow only on the outside by using a masking layer, so that the shadow does not interfere with the blur view. + * _blurViewContainer is a subview of self.HUDView and always covers the entire self.HUDView. The corners are also rounded in the same way as self.HUDView but it additionally clips to bounds. + * self.blurView is a subview of _blurViewContainer and provides the blur effect. The corners are not rounded and the view does not clip to bounds. + * self.vibrancyView is a subview of self.blurView.contentView and provides the vibrancy effect. The corners are not rounded and the view does not clip to bounds. + * self.contentView is a subview of self.vibrancyView.contentView. It does not always have the same frame as it's superview (during transitions). + * self.contentView contains the labels and the indicator view. + + */ +- (instancetype)initWithStyle:(JGProgressHUDStyle)style { + self = [super initWithFrame:CGRectZero]; + + if (self) { + _style = style; + _voiceOverEnabled = YES; + _automaticStyle = NO; + + _HUDView = [[UIView alloc] init]; + self.HUDView.backgroundColor = [UIColor clearColor]; + [self addSubview:self.HUDView]; + + _blurViewContainer = [[UIView alloc] init]; + _blurViewContainer.backgroundColor = [UIColor clearColor]; + _blurViewContainer.clipsToBounds = YES; + [self.HUDView addSubview:_blurViewContainer]; + + _shadowView = [[UIView alloc] init]; + _shadowView.backgroundColor = [UIColor blackColor]; + _shadowView.userInteractionEnabled = NO; + _shadowView.layer.shadowOpacity = 1.0; + _shadowView.alpha = 0.0; + + _shadowMaskLayer = [CAShapeLayer layer]; + _shadowMaskLayer.fillRule = kCAFillRuleEvenOdd; + _shadowMaskLayer.fillColor = [UIColor blackColor].CGColor; + _shadowMaskLayer.opacity = 1.0; + + _shadowView.layer.mask = _shadowMaskLayer; + + [self.HUDView addSubview:_shadowView]; + + _indicatorView = [[JGProgressHUDIndeterminateIndicatorView alloc] init]; + _effectiveIndicatorView = _indicatorView; + [self.effectiveIndicatorView setUpForHUDStyle:self.style vibrancyEnabled:self.vibrancyEnabled]; + + self.hidden = YES; + self.backgroundColor = [UIColor clearColor]; + + self.contentInsets = UIEdgeInsetsMake(20.0, 20.0, 20.0, 20.0); + self.layoutMargins = UIEdgeInsetsMake(20.0, 20.0, 20.0, 20.0); + + self.cornerRadius = 10.0; + + _dismissActions = [[NSMutableArray alloc] init]; + +#if TARGET_OS_IOS + [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)]]; +#elif TARGET_OS_TV + _wantsFocus = YES; +#endif + } + + return self; +} + ++ (instancetype)progressHUDWithStyle:(JGProgressHUDStyle)style { + return [(JGProgressHUD *)[self alloc] initWithStyle:style]; +} + +- (instancetype)initWithAutomaticStyle { + if (@available(iOS 12.0, tvOS 10.0, *)) { + JGProgressHUDStyle initialStyle; + + if (@available(iOS 13.0, tvOS 13.0, *)) { + initialStyle = JGProgressHUDStyleFromUIUserInterfaceStyle([[UITraitCollection currentTraitCollection] userInterfaceStyle]); + } + else { + initialStyle = JGProgressHUDStyleExtraLight; + } + + self = [self initWithStyle:initialStyle]; + + if (self != nil) { + _automaticStyle = YES; + } + } + else { + self = [self initWithStyle:JGProgressHUDStyleExtraLight]; + } + + return self; +} + ++ (instancetype)progressHUDWithAutomaticStyle { + return [[self alloc] initWithAutomaticStyle]; +} + +#pragma mark - Layout + +- (void)setHUDViewFrameCenterWithSize:(CGSize)size insetViewFrame:(CGRect)viewFrame { + CGRect frame = (CGRect){CGPointZero, size}; + + switch (self.position) { + case JGProgressHUDPositionTopLeft: + frame.origin.x = CGRectGetMinX(viewFrame); + frame.origin.y = CGRectGetMinY(viewFrame); + break; + + case JGProgressHUDPositionTopCenter: + frame.origin.x = CGRectGetMidX(viewFrame) - size.width/2.0; + frame.origin.y = CGRectGetMinY(viewFrame); + break; + + case JGProgressHUDPositionTopRight: + frame.origin.x = CGRectGetMaxX(viewFrame) - size.width; + frame.origin.y = CGRectGetMinY(viewFrame); + break; + + case JGProgressHUDPositionCenterLeft: + frame.origin.x = CGRectGetMinX(viewFrame); + frame.origin.y = CGRectGetMidY(viewFrame) - size.height/2.0; + break; + + case JGProgressHUDPositionCenter: + frame.origin.x = CGRectGetMidX(viewFrame) - size.width/2.0; + frame.origin.y = CGRectGetMidY(viewFrame) - size.height/2.0; + break; + + case JGProgressHUDPositionCenterRight: + frame.origin.x = CGRectGetMaxX(viewFrame) - frame.size.width; + frame.origin.y = CGRectGetMidY(viewFrame) - size.height/2.0; + break; + + case JGProgressHUDPositionBottomLeft: + frame.origin.x = CGRectGetMinX(viewFrame); + frame.origin.y = CGRectGetMaxY(viewFrame) - size.height; + break; + + case JGProgressHUDPositionBottomCenter: + frame.origin.x = CGRectGetMidX(viewFrame) - size.width/2.0; + frame.origin.y = CGRectGetMaxY(viewFrame) - frame.size.height; + break; + + case JGProgressHUDPositionBottomRight: + frame.origin.x = CGRectGetMaxX(viewFrame) - size.width; + frame.origin.y = CGRectGetMaxY(viewFrame) - size.height; + break; + } + + CGRect oldHUDFrame = self.HUDView.frame; + CGRect updatedHUDFrame = JGProgressHUD_CGRectIntegral(frame); + + self.HUDView.frame = updatedHUDFrame; + _shadowView.frame = self.HUDView.bounds; + [self updateShadowViewMask]; + + _blurViewContainer.frame = self.HUDView.bounds; + self.blurView.frame = self.HUDView.bounds; + self.vibrancyView.frame = self.HUDView.bounds; + + [UIView performWithoutAnimation:^{ + self.contentView.frame = (CGRect){{(oldHUDFrame.size.width - updatedHUDFrame.size.width)/2.0, (oldHUDFrame.size.height - updatedHUDFrame.size.height)/2.0}, updatedHUDFrame.size}; + }]; + + self.contentView.frame = self.HUDView.bounds; +} + +- (void)updateShadowViewMask { + if (CGRectIsEmpty(_shadowView.layer.bounds)) { + return; + } + + CGRect layerBounds = CGRectMake(0.0, 0.0, _shadowView.layer.bounds.size.width + self.shadow.radius*4.0, _shadowView.layer.bounds.size.height + self.shadow.radius*4.0); + + UIBezierPath *path = [UIBezierPath bezierPathWithRect:layerBounds]; + + CGRect maskRect = CGRectInset(layerBounds, self.shadow.radius*2.0, self.shadow.radius*2.0); + + UIBezierPath *roundedPath = [UIBezierPath bezierPathWithRoundedRect:maskRect cornerRadius:self.cornerRadius]; + + [path appendPath:roundedPath]; + + _shadowMaskLayer.frame = CGRectInset(_shadowView.layer.bounds, -self.shadow.radius*2.0, -self.shadow.radius*2.0); + + CAAnimation *currentAnimation = [self.HUDView.layer animationForKey:@"position"]; + if (currentAnimation != nil) { + [CATransaction begin]; + + [CATransaction setAnimationDuration:currentAnimation.duration]; + [CATransaction setAnimationTimingFunction:currentAnimation.timingFunction]; + + CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"path"]; + [_shadowMaskLayer addAnimation:pathAnimation forKey:@"path"]; + + _shadowMaskLayer.path = path.CGPath; + + [CATransaction commit]; + } + else { + _shadowMaskLayer.path = path.CGPath; + // Remove implicit CALayer animations: + [_shadowMaskLayer removeAllAnimations]; + } +} + +- (void)layoutHUD { + if (_transitioning) { + _updateAfterAppear = YES; + return; + } + + if (_targetView == nil) { + return; + } + + CGRect indicatorFrame = self.effectiveIndicatorView.frame; + indicatorFrame.origin.y = self.contentInsets.top; + + CGRect insetFrame = [self insetFrameForView:self]; + + CGFloat maxContentWidth = insetFrame.size.width - self.contentInsets.left - self.contentInsets.right; + CGFloat maxContentHeight = insetFrame.size.height - self.contentInsets.top - self.contentInsets.bottom; + + CGRect labelFrame = CGRectZero; + CGRect detailFrame = CGRectZero; + + CGFloat currentY = CGRectGetMaxY(indicatorFrame); + if (!CGRectIsEmpty(indicatorFrame)) { + currentY += 10.0; + } + + if (_textLabel.text.length > 0) { + _textLabel.preferredMaxLayoutWidth = maxContentWidth; + + CGSize neededSize = _textLabel.intrinsicContentSize; + neededSize.height = MIN(neededSize.height, maxContentHeight); + + labelFrame.size = neededSize; + labelFrame.origin.y = currentY; + currentY = CGRectGetMaxY(labelFrame) + 6.0; + } + + if (_detailTextLabel.text.length > 0) { + _detailTextLabel.preferredMaxLayoutWidth = maxContentWidth; + + CGSize neededSize = _detailTextLabel.intrinsicContentSize; + neededSize.height = MIN(neededSize.height, maxContentHeight); + + detailFrame.size = neededSize; + detailFrame.origin.y = currentY; + } + + CGSize size = CGSizeZero; + + CGFloat width = MIN(self.contentInsets.left + MAX(indicatorFrame.size.width, MAX(labelFrame.size.width, detailFrame.size.width)) + self.contentInsets.right, insetFrame.size.width); + + CGFloat height = MAX(CGRectGetMaxY(labelFrame), MAX(CGRectGetMaxY(detailFrame), CGRectGetMaxY(indicatorFrame))) + self.contentInsets.bottom; + + if (self.square) { + CGFloat uniSize = MAX(width, height); + + size.width = uniSize; + size.height = uniSize; + + CGFloat heightDelta = (uniSize-height)/2.0; + + labelFrame.origin.y += heightDelta; + detailFrame.origin.y += heightDelta; + indicatorFrame.origin.y += heightDelta; + } + else { + size.width = width; + size.height = height; + } + + CGPoint center = CGPointMake(size.width/2.0, size.height/2.0); + + indicatorFrame.origin.x = center.x - indicatorFrame.size.width/2.0; + labelFrame.origin.x = center.x - labelFrame.size.width/2.0; + detailFrame.origin.x = center.x - detailFrame.size.width/2.0; + + [UIView performWithoutAnimation:^{ + self.effectiveIndicatorView.frame = indicatorFrame; + self->_textLabel.frame = JGProgressHUD_CGRectIntegral(labelFrame); + self->_detailTextLabel.frame = JGProgressHUD_CGRectIntegral(detailFrame); + }]; + + [self setHUDViewFrameCenterWithSize:size insetViewFrame:insetFrame]; +} + +- (CGRect)insetFrameForView:(UIView *)view { + CGRect localKeyboardFrame = [view convertRect:[[self class] currentKeyboardFrame] fromView:nil]; + CGRect frame = view.bounds; + + if (!CGRectIsEmpty(localKeyboardFrame) && CGRectIntersectsRect(frame, localKeyboardFrame)) { + CGFloat keyboardMinY = CGRectGetMinY(localKeyboardFrame); + + if (@available(iOS 11, tvOS 11, *)) { + if (self.insetsLayoutMarginsFromSafeArea) { + // This makes sure that the bottom safe area inset is only respected when that area is not covered by the keyboard. When the keyboard covers the bottom area outside of the safe area it is not necessary to keep the bottom safe area insets part of the insets for the HUD. + keyboardMinY += self.safeAreaInsets.bottom; + } + } + + frame.size.height = MAX(MIN(frame.size.height, keyboardMinY), 0.0); + } + + return UIEdgeInsetsInsetRect(frame, view.layoutMargins); +} + +- (void)applyCornerRadius { + self.HUDView.layer.cornerRadius = self.cornerRadius; + _blurViewContainer.layer.cornerRadius = self.cornerRadius; + _shadowView.layer.cornerRadius = self.cornerRadius; + + [self updateShadowViewMask]; +} + +#pragma mark - Showing + +- (void)cleanUpAfterPresentation { +#if TARGET_OS_TV + if (self.wantsFocus) { + [self.targetView setNeedsFocusUpdate]; + } +#endif + + self.hidden = NO; + + _transitioning = NO; + // Correct timestamp to the current time for animated presentations: + _displayTimestamp = CFAbsoluteTimeGetCurrent(); + + if (_effectiveIndicatorViewNeedsUpdate) { + self.effectiveIndicatorView = self.indicatorView; + _effectiveIndicatorViewNeedsUpdate = NO; + _updateAfterAppear = NO; + } + else if (_updateAfterAppear) { + [self layoutHUD]; + _updateAfterAppear = NO; + } + + if ([self.delegate respondsToSelector:@selector(progressHUD:didPresentInView:)]){ + [self.delegate progressHUD:self didPresentInView:self.targetView]; + } + + if (_dismissAfterTransitionFinished) { + [self dismissAnimated:_dismissAfterTransitionFinishedWithAnimation]; + _dismissAfterTransitionFinished = NO; + _dismissAfterTransitionFinishedWithAnimation = NO; + } + else if (self.voiceOverEnabled && UIAccessibilityIsVoiceOverRunning()) { + UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, self); + } +} + +- (void)showInView:(UIView *)view { + [self showInView:view animated:YES]; +} + +- (void)layoutSubviews { + [super layoutSubviews]; + + [self layoutHUD]; +} + +- (void)showInView:(UIView *)view animated:(BOOL)animated { + if (_transitioning) { + return; + } + else if (self.targetView != nil) { +#if DEBUG + NSLog(@"[Warning] The HUD is already visible! Ignoring."); +#endif + return; + } + + if ([self.delegate respondsToSelector:@selector(progressHUD:willPresentInView:)]) { + [self.delegate progressHUD:self willPresentInView:view]; + } + + _targetView = view; + + self.frame = _targetView.bounds; + + [_targetView addSubview:self]; + + self.translatesAutoresizingMaskIntoConstraints = NO; + + [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:_targetView attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0.0].active = YES; + [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:_targetView attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0.0].active = YES; + [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:_targetView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0].active = YES; + [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:_targetView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0].active = YES; + + [self setNeedsLayout]; + [self layoutIfNeeded]; + + _transitioning = YES; + + _displayTimestamp = CFAbsoluteTimeGetCurrent(); + + if (animated && self.animation != nil) { + [self.animation show]; + } + else { + [self cleanUpAfterPresentation]; + } + +#if TARGET_OS_IOS + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChanged:) name:UIKeyboardWillChangeFrameNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChanged:) name:UIKeyboardDidChangeFrameNotification object:nil]; +#endif +} + +- (void)showInView:(UIView *__nonnull)view animated:(BOOL)animated afterDelay:(NSTimeInterval)delay { + __weak __typeof(self) weakSelf = self; + + if (_displayBlock != NULL) { + dispatch_cancel(_displayBlock); + } + + _displayBlock = dispatch_block_create(0, ^{ + if (weakSelf) { + __strong __typeof(weakSelf) strongSelf = weakSelf; + strongSelf->_displayBlock = NULL; + + if (!strongSelf.visible) { + [strongSelf showInView:view animated:animated]; + } + } + }); + + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), _displayBlock); +} + +#pragma mark - Dismissing + +- (void)cleanUpAfterDismissal { + self.hidden = YES; + [self removeFromSuperview]; + + [self removeObservers]; + + _transitioning = NO; + _dismissAfterTransitionFinished = NO; + _dismissAfterTransitionFinishedWithAnimation = NO; + + __typeof(self.targetView) targetView = self.targetView; + _targetView = nil; + + for (void (^action)(void) in _dismissActions) { + action(); + } + [_dismissActions removeAllObjects]; + + if ([self.delegate respondsToSelector:@selector(progressHUD:didDismissFromView:)]) { + [self.delegate progressHUD:self didDismissFromView:targetView]; + } +} + +- (void)dismiss { + [self dismissAnimated:YES]; +} + +- (void)dismissAnimated:(BOOL)animated { + if (_displayBlock != NULL) { + dispatch_cancel(_displayBlock); + _displayBlock = NULL; + } + + if (_transitioning) { + _dismissAfterTransitionFinished = YES; + _dismissAfterTransitionFinishedWithAnimation = animated; + return; + } + + if (self.targetView == nil) { + return; + } + + if (self.minimumDisplayTime > 0.0 && _displayTimestamp > 0.0) { + CFAbsoluteTime displayedTime = CFAbsoluteTimeGetCurrent()-_displayTimestamp; + + if (displayedTime < self.minimumDisplayTime) { + NSTimeInterval delta = self.minimumDisplayTime-displayedTime; + + [self dismissAfterDelay:delta animated:animated]; + + return; + } + } + + if ([self.delegate respondsToSelector:@selector(progressHUD:willDismissFromView:)]) { + [self.delegate progressHUD:self willDismissFromView:self.targetView]; + } + + _transitioning = YES; + + if (animated && self.animation) { + [self.animation hide]; + } + else { + [self cleanUpAfterDismissal]; + } +} + +- (void)dismissAfterDelay:(NSTimeInterval)delay { + [self dismissAfterDelay:delay animated:YES]; +} + +- (void)dismissAfterDelay:(NSTimeInterval)delay animated:(BOOL)animated { + [self dismissAfterDelay:delay animated:animated completion:nil]; +} + +- (void)dismissAfterDelay:(NSTimeInterval)delay animated:(BOOL)animated completion:(void (^_Nullable)(void))dismissCompletion { + __weak __typeof(self) weakSelf = self; + + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + if (weakSelf) { + __strong __typeof(weakSelf) strongSelf = weakSelf; + if (strongSelf.visible) { + if (dismissCompletion != nil) { + [self performAfterDismiss:dismissCompletion]; + } + [strongSelf dismissAnimated:animated]; + } + } + }); +} + +- (void)performAfterDismiss:(void (^_Nonnull)(void))dismissCompletion { + if (self.visible) { + [_dismissActions addObject:dismissCompletion]; + } +} + +#pragma mark - Callbacks + +#if TARGET_OS_IOS +- (void)tapped:(UITapGestureRecognizer *)t { + if (CGRectContainsPoint(self.contentView.bounds, [t locationInView:self.contentView])) { + if (self.tapOnHUDViewBlock != nil) { + self.tapOnHUDViewBlock(self); + } + } + else if (self.tapOutsideBlock != nil) { + self.tapOutsideBlock(self); + } +} + +static inline UIViewAnimationOptions UIViewAnimationOptionsFromUIViewAnimationCurve(UIViewAnimationCurve curve) { + UIViewAnimationOptions testOptions = UIViewAnimationCurveLinear << 16; + + if (testOptions != UIViewAnimationOptionCurveLinear) { + NSLog(@"Unexpected implementation of UIViewAnimationOptionCurveLinear"); + } + + return (UIViewAnimationOptions)(curve << 16); +} + +- (void)keyboardFrameChanged:(NSNotification *)notification { + NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue]; + + UIViewAnimationCurve curve = (UIViewAnimationCurve)[notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] unsignedIntegerValue]; + + [UIView animateWithDuration:duration delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionsFromUIViewAnimationCurve(curve) animations:^{ + [self layoutHUD]; + } completion:nil]; +} +#endif + +- (void)updateMotionOnHUDView { + BOOL reduceMotionEnabled = UIAccessibilityIsReduceMotionEnabled(); + + BOOL wantsParallax = ((self.parallaxMode == JGProgressHUDParallaxModeDevice && !reduceMotionEnabled) || self.parallaxMode == JGProgressHUDParallaxModeAlwaysOn); + BOOL hasParallax = (self.HUDView.motionEffects.count > 0); + + if (wantsParallax == hasParallax) { + return; + } + + if (!wantsParallax) { + self.HUDView.motionEffects = @[]; + } + else { + UIInterpolatingMotionEffect *x = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis]; + + CGFloat maxMovement = 20.0; + + x.minimumRelativeValue = @(-maxMovement); + x.maximumRelativeValue = @(maxMovement); + + UIInterpolatingMotionEffect *y = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis]; + + y.minimumRelativeValue = @(-maxMovement); + y.maximumRelativeValue = @(maxMovement); + + self.HUDView.motionEffects = @[x, y]; + } +} + +- (void)animationDidFinish:(BOOL)presenting { + if (presenting) { + [self cleanUpAfterPresentation]; + } + else { + [self cleanUpAfterDismissal]; + } +} + +#pragma mark - Getters + +- (BOOL)isVisible { + return (self.superview != nil); +} + +- (UIVisualEffectView *)blurView { + if (!_blurView) { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMotionOnHUDView) name:UIAccessibilityReduceMotionStatusDidChangeNotification object:nil]; + + UIBlurEffectStyle effect; + + if (self.style == JGProgressHUDStyleDark) { + effect = UIBlurEffectStyleDark; + } + else if (self.style == JGProgressHUDStyleLight) { + effect = UIBlurEffectStyleLight; + } + else { + effect = UIBlurEffectStyleExtraLight; + } + + UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:effect]; + + _blurView = [[UIVisualEffectView alloc] initWithEffect:blurEffect]; + + [self updateMotionOnHUDView]; + + [_blurViewContainer addSubview:_blurView]; + +#if TARGET_OS_IOS + [self.contentView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)]]; +#endif + } + + return _blurView; +} + +- (UIVisualEffectView *)vibrancyView { + if (!_vibrancyView) { + UIVibrancyEffect *vibrancyEffect = (self.vibrancyEnabled ? [UIVibrancyEffect effectForBlurEffect:(UIBlurEffect *)self.blurView.effect] : nil); + + _vibrancyView = [[UIVisualEffectView alloc] initWithEffect:vibrancyEffect]; + + [self.blurView.contentView addSubview:_vibrancyView]; + } + + return _vibrancyView; +} + +- (UIView *)contentView { + if (_contentView == nil) { + _contentView = [[UIView alloc] init]; + [self.vibrancyView.contentView addSubview:_contentView]; + + if (self.effectiveIndicatorView != nil) { + [self.contentView addSubview:self.effectiveIndicatorView]; + } + } + + return _contentView; +} + +- (UILabel *)textLabel { + if (!_textLabel) { + _textLabel = [[UILabel alloc] init]; + _textLabel.backgroundColor = [UIColor clearColor]; + _textLabel.textColor = (self.style == JGProgressHUDStyleDark ? [UIColor whiteColor] : [UIColor blackColor]); + _textLabel.textAlignment = NSTextAlignmentCenter; +#if TARGET_OS_TV + CGFloat fontSize = 20.0; +#else + CGFloat fontSize = 17.0; +#endif + if (self.thick) { + fontSize *= 1.3; + } + + _textLabel.font = [UIFont boldSystemFontOfSize:fontSize]; + _textLabel.numberOfLines = 0; + [_textLabel addObserver:self forKeyPath:@"attributedText" options:(NSKeyValueObservingOptions)kNilOptions context:NULL]; + [_textLabel addObserver:self forKeyPath:@"text" options:(NSKeyValueObservingOptions)kNilOptions context:NULL]; + [_textLabel addObserver:self forKeyPath:@"font" options:(NSKeyValueObservingOptions)kNilOptions context:NULL]; + _textLabel.isAccessibilityElement = YES; + + [self.contentView addSubview:_textLabel]; + } + + return _textLabel; +} + +- (UILabel *)detailTextLabel { + if (!_detailTextLabel) { + _detailTextLabel = [[UILabel alloc] init]; + _detailTextLabel.backgroundColor = [UIColor clearColor]; + _detailTextLabel.textColor = (self.style == JGProgressHUDStyleDark ? [UIColor whiteColor] : [UIColor blackColor]); + _detailTextLabel.textAlignment = NSTextAlignmentCenter; +#if TARGET_OS_TV + CGFloat fontSize = 17.0; +#else + CGFloat fontSize = 15.0; +#endif + if (self.thick) { + fontSize *= 1.3; + } + + _detailTextLabel.font = [UIFont systemFontOfSize:fontSize]; + _detailTextLabel.numberOfLines = 0; + [_detailTextLabel addObserver:self forKeyPath:@"attributedText" options:(NSKeyValueObservingOptions)kNilOptions context:NULL]; + [_detailTextLabel addObserver:self forKeyPath:@"text" options:(NSKeyValueObservingOptions)kNilOptions context:NULL]; + [_detailTextLabel addObserver:self forKeyPath:@"font" options:(NSKeyValueObservingOptions)kNilOptions context:NULL]; + _detailTextLabel.isAccessibilityElement = YES; + + [self.contentView addSubview:_detailTextLabel]; + } + + return _detailTextLabel; +} + +- (JGProgressHUDAnimation *)animation { + if (!_animation) { + self.animation = [JGProgressHUDFadeAnimation animation]; + } + + return _animation; +} + +#pragma mark - Setters + +- (void)setStyle:(JGProgressHUDStyle)style { + if (self.style == style) { + return; + } + + _style = style; + + // Update indicator + [self.effectiveIndicatorView setUpForHUDStyle:self.style vibrancyEnabled:self.vibrancyEnabled]; + + // Update labels + self.textLabel.textColor = (self.style == JGProgressHUDStyleDark ? [UIColor whiteColor] : [UIColor blackColor]); + self.detailTextLabel.textColor = (self.style == JGProgressHUDStyleDark ? [UIColor whiteColor] : [UIColor blackColor]); + + // Update blur effect + UIBlurEffectStyle effect; + + if (self.style == JGProgressHUDStyleDark) { + effect = UIBlurEffectStyleDark; + } + else if (self.style == JGProgressHUDStyleLight) { + effect = UIBlurEffectStyleLight; + } + else { + effect = UIBlurEffectStyleExtraLight; + } + + UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:effect]; + self.blurView.effect = blurEffect; + + // Update vibrancy effect + UIVibrancyEffect *vibrancyEffect = (self.vibrancyEnabled ? [UIVibrancyEffect effectForBlurEffect:(UIBlurEffect *)self.blurView.effect] : nil); + self.vibrancyView.effect = vibrancyEffect; +} + +#if TARGET_OS_TV +- (void)setWantsFocus:(BOOL)wantsFocus { + if (self.wantsFocus == wantsFocus) { + return; + } + + _wantsFocus = wantsFocus; + + self.userInteractionEnabled = self.wantsFocus; + + [self.targetView setNeedsFocusUpdate]; +} +#endif + +- (void)setCornerRadius:(CGFloat)cornerRadius { + if (fequal(self.cornerRadius, cornerRadius)) { + return; + } + + _cornerRadius = cornerRadius; + + [self applyCornerRadius]; +} + +- (void)setShadow:(JGProgressHUDShadow *)shadow { + if (shadow == self.shadow) { + return; + } + + _shadow = shadow; + + [self updateShadowViewMask]; + + if (_shadow != nil) { + _shadowView.layer.shadowColor = _shadow.color.CGColor; + _shadowView.layer.shadowOffset = _shadow.offset; + _shadowView.layer.shadowRadius = _shadow.radius; + + _shadowView.alpha = _shadow.opacity; + } + else { + _shadowView.layer.shadowOffset = CGSizeZero; + _shadowView.layer.shadowRadius = 0.0; + + _shadowView.alpha = 0.0; + } +} + +- (void)setAnimation:(JGProgressHUDAnimation *)animation { + if (_animation == animation) { + return; + } + + _animation.progressHUD = nil; + + _animation = animation; + + _animation.progressHUD = self; +} + +- (void)setParallaxMode:(JGProgressHUDParallaxMode)parallaxMode { + if (self.parallaxMode == parallaxMode) { + return; + } + + _parallaxMode = parallaxMode; + + [self updateMotionOnHUDView]; +} + +- (void)setPosition:(JGProgressHUDPosition)position { + if (self.position == position) { + return; + } + + _position = position; + [self layoutHUD]; +} + +- (void)setSquare:(BOOL)square { + if (self.square == square) { + return; + } + + _square = square; + + [self layoutHUD]; +} + +- (void)setThick:(BOOL)thick { + if (self.thick == thick) { + return; + } + + _thick = thick; + + if (self.thick) { + self.indicatorView.transform = CGAffineTransformMakeScale(1.5, 1.5); + } + else { + self.indicatorView.transform = CGAffineTransformIdentity; + } + +#if TARGET_OS_TV + CGFloat fontSize = 20.0; +#else + CGFloat fontSize = 17.0; +#endif + if (self.thick) { + fontSize *= 1.3; + } + + _textLabel.font = [UIFont boldSystemFontOfSize:fontSize]; +#if TARGET_OS_TV + fontSize = 17.0; +#else + fontSize = 15.0; +#endif + if (self.thick) { + fontSize *= 1.3; + } + + _detailTextLabel.font = [UIFont systemFontOfSize:fontSize]; + + [self layoutHUD]; +} + +- (void)setVibrancyEnabled:(BOOL)vibrancyEnabled { + if (vibrancyEnabled == self.vibrancyEnabled) { + return; + } + + _vibrancyEnabled = vibrancyEnabled; + + UIVibrancyEffect *vibrancyEffect = (self.vibrancyEnabled ? [UIVibrancyEffect effectForBlurEffect:(UIBlurEffect *)self.blurView.effect] : nil); + + self.vibrancyView.effect = vibrancyEffect; + + [self.effectiveIndicatorView setUpForHUDStyle:self.style vibrancyEnabled:self.vibrancyEnabled]; +} + +- (void)setIndicatorView:(JGProgressHUDIndicatorView *)indicatorView { + if (self.indicatorView == indicatorView) { + return; + } + + _indicatorView = indicatorView; + + if (_transitioning) { + _effectiveIndicatorViewNeedsUpdate = YES; + return; + } + else { + self.effectiveIndicatorView = self.indicatorView; + } +} + +- (void)setEffectiveIndicatorView:(JGProgressHUDIndicatorView * _Nonnull)effectiveIndicatorView { + if (self.effectiveIndicatorView == effectiveIndicatorView) { + return; + } + + [UIView performWithoutAnimation:^{ + [self->_effectiveIndicatorView removeFromSuperview]; + self->_effectiveIndicatorView = effectiveIndicatorView; + + if (self.indicatorView != nil) { + [self.effectiveIndicatorView setUpForHUDStyle:self.style vibrancyEnabled:self.vibrancyEnabled]; + + if (self.thick) { + self.effectiveIndicatorView.transform = CGAffineTransformMakeScale(1.5, 1.5); + } + else { + self.effectiveIndicatorView.transform = CGAffineTransformIdentity; + } + + [self.contentView addSubview:self.effectiveIndicatorView]; + } + }]; + + [self layoutHUD]; +} + +- (void)layoutMarginsDidChange { + [super layoutMarginsDidChange]; + + [self layoutHUD]; +} + +- (void)setContentInsets:(UIEdgeInsets)contentInsets { + if (UIEdgeInsetsEqualToEdgeInsets(self.contentInsets, contentInsets)) { + return; + } + + _contentInsets = contentInsets; + + [self layoutHUD]; +} + +- (void)setProgress:(float)progress { + [self setProgress:progress animated:NO]; +} + +- (void)setProgress:(float)progress animated:(BOOL)animated { + if (fequal(self.progress, progress)) { + return; + } + + _progress = progress; + + [self.effectiveIndicatorView setProgress:progress animated:animated]; +} + +#pragma mark - Overrides + +- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection { + [super traitCollectionDidChange:previousTraitCollection]; + + if (@available(iOS 12.0, tvOS 10.0, *)) { + if (_automaticStyle) { + self.style = JGProgressHUDStyleFromUIUserInterfaceStyle(self.traitCollection.userInterfaceStyle); + } + } +} + +#if TARGET_OS_IOS +- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { + if (self.interactionType == JGProgressHUDInteractionTypeBlockNoTouches) { + return nil; + } + else { + UIView *view = [super hitTest:point withEvent:event]; + + if (self.interactionType == JGProgressHUDInteractionTypeBlockAllTouches) { + return view; + } + else if (self.interactionType == JGProgressHUDInteractionTypeBlockTouchesOnHUDView && view != self) { + return view; + } + + return nil; + } +} +#elif TARGET_OS_TV +- (NSArray> *)preferredFocusEnvironments { + return @[self]; +} + +- (UIView *)preferredFocusedView { + return nil; +} + +- (BOOL)canBecomeFocused { + return self.wantsFocus; +} +#endif + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + if (object == _textLabel || object == _detailTextLabel) { + [self layoutHUD]; + } + else { + [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; + } +} + +- (void)dealloc { + [self removeObservers]; + + [_textLabel removeObserver:self forKeyPath:@"attributedText"]; + [_textLabel removeObserver:self forKeyPath:@"text"]; + [_textLabel removeObserver:self forKeyPath:@"font"]; + + [_detailTextLabel removeObserver:self forKeyPath:@"attributedText"]; + [_detailTextLabel removeObserver:self forKeyPath:@"text"]; + [_detailTextLabel removeObserver:self forKeyPath:@"font"]; +} + +- (void)removeObservers { + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIAccessibilityReduceMotionStatusDidChangeNotification object:nil]; + +#if TARGET_OS_IOS + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidChangeFrameNotification object:nil]; +#endif +} + +@end + +@implementation JGProgressHUD (HUDManagement) + ++ (NSArray *)allProgressHUDsInView:(UIView *)view { + NSMutableArray *HUDs = [NSMutableArray array]; + + for (UIView *v in view.subviews) { + if ([v isKindOfClass:[JGProgressHUD class]]) { + [HUDs addObject:v]; + } + } + + return HUDs.copy; +} + ++ (NSMutableArray *)_allProgressHUDsInViewHierarchy:(UIView *)view { + NSMutableArray *HUDs = [NSMutableArray array]; + + for (UIView *v in view.subviews) { + if ([v isKindOfClass:[JGProgressHUD class]]) { + [HUDs addObject:v]; + } + else { + [HUDs addObjectsFromArray:[self _allProgressHUDsInViewHierarchy:v]]; + } + } + + return HUDs; +} + ++ (NSArray *)allProgressHUDsInViewHierarchy:(UIView *)view { + return [self _allProgressHUDsInViewHierarchy:view].copy; +} + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDAnimation.h b/modules/JGProgressHUD/JGProgressHUDAnimation.h new file mode 100644 index 0000000..67679b6 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDAnimation.h @@ -0,0 +1,43 @@ +// +// JGProgressHUDAnimation.h +// JGProgressHUD +// +// Created by Jonas Gessner on 20.7.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#import +#import + +@class JGProgressHUD; + +/** + You may subclass this class to create a custom progress indicator view. + */ +@interface JGProgressHUDAnimation : NSObject + +/** Convenience initializer. */ ++ (instancetype __nonnull)animation; + +/** The HUD using this animation. */ +@property (nonatomic, weak, readonly, nullable) JGProgressHUD *progressHUD; + +/** + The @c progressHUD is hidden from screen with @c alpha = 1 and @c hidden = @c YES. Ideally, you should prepare the HUD for presentation, then set @c hidden to @c NO on the @c progressHUD and then perform the animation. + @post Call @c animationFinished. + */ +- (void)show NS_REQUIRES_SUPER; + +/** + The @c progressHUD wis visible on screen with @c alpha = 1 and @c hidden = @c NO. You should only perform the animation in this method, the @c progressHUD itself will take care of hiding itself and removing itself from superview. + @post Call @c animationFinished. + */ +- (void)hide NS_REQUIRES_SUPER; + +/** + @pre This method should only be called at the end of a @c show or @c hide animaiton. + @attention ALWAYS call this method after completing a @c show or @c hide animation. + */ +- (void)animationFinished NS_REQUIRES_SUPER; + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDAnimation.m b/modules/JGProgressHUD/JGProgressHUDAnimation.m new file mode 100755 index 0000000..fb2628f --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDAnimation.m @@ -0,0 +1,48 @@ +// +// JGProgressHUDAnimation.m +// JGProgressHUD +// +// Created by Jonas Gessner on 20.7.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#import "JGProgressHUDAnimation.h" +#import "JGProgressHUD.h" + +@interface JGProgressHUD (Private) + +- (void)animationDidFinish:(BOOL)presenting; + +@end + +@interface JGProgressHUDAnimation () { + BOOL _presenting; +} + +@property (nonatomic, weak) JGProgressHUD *progressHUD; + +@end + +@implementation JGProgressHUDAnimation + +#pragma mark - Initializers + ++ (instancetype)animation { + return [[self alloc] init]; +} + +#pragma mark - Public methods + +- (void)show { + _presenting = YES; +} + +- (void)hide { + _presenting = NO; +} + +- (void)animationFinished { + [self.progressHUD animationDidFinish:_presenting]; +} + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDErrorIndicatorView.h b/modules/JGProgressHUD/JGProgressHUDErrorIndicatorView.h new file mode 100644 index 0000000..96f7731 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDErrorIndicatorView.h @@ -0,0 +1,24 @@ +// +// JGProgressHUDErrorIndicatorView.h +// JGProgressHUD +// +// Created by Jonas Gessner on 19.08.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "JGProgressHUDImageIndicatorView.h" +#pragma clang diagnostic pop + +/** + An image indicator showing a cross, representing a failed operation. + */ +@interface JGProgressHUDErrorIndicatorView : JGProgressHUDImageIndicatorView + +/** + Default initializer for this class. + */ +- (instancetype __nonnull)init; + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDErrorIndicatorView.m b/modules/JGProgressHUD/JGProgressHUDErrorIndicatorView.m new file mode 100644 index 0000000..d9a7d31 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDErrorIndicatorView.m @@ -0,0 +1,57 @@ +// +// JGProgressHUDErrorIndicatorView.m +// JGProgressHUD +// +// Created by Jonas Gessner on 19.08.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#import "JGProgressHUDErrorIndicatorView.h" +#import "JGProgressHUD.h" + +static UIBezierPath *errorBezierPath() { + static UIBezierPath *path; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + path = [UIBezierPath bezierPath]; + [path moveToPoint:CGPointMake(3, 3)]; + [path addLineToPoint:CGPointMake(30, 30)]; + [path moveToPoint:CGPointMake(30, 3)]; + [path addLineToPoint:CGPointMake(3, 30)]; + + [path setLineWidth:3]; + [path setLineJoinStyle:kCGLineJoinRound]; + [path setLineCapStyle:kCGLineCapRound]; + }); + + return path; +} + +@implementation JGProgressHUDErrorIndicatorView + +- (instancetype)initWithContentView:(UIView *__unused)contentView { + UIBezierPath *path = errorBezierPath(); + + UIGraphicsBeginImageContextWithOptions(CGSizeMake(33, 33), NO, 0.0); + [[UIColor blackColor] setStroke]; + [path stroke]; + + UIImage *img = [UIGraphicsGetImageFromCurrentImageContext() imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; + + UIGraphicsEndImageContext(); + + self = [super initWithImage:img]; + + return self; +} + +- (instancetype)init { + return [self initWithContentView:nil]; +} + +- (void)updateAccessibility { + self.accessibilityLabel = NSLocalizedString(@"Error",); +} + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDFadeAnimation.h b/modules/JGProgressHUD/JGProgressHUDFadeAnimation.h new file mode 100644 index 0000000..6460265 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDFadeAnimation.h @@ -0,0 +1,33 @@ +// +// JGProgressHUDFadeAnimation.h +// JGProgressHUD +// +// Created by Jonas Gessner on 20.7.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "JGProgressHUDAnimation.h" +#pragma clang diagnostic pop + +/** + A simple fade animation that fades the HUD from alpha @c 0.0 to alpha @c 1.0. + */ +@interface JGProgressHUDFadeAnimation : JGProgressHUDAnimation + +/** + Duration of the animation. + + @b Default: 0.4. + */ +@property (nonatomic, assign) NSTimeInterval duration; + +/** + Animation options + + @b Default: UIViewAnimationOptionCurveEaseInOut. + */ +@property (nonatomic, assign) UIViewAnimationOptions animationOptions; + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDFadeAnimation.m b/modules/JGProgressHUD/JGProgressHUDFadeAnimation.m new file mode 100755 index 0000000..bd86290 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDFadeAnimation.m @@ -0,0 +1,56 @@ +// +// JGProgressHUDFadeAnimation.m +// JGProgressHUD +// +// Created by Jonas Gessner on 20.7.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#import "JGProgressHUDFadeAnimation.h" +#import "JGProgressHUD.h" + +@implementation JGProgressHUDFadeAnimation + +#pragma mark - Initializers + +- (instancetype)init { + self = [super init]; + if (self) { + self.duration = 0.4; + self.animationOptions = UIViewAnimationOptionCurveEaseInOut; + } + return self; +} + +- (void)setAnimationOptions:(UIViewAnimationOptions)animationOptions { + _animationOptions = (animationOptions | UIViewAnimationOptionBeginFromCurrentState); +} + +#pragma mark - Showing + +- (void)show { + [super show]; + + self.progressHUD.alpha = 0.0; + self.progressHUD.hidden = NO; + + [UIView animateWithDuration:self.duration delay:0.0 options:self.animationOptions animations:^{ + self.progressHUD.alpha = 1.0; + } completion:^(BOOL __unused finished) { + [self animationFinished]; + }]; +} + +#pragma mark - Hiding + +- (void)hide { + [super hide]; + + [UIView animateWithDuration:self.duration delay:0.0 options:self.animationOptions animations:^{ + self.progressHUD.alpha = 0.0; + } completion:^(BOOL __unused finished) { + [self animationFinished]; + }]; +} + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDFadeZoomAnimation.h b/modules/JGProgressHUD/JGProgressHUDFadeZoomAnimation.h new file mode 100644 index 0000000..0746f0b --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDFadeZoomAnimation.h @@ -0,0 +1,40 @@ +// +// JGProgressHUDFadeZoomAnimation.h +// JGProgressHUD +// +// Created by Jonas Gessner on 20.7.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "JGProgressHUDAnimation.h" +#pragma clang diagnostic pop + +/** + An animation that fades in the HUD and expands the HUD from scale @c (0, 0) to a customizable scale, and finally to scale @c (1, 1), creating a bouncing effect. + */ +@interface JGProgressHUDFadeZoomAnimation : JGProgressHUDAnimation + +/** + Duration of the animation from or to the shrinked state. + + @b Default: 0.2. + */ +@property (nonatomic, assign) NSTimeInterval shrinkAnimationDuaration; + +/** + Duration of the animation from or to the expanded state. + + @b Default: 0.1. + */ +@property (nonatomic, assign) NSTimeInterval expandAnimationDuaration; + +/** + The scale to apply to the HUD when expanding. + + @b Default: (1.1, 1.1). + */ +@property (nonatomic, assign) CGSize expandScale; + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDFadeZoomAnimation.m b/modules/JGProgressHUD/JGProgressHUDFadeZoomAnimation.m new file mode 100755 index 0000000..f95af60 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDFadeZoomAnimation.m @@ -0,0 +1,77 @@ +// +// JGProgressHUDFadeZoomAnimation.m +// JGProgressHUD +// +// Created by Jonas Gessner on 20.7.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#import "JGProgressHUDFadeZoomAnimation.h" +#import "JGProgressHUD.h" + +@implementation JGProgressHUDFadeZoomAnimation + +#pragma mark - Initializers + +- (instancetype)init { + self = [super init]; + if (self) { + self.shrinkAnimationDuaration = 0.2; + self.expandAnimationDuaration = 0.1; + self.expandScale = CGSizeMake(1.1, 1.1); + } + return self; +} + +#pragma mark - Showing + +- (void)show { + [super show]; + + self.progressHUD.alpha = 0.0; + self.progressHUD.HUDView.transform = CGAffineTransformMakeScale(0.1, 0.1); + + NSTimeInterval totalDuration = self.expandAnimationDuaration+self.shrinkAnimationDuaration; + + self.progressHUD.hidden = NO; + + [UIView animateWithDuration:totalDuration delay:0.0 options:(UIViewAnimationOptions)(UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut) animations:^{ + self.progressHUD.alpha = 1.0; + } completion:nil]; + + [UIView animateWithDuration:self.shrinkAnimationDuaration delay:0.0 options:(UIViewAnimationOptions)(UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionBeginFromCurrentState) animations:^{ + self.progressHUD.HUDView.transform = CGAffineTransformMakeScale(self.expandScale.width, self.expandScale.height); + } completion:^(BOOL __unused _finished) { + [UIView animateWithDuration:self.expandAnimationDuaration delay:0.0 options:(UIViewAnimationOptions)(UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionBeginFromCurrentState) animations:^{ + self.progressHUD.HUDView.transform = CGAffineTransformIdentity; + } completion:^(BOOL __unused __finished) { + [self animationFinished]; + }]; + }]; +} + +#pragma mark - Hiding + +- (void)hide { + [super hide]; + + NSTimeInterval totalDuration = self.expandAnimationDuaration+self.shrinkAnimationDuaration; + + [UIView animateWithDuration:totalDuration delay:0.0 options:(UIViewAnimationOptions)(UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionCurveEaseInOut) animations:^{ + self.progressHUD.alpha = 0.0; + } completion:nil]; + + [UIView animateWithDuration:self.expandAnimationDuaration delay:0.0 options:(UIViewAnimationOptions)(UIViewAnimationOptionCurveEaseIn | UIViewAnimationOptionBeginFromCurrentState) animations:^{ + self.progressHUD.HUDView.transform = CGAffineTransformMakeScale(self.expandScale.width, self.expandScale.height); + } completion:^(BOOL __unused _finished) { + [UIView animateWithDuration:self.shrinkAnimationDuaration delay:0.0 options:(UIViewAnimationOptions)(UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionBeginFromCurrentState) animations:^{ + self.progressHUD.HUDView.transform = CGAffineTransformMakeScale(0.1, 0.1); + } completion:^(BOOL __unused __finished) { + self.progressHUD.HUDView.transform = CGAffineTransformIdentity; + + [self animationFinished]; + }]; + }]; +} + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDImageIndicatorView.h b/modules/JGProgressHUD/JGProgressHUDImageIndicatorView.h new file mode 100644 index 0000000..4922238 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDImageIndicatorView.h @@ -0,0 +1,28 @@ +// +// JGProgressHUDImageIndicatorView.h +// JGProgressHUD +// +// Created by Jonas Gessner on 05.08.15. +// Copyright (c) 2015 Jonas Gessner. All rights reserved. +// + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "JGProgressHUDIndicatorView.h" +#pragma clang diagnostic pop + +/** + An indicator for displaying custom images. Supports animated images. + + You may subclass this class to create a custom image indicator view. + */ +@interface JGProgressHUDImageIndicatorView : JGProgressHUDIndicatorView + +/** + Initializes the indicator view with an UIImageView showing the @c image. + + @param image The image to show in the indicator view. + */ +- (instancetype __nonnull)initWithImage:(UIImage *__nonnull)image; + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDImageIndicatorView.m b/modules/JGProgressHUD/JGProgressHUDImageIndicatorView.m new file mode 100644 index 0000000..0a38d1f --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDImageIndicatorView.m @@ -0,0 +1,42 @@ +// +// JGProgressHUDImageIndicatorView.m +// JGProgressHUD +// +// Created by Jonas Gessner on 05.08.15. +// Copyright (c) 2015 Jonas Gessner. All rights reserved. +// + +#import "JGProgressHUDImageIndicatorView.h" + +@implementation JGProgressHUDImageIndicatorView { + BOOL _customizedTintColor; +} + +- (instancetype)initWithImage:(UIImage *)image { + UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; + + self = [super initWithContentView:imageView]; + + return self; +} + +- (void)setUpForHUDStyle:(JGProgressHUDStyle)style vibrancyEnabled:(BOOL)vibrancyEnabled { + [super setUpForHUDStyle:style vibrancyEnabled:vibrancyEnabled]; + + if (!_customizedTintColor) { + if (style == JGProgressHUDStyleDark) { + self.tintColor = [UIColor whiteColor]; + } + else { + self.tintColor = [UIColor blackColor]; + } + _customizedTintColor = NO; + } +} + +- (void)setTintColor:(UIColor *)tintColor { + [super setTintColor:tintColor]; + _customizedTintColor = YES; +} + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDIndeterminateIndicatorView.h b/modules/JGProgressHUD/JGProgressHUDIndeterminateIndicatorView.h new file mode 100644 index 0000000..74594be --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDIndeterminateIndicatorView.h @@ -0,0 +1,25 @@ +// +// JGProgressHUDIndeterminateIndicatorView.h +// JGProgressHUD +// +// Created by Jonas Gessner on 19.07.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "JGProgressHUDIndicatorView.h" +#pragma clang diagnostic pop + +/** + An indeterminate progress indicator showing a @c UIActivityIndicatorView. + */ +@interface JGProgressHUDIndeterminateIndicatorView : JGProgressHUDIndicatorView + +/** + Set the color of the activity indicator view. + @param color The color to apply to the activity indicator view. + */ +- (void)setColor:(UIColor *__nonnull)color; + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDIndeterminateIndicatorView.m b/modules/JGProgressHUD/JGProgressHUDIndeterminateIndicatorView.m new file mode 100644 index 0000000..c9880d4 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDIndeterminateIndicatorView.m @@ -0,0 +1,63 @@ +// +// JGProgressHUDIndeterminateIndicatorView.m +// JGProgressHUD +// +// Created by Jonas Gessner on 19.07.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#import "JGProgressHUDIndeterminateIndicatorView.h" + +#ifndef __IPHONE_13_0 +#define __IPHONE_13_0 130000 +#endif + +@implementation JGProgressHUDIndeterminateIndicatorView + +- (instancetype)init { + UIActivityIndicatorView *activityIndicatorView; + +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_13_0 + if (@available(iOS 13, tvOS 13, *)) { + activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleLarge]; + } + else { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; +#pragma clang diagnostic pop + } +#else + activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; +#endif + + [activityIndicatorView startAnimating]; + + self = [super initWithContentView:activityIndicatorView]; + return self; +} + +- (instancetype)initWithHUDStyle:(JGProgressHUDStyle)style { + return [self init]; +} + +- (void)setUpForHUDStyle:(JGProgressHUDStyle)style vibrancyEnabled:(BOOL)vibrancyEnabled { + [super setUpForHUDStyle:style vibrancyEnabled:vibrancyEnabled]; + + if (style != JGProgressHUDStyleDark) { + self.color = [UIColor blackColor]; + } + else { + self.color = [UIColor whiteColor]; + } +} + +- (void)setColor:(UIColor *)color { + [(UIActivityIndicatorView *)self.contentView setColor:color]; +} + +- (void)updateAccessibility { + self.accessibilityLabel = NSLocalizedString(@"Indeterminate progress",); +} + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDIndicatorView.h b/modules/JGProgressHUD/JGProgressHUDIndicatorView.h new file mode 100644 index 0000000..147616e --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDIndicatorView.h @@ -0,0 +1,61 @@ +// +// JGProgressHUDIndicatorView.h +// JGProgressHUD +// +// Created by Jonas Gessner on 20.7.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#import +#import + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "JGProgressHUD-Defines.h" +#pragma clang diagnostic pop + +/** You may subclass this class to create a custom progress indicator view. */ +@interface JGProgressHUDIndicatorView : UIView + +/** + Designated initializer for this class. + + @param contentView The content view to place on the container view (the container is the JGProgressHUDIndicatorView). + */ +- (instancetype __nonnull)initWithContentView:(UIView *__nullable)contentView; + +/** Use this method to set up the indicator view to fit the HUD style and vibrancy setting. This method is called by @c JGProgressHUD when the indicator view is added to the HUD and when the HUD's @c vibrancyEnabled property changes. This method may be called multiple times with different values. The default implementation does nothing. */ +- (void)setUpForHUDStyle:(JGProgressHUDStyle)style vibrancyEnabled:(BOOL)vibrancyEnabled; + +/** Ranges from 0.0 to 1.0. */ +@property (nonatomic, assign) float progress; + +/** + Adjusts the current progress shown by the receiver, optionally animating the change. + + The current progress is represented by a floating-point value between 0.0 and 1.0, inclusive, where 1.0 indicates the completion of the task. The default value is 0.0. Values less than 0.0 and greater than 1.0 are pinned to those limits. + + @param progress The new progress value. + @param animated YES if the change should be animated, NO if the change should happen immediately. + */ +- (void)setProgress:(float)progress animated:(BOOL)animated; + +/** + The content view which displays the progress. + */ +@property (nonatomic, strong, readonly, nullable) UIView *contentView; + +/** Schedules an accessibility update on the next run loop. */ +- (void)setNeedsAccessibilityUpdate; + +/** + Runs @c updateAccessibility immediately if an accessibility update has been scheduled (through @c setNeedsAccessibilityUpdate) but has not executed yet. + */ +- (void)updateAccessibilityIfNeeded; + +/** + Override to set custom accessibility properties. This method gets called once when initializing the view and after calling @c setNeedsAccessibilityUpdate. + */ +- (void)updateAccessibility; + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDIndicatorView.m b/modules/JGProgressHUD/JGProgressHUDIndicatorView.m new file mode 100755 index 0000000..1a69631 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDIndicatorView.m @@ -0,0 +1,103 @@ +// +// JGProgressHUDIndicatorView.m +// JGProgressHUD +// +// Created by Jonas Gessner on 20.7.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#import "JGProgressHUDIndicatorView.h" +#import "JGProgressHUD.h" + +@interface JGProgressHUDIndicatorView () { + BOOL _accessibilityUpdateScheduled; +} + ++ (void)runBlock:(void (^)(void))block; + +@end + +static void runOnNextRunLoop(void (^block)(void)) { + [[NSRunLoop currentRunLoop] performSelector:@selector(runBlock:) target:[JGProgressHUDIndicatorView class] argument:(id)block order:0 modes:@[NSRunLoopCommonModes]]; +} + +@implementation JGProgressHUDIndicatorView + +#pragma mark - Initializers + +- (instancetype)initWithFrame:(CGRect __unused)frame { + return [self init]; +} + +- (instancetype)init { + return [self initWithContentView:nil]; +} + +- (instancetype)initWithContentView:(UIView *)contentView { + self = [super initWithFrame:(contentView ? contentView.frame : CGRectMake(0.0, 0.0, 50.0, 50.0))]; + if (self) { + self.opaque = NO; + self.backgroundColor = [UIColor clearColor]; + + self.isAccessibilityElement = YES; + [self setNeedsAccessibilityUpdate]; + + if (contentView) { + _contentView = contentView; + + [self addSubview:self.contentView]; + } + } + return self; +} + +#pragma mark - Setup + +- (void)setUpForHUDStyle:(JGProgressHUDStyle)style vibrancyEnabled:(BOOL)vibrancyEnabled {} + +#pragma mark - Accessibility + ++ (void)runBlock:(void (^)(void))block { + if (block != nil) { + block(); + } +} + +- (void)setNeedsAccessibilityUpdate { + if (!_accessibilityUpdateScheduled) { + _accessibilityUpdateScheduled = YES; + + runOnNextRunLoop(^{ + [self updateAccessibilityIfNeeded]; + }); + } +} + +- (void)updateAccessibilityIfNeeded { + if (_accessibilityUpdateScheduled) { + [self updateAccessibility]; + _accessibilityUpdateScheduled = NO; + } +} + +- (void)updateAccessibility { + self.accessibilityLabel = [NSLocalizedString(@"Loading",) stringByAppendingFormat:@" %.f %%", self.progress]; +} + +#pragma mark - Getters & Setters + +- (void)setProgress:(float)progress { + [self setProgress:progress animated:NO]; +} + +- (void)setProgress:(float)progress animated:(__unused BOOL)animated { + if (fequal(self.progress, progress)) { + return; + } + + _progress = progress; + + [self setNeedsAccessibilityUpdate]; +} + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDPieIndicatorView.h b/modules/JGProgressHUD/JGProgressHUDPieIndicatorView.h new file mode 100644 index 0000000..94201cf --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDPieIndicatorView.h @@ -0,0 +1,35 @@ +// +// JGProgressHUDPieIndicatorView.h +// JGProgressHUD +// +// Created by Jonas Gessner on 19.07.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "JGProgressHUDIndicatorView.h" +#pragma clang diagnostic pop + +/** + A pie shaped determinate progress indicator. + */ +@interface JGProgressHUDPieIndicatorView : JGProgressHUDIndicatorView + +/** + Tint color of the Pie. + @attention Custom values need to be set after assigning the indicator view to @c JGProgressHUD's @c indicatorView property. + + @b Default: White for JGProgressHUDStyleDark, otherwise black. + */ +@property (nonatomic, strong, nonnull) UIColor *color; + +/** + The background fill color inside the pie. + @attention Custom values need to be set after assigning the indicator view to @c JGProgressHUD's @c indicatorView property. + + @b Default: Dark gray for JGProgressHUDStyleDark, otherwise light gray. + */ +@property (nonatomic, strong, nonnull) UIColor *fillColor; + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDPieIndicatorView.m b/modules/JGProgressHUD/JGProgressHUDPieIndicatorView.m new file mode 100755 index 0000000..15a65d2 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDPieIndicatorView.m @@ -0,0 +1,171 @@ +// +// JGProgressHUDPieIndicatorView.m +// JGProgressHUD +// +// Created by Jonas Gessner on 19.07.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#import "JGProgressHUDPieIndicatorView.h" + +@interface JGProgressHUDPieIndicatorLayer : CALayer + +@property (nonatomic, assign) float progress; + +@property (nonatomic, weak) UIColor *color; + +@property (nonatomic, weak) UIColor *fillColor; + +@end + +@implementation JGProgressHUDPieIndicatorLayer + +@dynamic progress, color, fillColor; + ++ (BOOL)needsDisplayForKey:(NSString *)key { + return ([key isEqualToString:@"progress"] || [key isEqualToString:@"color"] || [key isEqualToString:@"fillColor"] || [super needsDisplayForKey:key]); +} + +- (id )actionForKey:(NSString *)key { + if ([key isEqualToString:@"progress"]) { + CABasicAnimation *progressAnimation = [CABasicAnimation animation]; + progressAnimation.fromValue = [self.presentationLayer valueForKey:key]; + + progressAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + + return progressAnimation; + } + + return [super actionForKey:key]; +} + +- (void)drawInContext:(CGContextRef)ctx { + UIGraphicsPushContext(ctx); + + CGRect rect = self.bounds; + + CGPoint center = CGPointMake(rect.origin.x + (CGFloat)floor(rect.size.width/2.0), rect.origin.y + (CGFloat)floor(rect.size.height/2.0)); + CGFloat lineWidth = 2.0; + CGFloat radius = (CGFloat)floor(MIN(rect.size.width, rect.size.height)/2.0)-lineWidth; + + UIBezierPath *borderPath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:0.0 endAngle:2.0*(CGFloat)M_PI clockwise:NO]; + + [borderPath setLineWidth:lineWidth]; + + if (self.fillColor) { + [self.fillColor setFill]; + + [borderPath fill]; + } + + [self.color set]; + + [borderPath stroke]; + + if (self.progress > 0.0) { + UIBezierPath *processPath = [UIBezierPath bezierPath]; + + [processPath setLineWidth:radius]; + + CGFloat startAngle = -((CGFloat)M_PI/2.0); + CGFloat endAngle = startAngle + 2.0 * (CGFloat)M_PI * self.progress; + + [processPath addArcWithCenter:center radius:radius/2.0 startAngle:startAngle endAngle:endAngle clockwise:YES]; + + [processPath stroke]; + } + + UIGraphicsPopContext(); +} + +@end + + +@implementation JGProgressHUDPieIndicatorView + +#pragma mark - Initializers + +- (instancetype)init { + self = [super initWithContentView:nil]; + + if (self) { + self.layer.contentsScale = [UIScreen mainScreen].scale; + [self.layer setNeedsDisplay]; + + self.color = [UIColor clearColor]; + self.fillColor = [UIColor clearColor]; + } + + return self; +} + +- (instancetype)initWithHUDStyle:(JGProgressHUDStyle)style { + return [self init]; +} + +- (instancetype)initWithContentView:(UIView *)contentView { + return [self init]; +} + +#pragma mark - Getters & Setters + +- (void)setColor:(UIColor *)tintColor { + if ([tintColor isEqual:self.color]) { + return; + } + + _color = tintColor; + + [(JGProgressHUDPieIndicatorLayer *)self.layer setColor:self.color]; +} + +- (void)setFillColor:(UIColor *)fillColor { + if ([fillColor isEqual:self.fillColor]) { + return; + } + + _fillColor = fillColor; + + [(JGProgressHUDPieIndicatorLayer *)self.layer setFillColor:self.fillColor]; +} + +- (void)setProgress:(float)progress animated:(BOOL)animated { + if (fequal(self.progress, progress)) { + return; + } + + [super setProgress:progress animated:animated]; + + [CATransaction begin]; + [CATransaction setAnimationDuration:(animated ? 0.3 : 0.0)]; + + [(JGProgressHUDPieIndicatorLayer *)self.layer setProgress:progress]; + + [CATransaction commit]; +} + +#pragma mark - Overrides + +- (void)setUpForHUDStyle:(JGProgressHUDStyle)style vibrancyEnabled:(BOOL)vibrancyEnabled { + [super setUpForHUDStyle:style vibrancyEnabled:vibrancyEnabled]; + + if (style == JGProgressHUDStyleDark) { + self.color = [UIColor colorWithWhite:1.0 alpha:1.0]; + self.fillColor = [UIColor colorWithWhite:0.2 alpha:1.0]; + } + else { + self.color = [UIColor blackColor]; + if (style == JGProgressHUDStyleLight) { + self.fillColor = [UIColor colorWithWhite:0.85 alpha:1.0]; + } + else { + self.fillColor = [UIColor colorWithWhite:0.9 alpha:1.0]; + } + } +} + ++ (Class)layerClass { + return [JGProgressHUDPieIndicatorLayer class]; +} + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDRingIndicatorView.h b/modules/JGProgressHUD/JGProgressHUDRingIndicatorView.h new file mode 100644 index 0000000..3306708 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDRingIndicatorView.h @@ -0,0 +1,50 @@ +// +// JGProgressHUDRingIndicatorView.h +// JGProgressHUD +// +// Created by Jonas Gessner on 20.7.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "JGProgressHUDIndicatorView.h" +#pragma clang diagnostic pop + +/** + A ring shaped determinate progress indicator. + */ +@interface JGProgressHUDRingIndicatorView : JGProgressHUDIndicatorView + +/** + Background color of the ring. + @attention Custom values need to be set after assigning the indicator view to @c JGProgressHUD's @c indicatorView property. + + @b Default: Black for JGProgressHUDStyleDark, light gray otherwise. + */ +@property (nonatomic, strong, nonnull) UIColor *ringBackgroundColor; + +/** + Progress color of the progress ring. + @attention Custom values need to be set after assigning the indicator view to @c JGProgressHUD's @c indicatorView property. + + @b Default: White for JGProgressHUDStyleDark, otherwise black. + */ +@property (nonatomic, strong, nonnull) UIColor *ringColor; + +/** + Sets if the progress ring should have a rounded line cap. + + @b Default: NO. + */ +@property (nonatomic, assign) BOOL roundProgressLine; + +/** + Width of the ring. + + @b Default: 3.0. + */ +@property (nonatomic, assign) CGFloat ringWidth; + +@end + diff --git a/modules/JGProgressHUD/JGProgressHUDRingIndicatorView.m b/modules/JGProgressHUD/JGProgressHUDRingIndicatorView.m new file mode 100755 index 0000000..d19d3e8 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDRingIndicatorView.m @@ -0,0 +1,194 @@ +// +// JGProgressHUDRingIndicatorView.m +// JGProgressHUD +// +// Created by Jonas Gessner on 20.7.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#import "JGProgressHUDRingIndicatorView.h" + + +@interface JGProgressHUDRingIndicatorLayer : CALayer + +@property (nonatomic, assign) float progress; + +@property (nonatomic, weak) UIColor *ringColor; +@property (nonatomic, weak) UIColor *ringBackgroundColor; + +@property (nonatomic, assign) BOOL roundProgressLine; + +@property (nonatomic, assign) CGFloat ringWidth; + +@end + +@implementation JGProgressHUDRingIndicatorLayer + +@dynamic progress, ringBackgroundColor, ringColor, ringWidth, roundProgressLine; + ++ (BOOL)needsDisplayForKey:(NSString *)key { + return ([key isEqualToString:@"progress"] || [key isEqualToString:@"ringColor"] || [key isEqualToString:@"ringBackgroundColor"] || [key isEqualToString:@"roundProgressLine"] || [key isEqualToString:@"ringWidth"] || [super needsDisplayForKey:key]); +} + +- (id )actionForKey:(NSString *)key { + if ([key isEqualToString:@"progress"]) { + CABasicAnimation *progressAnimation = [CABasicAnimation animation]; + progressAnimation.fromValue = [self.presentationLayer valueForKey:key]; + + progressAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; + + return progressAnimation; + } + + return [super actionForKey:key]; +} + +- (void)drawInContext:(CGContextRef)ctx { + UIGraphicsPushContext(ctx); + + CGRect rect = self.bounds; + + CGPoint center = CGPointMake(rect.origin.x + (CGFloat)floor(rect.size.width/2.0), rect.origin.y + (CGFloat)floor(rect.size.height/2.0)); + CGFloat lineWidth = self.ringWidth; + CGFloat radius = (CGFloat)floor(MIN(rect.size.width, rect.size.height)/2.0) - lineWidth; + + //Background + [self.ringBackgroundColor setStroke]; + + UIBezierPath *borderPath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:0.0 endAngle:2.0*(CGFloat)M_PI clockwise:NO]; + + [borderPath setLineWidth:lineWidth]; + [borderPath stroke]; + + //Progress + [self.ringColor setStroke]; + + if (self.progress > 0.0) { + UIBezierPath *processPath = [UIBezierPath bezierPath]; + + [processPath setLineWidth:lineWidth]; + [processPath setLineCapStyle:(self.roundProgressLine ? kCGLineCapRound : kCGLineCapSquare)]; + + CGFloat startAngle = -((CGFloat)M_PI / 2.0); + CGFloat endAngle = startAngle + 2.0 * (CGFloat)M_PI * self.progress; + + [processPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES]; + + [processPath stroke]; + } + + UIGraphicsPopContext(); +} + +@end + + +@implementation JGProgressHUDRingIndicatorView + +#pragma mark - Initializers + +- (instancetype)init { + self = [super initWithContentView:nil];; + + if (self) { + self.layer.contentsScale = [UIScreen mainScreen].scale; + [self.layer setNeedsDisplay]; + + self.ringWidth = 3.0; + self.ringColor = [UIColor clearColor]; + self.ringBackgroundColor = [UIColor clearColor]; + } + + return self; +} + +- (instancetype)initWithHUDStyle:(JGProgressHUDStyle)style { + return [self init]; +} + +- (instancetype)initWithContentView:(UIView *)contentView { + return [self init]; +} + +#pragma mark - Getters & Setters + +- (void)setRoundProgressLine:(BOOL)roundProgressLine { + if (roundProgressLine == self.roundProgressLine) { + return; + } + + _roundProgressLine = roundProgressLine; + + [(JGProgressHUDRingIndicatorLayer *)self.layer setRoundProgressLine:self.roundProgressLine]; +} + +- (void)setRingColor:(UIColor *)tintColor { + if ([tintColor isEqual:self.ringColor]) { + return; + } + + _ringColor = tintColor; + + [(JGProgressHUDRingIndicatorLayer *)self.layer setRingColor:self.ringColor]; +} + +- (void)setRingBackgroundColor:(UIColor *)backgroundTintColor { + if ([backgroundTintColor isEqual:self.ringBackgroundColor]) { + return; + } + + _ringBackgroundColor = backgroundTintColor; + + [(JGProgressHUDRingIndicatorLayer *)self.layer setRingBackgroundColor:self.ringBackgroundColor]; +} + +- (void)setRingWidth:(CGFloat)ringWidth { + if (fequal(ringWidth, self.ringWidth)) { + return; + } + + _ringWidth = ringWidth; + + [(JGProgressHUDRingIndicatorLayer *)self.layer setRingWidth:self.ringWidth]; +} + +- (void)setProgress:(float)progress animated:(BOOL)animated { + if (fequal(self.progress, progress)) { + return; + } + + [super setProgress:progress animated:animated]; + + [CATransaction begin]; + [CATransaction setAnimationDuration:(animated ? 0.3 : 0.0)]; + + [(JGProgressHUDRingIndicatorLayer *)self.layer setProgress:self.progress]; + + [CATransaction commit]; +} + +#pragma mark - Overrides + +- (void)setUpForHUDStyle:(JGProgressHUDStyle)style vibrancyEnabled:(BOOL)vibrancyEnabled { + [super setUpForHUDStyle:style vibrancyEnabled:vibrancyEnabled]; + + if (style == JGProgressHUDStyleDark) { + self.ringColor = [UIColor colorWithWhite:1.0 alpha:1.0]; + self.ringBackgroundColor = [UIColor colorWithWhite:0.0 alpha:1.0]; + } + else { + self.ringColor = [UIColor blackColor]; + if (style == JGProgressHUDStyleLight) { + self.ringBackgroundColor = [UIColor colorWithWhite:0.85 alpha:1.0]; + } + else { + self.ringBackgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0]; + } + } +} + ++ (Class)layerClass { + return [JGProgressHUDRingIndicatorLayer class]; +} + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDShadow.h b/modules/JGProgressHUD/JGProgressHUDShadow.h new file mode 100644 index 0000000..105b1fa --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDShadow.h @@ -0,0 +1,37 @@ +// +// JGProgressHUDShadow.h +// JGProgressHUD +// +// Created by Jonas Gessner on 25.09.17. +// Copyright © 2017 Jonas Gessner. All rights reserved. +// + +#import + +/** + A wrapper representing properties of a shadow. + */ +@interface JGProgressHUDShadow : NSObject + +- (instancetype __nonnull)initWithColor:(UIColor *__nonnull)color offset:(CGSize)offset radius:(CGFloat)radius opacity:(float)opacity; + +/** Convenience initializer. */ ++ (instancetype __nonnull)shadowWithColor:(UIColor *__nonnull)color offset:(CGSize)offset radius:(CGFloat)radius opacity:(float)opacity; + +/** + The color of the shadow. Colors created from patterns are currently NOT supported. + */ +@property (nonatomic, strong, readonly, nonnull) UIColor *color; + +/** The shadow offset. */ +@property (nonatomic, assign, readonly) CGSize offset; + +/** The blur radius used to create the shadow. */ +@property (nonatomic, assign, readonly) CGFloat radius; + +/** + The opacity of the shadow. Specifying a value outside the [0,1] range will give undefined results. + */ +@property (nonatomic, assign, readonly) float opacity; + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDShadow.m b/modules/JGProgressHUD/JGProgressHUDShadow.m new file mode 100644 index 0000000..3c67bcd --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDShadow.m @@ -0,0 +1,30 @@ +// +// JGProgressHUDShadow.m +// JGProgressHUD +// +// Created by Jonas Gessner on 25.09.17. +// Copyright © 2017 Jonas Gessner. All rights reserved. +// + +#import "JGProgressHUDShadow.h" + +@implementation JGProgressHUDShadow + ++ (instancetype)shadowWithColor:(UIColor *)color offset:(CGSize)offset radius:(CGFloat)radius opacity:(float)opacity { + return [[self alloc] initWithColor:color offset:offset radius:radius opacity:opacity]; +} + +- (instancetype)initWithColor:(UIColor *)color offset:(CGSize)offset radius:(CGFloat)radius opacity:(float)opacity { + self = [super init]; + + if (self) { + _color = color; + _offset = offset; + _radius = radius; + _opacity = opacity; + } + + return self; +} + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDSuccessIndicatorView.h b/modules/JGProgressHUD/JGProgressHUDSuccessIndicatorView.h new file mode 100644 index 0000000..c1e7fc8 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDSuccessIndicatorView.h @@ -0,0 +1,24 @@ +// +// JGProgressHUDSuccessIndicatorView.h +// JGProgressHUD +// +// Created by Jonas Gessner on 19.08.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wquoted-include-in-framework-header" +#import "JGProgressHUDImageIndicatorView.h" +#pragma clang diagnostic pop + +/** + An image indicator showing a checkmark, representing a failed operation. + */ +@interface JGProgressHUDSuccessIndicatorView : JGProgressHUDImageIndicatorView + +/** + Default initializer for this class. + */ +- (instancetype __nonnull)init; + +@end diff --git a/modules/JGProgressHUD/JGProgressHUDSuccessIndicatorView.m b/modules/JGProgressHUD/JGProgressHUDSuccessIndicatorView.m new file mode 100644 index 0000000..1fcbae2 --- /dev/null +++ b/modules/JGProgressHUD/JGProgressHUDSuccessIndicatorView.m @@ -0,0 +1,56 @@ +// +// JGProgressHUDSuccessIndicatorView.m +// JGProgressHUD +// +// Created by Jonas Gessner on 19.08.14. +// Copyright (c) 2014 Jonas Gessner. All rights reserved. +// + +#import "JGProgressHUDSuccessIndicatorView.h" +#import "JGProgressHUD.h" + +static UIBezierPath *successBezierPath() { + static UIBezierPath *path; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + path = [UIBezierPath bezierPath]; + [path moveToPoint:CGPointMake(1.5, 18)]; + [path addLineToPoint:CGPointMake(11, 28)]; + [path addLineToPoint:CGPointMake(31.5, 5.5)]; + + [path setLineWidth:3]; + [path setLineJoinStyle:kCGLineJoinRound]; + [path setLineCapStyle:kCGLineCapRound]; + }); + + return path; +} + +@implementation JGProgressHUDSuccessIndicatorView + +- (instancetype)initWithContentView:(UIView *__unused)contentView { + UIBezierPath *path = successBezierPath(); + + UIGraphicsBeginImageContextWithOptions(CGSizeMake(33, 33), NO, 0.0); + [[UIColor blackColor] setStroke]; + [path stroke]; + + UIImage *img = [UIGraphicsGetImageFromCurrentImageContext() imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; + + UIGraphicsEndImageContext(); + + self = [super initWithImage:img]; + + return self; +} + +- (instancetype)init { + return [self initWithContentView:nil]; +} + +- (void)updateAccessibility { + self.accessibilityLabel = NSLocalizedString(@"Success",); +} + +@end diff --git a/src/Downloader/Download.h b/src/Downloader/Download.h new file mode 100644 index 0000000..e275ae3 --- /dev/null +++ b/src/Downloader/Download.h @@ -0,0 +1,41 @@ +#import +#import +#import "../../modules/JGProgressHUD/JGProgressHUD.h" + +#import "../InstagramHeaders.h" +#import "../Utils.h" + +#import "Manager.h" + +@interface SCIDownloadPillView : UIView +@property (nonatomic, strong) UIProgressView *progressRing; +@property (nonatomic, strong) UILabel *textLabel; +@property (nonatomic, strong) UILabel *subtitleLabel; +@property (nonatomic, strong) UIButton *cancelButton; +@property (nonatomic, copy) void (^onCancel)(void); + +- (void)showInView:(UIView *)view; +- (void)dismiss; +- (void)dismissAfterDelay:(NSTimeInterval)delay; +- (void)setProgress:(float)progress; +- (void)setText:(NSString *)text; +@end + +@interface SCIDownloadDelegate : NSObject + +typedef NS_ENUM(NSUInteger, DownloadAction) { + share, + quickLook, + saveToPhotos +}; +@property (nonatomic, readonly) DownloadAction action; +@property (nonatomic, readonly) BOOL showProgress; + +@property (nonatomic, strong) SCIDownloadManager *downloadManager; +@property (nonatomic, strong) SCIDownloadPillView *pill; + +- (instancetype)initWithAction:(DownloadAction)action showProgress:(BOOL)showProgress; + +- (void)downloadFileWithURL:(NSURL *)url fileExtension:(NSString *)fileExtension hudLabel:(NSString *)hudLabel; + +@end diff --git a/src/Downloader/Download.m b/src/Downloader/Download.m new file mode 100644 index 0000000..7ab86fd --- /dev/null +++ b/src/Downloader/Download.m @@ -0,0 +1,261 @@ +#import "Download.h" +#import + +#pragma mark - SCIDownloadPillView + +@implementation SCIDownloadPillView + +- (instancetype)init { + self = [super initWithFrame:CGRectZero]; + if (self) { + self.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.92]; + self.layer.cornerRadius = 20; + self.clipsToBounds = YES; + self.alpha = 0; + + // Circular progress (using a small CAShapeLayer ring) + _progressRing = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault]; + _progressRing.progressTintColor = [UIColor systemBlueColor]; + _progressRing.trackTintColor = [UIColor colorWithWhite:0.3 alpha:1.0]; + _progressRing.translatesAutoresizingMaskIntoConstraints = NO; + _progressRing.layer.cornerRadius = 2; + _progressRing.clipsToBounds = YES; + [self addSubview:_progressRing]; + + // Text + _textLabel = [[UILabel alloc] init]; + _textLabel.text = @"Downloading 0%"; + _textLabel.textColor = [UIColor whiteColor]; + _textLabel.font = [UIFont systemFontOfSize:13 weight:UIFontWeightSemibold]; + _textLabel.translatesAutoresizingMaskIntoConstraints = NO; + [self addSubview:_textLabel]; + + // Subtitle + _subtitleLabel = [[UILabel alloc] init]; + _subtitleLabel.text = @"Tap to cancel"; + _subtitleLabel.textColor = [UIColor colorWithWhite:0.6 alpha:1.0]; + _subtitleLabel.font = [UIFont systemFontOfSize:10 weight:UIFontWeightRegular]; + _subtitleLabel.textAlignment = NSTextAlignmentCenter; + _subtitleLabel.translatesAutoresizingMaskIntoConstraints = NO; + [self addSubview:_subtitleLabel]; + + // Tap gesture for cancel + UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap)]; + [self addGestureRecognizer:tap]; + + // Layout: [progress bar] + // [text centered] + // [subtitle centered] + [NSLayoutConstraint activateConstraints:@[ + [_progressRing.topAnchor constraintEqualToAnchor:self.topAnchor constant:12], + [_progressRing.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:16], + [_progressRing.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-16], + [_progressRing.heightAnchor constraintEqualToConstant:4], + + [_textLabel.topAnchor constraintEqualToAnchor:_progressRing.bottomAnchor constant:6], + [_textLabel.centerXAnchor constraintEqualToAnchor:self.centerXAnchor], + + [_subtitleLabel.topAnchor constraintEqualToAnchor:_textLabel.bottomAnchor constant:2], + [_subtitleLabel.centerXAnchor constraintEqualToAnchor:self.centerXAnchor], + [_subtitleLabel.bottomAnchor constraintEqualToAnchor:self.bottomAnchor constant:-10], + ]]; + } + return self; +} + +- (void)handleTap { + if (self.onCancel) self.onCancel(); +} + +- (void)showInView:(UIView *)view { + [self removeFromSuperview]; + self.translatesAutoresizingMaskIntoConstraints = NO; + [view addSubview:self]; + + [NSLayoutConstraint activateConstraints:@[ + [self.topAnchor constraintEqualToAnchor:view.safeAreaLayoutGuide.topAnchor constant:4], + [self.centerXAnchor constraintEqualToAnchor:view.centerXAnchor], + [self.widthAnchor constraintGreaterThanOrEqualToConstant:160], + [self.widthAnchor constraintLessThanOrEqualToConstant:220], + ]]; + + [UIView animateWithDuration:0.25 animations:^{ + self.alpha = 1; + }]; +} + +- (void)dismiss { + [UIView animateWithDuration:0.2 animations:^{ + self.alpha = 0; + } completion:^(BOOL finished) { + [self removeFromSuperview]; + }]; +} + +- (void)dismissAfterDelay:(NSTimeInterval)delay { + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + [self dismiss]; + }); +} + +- (void)setProgress:(float)progress { + [self.progressRing setProgress:progress animated:YES]; +} + +- (void)setText:(NSString *)text { + self.textLabel.text = text; +} + +@end + + +#pragma mark - SCIDownloadDelegate + +@implementation SCIDownloadDelegate + +- (instancetype)initWithAction:(DownloadAction)action showProgress:(BOOL)showProgress { + self = [super init]; + + if (self) { + _action = action; + _showProgress = showProgress; + self.downloadManager = [[SCIDownloadManager alloc] initWithDelegate:self]; + } + + return self; +} + +- (void)downloadFileWithURL:(NSURL *)url fileExtension:(NSString *)fileExtension hudLabel:(NSString *)hudLabel { + // Dismiss any existing pill + [self.pill dismiss]; + + self.pill = [[SCIDownloadPillView alloc] init]; + + if (hudLabel) { + [self.pill setText:hudLabel]; + } + + if (!self.showProgress) { + self.pill.progressRing.hidden = YES; + self.pill.subtitleLabel.text = nil; + } + + __weak typeof(self) weakSelf = self; + self.pill.onCancel = ^{ + [weakSelf.downloadManager cancelDownload]; + }; + + UIViewController *topVC = topMostController(); + UIView *hostView = topVC.view; + if (!hostView) hostView = [UIApplication sharedApplication].keyWindow; + if (!hostView) { + NSLog(@"[SCInsta] Download: No valid view"); + return; + } + [self.pill showInView:hostView]; + + NSLog(@"[SCInsta] Download: Will start download for url \"%@\" with file extension: \".%@\"", url, fileExtension); + [self.downloadManager downloadFileWithURL:url fileExtension:fileExtension]; +} + +- (void)downloadDidStart { + NSLog(@"[SCInsta] Download: Download started"); +} + +- (void)downloadDidCancel { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.pill setText:@"Cancelled"]; + self.pill.subtitleLabel.text = nil; + self.pill.progressRing.hidden = YES; + [self.pill dismissAfterDelay:0.8]; + }); + NSLog(@"[SCInsta] Download: Download cancelled"); +} + +- (void)downloadDidProgress:(float)progress { + if (self.showProgress) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.pill setProgress:progress]; + [self.pill setText:[NSString stringWithFormat:@"Downloading %d%%", (int)(progress * 100)]]; + }); + } +} + +- (void)downloadDidFinishWithError:(NSError *)error { + dispatch_async(dispatch_get_main_queue(), ^{ + if (error && error.code != NSURLErrorCancelled) { + NSLog(@"[SCInsta] Download: Download failed with error: \"%@\"", error); + [self.pill setText:@"Download failed"]; + self.pill.subtitleLabel.text = nil; + self.pill.progressRing.hidden = YES; + [self.pill dismissAfterDelay:2.0]; + } + }); +} + +- (void)downloadDidFinishWithFileURL:(NSURL *)fileURL { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.pill dismiss]; + + NSLog(@"[SCInsta] Download: Finished with url: \"%@\"", [fileURL absoluteString]); + + switch (self.action) { + case share: + [SCIUtils showShareVC:fileURL]; + break; + + case quickLook: + [SCIUtils showQuickLookVC:@[fileURL]]; + break; + + case saveToPhotos: { + [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) { + if (status != PHAuthorizationStatusAuthorized) { + dispatch_async(dispatch_get_main_queue(), ^{ + [SCIUtils showErrorHUDWithDescription:@"Photo library access denied"]; + }); + return; + } + + [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ + NSString *ext = [[fileURL pathExtension] lowercaseString]; + BOOL isVideo = [@[@"mp4", @"mov", @"m4v"] containsObject:ext]; + + if (isVideo) { + PHAssetCreationRequest *req = [PHAssetCreationRequest creationRequestForAsset]; + PHAssetResourceCreationOptions *opts = [[PHAssetResourceCreationOptions alloc] init]; + opts.shouldMoveFile = YES; + [req addResourceWithType:PHAssetResourceTypeVideo fileURL:fileURL options:opts]; + req.creationDate = [NSDate date]; + } else { + PHAssetCreationRequest *req = [PHAssetCreationRequest creationRequestForAsset]; + PHAssetResourceCreationOptions *opts = [[PHAssetResourceCreationOptions alloc] init]; + opts.shouldMoveFile = YES; + [req addResourceWithType:PHAssetResourceTypePhoto fileURL:fileURL options:opts]; + req.creationDate = [NSDate date]; + } + } completionHandler:^(BOOL success, NSError *error) { + dispatch_async(dispatch_get_main_queue(), ^{ + if (success) { + SCIDownloadPillView *donePill = [[SCIDownloadPillView alloc] init]; + donePill.progressRing.hidden = YES; + donePill.subtitleLabel.text = nil; + [donePill setText:@"Saved to Photos"]; + UIView *hostView = topMostController().view; + if (hostView) { + [donePill showInView:hostView]; + [donePill dismissAfterDelay:1.5]; + } + } else { + [SCIUtils showErrorHUDWithDescription:@"Failed to save to Photos"]; + } + }); + }]; + }]; + break; + } + } + }); +} + +@end diff --git a/src/Downloader/Manager.h b/src/Downloader/Manager.h new file mode 100644 index 0000000..5d67b67 --- /dev/null +++ b/src/Downloader/Manager.h @@ -0,0 +1,32 @@ +#import +#import + +@protocol SCIDownloadDelegateProtocol + +// Methods +- (void)downloadDidStart; +- (void)downloadDidCancel; +- (void)downloadDidProgress:(float)progress; +- (void)downloadDidFinishWithError:(NSError *)error; +- (void)downloadDidFinishWithFileURL:(NSURL *)fileURL; + +@end + +@interface SCIDownloadManager : NSObject + +// Properties +@property (nonatomic, weak) id delegate; +@property (nonatomic, strong) NSURLSession *session; +@property (nonatomic, strong) NSURLSessionDownloadTask *task; +@property (nonatomic, strong) NSString *fileExtension; + +// Methods +- (instancetype)initWithDelegate:(id)downloadDelegate; + +- (void)downloadFileWithURL:(NSURL *)url fileExtension:(NSString *)fileExtension; + +- (void)cancelDownload; + +- (NSURL *)moveFileToCacheDir:(NSURL *)oldPath; + +@end \ No newline at end of file diff --git a/src/Downloader/Manager.m b/src/Downloader/Manager.m new file mode 100644 index 0000000..6d394ce --- /dev/null +++ b/src/Downloader/Manager.m @@ -0,0 +1,75 @@ +#import "Manager.h" + +@implementation SCIDownloadManager + +- (instancetype)initWithDelegate:(id)downloadDelegate { + self = [super init]; + + if (self) { + self.delegate = downloadDelegate; + } + + return self; +} + +- (void)downloadFileWithURL:(NSURL *)url fileExtension:(NSString *)fileExtension { + // Properties + self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil]; + self.task = [self.session downloadTaskWithURL:url]; + + // Default to jpg if no other reasonable length extension is provided + self.fileExtension = [fileExtension length] >= 3 ? fileExtension : @"jpg"; + + [self.task resume]; + [self.delegate downloadDidStart]; +} + +- (void)cancelDownload { + [self.task cancel]; + [self.delegate downloadDidCancel]; +} + +// URLSession methods +- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { + NSLog(@"Task wrote %lld bytes of %lld bytes", bytesWritten, totalBytesExpectedToWrite); + + float progress = (float)totalBytesWritten / (float)totalBytesExpectedToWrite; + + [self.delegate downloadDidProgress:progress]; +} + +- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { + // Move downloaded file to cache directory + NSURL *finalLocation = [self moveFileToCacheDir:location]; + + [self.delegate downloadDidFinishWithFileURL:finalLocation]; +} + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { + NSLog(@"Task completed with error: %@", error); + + [self.delegate downloadDidFinishWithError:error]; +} + +// Rename downloaded file & move from documents dir -> cache dir +- (NSURL *)moveFileToCacheDir:(NSURL *)oldPath { + NSFileManager *fileManager = [NSFileManager defaultManager]; + + NSString *cacheDirectoryPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject; + NSURL *newPath = [[NSURL fileURLWithPath:cacheDirectoryPath] URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", NSUUID.UUID.UUIDString, self.fileExtension]]; + + NSLog(@"[SCInsta] Download Handler: Moving file from: %@ to: %@", oldPath.absoluteString, newPath.absoluteString); + + // Move file to cache directory + NSError *fileMoveError; + [fileManager moveItemAtURL:oldPath toURL:newPath error:&fileMoveError]; + + if (fileMoveError) { + NSLog(@"[SCInsta] Download Handler: Error while moving file: %@", oldPath.absoluteString); + NSLog(@"[SCInsta] Download Handler: %@", fileMoveError); + } + + return newPath; +} + +@end \ No newline at end of file diff --git a/src/Features/Confirm/CallConfirm.x b/src/Features/Confirm/CallConfirm.x new file mode 100644 index 0000000..48f78a5 --- /dev/null +++ b/src/Features/Confirm/CallConfirm.x @@ -0,0 +1,25 @@ +#import "../../Utils.h" + +%hook IGDirectThreadCallButtonsCoordinator +// Voice Call +- (void)_didTapAudioButton:(id)arg1 { + if ([SCIUtils getBoolPref:@"call_confirm"]) { + NSLog(@"[SCInsta] Call confirm triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } else { + return %orig; + } +} + +// Video Call +- (void)_didTapVideoButton:(id)arg1 { + if ([SCIUtils getBoolPref:@"call_confirm"]) { + NSLog(@"[SCInsta] Call confirm triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } else { + return %orig; + } +} +%end \ No newline at end of file diff --git a/src/Features/Confirm/ChangeThemeConfirm.x b/src/Features/Confirm/ChangeThemeConfirm.x new file mode 100644 index 0000000..d9b4645 --- /dev/null +++ b/src/Features/Confirm/ChangeThemeConfirm.x @@ -0,0 +1,35 @@ +#import "../../InstagramHeaders.h" +#import "../../Utils.h" + +%hook IGDirectThreadThemePickerViewController +- (void)themeNewPickerSectionController:(id)arg1 didSelectTheme:(id)arg2 atIndex:(NSInteger)arg3 { + if ([SCIUtils getBoolPref:@"change_direct_theme_confirm"]) { + NSLog(@"[SCInsta] Confirm change direct theme triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } else { + return %orig; + } +} +- (void)themePickerSectionController:(id)arg1 didSelectThemeId:(id)arg2 { + if ([SCIUtils getBoolPref:@"change_direct_theme_confirm"]) { + NSLog(@"[SCInsta] Confirm change direct theme triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } else { + return %orig; + } +} +%end + +%hook IGDirectThreadThemeKitSwift.IGDirectThreadThemePreviewController +- (void)primaryButtonTapped { + if ([SCIUtils getBoolPref:@"change_direct_theme_confirm"]) { + NSLog(@"[SCInsta] Confirm change direct theme triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } else { + return %orig; + } +} +%end \ No newline at end of file diff --git a/src/Features/Confirm/DMAudioMsgConfirm.x b/src/Features/Confirm/DMAudioMsgConfirm.x new file mode 100644 index 0000000..38760c2 --- /dev/null +++ b/src/Features/Confirm/DMAudioMsgConfirm.x @@ -0,0 +1,38 @@ +#import "../../Utils.h" + +// Legacy hook (for non ai voices interface) +%hook IGDirectThreadViewController +- (void)voiceRecordViewController:(id)arg1 didRecordAudioClipWithURL:(id)arg2 waveform:(id)arg3 duration:(CGFloat)arg4 entryPoint:(NSInteger)arg5 { + if ([SCIUtils getBoolPref:@"voice_message_confirm"]) { + NSLog(@"[SCInsta] DM audio message confirm triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } else { + return %orig; + } +} +%end + +// Workaround until I can figure out how to stop long press recording from automatically sending +%hook IGDirectComposer +- (void)_didLongPressVoiceMessage:(id)arg1 { + if ([SCIUtils getBoolPref:@"voice_message_confirm"]) { + return; + } else { + return %orig; + } +} +%end + +// Demangled name: IGDirectAIVoiceUIKit.CompactBarContentView +%hook _TtC20IGDirectAIVoiceUIKitP33_5754F7617E0D924F9A84EFA352BBD29A21CompactBarContentView +- (void)didTapSend { + if ([SCIUtils getBoolPref:@"voice_message_confirm"]) { + NSLog(@"[SCInsta] DM audio message confirm triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } else { + return %orig; + } +} +%end \ No newline at end of file diff --git a/src/Features/Confirm/FollowConfirm.x b/src/Features/Confirm/FollowConfirm.x new file mode 100644 index 0000000..52ca1c3 --- /dev/null +++ b/src/Features/Confirm/FollowConfirm.x @@ -0,0 +1,103 @@ +#import "../../Utils.h" +#import "../../InstagramHeaders.h" + +//////////////////////////////////////////////////////// + +#define CONFIRMFOLLOW(orig) \ + if ([SCIUtils getBoolPref:@"follow_confirm"]) { \ + NSLog(@"[SCInsta] Confirm follow triggered"); \ + \ + [SCIUtils showConfirmation:^(void) { orig; }]; \ + } \ + else { \ + return orig; \ + } \ + +//////////////////////////////////////////////////////// + +// Follow button on profile page +%hook IGFollowController +- (void)_didPressFollowButton { + // Get user follow status (check if already following user) + NSInteger UserFollowStatus = self.user.followStatus; + + // Only show confirm dialog if user is not following + if (UserFollowStatus == 2) { + CONFIRMFOLLOW(%orig); + } + else { + return %orig; + } +} +%end + +// Follow button on discover people page +%hook IGDiscoverPeopleButtonGroupView +- (void)_onFollowButtonTapped:(id)arg1 { + CONFIRMFOLLOW(%orig); +} +- (void)_onFollowingButtonTapped:(id)arg1 { + CONFIRMFOLLOW(%orig); +} +%end + +// Suggested for you (home feed & profile) follow button +%hook IGHScrollAYMFCell +- (void)_didTapAYMFActionButton { + CONFIRMFOLLOW(%orig); +} +%end +%hook IGHScrollAYMFActionButton +- (void)_didTapTextActionButton { + CONFIRMFOLLOW(%orig); +} +%end + +// Follow button on reels +%hook IGUnifiedVideoFollowButton +- (void)_hackilyHandleOurOwnButtonTaps:(id)arg1 event:(id)arg2 { + CONFIRMFOLLOW(%orig); +} +%end + +// Follow text on profile (when collapsed into top bar) +%hook IGProfileViewController +- (void)navigationItemsControllerDidTapHeaderFollowButton:(id)arg1 { + CONFIRMFOLLOW(%orig); +} +%end + +// Follow button on suggested friends (in story section) +%hook IGStorySectionController +- (void)followButtonTapped:(id)arg1 cell:(id)arg2 { + CONFIRMFOLLOW(%orig); +} +%end + +// Follow all button in group chats (3+ members) people view +static void (*orig_listSectionController)(id, SEL, id, id); + +static void hooked_listSectionController(id self, SEL _cmd, id arg1, id arg2) { + if ([SCIUtils getBoolPref:@"follow_confirm"]) { + + [SCIUtils showConfirmation:^{ + orig_listSectionController(self, _cmd, arg1, arg2); + }]; + + return; + } + + orig_listSectionController(self, _cmd, arg1, arg2); +} + +%ctor { + Class cls = objc_getClass("IGDirectDetailMembersKit.IGDirectThreadDetailsMembersListViewController"); + if (!cls) return; + + MSHookMessageEx( + cls, + @selector(listSectionController:didTapHeaderButtonWithViewModel:), + (IMP)hooked_listSectionController, + (IMP *)&orig_listSectionController + ); +} diff --git a/src/Features/Confirm/FollowRequestConfirm.xm b/src/Features/Confirm/FollowRequestConfirm.xm new file mode 100644 index 0000000..6bcc424 --- /dev/null +++ b/src/Features/Confirm/FollowRequestConfirm.xm @@ -0,0 +1,22 @@ +#import "../../Utils.h" + +%hook IGPendingRequestView +- (void)_onApproveButtonTapped { + if ([SCIUtils getBoolPref:@"follow_request_confirm"]) { + NSLog(@"[SCInsta] Confirm follow request triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } else { + return %orig; + } +} +- (void)_onIgnoreButtonTapped { + if ([SCIUtils getBoolPref:@"follow_request_confirm"]) { + NSLog(@"[SCInsta] Confirm follow request triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } else { + return %orig; + } +} +%end \ No newline at end of file diff --git a/src/Features/Confirm/LikeConfirm.x b/src/Features/Confirm/LikeConfirm.x new file mode 100644 index 0000000..4d7e868 --- /dev/null +++ b/src/Features/Confirm/LikeConfirm.x @@ -0,0 +1,150 @@ +#import "../../Utils.h" + +/////////////////////////////////////////////////////////// + +// Confirmation handlers + +#define CONFIRMPOSTLIKE(orig) \ + if ([SCIUtils getBoolPref:@"like_confirm"]) { \ + NSLog(@"[SCInsta] Confirm post like triggered"); \ + \ + [SCIUtils showConfirmation:^(void) { orig; }]; \ + } \ + else { \ + return orig; \ + } \ + +#define CONFIRMREELSLIKE(orig) \ + if ([SCIUtils getBoolPref:@"like_confirm_reels"]) { \ + NSLog(@"[SCInsta] Confirm reels like triggered"); \ + \ + [SCIUtils showConfirmation:^(void) { orig; }]; \ + } \ + else { \ + return orig; \ + } \ + +/////////////////////////////////////////////////////////// + +// Liking posts +%hook IGUFIButtonBarView +- (void)_onLikeButtonPressed:(id)arg1 { + CONFIRMPOSTLIKE(%orig); +} +%end +%hook IGFeedPhotoView +- (void)_onDoubleTap:(id)arg1 { + CONFIRMPOSTLIKE(%orig); +} +%end +%hook IGVideoPlayerOverlayContainerView +- (void)_handleDoubleTapGesture:(id)arg1 { + CONFIRMPOSTLIKE(%orig); +} +%end + +// Liking reels +%hook IGSundialViewerVideoCell +- (void)controlsOverlayControllerDidTapLikeButton:(id)arg1 { + CONFIRMREELSLIKE(%orig); +} +- (void)controlsOverlayControllerDidLongPressLikeButton:(id)arg1 gestureRecognizer:(id)arg2 { + CONFIRMREELSLIKE(%orig); +} +- (void)gestureController:(id)arg1 didObserveDoubleTap:(id)arg2 { + CONFIRMREELSLIKE(%orig); +} +%end +%hook IGSundialViewerPhotoCell +- (void)controlsOverlayControllerDidTapLikeButton:(id)arg1 { + CONFIRMREELSLIKE(%orig); +} +- (void)gestureController:(id)arg1 didObserveDoubleTap:(id)arg2 { + CONFIRMREELSLIKE(%orig); +} +%end +%hook IGSundialViewerCarouselCell +- (void)controlsOverlayControllerDidTapLikeButton:(id)arg1 { + CONFIRMREELSLIKE(%orig); +} +- (void)gestureController:(id)arg1 didObserveDoubleTap:(id)arg2 { + CONFIRMREELSLIKE(%orig); +} +%end + +// Liking comments +%hook IGCommentCellController +- (void)commentCell:(id)arg1 didTapLikeButton:(id)arg2 { + CONFIRMPOSTLIKE(%orig); +} +- (void)commentCell:(id)arg1 didTapLikedByButtonForUser:(id)arg2 { + CONFIRMPOSTLIKE(%orig); +} +- (void)commentCellDidLongPressOnLikeButton:(id)arg1 { + CONFIRMPOSTLIKE(%orig); +} +- (void)commentCellDidEndLongPressOnLikeButton:(id)arg1 { + CONFIRMPOSTLIKE(%orig); +} +- (void)commentCellDidDoubleTap:(id)arg1 { + CONFIRMPOSTLIKE(%orig); +} +%end +%hook IGFeedItemPreviewCommentCell +- (void)_didTapLikeButton { + CONFIRMPOSTLIKE(%orig); +} +%end + +// Liking stories +%hook IGStoryFullscreenDefaultFooterView +- (void)_handleLikeTapped { + CONFIRMPOSTLIKE(%orig); +} +- (void)_likeTapped { + CONFIRMPOSTLIKE(%orig); +} +- (void)inputView:(id)arg1 didTapLikeButton:(id)arg2 { + CONFIRMPOSTLIKE(%orig); +} + +// For some stupid reason they removed the "liketapped" methods on newer Instagram versions +// Now we have to do a shitty workaround instead :( +// Works 99% of the time, but sometimes clicks get through directly to the like button (somehow) +- (void)layoutSubviews { + %orig; + + if (![SCIUtils getBoolPref:@"like_confirm"]) return; + + UIButton *likeButton = [self valueForKey:@"likeButton"]; + if (!likeButton) return; + + // 129115 = L(12) I(9) K(11) E(5) + static NSInteger kOverlayTag = 129115; + if ([likeButton viewWithTag:kOverlayTag]) return; + + UIButton *overlay = [UIButton buttonWithType:UIButtonTypeCustom]; + overlay.tag = kOverlayTag; + overlay.frame = likeButton.bounds; + overlay.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + [overlay addTarget:self action:@selector(overlayTapped:) forControlEvents:UIControlEventTouchUpInside]; + [likeButton addSubview:overlay]; +} + +%new - (void)overlayTapped:(UIButton *)overlay { + UIButton *likeButton = (UIButton *)overlay.superview; + + [SCIUtils showConfirmation:^{ + dispatch_async(dispatch_get_main_queue(), ^{ + [likeButton sendActionsForControlEvents:UIControlEventTouchUpInside]; + }); + }]; +} +%end + +// DM like button (seems to be hidden) +%hook IGDirectThreadViewController +- (void)_didTapLikeButton { + CONFIRMPOSTLIKE(%orig); +} +%end \ No newline at end of file diff --git a/src/Features/Confirm/PostCommentConfirm.x b/src/Features/Confirm/PostCommentConfirm.x new file mode 100644 index 0000000..65a667f --- /dev/null +++ b/src/Features/Confirm/PostCommentConfirm.x @@ -0,0 +1,13 @@ +#import "../../Utils.h" + +%hook IGCommentComposer.IGCommentComposerController +- (void)onSendButtonTap { + if ([SCIUtils getBoolPref:@"post_comment_confirm"]) { + NSLog(@"[SCInsta] Confirm post comment triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } else { + return %orig; + } +} +%end \ No newline at end of file diff --git a/src/Features/Confirm/ShhConfirm.x b/src/Features/Confirm/ShhConfirm.x new file mode 100644 index 0000000..50dd6b9 --- /dev/null +++ b/src/Features/Confirm/ShhConfirm.x @@ -0,0 +1,33 @@ +#import "../../Utils.h" + +%hook IGDirectThreadViewController +- (void)swipeableScrollManagerDidEndDraggingAboveSwipeThreshold:(id)arg1 { + if ([SCIUtils getBoolPref:@"shh_mode_confirm"]) { + NSLog(@"[SCInsta] Confirm shh mode triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } else { + return %orig; + } +} + +- (void)shhModeTransitionButtonDidTap:(id)arg1 { + if ([SCIUtils getBoolPref:@"shh_mode_confirm"]) { + NSLog(@"[SCInsta] Confirm shh mode triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } else { + return %orig; + } +} + +- (void)messageListViewControllerDidToggleShhMode:(id)arg1 { + if ([SCIUtils getBoolPref:@"shh_mode_confirm"]) { + NSLog(@"[SCInsta] Confirm shh mode triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } else { + return %orig; + } +} +%end \ No newline at end of file diff --git a/src/Features/Confirm/StickerInteractConfirm.x b/src/Features/Confirm/StickerInteractConfirm.x new file mode 100644 index 0000000..a7f1c28 --- /dev/null +++ b/src/Features/Confirm/StickerInteractConfirm.x @@ -0,0 +1,13 @@ +#import "../../Utils.h" + +%hook IGStoryViewerTapTarget +- (void)_didTap:(id)arg1 forEvent:(id)arg2 { + if ([SCIUtils getBoolPref:@"sticker_interact_confirm"]) { + NSLog(@"[SCInsta] Confirm sticker interact triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } else { + return %orig; + } +} +%end \ No newline at end of file diff --git a/src/Features/Experimental/EnableAllTextEffects.xm_ b/src/Features/Experimental/EnableAllTextEffects.xm_ new file mode 100644 index 0000000..cdb0810 --- /dev/null +++ b/src/Features/Experimental/EnableAllTextEffects.xm_ @@ -0,0 +1,35 @@ +#import "../../Utils.h" +#import "../../InstagramHeaders.h" + +%hook IGStoryTextEntryControlsOverlayView +- (void)didMoveToSuperview { + %orig; + + if ([SCIUtils getBoolPref:@"enable_hidden_texteffectsstyles"]) { + + // Clear previous option values + [self.animationTypes removeAllObjects]; + [self.effectTypes removeAllObjects]; + + // Generate new animation values + // * Animation effects <= 9 are invalid + // * Animations past the maximum count (changing each app update) will crash the app when selected + for (int i = 10; i <= 76; i++) { + [self.animationTypes addObject:@(i)]; + } + + // Generate new effect values + // * Effects past the maximum count (changing each app update) will gracefully just do nothing + for (int i = 0; i <= 84; i++) { + [self.effectTypes addObject:@(i)]; + } + + // Refresh option picker + if ([self respondsToSelector:@selector(reloadData)]) { + NSLog(@"[SCInsta] Enable all text effects: Reloading data..."); + [self reloadData]; + } + + } +} +%end \ No newline at end of file diff --git a/src/Features/Experimental/EnableHomecomingUI.x_ b/src/Features/Experimental/EnableHomecomingUI.x_ new file mode 100644 index 0000000..ac94607 --- /dev/null +++ b/src/Features/Experimental/EnableHomecomingUI.x_ @@ -0,0 +1,26 @@ +%hook IGSundialFeedViewController +- (_Bool)_isHomecomingEnabled { + return true; +} +- (_Bool)_isHomeComingHomeFeed { + return true; +} +%end + +%hook IGSundialViewerManagedRequestItem +- (id)initWithMedia:(id)media launcherSet:(id)set isHomecomingEnabled:(_Bool)enabled { + return %orig(media, set, true); +} +%end + +%hook IGTabBarViewControllerManager + - (_Bool)_isHomecomingEnabled { + return true; +} +%end + +%hook IGMainAppSurfaceIntent ++ (id)resolvedHomeAppSurfaceIntentWithIsHomecomingEnabled:(_Bool)enabled { + return %orig(true); +} +%end \ No newline at end of file diff --git a/src/Features/Feed/DisableFeedAutoplay.x b/src/Features/Feed/DisableFeedAutoplay.x new file mode 100644 index 0000000..1edf42f --- /dev/null +++ b/src/Features/Feed/DisableFeedAutoplay.x @@ -0,0 +1,10 @@ +#import "../../Utils.h" + +// Demangled name: IGFeedPlayback.IGFeedPlaybackStrategy +%hook _TtC14IGFeedPlayback22IGFeedPlaybackStrategy +- (id)initWithShouldDisableAutoplay:(_Bool)autoplay { + if ([SCIUtils getBoolPref:@"disable_feed_autoplay"]) return %orig(true); + + return %orig(autoplay); +} +%end \ No newline at end of file diff --git a/src/Features/Feed/HideFeedItems.xm b/src/Features/Feed/HideFeedItems.xm new file mode 100644 index 0000000..60eb85f --- /dev/null +++ b/src/Features/Feed/HideFeedItems.xm @@ -0,0 +1,334 @@ +#import "../../Utils.h" +#import "../../InstagramHeaders.h" + +static NSArray *removeItemsInList(NSArray *list, BOOL isFeed) { + NSArray *originalObjs = list; + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (id obj in originalObjs) { + // Remove suggested posts + if (isFeed && [SCIUtils getBoolPref:@"no_suggested_post"]) { + + // Posts + if ( + ([obj isKindOfClass:%c(IGMedia)] && [((IGMedia *)obj).explorePostInFeed isEqual:@YES]) + || ([obj isKindOfClass:%c(IGFeedGroupHeaderViewModel)] && [[obj title] isEqualToString:@"Suggested Posts"]) + ) { + NSLog(@"[SCInsta] Removing suggested posts"); + + continue; + } + + // Suggested stories (carousel) + if ([obj isKindOfClass:%c(IGInFeedStoriesTrayModel)]) { + NSLog(@"[SCInsta] Hiding suggested stories carousel"); + + continue; + } + + } + + // Remove suggested reels (carousel) + if (isFeed && [SCIUtils getBoolPref:@"no_suggested_reels"]) { + if ([obj isKindOfClass:%c(IGFeedScrollableClipsModel)]) { + NSLog(@"[SCInsta] Hiding suggested reels carousel"); + + continue; + } + } + + // Remove suggested for you (accounts) + if ([SCIUtils getBoolPref:@"no_suggested_account"]) { + + // Feed + if (isFeed && [obj isKindOfClass:%c(IGHScrollAYMFModel)]) { + NSLog(@"[SCInsta] Hiding accounts suggested for you (feed)"); + + continue; + } + + // Reels + if ([obj isKindOfClass:%c(IGSuggestedUserInReelsModel)]) { + NSLog(@"[SCInsta] Hiding accounts suggested for you (reels)"); + + continue; + } + } + + // Remove suggested threads posts + if ([SCIUtils getBoolPref:@"no_suggested_threads"]) { + + // Feed (carousel) + if (isFeed) { + if ([obj isKindOfClass:%c(IGBloksFeedUnitModel)] || [obj isKindOfClass:objc_getClass("IGThreadsInFeedModels.IGThreadsInFeedModel")]) { + NSLog(@"[SCInsta] Hiding suggested threads posts (carousel)"); + + continue; + } + } + + // Reels + if ([obj isKindOfClass:%c(IGSundialNetegoItem)]) { + NSLog(@"[SCInsta] Hiding suggested threads posts (reels)"); + + continue; + } + + } + + // Remove story tray + if (isFeed && [SCIUtils getBoolPref:@"hide_stories_tray"]) { + if ([obj isKindOfClass:%c(IGStoryDataController)]) { + NSLog(@"[SCInsta] Hiding stories tray"); + + continue; + } + } + + // Hide entire feed + if (isFeed && [SCIUtils getBoolPref:@"hide_entire_feed"]) { + if ([obj isKindOfClass:%c(IGPostCreationManager)] || [obj isKindOfClass:%c(IGMedia)] || [obj isKindOfClass:%c(IGEndOfFeedDemarcatorModel)] || [obj isKindOfClass:%c(IGSpinnerLabelViewModel)]) { + NSLog(@"[SCInsta] Hiding entire feed"); + + continue; + } + } + + // Remove ads + if ([SCIUtils getBoolPref:@"hide_ads"]) { + if ( + ([obj isKindOfClass:%c(IGFeedItem)] && ([obj isSponsored] || [obj isSponsoredApp])) + || ([obj isKindOfClass:%c(IGDiscoveryGridItem)] && [[obj model] isKindOfClass:%c(IGAdItem)]) + || [obj isKindOfClass:%c(IGAdItem)] + ) { + NSLog(@"[SCInsta] Removing ads"); + + continue; + } + } + + [filteredObjs addObject:obj]; + } + + return [filteredObjs copy]; +} + +// Suggested posts/reels +%hook IGMainFeedListAdapterDataSource +- (NSArray *)objectsForListAdapter:(id)arg1 { + NSArray *filteredObjs = removeItemsInList(%orig, YES); + + // Remove loading spinner at end of feed (if 5 or less items in feed) + NSUInteger arrayLength = [filteredObjs count]; + + if (arrayLength <= 5) { + filteredObjs = [filteredObjs filteredArrayUsingPredicate: + [NSPredicate predicateWithBlock:^BOOL(id obj, NSDictionary *bindings) { + return ![obj isKindOfClass:[%c(IGSpinnerLabelViewModel) class]]; + }] + ]; + } + + return filteredObjs; +} +%end +%hook IGSundialFeedDataSource +- (NSArray *)objectsForListAdapter:(id)arg1 { + NSArray *filteredList = removeItemsInList(%orig, NO); + + if ([SCIUtils getBoolPref:@"prevent_doom_scrolling"]) { + double reelCount = [SCIUtils getDoublePref:@"doom_scrolling_reel_count"]; + return [filteredList subarrayWithRange:NSMakeRange(0, MIN((NSUInteger)reelCount, filteredList.count))]; + } + + return filteredList; +} +%end +%hook IGContextualFeedViewController +- (NSArray *)objectsForListAdapter:(id)arg1 { + if ([SCIUtils getBoolPref:@"hide_ads"]) { + return removeItemsInList(%orig, NO); + } + + return %orig; +} +%end +%hook IGVideoFeedViewController +- (NSArray *)objectsForListAdapter:(id)arg1 { + if ([SCIUtils getBoolPref:@"hide_ads"]) { + return removeItemsInList(%orig, NO); + } + + return %orig; +} +%end +%hook IGChainingFeedViewController +- (NSArray *)objectsForListAdapter:(id)arg1 { + if ([SCIUtils getBoolPref:@"hide_ads"]) { + return removeItemsInList(%orig, NO); + } + + return %orig; +} +%end +%hook IGStoryAdPool +- (id)initWithUserSession:(id)arg1 { + if ([SCIUtils getBoolPref:@"hide_ads"]) { + NSLog(@"[SCInsta] Removing ads"); + + return nil; + } + + return %orig; +} +%end +%hook IGStoryAdsManager +- (id)initWithUserSession:(id)arg1 storyViewerLoggingContext:(id)arg2 storyFullscreenSectionLoggingContext:(id)arg3 viewController:(id)arg4 { + if ([SCIUtils getBoolPref:@"hide_ads"]) { + NSLog(@"[SCInsta] Removing ads"); + + return nil; + } + + return %orig; +} +%end +%hook IGStoryAdsFetcher +- (id)initWithUserSession:(id)arg1 delegate:(id)arg2 { + if ([SCIUtils getBoolPref:@"hide_ads"]) { + NSLog(@"[SCInsta] Removing ads"); + + return nil; + } + + return %orig; +} +%end +// IG 148.0 +%hook IGStoryAdsResponseParser +- (id)parsedObjectFromResponse:(id)arg1 { + if ([SCIUtils getBoolPref:@"hide_ads"]) { + NSLog(@"[SCInsta] Removing ads"); + + return nil; + } + + return %orig; +} +- (id)initWithReelStore:(id)arg1 { + if ([SCIUtils getBoolPref:@"hide_ads"]) { + NSLog(@"[SCInsta] Removing ads"); + + return nil; + } + + return %orig; +} +%end +%hook IGStoryAdsOptInTextView +- (id)initWithBrandedContentStyledString:(id)arg1 sponsoredPostLabel:(id)arg2 { + if ([SCIUtils getBoolPref:@"hide_ads"]) { + NSLog(@"[SCInsta] Removing ads"); + + return nil; + } + + return %orig; +} +%end +%hook IGSundialAdsResponseParser +- (id)parsedObjectFromResponse:(id)arg1 { + if ([SCIUtils getBoolPref:@"hide_ads"]) { + NSLog(@"[SCInsta] Removing ads"); + + return nil; + } + + return %orig; +} +- (id)initWithMediaStore:(id)arg1 userStore:(id)arg2 { + if ([SCIUtils getBoolPref:@"hide_ads"]) { + NSLog(@"[SCInsta] Removing ads"); + + return nil; + } + + return %orig; +} +%end +// "Sponsored" posts on discover/search page +%hook IGExploreListKitDataSource +- (NSArray *)objectsForListAdapter:(id)arg1 { + if ([SCIUtils getBoolPref:@"hide_ads"]) { + return removeItemsInList(%orig, NO); + } + + return %orig; +} +%end +// Demangled name: IGExploreViewControllerSwift.IGExploreListKitDataSource +%hook _TtC28IGExploreViewControllerSwift26IGExploreListKitDataSource +- (NSArray *)objectsForListAdapter:(id)arg1 { + if ([SCIUtils getBoolPref:@"hide_ads"]) { + return removeItemsInList(%orig, NO); + } + + return %orig; +} +%end + +// Hide shopping carousel in reel comments +// Demangled name: IGCommentThreadCommerceCarouselPill.IGCommentThreadCommerceCarousel +%hook _TtC35IGCommentThreadCommerceCarouselPill31IGCommentThreadCommerceCarousel +- (id)initWithFrame:(CGRect)frame pillText:(id)text pillStyle:(NSInteger)style { + if ([SCIUtils getBoolPref:@"hide_ads"]) { + return nil; + } + + return %orig(frame, text, style); +} +%end + +// Hide suggested search/shopping on reels + +// Demangled name: IGShoppableEverythingCommon.IGRapEntrypointResolver +%hook _TtC27IGShoppableEverythingCommon23IGRapEntrypointResolver +- (id)initWithLauncherSet:(id)arg1 { + if ([SCIUtils getBoolPref:@"hide_ads"]) { + return nil; + } + + return %orig(arg1); +} +%end +// Demangled name: IGSundialOrganicCTAContainerView.IGSundialOrganicCTAContainerView +%hook _TtC32IGSundialOrganicCTAContainerView32IGSundialOrganicCTAContainerView +- (void)didMoveToWindow { + %orig; + + if ([SCIUtils getBoolPref:@"hide_ads"]) { + [self removeFromSuperview]; + } +} +%end + + +// Hide "suggested for you" text at end of feed +%hook IGEndOfFeedDemarcatorCellTopOfFeed +- (void)configureWithViewConfig:(id)arg1 { + %orig; + + if ([SCIUtils getBoolPref:@"no_suggested_post"]) { + NSLog(@"[SCInsta] Hiding end of feed message"); + + // Hide suggested for you text + UILabel *_titleLabel = MSHookIvar(self, "_titleLabel"); + + if (_titleLabel != nil) { + [_titleLabel setText:@""]; + } + } + + return; +} +%end \ No newline at end of file diff --git a/src/Features/Feed/HideStoryTray.x b/src/Features/Feed/HideStoryTray.x new file mode 100644 index 0000000..c0257c5 --- /dev/null +++ b/src/Features/Feed/HideStoryTray.x @@ -0,0 +1,15 @@ +#import "../../Utils.h" +#import "../../InstagramHeaders.h" + +// Disable story data source +%hook IGMainStoryTrayDataSource +- (id)initWithUserSession:(id)arg1 { + if ([SCIUtils getBoolPref:@"hide_stories_tray"]) { + NSLog(@"[SCInsta] Hiding story tray"); + + return nil; + } + + return %orig; +} +%end \ No newline at end of file diff --git a/src/Features/Feed/HideThreads.x b/src/Features/Feed/HideThreads.x new file mode 100644 index 0000000..5059fae --- /dev/null +++ b/src/Features/Feed/HideThreads.x @@ -0,0 +1,15 @@ +#import "../../Utils.h" +#import "../../InstagramHeaders.h" + +// Remove suggested threads posts (carousel, under suggested posts in feed) +%hook BKBloksViewHelper +- (id)initWithObjectSet:(id)arg1 bloksData:(id)arg2 delegate:(id)arg3 { + if ([SCIUtils getBoolPref:@"no_suggested_threads"]) { + NSLog(@"[SCInsta] Hiding threads posts"); + + return nil; + } + + return %orig; +} +%end \ No newline at end of file diff --git a/src/Features/General/CopyDescription.x b/src/Features/General/CopyDescription.x new file mode 100644 index 0000000..2dafcc6 --- /dev/null +++ b/src/Features/General/CopyDescription.x @@ -0,0 +1,50 @@ +#import "../../Utils.h" +#import "../../InstagramHeaders.h" +#import "../../../modules/JGProgressHUD/JGProgressHUD.h" + +%hook IGCoreTextView +- (void)didMoveToSuperview { + %orig; + + if ([SCIUtils getBoolPref:@"copy_description"]) { + [self addHandleLongPress]; + } + + return; +} +%new - (void)addHandleLongPress { + UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; + longPress.minimumPressDuration = 0.5; + [self addGestureRecognizer:longPress]; +} + +%new - (void)handleLongPress:(UILongPressGestureRecognizer *)sender { + if (sender.state != UIGestureRecognizerStateBegan) return; + + // Remove hashtags at end of string + NSRegularExpression *regex = + [NSRegularExpression regularExpressionWithPattern:@"\\s*(?:#[^\\s]+\\s*)+$" + options:0 + error:nil]; + + NSString *result = [[regex stringByReplacingMatchesInString:self.text + options:0 + range:NSMakeRange(0, self.text.length) + withTemplate:@""] + stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; + + NSLog(@"[SCInsta] Copying description"); + + // Copy text to system clipboard + UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; + pasteboard.string = result; + + // Notify user + JGProgressHUD *HUD = [[JGProgressHUD alloc] init]; + HUD.textLabel.text = @"Copied text to clipboard"; + HUD.indicatorView = [[JGProgressHUDSuccessIndicatorView alloc] init]; + + [HUD showInView:topMostController().view]; + [HUD dismissAfterDelay:2.0]; +} +%end \ No newline at end of file diff --git a/src/Features/General/DetailedColorPicker.xm b/src/Features/General/DetailedColorPicker.xm new file mode 100644 index 0000000..7bceaa5 --- /dev/null +++ b/src/Features/General/DetailedColorPicker.xm @@ -0,0 +1,87 @@ +#import "../../InstagramHeaders.h" +#import "../../Utils.h" + +%hook IGStoryEyedropperToggleButton +- (void)didMoveToWindow { + %orig; + + if ([SCIUtils getBoolPref:@"detailed_color_picker"]) { + [self addLongPressGestureRecognizer]; + } + + return; +} + +%new - (void)addLongPressGestureRecognizer { + if ([self.gestureRecognizers count] == 0) { + NSLog(@"[SCInsta] Adding color eyedroppper long press gesture recognizer"); + + UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; + longPress.minimumPressDuration = 0.25; + [self addGestureRecognizer:longPress]; + } +} +%new - (void)handleLongPress:(UILongPressGestureRecognizer *)sender { + if (sender.state != UIGestureRecognizerStateBegan) return; + + UIColorPickerViewController *colorPickerController = [[UIColorPickerViewController alloc] init]; + + colorPickerController.delegate = (id)self; // cast to suppress warnings + colorPickerController.title = @"Select color"; + colorPickerController.modalPresentationStyle = UIModalPresentationPopover; + colorPickerController.supportsAlpha = NO; + colorPickerController.selectedColor = self.color; + + UIViewController *presentingVC = [SCIUtils nearestViewControllerForView:self]; + + if (presentingVC != nil) { + [presentingVC presentViewController:colorPickerController animated:YES completion:nil]; + } +} + +// UIColorPickerViewControllerDelegate Protocol +%new - (void)colorPickerViewController:(UIColorPickerViewController *)viewController + didSelectColor:(UIColor *)color + continuously:(BOOL)continuously +{ + NSLog(@"[SCInsta] Selected text color: %@", color); + + UIColor *opaque = [color colorWithAlphaComponent:1.0]; + self.color = opaque; + + [self setPushedDown:YES]; + + // Trigger change for text color + id presentingVC = [SCIUtils nearestViewControllerForView:self]; + + if ([presentingVC isKindOfClass:%c(IGStoryTextEntryViewController)]) { + [presentingVC textViewControllerDidUpdateWithColor:color colorSource:0]; + } + else if ( + [presentingVC isKindOfClass:%c(IGStoryCreationDrawingViewController)] + || [presentingVC isKindOfClass:%c(IGDirectThreadViewDrawingViewController)] + ) { + [presentingVC drawingControls:nil didSelectColor:color]; + } + +}; +%end + +%hook IGStoryColorPaletteView +- (CGFloat)collectionView:(id)view didSelectItemAtIndexPath:(id)index { + UIView *colorPickingControls = [self superview]; + + if ( + [colorPickingControls isKindOfClass:%c(IGStoryColorPickingControls)] + || [colorPickingControls isKindOfClass:%c(IGDirectThreadColorPickingControls)] + ) { + IGStoryEyedropperToggleButton *_eyedropperToggleButton = MSHookIvar(colorPickingControls, "_eyedropperToggleButton"); + + if (_eyedropperToggleButton != nil) { + [_eyedropperToggleButton setPushedDown:NO]; + } + } + + return %orig; +} +%end \ No newline at end of file diff --git a/src/Features/General/DisableScrollingReels.x b/src/Features/General/DisableScrollingReels.x new file mode 100644 index 0000000..a103328 --- /dev/null +++ b/src/Features/General/DisableScrollingReels.x @@ -0,0 +1,36 @@ +#import "../../Utils.h" +#import "../../InstagramHeaders.h" + +%hook IGUnifiedVideoCollectionView +- (void)didMoveToWindow { + %orig; + + if ([SCIUtils getBoolPref:@"disable_scrolling_reels"]) { + NSLog(@"[SCInsta] Disabling scrolling reels"); + + self.scrollEnabled = false; + } +} + +- (void)setScrollEnabled:(BOOL)arg1 { + if ([SCIUtils getBoolPref:@"disable_scrolling_reels"]) { + NSLog(@"[SCInsta] Disabling scrolling reels"); + + return %orig(NO); + } + + return %orig; +} +%end + +// Disable auto-scrolling reels +%hook _TtC19IGSundialAutoScroll19IGSundialAutoScroll +- (void)setIsEnabled:(BOOL)enabled { + if ([SCIUtils getBoolPref:@"disable_scrolling_reels"]) { + %orig(NO); + } + else { + %orig(enabled); + } +} +%end \ No newline at end of file diff --git a/src/Features/General/HideExploreGrid.xm b/src/Features/General/HideExploreGrid.xm new file mode 100644 index 0000000..732c587 --- /dev/null +++ b/src/Features/General/HideExploreGrid.xm @@ -0,0 +1,31 @@ +#import "../../Utils.h" +#import "../../InstagramHeaders.h" + +%hook IGExploreGridViewController +- (void)viewDidLoad { + if ([SCIUtils getBoolPref:@"hide_explore_grid"]) { + NSLog(@"[SCInsta] Hiding explore grid"); + + [[self view] removeFromSuperview]; + + return; + } + + return %orig; +} +%end + +%hook IGExploreViewController +- (void)viewDidLoad { + %orig; + + if ([SCIUtils getBoolPref:@"hide_explore_grid"]) { + NSLog(@"[SCInsta] Hiding explore grid"); + + IGShimmeringGridView *shimmeringGridView = MSHookIvar(self, "_shimmeringGridView"); + if (shimmeringGridView != nil) { + [shimmeringGridView removeFromSuperview]; + } + } +} +%end \ No newline at end of file diff --git a/src/Features/General/HideFriendsMap.x b/src/Features/General/HideFriendsMap.x new file mode 100644 index 0000000..ffb95e2 --- /dev/null +++ b/src/Features/General/HideFriendsMap.x @@ -0,0 +1,33 @@ +#import "../../Utils.h" + +%hook IGDirectNotesTrayRowCell +- (id)listAdapterObjects { + NSArray *originalObjs = %orig(); + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (id obj in originalObjs) { + BOOL shouldHide = NO; + + if ([SCIUtils getBoolPref:@"hide_friends_map"]) { + + if ([obj isKindOfClass:%c(IGDirectNotesTrayUserViewModel)]) { + + if ([[obj valueForKey:@"notePk"] isEqualToString:@"friends_map"]) { + NSLog(@"[SCInsta] Hiding friends map"); + + shouldHide = YES; + } + + } + + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + } + + return [filteredObjs copy]; +} +%end \ No newline at end of file diff --git a/src/Features/General/HideMetaAI.xm b/src/Features/General/HideMetaAI.xm new file mode 100644 index 0000000..1134ca9 --- /dev/null +++ b/src/Features/General/HideMetaAI.xm @@ -0,0 +1,572 @@ +#import "../../Utils.h" +#import "../../InstagramHeaders.h" + +// Direct + +// Meta AI button functionality on direct search bar +%hook IGDirectInboxViewController +- (void)searchBarMetaAIButtonTappedOnSearchBar:(id)arg1 { + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) +{ + NSLog(@"[SCInsta] Hiding meta ai: direct search bar functionality"); + + return; + } + + return %orig; +} +%end + +// AI agents in direct new message view +%hook IGDirectRecipientGenAIBotsResult +- (id)initWithGenAIBots:(id)arg1 lastFetchedTimestamp:(id)arg2 { + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) +{ + NSLog(@"[SCInsta] Hiding meta ai: direct recipient ai agents"); + + return nil; + } + + return %orig; +} +%end + +// Meta AI in message composer +%hook IGDirectCommandSystemListViewController +- (id)objectsForListAdapter:(id)arg1 { + NSArray *originalObjs = %orig(); + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (id obj in originalObjs) { + BOOL shouldHide = NO; + + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + + if ([obj isKindOfClass:%c(IGDirectCommandSystemViewModel)]) { + IGDirectCommandSystemViewModel *typedObj = (IGDirectCommandSystemViewModel *)obj; + IGDirectCommandSystemRow *cmdSystemRow = (IGDirectCommandSystemRow *)[typedObj row]; + + IGDirectCommandSystemResult *_commandResult_command = MSHookIvar(cmdSystemRow, "_commandResult_command"); + + if (_commandResult_command != nil) { + + // Meta AI + if ([[_commandResult_command title] isEqualToString:@"Meta AI"]) { + NSLog(@"[SCInsta] Hiding meta ai: direct message composer suggestion"); + + shouldHide = YES; + } + + // Meta AI (Imagine) + else if ([[_commandResult_command commandString] hasPrefix:@"/imagine"]) { + NSLog(@"[SCInsta] Hiding meta ai: direct message composer /imagine suggestion"); + + shouldHide = YES; + } + + } + } + + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + } + + return [filteredObjs copy]; +} +%end + +// Suggested AI chats in direct inbox header +%hook IGDirectInboxNavigationHeaderView +- (id)initWithFrame:(CGRect)arg1 + title:(id)arg2 + titleView:(id)arg3 + directInboxConfig:(IGDirectInboxConfig *)config + userSession:(id)arg5 + loggingDelegate:(id)arg6 +{ + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + NSLog(@"[SCInsta] Hiding meta ai: suggested ai chats in direct inbox header"); + + @try { + [config setValue:0 forKey:@"shouldShowAIChatsEntrypointButton"]; + } + @catch (NSException *exception) { + NSLog(@"[SCInsta] WARNING: %@\n\nFull object: %@", exception.reason, config); + } + } + + return %orig(arg1, arg2, arg3, [config copy], arg5, arg6); +} +%end + +// Meta AI "imagine" in media picker +%hook IGDirectMediaPickerViewController +- (id)initWithUserSession:(id)arg1 + config:(IGDirectMediaPickerConfig *)config + capabilities:(id)arg3 + threadMetadata:(id)arg4 + messageSender:(id)arg5 + threadAnalyticsLogger:(id)arg6 + multimodalPerfLogger:(id)arg7 + localSendSpeedLogger:(id)arg8 + sendAttributionFactory:(id)arg9 +{ + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + NSLog(@"[SCInsta] Hiding meta ai: imagine tile in media picker"); + + @try { + IGDirectMediaPickerGalleryConfig *galleryConfig = [config valueForKey:@"galleryConfig"]; + + [galleryConfig setValue:0 forKey:@"isImagineEntryPointEnabled"]; + } + @catch (NSException *exception) { + NSLog(@"[SCInsta] WARNING: %@\n\nFull object: %@", exception.reason, config); + } + } + + return %orig(arg1, [config copy], arg3, arg4, arg5, arg6, arg7, arg8, arg9); +} +%end + +// Write with meta ai in message composer +%hook IGDirectComposer +- (id)initWithLayoutSpecProvider:(id)arg1 + userLauncherSetProviding:(id)arg2 + config:(IGDirectComposerConfig *)config + style:(id)arg4 + text:(id)arg5 +{ + return %orig(arg1, arg2, [self patchConfig:config], arg4, arg5); +} + +- (id)initWithLayoutSpecProvider:(id)arg1 + userLauncherSetProviding:(id)arg2 + config:(IGDirectComposerConfig *)config + style:(id)arg4 + text:(id)arg5 + shouldUpdateModeLater:(BOOL)arg6 +{ + return %orig(arg1, arg2, [self patchConfig:config], arg4, arg5, arg6); +} + +- (void)setConfig:(IGDirectComposerConfig *)config { + %orig([self patchConfig:config]); + + return; +} + +%new - (IGDirectComposerConfig *)patchConfig:(IGDirectComposerConfig *)config { + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + + NSLog(@"[SCInsta] Hiding meta ai: reconfiguring direct composer"); + + // writeWithAIEnabled + @try { + [config setValue:0 forKey:@"writeWithAIEnabled"]; + } + @catch (NSException *exception) { + NSLog(@"[SCInsta] WARNING: %@\n\nFull object: %@", exception.reason, config); + } + + } + + return [config copy]; +} +%end + +// Direct sticker tray picker view +%hook IGStickerTrayListAdapterDataSource +- (id)objectsForListAdapter:(id)arg1 { + NSArray *originalObjs = %orig(); + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (id obj in originalObjs) { + BOOL shouldHide = NO; + + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + + if ([obj isKindOfClass:%c(IGDirectUnifiedComposerAIStickerModel)]) { + NSLog(@"[SCInsta] Hiding meta ai: AI stickers option in sticker view"); + + shouldHide = YES; + } + + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + } + + return [filteredObjs copy]; +} +%end + +// Long press menu on messages +// Demangled name: IGDirectMessageMenuConfiguration.IGDirectMessageMenuConfiguration +%hook _TtC32IGDirectMessageMenuConfiguration32IGDirectMessageMenuConfiguration ++ (id)menuConfigurationWithEligibleOptions:(id)options + messageViewModel:(id)arg2 + contentType:(id)arg3 + isSticker:(_Bool)arg4 + isMusicSticker:(_Bool)arg5 + directNuxManager:(id)arg6 + sessionUserDefaults:(id)arg7 + launcherSet:(id)arg8 + userSession:(id)arg9 + tapHandler:(id)arg10 +{ + // 31: Restyle + // 41: Make AI image + NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)", @[ @(31), @(41) ]]; + NSArray *newOptions = [options filteredArrayUsingPredicate:predicate]; + + return %orig([newOptions copy], arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); +} +%end + +// Expanded in-chat photo UI +// Demangled name: IGDirectAggregatedMediaViewerComponentsSwift.IGDirectAggregatedMediaViewerViewControllerTitleViewModelObject +%hook _TtC44IGDirectAggregatedMediaViewerComponentsSwift63IGDirectAggregatedMediaViewerViewControllerTitleViewModelObject +- (id)initWithAuthorProfileImage:(id)arg1 + authorUsername:(id)arg2 + canForward:(_Bool)arg3 + canSave:(_Bool)arg4 + canAddToStory:(_Bool)arg5 + canShowAIRestyle:(_Bool)arg6 + canUnsend:(_Bool)arg7 + canReport:(_Bool)arg8 + displayConfig:(id)arg9 + isPending:(_Bool)arg10 + isMoreMenuListStyle:(_Bool)arg11 + senderIsCurrentUser:(_Bool)arg12 + shouldHideInfoViews:(_Bool)arg13 + subtitle:(id)arg14 + entryPoint:(long long)arg15 + canTapAuthor:(_Bool)arg16 +{ + BOOL showAiRestyle = [SCIUtils getBoolPref:@"hide_meta_ai"] ? false : arg6; + + return %orig(arg1, arg2, arg3, arg4, arg5, showAiRestyle, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16); +} +%end + +// AI generated DM channel themes +%hook IGDirectThreadThemePickerViewController +- (id)objectsForListAdapter:(id)arg1 { + NSArray *originalObjs = %orig(); + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (id obj in originalObjs) { + BOOL shouldHide = NO; + + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + + if ( + [obj isKindOfClass:%c(IGDirectThreadThemePickerOption)] + && [[obj valueForKey:@"themeId"] isEqualToString:@"direct_ai_theme_creation"] + ) { + NSLog(@"[SCInsta] Hiding meta ai: AI generated DM channel themes"); + + shouldHide = YES; + } + + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + } + + return [filteredObjs copy]; +} +%end + +// "Click to summarize" pill under DM navigation bar +%hook IGDirectThreadViewMetaAISummaryFeatureController +- (id)initWithUserSession:(id)arg1 mutableStateProvider:(id)arg2 threadViewControllerFeatureDelegate:(id)arg3 presentingViewController:(id)arg4 { + return nil; +} +%end + +///////////////////////////////////////////////////////////////////////////// + +// Explore + +// Meta AI explore search summary +%hook IGDiscoveryListKitGQLDataSource +- (id)objectsForListAdapter:(id)arg1 { + NSArray *originalObjs = %orig(); + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (id obj in originalObjs) { + BOOL shouldHide = NO; + + // Meta AI summary + if ([obj isKindOfClass:%c(IGSearchMetaAIHCMModel)]) { + + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + NSLog(@"[SCInsta] Hiding explore meta ai search summary"); + + shouldHide = YES; + } + + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + + } + + return [filteredObjs copy]; +} +%end + +// Meta AI search bar ring button +%hook IGSearchBarDonutButton +- (void)didMoveToWindow { + %orig; + + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + [self removeFromSuperview]; + } +} +%end + +///////////////////////////////////////////////////////////////////////////// + +// Reels/Sundial + +// Suggested AI searches in comment section +%hook IGCommentThreadAICarousel +- (id)initWithLauncherSet:(id)arg1 hasSearchPrefix:(BOOL)arg2 { + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + NSLog(@"[SCInsta] Hiding meta ai: suggested ai searches comment carousel"); + + return nil; + } + + return %orig; +} +%end + +%hook _TtC34IGCommentThreadAICarouselPillSwift30IGCommentThreadAICarouselSwift +- (id)initWithLauncherSet:(id)arg1 hasSearchPrefix:(BOOL)arg2 { + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + NSLog(@"[SCInsta] Hiding meta ai: suggested ai searches comment carousel"); + + return nil; + } + + return %orig; +} +%end + +///////////////////////////////////////////////////////////////////////////// + +// Story + +// AI images "add to story" suggestion +// Demangled name: IGGalleryDestinationToolbar.IGGalleryDestinationToolbarView +%hook _TtC27IGGalleryDestinationToolbar31IGGalleryDestinationToolbarView +- (void)setTools:(id)tools { + NSArray *newTools = [tools copy]; + + NSLog(@"[SCInsta] Hiding meta ai: ai images add to story suggestion"); + + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)", @[ @(10), @(11) ]]; + newTools = [tools filteredArrayUsingPredicate:predicate]; + } + + %orig(newTools); + + return; +} +%end + +// AI generated fonts in text entry +%hook IGCreationTextToolView +- (id)initWithMenuConfiguration:(unsigned long long)configuration userSession:(id)session creationEntryPoint:(long long)point isAIFontsEnabled:(_Bool)enabled genAINuxManager:(id)manager showFontBadge:(_Bool)badge { + return %orig(configuration, session, point, [SCIUtils getBoolPref:@"hide_meta_ai"] ? false : enabled, manager, badge); +} +%end + +// Text rewrite in text entry +%hook IGStoryTextMentionLocationPickerView +- (id)initWithIsTextRewriteEnabled:(_Bool)arg1 + isImageRewriteEnabled:(_Bool)arg2 + isStackedToolSelectorEnabled:(_Bool)arg3 + isMentionLocationVisible:(_Bool)arg4 + isEnabledForFeedCaption:(_Bool)arg5 + isFeedEntryPoint:(_Bool)arg6 +{ + _Bool isTextRewriteEnabled = [SCIUtils getBoolPref:@"hide_meta_ai"] ? false : arg1; + _Bool isImageRewriteEnabled = [SCIUtils getBoolPref:@"hide_meta_ai"] ? false : arg2; + + return %orig(isTextRewriteEnabled, isImageRewriteEnabled, arg3, arg4, arg5, arg6); +} +%end + +// "Imagine background" in story editor vertical action bar +%hook _TtC17IGCreationOSSwift19IGCreationHeaderBar +- (void)setButtons:(id)buttons maxItems:(NSInteger)max { + NSArray *filteredObjs = buttons; + + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + filteredObjs = [filteredObjs filteredArrayUsingPredicate: + [NSPredicate predicateWithBlock:^BOOL(IGCreationActionBarLabeledButton *obj, NSDictionary *bindings) { + + return !( + obj.button + && [((IGCreationActionBarButton *)obj.button).accessibilityIdentifier isEqualToString:@"contextual-background"] + ); + + }] + ]; + } + + %orig(filteredObjs, max); +} +%end + +///////////////////////////////////////////////////////////////////////////// + +// Other + +// Meta AI-branded search bars +%hook IGSearchBar +- (id)initWithConfig:(IGSearchBarConfig *)config { + return %orig([self sanitizePlaceholderForConfig:config]); +} + +- (id)initWithConfig:(IGSearchBarConfig *)config userSession:(id)arg2 { + return %orig([self sanitizePlaceholderForConfig:config], arg2); +} + +- (void)setConfig:(IGSearchBarConfig *)config { + %orig([self sanitizePlaceholderForConfig:config]); + + return; +} + +%new - (IGSearchBarConfig *)sanitizePlaceholderForConfig:(IGSearchBarConfig *)config { + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + + NSLog(@"[SCInsta] Hiding meta ai: reconfiguring search bar"); + + NSString *placeholder = [config valueForKey:@"placeholder"]; + + if ([placeholder containsString:@"Meta AI"]) { + + // placeholder + @try { + [config setValue:@"Search" forKey:@"placeholder"]; + } + @catch (NSException *exception) { + NSLog(@"[SCInsta] WARNING: %@\n\nFull object: %@", exception.reason, config); + } + + // shouldAnimatePlaceholder + @try { + [config setValue:0 forKey:@"shouldAnimatePlaceholder"]; + } + @catch (NSException *exception) { + NSLog(@"[SCInsta] WARNING: %@\n\nFull object: %@", exception.reason, config); + } + + NSLog(@"[SCInsta] Changed search bar placeholder from: \"%@\" to \"%@\"", placeholder, [config valueForKey:@"placeholder"]); + + // leftIconStyle + @try { + [config setValue:0 forKey:@"leftIconStyle"]; + } + @catch (NSException *exception) { + NSLog(@"[SCInsta] WARNING: %@\n\nFull object: %@", exception.reason, config); + } + + // rightButtonStyle + @try { + [config setValue:0 forKey:@"rightButtonStyle"]; + } + @catch (NSException *exception) { + NSLog(@"[SCInsta] WARNING: %@\n\nFull object: %@", exception.reason, config); + } + + } + + } + + return [config copy]; +} +%end + +// Themed in-app buttons +%hook IGTapButton +- (void)didMoveToWindow { + %orig; + + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + + // Hide buttons that are associated with meta ai + if ([self.accessibilityIdentifier containsString:@"meta_ai"]) { + NSLog(@"[SCInsta] Hiding meta ai: meta ai associated button"); + + [self removeFromSuperview]; + } + + } +} +%end + +// Home feed meta ai button +%hook IGFloatingActionButton.IGFloatingActionButton +- (void)didMoveToSuperview { + %orig; + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + [self removeFromSuperview]; + NSLog(@"[SCInsta] Hiding meta ai: home feed meta ai button"); + } +} +%end + +// Share menu recipients +%hook IGDirectRecipientListViewController +- (id)objectsForListAdapter:(id)arg1 { + NSArray *originalObjs = %orig(); + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (id obj in originalObjs) { + BOOL shouldHide = NO; + + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + if ([obj isKindOfClass:%c(IGDirectRecipientCellViewModel)]) { + + // Meta AI (catch-all) + if ([[[obj recipient] threadName] isEqualToString:@"Meta AI"]) { + NSLog(@"[SCInsta] Hiding meta ai suggested as recipient (share menu)"); + + shouldHide = YES; + } + + } + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + + } + + return [filteredObjs copy]; +} +%end \ No newline at end of file diff --git a/src/Features/General/HideTrendingSearches.x b/src/Features/General/HideTrendingSearches.x new file mode 100644 index 0000000..c30de0c --- /dev/null +++ b/src/Features/General/HideTrendingSearches.x @@ -0,0 +1,16 @@ +#import "../../Utils.h" +#import "../../InstagramHeaders.h" + +%hook IGDSSegmentedPillBarView +- (void)didMoveToWindow { + %orig; + + if ([[self delegate] isKindOfClass:%c(IGSearchTypeaheadNavigationHeaderView)]) { + if ([SCIUtils getBoolPref:@"hide_trending_searches"]) { + NSLog(@"[SCInsta] Hiding trending searches"); + + [self removeFromSuperview]; + } + } +} +%end \ No newline at end of file diff --git a/src/Features/General/Navigation.xm b/src/Features/General/Navigation.xm new file mode 100644 index 0000000..ccf9d04 --- /dev/null +++ b/src/Features/General/Navigation.xm @@ -0,0 +1,100 @@ +#import "../../Utils.h" + +BOOL isSurfaceShown(IGMainAppSurfaceIntent *surface) { + BOOL isShown = YES; + + // Feed + if ([[surface tabStringFromSurfaceIntent] isEqualToString:@"FEED"] && [SCIUtils getBoolPref:@"hide_feed_tab"]) { + isShown = NO; + } + + // Reels + else if ([[surface tabStringFromSurfaceIntent] isEqualToString:@"CLIPS"] && [SCIUtils getBoolPref:@"hide_reels_tab"]) { + isShown = NO; + } + + // Explore + else if ([[surface tabStringFromSurfaceIntent] isEqualToString:@"SEARCH"] && [SCIUtils getBoolPref:@"hide_explore_tab"]) { + isShown = NO; + } + + // Create + else if ([(NSNumber *)[surface valueForKey:@"_subtype"] unsignedIntegerValue] == 3 && [SCIUtils getBoolPref:@"hide_create_tab"]) { + isShown = NO; + } + + return isShown; +} + +NSArray *filterSurfacesArray(NSArray *surfaces) { + NSMutableArray *filteredSurfaces = [NSMutableArray array]; + + for (IGMainAppSurfaceIntent *surface in surfaces) { + if (![surface isKindOfClass:%c(IGMainAppSurfaceIntent)]) break; + + if (isSurfaceShown(surface)) { + [filteredSurfaces addObject:surface]; + } + } + + return filteredSurfaces; +} + +/////////////////////////////////////////////// + +%hook IGTabBarControllerSwipeCoordinator +- (id)initWithSurfaces:(id)surfaces parentViewController:(id)controller enableHaptics:(_Bool)haptics launcherSet:(id)set { + // Removes the surface from the main swipeable app collection view + return %orig(filterSurfacesArray(surfaces), controller, haptics, set); +} +%end + +%hook IGTabBarController +- (void)_layoutTabBar { + // Prevents the wrong icon from being shown as selected because of mismatched surface array indexes + NSArray *_tabBarSurfaces = [SCIUtils getIvarForObj:self name:"_tabBarSurfaces"]; + + [SCIUtils setIvarForObj:self name:"_tabBarSurfaces" value:filterSurfacesArray(_tabBarSurfaces)]; + + %orig; +} + +- (id)_buttonForTabBarSurface:(id)surface { + // Prevents the button from being added to the tab bar + id button = %orig(surface); + + if (!isSurfaceShown(surface)) { + return nil; + } + + return button; +} +%end + +// Demangled name: IGNavConfiguration.IGNavConfiguration +%hook _TtC18IGNavConfiguration18IGNavConfiguration +- (NSInteger)tabOrdering { + + if ([[SCIUtils getStringPref:@"nav_icon_ordering"] isEqualToString:@"classic"]) return 0; + else if ([[SCIUtils getStringPref:@"nav_icon_ordering"] isEqualToString:@"standard"]) return 1; + else if ([[SCIUtils getStringPref:@"nav_icon_ordering"] isEqualToString:@"alternate"]) return 2; + + return %orig; + +} +- (void)setTabOrdering:(NSInteger)arg1 { + return; +} + +- (BOOL)isTabSwipingEnabled { + + if ([[SCIUtils getStringPref:@"swipe_nav_tabs"] isEqualToString:@"enabled"]) return YES; + else if ([[SCIUtils getStringPref:@"swipe_nav_tabs"] isEqualToString:@"disabled"]) return NO; + + return %orig; + +} +- (void)setIsTabSwipingEnabled:(BOOL)arg1 { + return; +} +%end \ No newline at end of file diff --git a/src/Features/General/NoRecentSearches.x b/src/Features/General/NoRecentSearches.x new file mode 100644 index 0000000..6f92159 --- /dev/null +++ b/src/Features/General/NoRecentSearches.x @@ -0,0 +1,50 @@ +#import "../../Utils.h" +#import "../../InstagramHeaders.h" + +// Disable logging of searches at server-side +%hook IGSearchEntityRouter +- (id)initWithUserSession:(id)arg1 analyticsModule:(id)arg2 shouldAddToRecents:(BOOL)shouldAddToRecents { + if ([SCIUtils getBoolPref:@"no_recent_searches"]) { + NSLog(@"[SCInsta] Disabling recent searches"); + + shouldAddToRecents = false; + } + + return %orig(arg1, arg2, shouldAddToRecents); +} +%end + +// Most in-app search bars +%hook IGRecentSearchStore +- (id)initWithDiskManager:(id)arg1 recentSearchStoreConfiguration:(id)arg2 { + if ([SCIUtils getBoolPref:@"no_recent_searches"]) { + NSLog(@"[SCInsta] Disabling recent searches"); + + return nil; + } + + return %orig; +} +- (BOOL)addItem:(id)arg1 { + if ([SCIUtils getBoolPref:@"no_recent_searches"]) { + NSLog(@"[SCInsta] Disabling recent searches"); + + return nil; + } + + return %orig; +} +%end + +// Recent dm message recipients search bar +%hook IGDirectRecipientRecentSearchStorage +- (id)initWithDiskManager:(id)arg1 directCache:(id)arg2 userStore:(id)arg3 currentUser:(id)arg4 featureSets:(id)arg5 { + if ([SCIUtils getBoolPref:@"no_recent_searches"]) { + NSLog(@"[SCInsta] Disabling recent searches"); + + return nil; + } + + return %orig; +} +%end \ No newline at end of file diff --git a/src/Features/General/NoSuggestedChats.x b/src/Features/General/NoSuggestedChats.x new file mode 100644 index 0000000..25e6615 --- /dev/null +++ b/src/Features/General/NoSuggestedChats.x @@ -0,0 +1,19 @@ +#import "../../Utils.h" +#import "../../InstagramHeaders.h" + +// Channels dms tab (header) +%hook IGDirectInboxHeaderSectionController +- (id)viewModel { + if ([[%orig title] isEqualToString:@"Suggested"]) { + + if ([SCIUtils getBoolPref:@"no_suggested_chats"]) { + NSLog(@"[SCInsta] Hiding suggested chats (header: channels tab)"); + + return nil; + } + + } + + return %orig; +} +%end \ No newline at end of file diff --git a/src/Features/General/NoSuggestedUsers.x b/src/Features/General/NoSuggestedUsers.x new file mode 100644 index 0000000..f09facf --- /dev/null +++ b/src/Features/General/NoSuggestedUsers.x @@ -0,0 +1,263 @@ +#import "../../Utils.h" +#import "../../InstagramHeaders.h" + +// "Welcome to instagram" suggested users in feed +%hook IGSuggestedUnitViewModel +- (id)initWithAYMFModel:(id)arg1 headerViewModel:(id)arg2 { + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + NSLog(@"[SCInsta] Hiding suggested users: main feed welcome section"); + + return nil; + } + + return %orig; +} +%end +%hook IGSuggestionsUnitViewModel +- (id)initWithAYMFModel:(id)arg1 headerViewModel:(id)arg2 { + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + NSLog(@"[SCInsta] Hiding suggested users: main feed welcome section"); + + return nil; + } + + return %orig; +} +%end + +// Suggested users in profile header +%hook IGProfileHeaderView +- (id)objectsForListAdapter:(id)arg1 { + NSArray *originalObjs = %orig(); + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (id obj in originalObjs) { + BOOL shouldHide = NO; + + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + if ([obj isKindOfClass:%c(IGProfileChainingModel)]) { + NSLog(@"[SCInsta] Hiding suggested users: profile header"); + + shouldHide = YES; + } + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + } + + return [filteredObjs copy]; +} +%end + +// Notifications/activity feed +%hook IGActivityFeedViewController +- (id)objectsForListAdapter:(id)arg1 { + NSArray *originalObjs = %orig(); + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (id obj in originalObjs) { + BOOL shouldHide = NO; + + // Section header + if ([obj isKindOfClass:%c(IGLabelItemViewModel)]) { + // Suggested for you + if ([[obj labelTitle] isEqualToString:@"Suggested for you"]) { + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + NSLog(@"[SCInsta] Hiding suggested users (header: activity feed)"); + + shouldHide = YES; + } + } + } + + // Suggested user + else if ([obj isKindOfClass:%c(IGDiscoverPeopleItemConfiguration)]) { + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + NSLog(@"[SCInsta] Hiding suggested users: (user: activity feed)"); + + shouldHide = YES; + } + } + + // "See all" button + else if ([obj isKindOfClass:%c(IGSeeAllItemConfiguration)]) { + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + NSLog(@"[SCInsta] Hiding suggested users: (see all: activity feed)"); + + shouldHide = YES; + } + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + } + + return [filteredObjs copy]; +} +%end + +// Profile "following" and "followers" tabs +%hook IGFollowListViewController +- (id)objectsForListAdapter:(id)arg1 { + NSArray *originalObjs = %orig(arg1); + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (IGStoryTrayViewModel *obj in originalObjs) { + BOOL shouldHide = NO; + + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + + // Suggested user + if ([obj isKindOfClass:%c(IGDiscoverPeopleItemConfiguration)]) { + NSLog(@"[SCInsta] Hiding suggested users: follow list suggested user"); + + shouldHide = YES; + } + + // Section header + else if ([obj isKindOfClass:%c(IGLabelItemViewModel)]) { + + // "Suggested for you" search results header + if ([[obj valueForKey:@"labelTitle"] isEqualToString:@"Suggested for you"]) { + shouldHide = YES; + } + + } + + // See all suggested users + else if ([obj isKindOfClass:%c(IGSeeAllItemConfiguration)] && ((IGSeeAllItemConfiguration *)obj).destination == 4) { + NSLog(@"[SCInsta] Hiding suggested users: follow list suggested user"); + + shouldHide = YES; + } + + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + } + + return [filteredObjs copy]; +} +%end + +%hook IGSegmentedTabControl +- (void)setSegments:(id)segments { + NSArray *originalObjs = segments; + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (IGStoryTrayViewModel *obj in originalObjs) { + BOOL shouldHide = NO; + + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + if ([obj isKindOfClass:%c(IGFindUsersViewController)]) { + NSLog(@"[SCInsta] Hiding suggested users: find users segmented tab"); + + shouldHide = YES; + } + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + } + + return %orig([filteredObjs copy]); +} +%end + +// Suggested subscriptions +%hook IGFanClubSuggestedUsersDataSource +- (id)initWithUserSession:(id)arg1 delegate:(id)arg2 { + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + return nil; + } + + return %orig(arg1, arg2); +} +%end + +// Follow request/discover section (accessed through notifications page) +// Demangled name: IGFriendingCenter.IGFriendingCenterViewController +%hook _TtC17IGFriendingCenter31IGFriendingCenterViewController +- (id)objectsForListAdapter:(id)arg1 { + NSArray *originalObjs = %orig(arg1); + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (IGStoryTrayViewModel *obj in originalObjs) { + BOOL shouldHide = NO; + + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + + // Suggested user + if ([obj isKindOfClass:%c(IGDiscoverPeopleItemConfiguration)]) { + NSLog(@"[SCInsta] Hiding suggested users: follow list suggested user"); + + shouldHide = YES; + } + + // Section header + else if ([obj isKindOfClass:%c(IGLabelItemViewModel)]) { + + // "Suggested for you" search results header + if ([[obj valueForKey:@"labelTitle"] isEqualToString:@"Suggested for you"]) { + shouldHide = YES; + } + + } + + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + } + + return [filteredObjs copy]; +} +%end + +%hook IGProfileActionBarViewModel +- (id)initWithIdentifier:(id)arg1 + rows:(id)arg2 + allActionsToDisplay:(id)arg3 + overflowActions:(id)arg4 + actionToBadgeInfoMap:(id)arg5 + allBusinessActions:(id)arg6 + overflowBusinessActions:(id)arg7 + contactSheetActions:(id)arg8 + user:(id)arg9 + sponsoredInfoProvider:(id)arg10 + profileBackgroundColor:(id)arg11 +{ + NSArray *rows = arg2; + NSOrderedSet *allActions = [arg3 copy]; + NSOrderedSet *overflowActions = [arg4 copy]; + + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)", @[ @(3) ]]; + + // Actions sets + allActions = [allActions filteredOrderedSetUsingPredicate:predicate]; + overflowActions = [overflowActions filteredOrderedSetUsingPredicate:predicate]; + + // Rows of actions sets + NSMutableArray *filteredRows = [NSMutableArray new]; + for (NSOrderedSet *set in rows) { + [filteredRows addObject:[set filteredOrderedSetUsingPredicate:predicate]]; + } + rows = [filteredRows copy]; + } + + return %orig(arg1, rows, allActions, overflowActions, arg5, arg6, arg7, arg8, arg9, arg10, arg11); +} +%end \ No newline at end of file diff --git a/src/Features/General/NotesCustomization.x b/src/Features/General/NotesCustomization.x new file mode 100644 index 0000000..36d5bd9 --- /dev/null +++ b/src/Features/General/NotesCustomization.x @@ -0,0 +1,293 @@ +#import "../../Utils.h" + +static char targetStaticRef[] = "target"; + +%hook IGDirectNotesCreationView +- (id)initWithViewModel:(id)model + featureSupport:(IGNotesCreationFeatureSupportModel *)support + presentationAnimation:(id)animation + composerUpdateListener:(id)listener + delegate:(id)delegate + layoutType:(long long)type + userSession:(id)session +{ + if ([SCIUtils getBoolPref:@"enable_notes_customization"]) { + + // enableAnimatedEmojisInCreation + @try { + [support setValue:@(YES) forKey:@"enableAnimatedEmojisInCreation"]; + } + @catch (NSException *exception) { + NSLog(@"[SCInsta] WARNING: %@\n\nFull object: %@", exception.reason, support); + } + + // enableBubbleCustomization + @try { + [support setValue:@(YES) forKey:@"enableBubbleCustomization"]; + } + @catch (NSException *exception) { + NSLog(@"[SCInsta] WARNING: %@\n\nFull object: %@", exception.reason, support); + } + + // enableRandomThemeGenerator + @try { + [support setValue:@(YES) forKey:@"enableRandomThemeGenerator"]; + } + @catch (NSException *exception) { + NSLog(@"[SCInsta] WARNING: %@\n\nFull object: %@", exception.reason, support); + } + + } + + return %orig(model, support, animation, listener, delegate, type, session); +} +%end + +// Demangled name: IGDirectNotesUISwift.IGDirectNotesBubbleEditorColorPaletteView +%hook _TtC20IGDirectNotesUISwift41IGDirectNotesBubbleEditorColorPaletteView +%property (nonatomic, copy) UIColor *backgroundColor; +%property (nonatomic, copy) UIColor *textColor; +%property (nonatomic, copy) NSString *emojiText; + +- (void)didMoveToWindow { + %orig; + + if (![SCIUtils getBoolPref:@"custom_note_themes"]) return; + + // Inject buttons once in view lifecycle + static char didInjectButtons; + if (objc_getAssociatedObject(self, &didInjectButtons)) { + return; + } + + __weak typeof(self) weakSelf = self; + dispatch_async(dispatch_get_main_queue(), ^{ + __strong typeof(weakSelf) self = weakSelf; + if (!self || !self.window) { + return; + } + + UIView *container = self.superview ?: self.window; + if (!container) { + return; + } + + // Button config + UIButtonConfiguration *config = [UIButtonConfiguration tintedButtonConfiguration]; + config.background.cornerRadius = 12.0; + config.cornerStyle = UIButtonConfigurationCornerStyleFixed; + config.contentInsets = NSDirectionalEdgeInsetsMake(13.7, 10, 13.7, 10); + + + // Left button + UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeSystem]; + leftButton.configuration = config; + leftButton.translatesAutoresizingMaskIntoConstraints = NO; + leftButton.tintColor = [SCIUtils SCIColor_Primary]; + + NSMutableAttributedString *attrTitleLeft = [[NSMutableAttributedString alloc] initWithString:@"Background"]; + [attrTitleLeft addAttribute:NSFontAttributeName + value:[UIFont systemFontOfSize:14 weight:UIFontWeightSemibold] + range:NSMakeRange(0, attrTitleLeft.length) + ]; + [leftButton setAttributedTitle:attrTitleLeft forState:UIControlStateNormal]; + [leftButton sizeToFit]; + + [leftButton addAction:[UIAction actionWithHandler:^(__kindof UIAction * _Nonnull action) { + [self presentColorPicker:@"Background"]; + }] forControlEvents:UIControlEventTouchUpInside]; + + // Middle button + UIButton *middleButton = [UIButton buttonWithType:UIButtonTypeSystem]; + middleButton.configuration = config; + middleButton.translatesAutoresizingMaskIntoConstraints = NO; + middleButton.tintColor = [SCIUtils SCIColor_Primary]; + + NSMutableAttributedString *attrTitleMiddle = [[NSMutableAttributedString alloc] initWithString:@"Text"]; + [attrTitleMiddle addAttribute:NSFontAttributeName + value:[UIFont systemFontOfSize:14 weight:UIFontWeightSemibold] + range:NSMakeRange(0, attrTitleMiddle.length) + ]; + [middleButton setAttributedTitle:attrTitleMiddle forState:UIControlStateNormal]; + [middleButton sizeToFit]; + + [middleButton addAction:[UIAction actionWithHandler:^(__kindof UIAction * _Nonnull action) { + [self presentColorPicker:@"Text"]; + }] forControlEvents:UIControlEventTouchUpInside]; + + // Right button + UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem]; + rightButton.configuration = config; + rightButton.translatesAutoresizingMaskIntoConstraints = NO; + rightButton.tintColor = [SCIUtils SCIColor_Primary]; + + NSMutableAttributedString *attrTitleRight = [[NSMutableAttributedString alloc] initWithString:@"Emoji"]; + [attrTitleRight addAttribute:NSFontAttributeName + value:[UIFont systemFontOfSize:14 weight:UIFontWeightSemibold] + range:NSMakeRange(0, attrTitleRight.length) + ]; + [rightButton setAttributedTitle:attrTitleRight forState:UIControlStateNormal]; + [rightButton sizeToFit]; + + [rightButton addAction:[UIAction actionWithHandler:^(__kindof UIAction * _Nonnull action) { + UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Emoji Text" + message:@"Click the Apply button after this to see the emoji" + preferredStyle:UIAlertControllerStyleAlert]; + + [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) { + textField.placeholder = @"Type emoji..."; + }]; + + [alert addAction:[UIAlertAction actionWithTitle:@"OK" + style:UIAlertActionStyleDefault + handler:^(UIAlertAction *action) { + self.emojiText = alert.textFields[0].text; + [self applySCICustomTheme:@"Emoji"]; + }]]; + + [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" + style:UIAlertActionStyleCancel + handler:nil]]; + + UIViewController *vc = [SCIUtils nearestViewControllerForView:self]; + [vc presentViewController:alert animated:YES completion:nil]; + }] forControlEvents:UIControlEventTouchUpInside]; + + + // Create stack view + UIStackView *stack = [[UIStackView alloc] initWithArrangedSubviews:@[leftButton, middleButton, rightButton]]; + stack.axis = UILayoutConstraintAxisHorizontal; + stack.spacing = 15.0; + stack.alignment = UIStackViewAlignmentCenter; + stack.distribution = UIStackViewDistributionFillEqually; + + // Find max height among arranged subviews + CGFloat maxHeight = 0.0; + for (UIView *subview in stack.arrangedSubviews) { + maxHeight = MAX(maxHeight, subview.bounds.size.height); + } + + // Manual frame with side padding + CGFloat bottomMargin = 15.0; + + CGRect viewFrame = [self convertRect:self.bounds toView:container]; + CGFloat y = CGRectGetMinY(viewFrame) - maxHeight - bottomMargin; + CGFloat width = container.bounds.size.width - stack.spacing * 2; + + stack.frame = CGRectMake(stack.spacing, y, width, maxHeight); + + [stack layoutIfNeeded]; + [container addSubview:stack]; + + objc_setAssociatedObject( + self, + &didInjectButtons, + @YES, + OBJC_ASSOCIATION_RETAIN_NONATOMIC + ); + }); +} + +%new - (void)presentColorPicker:(NSString *)target { + UIColorPickerViewController *colorPickerController = [[UIColorPickerViewController alloc] init]; + + colorPickerController.delegate = (id)self; // cast to suppress warnings + colorPickerController.title = [NSString stringWithFormat:@"%@ color", target]; + colorPickerController.modalPresentationStyle = UIModalPresentationPopover; + colorPickerController.supportsAlpha = NO; + + // Show last picked color for type + if ([target isEqualToString:@"Background"]) { + colorPickerController.selectedColor = self.backgroundColor; + } + else if ([target isEqualToString:@"Text"]) { + colorPickerController.selectedColor = self.textColor; + } + + UIViewController *presentingVC = [SCIUtils nearestViewControllerForView:self]; + + if (presentingVC != nil) { + [presentingVC presentViewController:colorPickerController animated:YES completion:nil]; + } + + // Save which color target to update + objc_setAssociatedObject( + presentingVC, + &targetStaticRef, + target, + OBJC_ASSOCIATION_RETAIN_NONATOMIC + ); +} + +// UIColorPickerViewControllerDelegate Protocol +%new - (void)colorPickerViewController:(UIColorPickerViewController *)viewController + didSelectColor:(UIColor *)color + continuously:(BOOL)continuously +{ + _TtC20IGDirectNotesUISwift41IGDirectNotesBubbleEditorColorPaletteView *bubbleEditorVC = [SCIUtils nearestViewControllerForView:self]; + + NSString *target = objc_getAssociatedObject(bubbleEditorVC, &targetStaticRef); + if (!target) return; + + // Update saved color target + if ([target isEqualToString:@"Background"]) { + self.backgroundColor = color; + } + else if ([target isEqualToString:@"Text"]) { + self.textColor = color; + } + + [self applySCICustomTheme:target]; +}; + +%new - (void)applySCICustomTheme:(NSString *)target { + // Get notes composer vc + _TtC20IGDirectNotesUISwift39IGDirectNotesBubbleEditorViewController *parentVC = [SCIUtils nearestViewControllerForView:self]; + if (!parentVC) return; + + IGDirectNotesComposerViewController *composerVC = parentVC.delegate; + if (!composerVC) return; + + // Get current theme model + IGNotesCustomThemeCreationModel *model = [composerVC valueForKey:@"_selectedCustomThemeCreationModel"]; + if (!model) { + // Create new note theme model + model = [[%c(IGNotesCustomThemeCreationModel) alloc] init]; + if (!model) return; + } + + //SCILog(@"Current note theme model: %@", model); + [model setValue:[composerVC valueForKey:@"_composerText"] forKey:@"customEmoji"]; + + // Update saved color target + if ([target isEqualToString:@"Background"]) { + [model setValue:self.backgroundColor forKey:@"backgroundColor"]; + } + else if ([target isEqualToString:@"Text"]) { + [model setValue:self.textColor forKey:@"textColor"]; + [model setValue:self.textColor forKey:@"secondaryTextColor"]; + } + + // Always set emoji to prevent it being overwritten + [model setValue:self.emojiText forKey:@"customEmoji"]; + + //SCILog(@"Updated note theme model: %@", model); + + // Apply custom notes theme + [composerVC notesBubbleEditorViewControllerDidUpdateWithCustomThemeCreationModel:model]; + + // Enable apply/cancel buttons + UIView *parentVCView = [parentVC view]; + if (!parentVCView) return; + + NSArray *parentVCSubviews = [parentVCView subviews]; + if (!parentVCSubviews) return; + + [parentVCSubviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + if ([obj isKindOfClass:%c(IGDSBottomButtonsView)]) { + [obj setPrimaryButtonEnabled:YES]; + [obj setSecondaryButtonEnabled:YES]; + } + }]; +} +%end \ No newline at end of file diff --git a/src/Features/General/SCSettingsMenuEntry.x b/src/Features/General/SCSettingsMenuEntry.x new file mode 100644 index 0000000..460315a --- /dev/null +++ b/src/Features/General/SCSettingsMenuEntry.x @@ -0,0 +1,58 @@ +#import "../../InstagramHeaders.h" +#import "../../Settings/SCISettingsViewController.h" + +// Show SCInsta tweak settings by holding on the settings/more icon under profile for ~1 second +%hook IGBadgedNavigationButton +- (void)didMoveToWindow { + %orig; + + if ([self.accessibilityIdentifier isEqualToString:@"profile-more-button"]) { + [self addLongPressGestureRecognizer]; + } + + return; +} + +%new - (void)addLongPressGestureRecognizer { + if ([self.gestureRecognizers count] == 0) { + NSLog(@"[SCInsta] Adding tweak settings long press gesture recognizer"); + + UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; + [self addGestureRecognizer:longPress]; + } +} +%new - (void)handleLongPress:(UILongPressGestureRecognizer *)sender { + if (sender.state != UIGestureRecognizerStateBegan) return; + + NSLog(@"[SCInsta] Tweak settings gesture activated"); + + [SCIUtils showSettingsVC:[self window]]; +} +%end + +// Quick access to tweak settings by holding on home tab button +%hook IGTabBarButton +- (void)didMoveToSuperview { + %orig; + + // Only work on home/feed tab + if (![self.accessibilityIdentifier isEqualToString:@"mainfeed-tab"]) return; + + if ([SCIUtils getBoolPref:@"settings_shortcut"]) { + UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; + longPress.minimumPressDuration = 0.3; + + // Take precidence over existing gesture recognizers + for (UIGestureRecognizer *existing in self.gestureRecognizers) { + [existing requireGestureRecognizerToFail:longPress]; + } + + [self addGestureRecognizer:longPress]; + } +} +%new - (void)handleLongPress:(UILongPressGestureRecognizer *)sender { + if (sender.state != UIGestureRecognizerStateBegan) return; + + [SCIUtils showSettingsVC:[self window]]; +} +%end \ No newline at end of file diff --git a/src/Features/General/TeenAppIcons.x b/src/Features/General/TeenAppIcons.x new file mode 100644 index 0000000..27ab96a --- /dev/null +++ b/src/Features/General/TeenAppIcons.x @@ -0,0 +1,38 @@ +#import "../../InstagramHeaders.h" +#import "../../Utils.h" + +%hook IGImageWithAccessoryButton + +- (void)didMoveToSuperview { + %orig; + + [self addLongPressGestureRecognizer]; +} + +%new - (void)addLongPressGestureRecognizer { + BOOL hasLongPress = [self.gestureRecognizers filteredArrayUsingPredicate: + [NSPredicate predicateWithBlock:^BOOL(NSObject *item, NSDictionary *_) { + return [item isKindOfClass:[UILongPressGestureRecognizer class]]; + }] + ].count > 0; + + if (!hasLongPress) { + NSLog(@"[SCInsta] Adding teen app icons long press gesture recognizer"); + + UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; + [self addGestureRecognizer:longPress]; + } +} +%new - (void)handleLongPress:(UILongPressGestureRecognizer *)sender { + if (sender.state != UIGestureRecognizerStateBegan) return; + + if ([SCIUtils getBoolPref:@"teen_app_icons"]) { + IGHomeFeedHeaderViewController *homeFeedHeaderVC = [SCIUtils nearestViewControllerForView:self]; + + if (homeFeedHeaderVC != nil) { + [homeFeedHeaderVC headerDidLongPressLogo:nil]; + } + } +} + +%end \ No newline at end of file diff --git a/src/Features/Media/MediaDownload.xm b/src/Features/Media/MediaDownload.xm new file mode 100644 index 0000000..e25404b --- /dev/null +++ b/src/Features/Media/MediaDownload.xm @@ -0,0 +1,703 @@ +#import "../../InstagramHeaders.h" +#import "../../Utils.h" +#import "../../Downloader/Download.h" +#import + +static SCIDownloadDelegate *imageDownloadDelegate; +static SCIDownloadDelegate *videoDownloadDelegate; + +static DownloadAction sciGetDownloadAction() { + NSString *method = [SCIUtils getStringPref:@"dw_save_action"]; + if ([method isEqualToString:@"photos"]) return saveToPhotos; + return share; +} + +static void initDownloaders () { + // Re-init each time to pick up the current save action preference + DownloadAction action = sciGetDownloadAction(); + DownloadAction imgAction = (action == saveToPhotos) ? saveToPhotos : quickLook; + imageDownloadDelegate = [[SCIDownloadDelegate alloc] initWithAction:imgAction showProgress:NO]; + videoDownloadDelegate = [[SCIDownloadDelegate alloc] initWithAction:action showProgress:YES]; +} + +// Helper: run a download block with optional confirmation dialog +static void sciConfirmAndDownload(NSString *title, void(^downloadBlock)(void)) { + if ([SCIUtils getBoolPref:@"dw_confirm"]) { + [SCIUtils showConfirmation:downloadBlock title:title]; + } else { + downloadBlock(); + } +} + +// Helper: recursively search within a view tree for downloadable media (bounded to one post) +static BOOL sciFindAndDownloadMediaInView(UIView *root) { + if (!root) return NO; + + // Check for video media via mediaCellFeedItem + if ([root respondsToSelector:@selector(mediaCellFeedItem)]) { + IGMedia *media = [root performSelector:@selector(mediaCellFeedItem)]; + if (media) { + NSURL *videoUrl = [SCIUtils getVideoUrlForMedia:media]; + if (videoUrl) { + initDownloaders(); + [videoDownloadDelegate downloadFileWithURL:videoUrl fileExtension:[[videoUrl lastPathComponent] pathExtension] hudLabel:nil]; + return YES; + } + NSURL *photoUrl = [SCIUtils getPhotoUrlForMedia:media]; + if (photoUrl) { + initDownloaders(); + [imageDownloadDelegate downloadFileWithURL:photoUrl fileExtension:[[photoUrl lastPathComponent] pathExtension] hudLabel:nil]; + return YES; + } + } + } + + // Check for IGFeedPhotoView with delegate chain + if ([root isKindOfClass:NSClassFromString(@"IGFeedPhotoView")] && [root respondsToSelector:@selector(delegate)]) { + id delegate = [root performSelector:@selector(delegate)]; + if ([delegate isKindOfClass:NSClassFromString(@"IGFeedItemPhotoCell")]) { + @try { + Ivar cfgIvar = class_getInstanceVariable([delegate class], "_configuration"); + if (cfgIvar) { + id cfg = object_getIvar(delegate, cfgIvar); + if (cfg) { + Ivar photoIvar = class_getInstanceVariable([cfg class], "_photo"); + if (photoIvar) { + IGPhoto *photo = object_getIvar(cfg, photoIvar); + NSURL *photoUrl = [SCIUtils getPhotoUrl:photo]; + if (photoUrl) { + initDownloaders(); + [imageDownloadDelegate downloadFileWithURL:photoUrl fileExtension:[[photoUrl lastPathComponent] pathExtension] hudLabel:nil]; + return YES; + } + } + } + } + } @catch (NSException *e) {} + } + if ([delegate isKindOfClass:NSClassFromString(@"IGFeedItemPagePhotoCell")]) { + @try { + if ([delegate respondsToSelector:@selector(pagePhotoPost)]) { + id pagePhotoPost = [delegate performSelector:@selector(pagePhotoPost)]; + if (pagePhotoPost && [pagePhotoPost respondsToSelector:@selector(photo)]) { + IGPhoto *photo = [pagePhotoPost performSelector:@selector(photo)]; + NSURL *photoUrl = [SCIUtils getPhotoUrl:photo]; + if (photoUrl) { + initDownloaders(); + [imageDownloadDelegate downloadFileWithURL:photoUrl fileExtension:[[photoUrl lastPathComponent] pathExtension] hudLabel:nil]; + return YES; + } + } + } + } @catch (NSException *e) {} + } + } + + // Recurse into subviews + for (UIView *sub in root.subviews) { + if (sciFindAndDownloadMediaInView(sub)) return YES; + } + return NO; +} + +// Helper: find IGMedia from a cell using runtime ivar scanning +// Avoids property getters which can cause EXC_BAD_ACCESS on certain IG versions +static IGMedia * _Nullable sciGetMediaFromView(UIView *view) { + if (!view) return nil; + + unsigned int ivarCount = 0; + Ivar *ivars = class_copyIvarList([view class], &ivarCount); + if (!ivars) return nil; + + IGMedia *found = nil; + Class mediaClass = NSClassFromString(@"IGMedia"); + + for (unsigned int i = 0; i < ivarCount; i++) { + const char *name = ivar_getName(ivars[i]); + if (!name) continue; + + NSString *ivarName = [NSString stringWithUTF8String:name]; + NSString *lower = [ivarName lowercaseString]; + + if ([lower containsString:@"video"] || [lower containsString:@"media"] || [lower containsString:@"item"]) { + id value = object_getIvar(view, ivars[i]); + if (value && mediaClass && [value isKindOfClass:mediaClass]) { + found = (IGMedia *)value; + NSLog(@"[SCInsta] Found IGMedia in ivar '%@' of %@", ivarName, NSStringFromClass([view class])); + break; + } + } + } + + free(ivars); + return found; +} + +// Helper: walk superview chain to find a view of a given class +static UIView * _Nullable sciFindSuperviewOfClass(UIView *view, NSString *className) { + Class cls = NSClassFromString(className); + if (!cls) return nil; + UIView *current = view.superview; + int depth = 0; + while (current && depth < 15) { + if ([current isKindOfClass:cls]) return current; + current = current.superview; + depth++; + } + return nil; +} + +// Helper: show debug ivar dump when media extraction fails (survives IG updates) +static void sciShowDebugIvarDump(UIView *cell) { + NSMutableString *debug = [NSMutableString stringWithFormat:@"No IGMedia found in %@\n\nIvars:\n", NSStringFromClass([cell class])]; + unsigned int count = 0; + Ivar *ivars = class_copyIvarList([cell class], &count); + for (unsigned int i = 0; i < count && i < 50; i++) { + const char *name = ivar_getName(ivars[i]); + const char *type = ivar_getTypeEncoding(ivars[i]); + if (name) [debug appendFormat:@"%s (%s)\n", name, type ? type : "?"]; + } + if (ivars) free(ivars); + + NSLog(@"[SCInsta] Debug: %@", debug); + + dispatch_async(dispatch_get_main_queue(), ^{ + UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"SCInsta Debug" + message:debug + preferredStyle:UIAlertControllerStyleAlert]; + [alert addAction:[UIAlertAction actionWithTitle:@"Copy & Close" style:UIAlertActionStyleDefault handler:^(UIAlertAction *a) { + [[UIPasteboard generalPasteboard] setString:debug]; + }]]; + [alert addAction:[UIAlertAction actionWithTitle:@"Close" style:UIAlertActionStyleCancel handler:nil]]; + UIViewController *topVC = topMostController(); + if (topVC) [topVC presentViewController:alert animated:YES completion:nil]; + }); +} + +// Whether download buttons (not long-press) are enabled +static BOOL sciUseDownloadButtons() { + return [[SCIUtils getStringPref:@"dw_method"] isEqualToString:@"button"]; +} + + +/* * Feed * */ + +// Download feed images +%hook IGFeedPhotoView +- (void)didMoveToSuperview { + %orig; + + if (![SCIUtils getBoolPref:@"dw_feed_posts"]) return; + + if (sciUseDownloadButtons()) { + [self sciAddDownloadButton]; + } else { + [self addLongPressGestureRecognizer]; + } +} +%new - (void)sciAddDownloadButton { + if ([self viewWithTag:1338]) return; + + UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; + btn.tag = 1338; + UIImageSymbolConfiguration *config = [UIImageSymbolConfiguration configurationWithPointSize:20 weight:UIImageSymbolWeightMedium]; + [btn setImage:[UIImage systemImageNamed:@"arrow.down.to.line" withConfiguration:config] forState:UIControlStateNormal]; + btn.tintColor = [UIColor whiteColor]; + btn.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.4]; + btn.layer.cornerRadius = 16; + btn.clipsToBounds = YES; + btn.translatesAutoresizingMaskIntoConstraints = NO; + [btn addTarget:self action:@selector(sciDownloadBtnTapped:) forControlEvents:UIControlEventTouchUpInside]; + [self addSubview:btn]; + + [NSLayoutConstraint activateConstraints:@[ + [btn.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:10], + [btn.bottomAnchor constraintEqualToAnchor:self.bottomAnchor constant:-10], + [btn.widthAnchor constraintEqualToConstant:32], + [btn.heightAnchor constraintEqualToConstant:32] + ]]; +} +%new - (void)sciDownloadBtnTapped:(UIButton *)sender { + UIImpactFeedbackGenerator *haptic = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium]; + [haptic impactOccurred]; + [UIView animateWithDuration:0.1 animations:^{ sender.transform = CGAffineTransformMakeScale(0.75, 0.75); } + completion:^(BOOL f) { [UIView animateWithDuration:0.1 animations:^{ sender.transform = CGAffineTransformIdentity; }]; }]; + + sciConfirmAndDownload(@"Download photo?", ^{ + [self handleLongPress:nil]; + }); +} +%new - (void)addLongPressGestureRecognizer { + UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; + longPress.minimumPressDuration = [SCIUtils getDoublePref:@"dw_finger_duration"]; + longPress.numberOfTouchesRequired = [SCIUtils getDoublePref:@"dw_finger_count"]; + [self addGestureRecognizer:longPress]; +} +%new - (void)handleLongPress:(UILongPressGestureRecognizer *)sender { + if (sender && sender.state != UIGestureRecognizerStateBegan) return; + + IGPhoto *photo; + + if ([self.delegate isKindOfClass:%c(IGFeedItemPhotoCell)]) { + IGFeedItemPhotoCellConfiguration *_configuration = MSHookIvar(self.delegate, "_configuration"); + if (!_configuration) return; + photo = MSHookIvar(_configuration, "_photo"); + } + else if ([self.delegate isKindOfClass:%c(IGFeedItemPagePhotoCell)]) { + IGFeedItemPagePhotoCell *pagePhotoCell = self.delegate; + photo = pagePhotoCell.pagePhotoPost.photo; + } + + NSURL *photoUrl = [SCIUtils getPhotoUrl:photo]; + if (!photoUrl) { + [SCIUtils showErrorHUDWithDescription:@"Could not extract photo url from post"]; + return; + } + + initDownloaders(); + [imageDownloadDelegate downloadFileWithURL:photoUrl + fileExtension:[[photoUrl lastPathComponent]pathExtension] + hudLabel:nil]; +} +%end + +// Download feed videos +%hook IGModernFeedVideoCell.IGModernFeedVideoCell +- (void)didMoveToSuperview { + %orig; + + if (![SCIUtils getBoolPref:@"dw_feed_posts"]) return; + + if (sciUseDownloadButtons()) { + [self sciAddDownloadButton]; + } else { + [self addLongPressGestureRecognizer]; + } +} +%new - (void)sciAddDownloadButton { + UIView *selfView = (UIView *)self; + if ([selfView viewWithTag:1338]) return; + + UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; + btn.tag = 1338; + UIImageSymbolConfiguration *config = [UIImageSymbolConfiguration configurationWithPointSize:20 weight:UIImageSymbolWeightMedium]; + [btn setImage:[UIImage systemImageNamed:@"arrow.down.to.line" withConfiguration:config] forState:UIControlStateNormal]; + btn.tintColor = [UIColor whiteColor]; + btn.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.4]; + btn.layer.cornerRadius = 16; + btn.clipsToBounds = YES; + btn.translatesAutoresizingMaskIntoConstraints = NO; + [btn addTarget:self action:@selector(sciDownloadBtnTapped:) forControlEvents:UIControlEventTouchUpInside]; + [selfView addSubview:btn]; + + [NSLayoutConstraint activateConstraints:@[ + [btn.leadingAnchor constraintEqualToAnchor:selfView.leadingAnchor constant:10], + [btn.bottomAnchor constraintEqualToAnchor:selfView.bottomAnchor constant:-10], + [btn.widthAnchor constraintEqualToConstant:32], + [btn.heightAnchor constraintEqualToConstant:32] + ]]; +} +%new - (void)sciDownloadBtnTapped:(UIButton *)sender { + UIImpactFeedbackGenerator *haptic = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium]; + [haptic impactOccurred]; + [UIView animateWithDuration:0.1 animations:^{ sender.transform = CGAffineTransformMakeScale(0.75, 0.75); } + completion:^(BOOL f) { [UIView animateWithDuration:0.1 animations:^{ sender.transform = CGAffineTransformIdentity; }]; }]; + + sciConfirmAndDownload(@"Download video?", ^{ + [self handleLongPress:nil]; + }); +} +%new - (void)addLongPressGestureRecognizer { + UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; + longPress.minimumPressDuration = [SCIUtils getDoublePref:@"dw_finger_duration"]; + longPress.numberOfTouchesRequired = [SCIUtils getDoublePref:@"dw_finger_count"]; + [self addGestureRecognizer:longPress]; +} +%new - (void)handleLongPress:(UILongPressGestureRecognizer *)sender { + if (sender && sender.state != UIGestureRecognizerStateBegan) return; + + NSURL *videoUrl = [SCIUtils getVideoUrlForMedia:[self mediaCellFeedItem]]; + if (!videoUrl) { + [SCIUtils showErrorHUDWithDescription:@"Could not extract video url from post"]; + return; + } + + initDownloaders(); + [videoDownloadDelegate downloadFileWithURL:videoUrl + fileExtension:[[videoUrl lastPathComponent] pathExtension] + hudLabel:nil]; +} +%end + + + +/* * Reels * */ + +// Download reels (photos) — long press only when gesture mode selected +%hook IGSundialViewerPhotoView +- (void)didMoveToSuperview { + %orig; + + if ([SCIUtils getBoolPref:@"dw_reels"] && !sciUseDownloadButtons()) { + [self addLongPressGestureRecognizer]; + } + + return; +} +%new - (void)addLongPressGestureRecognizer { + UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; + longPress.minimumPressDuration = [SCIUtils getDoublePref:@"dw_finger_duration"]; + longPress.numberOfTouchesRequired = [SCIUtils getDoublePref:@"dw_finger_count"]; + [self addGestureRecognizer:longPress]; +} +%new - (void)handleLongPress:(UILongPressGestureRecognizer *)sender { + if (sender.state != UIGestureRecognizerStateBegan) return; + + @try { + IGPhoto *_photo = nil; + @try { + _photo = MSHookIvar(self, "_photo"); + } @catch (NSException *e) {} + + if (!_photo) { + [SCIUtils showErrorHUDWithDescription:@"Could not access reel photo"]; + return; + } + + NSURL *photoUrl = [SCIUtils getPhotoUrl:_photo]; + if (!photoUrl) { + [SCIUtils showErrorHUDWithDescription:@"Could not extract photo url from reel"]; + return; + } + + initDownloaders(); + [imageDownloadDelegate downloadFileWithURL:photoUrl + fileExtension:[[photoUrl lastPathComponent]pathExtension] + hudLabel:nil]; + } @catch (NSException *exception) { + NSLog(@"[SCInsta] Reel photo download error: %@", exception); + [SCIUtils showErrorHUDWithDescription:[NSString stringWithFormat:@"Reel photo download failed: %@", exception.reason]]; + } +} +%end + +// Download reels (videos) — long press only when gesture mode selected +%hook IGSundialViewerVideoCell +- (void)didMoveToSuperview { + %orig; + + if ([SCIUtils getBoolPref:@"dw_reels"] && !sciUseDownloadButtons()) { + [self addLongPressGestureRecognizer]; + } + + return; +} +%new - (void)addLongPressGestureRecognizer { + UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; + longPress.minimumPressDuration = [SCIUtils getDoublePref:@"dw_finger_duration"]; + longPress.numberOfTouchesRequired = [SCIUtils getDoublePref:@"dw_finger_count"]; + [self addGestureRecognizer:longPress]; +} +%new - (void)handleLongPress:(UILongPressGestureRecognizer *)sender { + if (sender.state != UIGestureRecognizerStateBegan) return; + + @try { + IGMedia *media = sciGetMediaFromView(self); + if (!media) { + [SCIUtils showErrorHUDWithDescription:@"Could not access reel media"]; + return; + } + + NSURL *videoUrl = [SCIUtils getVideoUrlForMedia:media]; + if (!videoUrl) { + [SCIUtils showErrorHUDWithDescription:@"Could not extract video url from reel"]; + return; + } + + initDownloaders(); + [videoDownloadDelegate downloadFileWithURL:videoUrl + fileExtension:[[videoUrl lastPathComponent] pathExtension] + hudLabel:nil]; + } @catch (NSException *exception) { + NSLog(@"[SCInsta] Reel download error: %@", exception); + [SCIUtils showErrorHUDWithDescription:[NSString stringWithFormat:@"Reel download failed: %@", exception.reason]]; + } +} +%end + +// Download button on reels vertical UFI (like/comment/share sidebar) +%hook IGSundialViewerVerticalUFI +- (void)didMoveToSuperview { + %orig; + + if (![SCIUtils getBoolPref:@"dw_reels"]) return; + if (!sciUseDownloadButtons()) return; + if (!self.superview) return; + + // Add to superview so we're not clipped by the narrow 29pt UFI + UIView *parent = self.superview; + if ([parent viewWithTag:1337]) return; + + UIButton *downloadBtn = [UIButton buttonWithType:UIButtonTypeCustom]; + downloadBtn.tag = 1337; + + // Match IG reel sidebar style: outline icon, semi-transparent white + UIImageSymbolConfiguration *config = [UIImageSymbolConfiguration configurationWithPointSize:24 weight:UIImageSymbolWeightSemibold]; + UIImage *icon = [UIImage systemImageNamed:@"arrow.down" withConfiguration:config]; + [downloadBtn setImage:icon forState:UIControlStateNormal]; + downloadBtn.tintColor = [UIColor colorWithWhite:1.0 alpha:0.9]; + + downloadBtn.layer.shadowColor = [UIColor blackColor].CGColor; + downloadBtn.layer.shadowOffset = CGSizeMake(0, 1); + downloadBtn.layer.shadowOpacity = 0.5; + downloadBtn.layer.shadowRadius = 3; + + downloadBtn.translatesAutoresizingMaskIntoConstraints = NO; + [downloadBtn addTarget:self action:@selector(sciDownloadTapped:) forControlEvents:UIControlEventTouchUpInside]; + [parent addSubview:downloadBtn]; + + [NSLayoutConstraint activateConstraints:@[ + [downloadBtn.centerXAnchor constraintEqualToAnchor:self.centerXAnchor], + [downloadBtn.bottomAnchor constraintEqualToAnchor:self.topAnchor constant:-10], + [downloadBtn.widthAnchor constraintEqualToConstant:40], + [downloadBtn.heightAnchor constraintEqualToConstant:40] + ]]; +} + +%new - (void)sciDownloadTapped:(UIButton *)sender { + NSLog(@"[SCInsta] Reel download button tapped"); + + // Haptic + visual feedback + UIImpactFeedbackGenerator *haptic = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium]; + [haptic impactOccurred]; + [UIView animateWithDuration:0.1 animations:^{ + sender.transform = CGAffineTransformMakeScale(0.75, 0.75); + } completion:^(BOOL finished) { + [UIView animateWithDuration:0.1 animations:^{ + sender.transform = CGAffineTransformIdentity; + }]; + }]; + + sciConfirmAndDownload(@"Download reel?", ^{ + // Find IGSundialViewerVideoCell in superview chain + UIView *videoCell = sciFindSuperviewOfClass(self, @"IGSundialViewerVideoCell"); + + if (videoCell) { + IGMedia *media = sciGetMediaFromView(videoCell); + if (media) { + NSURL *videoUrl = [SCIUtils getVideoUrlForMedia:media]; + if (videoUrl) { + initDownloaders(); + [videoDownloadDelegate downloadFileWithURL:videoUrl + fileExtension:[[videoUrl lastPathComponent] pathExtension] + hudLabel:nil]; + return; + } + [SCIUtils showErrorHUDWithDescription:@"Could not extract video URL from reel"]; + return; + } + sciShowDebugIvarDump(videoCell); + return; + } + + // Try photo reel + UIView *photoView = sciFindSuperviewOfClass(self, @"IGSundialViewerPhotoView"); + if (photoView) { + unsigned int count = 0; + Ivar *ivars = class_copyIvarList([photoView class], &count); + Class photoClass = NSClassFromString(@"IGPhoto"); + for (unsigned int i = 0; i < count; i++) { + const char *name = ivar_getName(ivars[i]); + if (!name) continue; + NSString *ivarName = [NSString stringWithUTF8String:name]; + if ([[ivarName lowercaseString] containsString:@"photo"]) { + id value = object_getIvar(photoView, ivars[i]); + if (value && photoClass && [value isKindOfClass:photoClass]) { + NSURL *photoUrl = [SCIUtils getPhotoUrl:(IGPhoto *)value]; + if (photoUrl) { + free(ivars); + initDownloaders(); + [imageDownloadDelegate downloadFileWithURL:photoUrl + fileExtension:[[photoUrl lastPathComponent] pathExtension] + hudLabel:nil]; + return; + } + } + } + } + if (ivars) free(ivars); + sciShowDebugIvarDump(photoView); + return; + } + + [SCIUtils showErrorHUDWithDescription:@"Could not find reel cell in view hierarchy"]; + }); +} +%end + + +/* * Stories * */ + +// Download story (images) +%hook IGStoryPhotoView +- (void)didMoveToSuperview { + %orig; + + if ([SCIUtils getBoolPref:@"dw_story"]) { + [self addLongPressGestureRecognizer]; + } + + return; +} +%new - (void)addLongPressGestureRecognizer { + UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; + longPress.minimumPressDuration = [SCIUtils getDoublePref:@"dw_finger_duration"]; + longPress.numberOfTouchesRequired = [SCIUtils getDoublePref:@"dw_finger_count"]; + + [self addGestureRecognizer:longPress]; +} +%new - (void)handleLongPress:(UILongPressGestureRecognizer *)sender { + if (sender.state != UIGestureRecognizerStateBegan) return; + + NSURL *photoUrl = [SCIUtils getPhotoUrlForMedia:[self item]]; + if (!photoUrl) { + [SCIUtils showErrorHUDWithDescription:@"Could not extract photo url from story"]; + + return; + } + + initDownloaders(); + [imageDownloadDelegate downloadFileWithURL:photoUrl + fileExtension:[[photoUrl lastPathComponent]pathExtension] + hudLabel:nil]; +} +%end + +// Download story (videos) +%hook IGStoryModernVideoView +- (void)didMoveToSuperview { + %orig; + + if ([SCIUtils getBoolPref:@"dw_story"]) { + [self addLongPressGestureRecognizer]; + } + + return; +} +%new - (void)addLongPressGestureRecognizer { + UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; + longPress.minimumPressDuration = [SCIUtils getDoublePref:@"dw_finger_duration"]; + longPress.numberOfTouchesRequired = [SCIUtils getDoublePref:@"dw_finger_count"]; + + [self addGestureRecognizer:longPress]; +} +%new - (void)handleLongPress:(UILongPressGestureRecognizer *)sender { + if (sender.state != UIGestureRecognizerStateBegan) return; + + NSURL *videoUrl = [SCIUtils getVideoUrlForMedia:self.item]; + + if (!videoUrl) { + [SCIUtils showErrorHUDWithDescription:@"Could not extract video url from story"]; + + return; + } + + initDownloaders(); + [videoDownloadDelegate downloadFileWithURL:videoUrl + fileExtension:[[videoUrl lastPathComponent] pathExtension] + hudLabel:nil]; +} +%end + +// Download story (videos, legacy) +%hook IGStoryVideoView +- (void)didMoveToSuperview { + %orig; + + if ([SCIUtils getBoolPref:@"dw_story"]) { + [self addLongPressGestureRecognizer]; + } + + return; +} +%new - (void)addLongPressGestureRecognizer { + UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; + longPress.minimumPressDuration = [SCIUtils getDoublePref:@"dw_finger_duration"]; + longPress.numberOfTouchesRequired = [SCIUtils getDoublePref:@"dw_finger_count"]; + + [self addGestureRecognizer:longPress]; +} +%new - (void)handleLongPress:(UILongPressGestureRecognizer *)sender { + if (sender.state != UIGestureRecognizerStateBegan) return; + + NSURL *videoUrl; + + IGStoryFullscreenSectionController *captionDelegate = self.captionDelegate; + if (captionDelegate) { + videoUrl = [SCIUtils getVideoUrlForMedia:captionDelegate.currentStoryItem]; + } + else { + // Direct messages video player + id parentVC = [SCIUtils nearestViewControllerForView:self]; + if (!parentVC || ![parentVC isKindOfClass:%c(IGDirectVisualMessageViewerController)]) return; + + IGDirectVisualMessageViewerViewModeAwareDataSource *_dataSource = MSHookIvar(parentVC, "_dataSource"); + if (!_dataSource) return; + + IGDirectVisualMessage *_currentMessage = MSHookIvar(_dataSource, "_currentMessage"); + if (!_currentMessage) return; + + IGVideo *rawVideo = _currentMessage.rawVideo; + if (!rawVideo) return; + + videoUrl = [SCIUtils getVideoUrl:rawVideo]; + } + + if (!videoUrl) { + [SCIUtils showErrorHUDWithDescription:@"Could not extract video url from story"]; + + return; + } + + initDownloaders(); + [videoDownloadDelegate downloadFileWithURL:videoUrl + fileExtension:[[videoUrl lastPathComponent] pathExtension] + hudLabel:nil]; +} +%end + + +/* * Profile pictures * */ + +%hook IGProfilePictureImageView +- (void)didMoveToSuperview { + %orig; + + if ([SCIUtils getBoolPref:@"save_profile"]) { + [self addLongPressGestureRecognizer]; + } + + return; +} +%new - (void)addLongPressGestureRecognizer { + UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; + [self addGestureRecognizer:longPress]; +} +%new - (void)handleLongPress:(UILongPressGestureRecognizer *)sender { + if (sender.state != UIGestureRecognizerStateBegan) return; + + IGImageView *_imageView = MSHookIvar(self, "_imageView"); + if (!_imageView) return; + + IGImageSpecifier *imageSpecifier = _imageView.imageSpecifier; + if (!imageSpecifier) return; + + NSURL *imageUrl = imageSpecifier.url; + if (!imageUrl) return; + + initDownloaders(); + [imageDownloadDelegate downloadFileWithURL:imageUrl + fileExtension:[[imageUrl lastPathComponent] pathExtension] + hudLabel:@"Loading"]; +} +%end diff --git a/src/Features/Reels/HideReelsHeader.x b/src/Features/Reels/HideReelsHeader.x new file mode 100644 index 0000000..25a7d2f --- /dev/null +++ b/src/Features/Reels/HideReelsHeader.x @@ -0,0 +1,13 @@ +#import "../../Utils.h" + +%hook IGSundialViewerNavigationBarOld +- (void)didMoveToWindow { + %orig; + + if ([SCIUtils getBoolPref:@"hide_reels_header"]) { + NSLog(@"[SCInsta] Hiding reels header"); + + [self removeFromSuperview]; + } +} +%end diff --git a/src/Features/Reels/ReelsPlayback.xm b/src/Features/Reels/ReelsPlayback.xm new file mode 100644 index 0000000..9919ddb --- /dev/null +++ b/src/Features/Reels/ReelsPlayback.xm @@ -0,0 +1,72 @@ +#import "../../Utils.h" + +%hook IGSundialPlaybackControlsTestConfiguration +- (id)initWithLauncherSet:(id)set + tapToPauseEnabled:(_Bool)tapPauseEnabled + combineSingleTapPlaybackControls:(_Bool)controls + isVideoPreviewThumbnailEnabled:(_Bool)previewThumbEnabled + minScrubberDurationSec:(long long)minSec + seekResumeScrubberCooldownSec:(double)seekSec + tapResumeScrubberCooldownSec:(double)tapSec + persistentScrubberMinVideoDuration:(long long)duration + isScrubberForShortVideoEnabled:(_Bool)shortScrubberEnabled +{ + _Bool userTapPauseEnabled = tapPauseEnabled; + if ([[SCIUtils getStringPref:@"reels_tap_control"] isEqualToString:@"pause"]) userTapPauseEnabled = true; + else if ([[SCIUtils getStringPref:@"reels_tap_control"] isEqualToString:@"mute"]) userTapPauseEnabled = false; + + long long userMinSec = minSec; + long long userDuration = duration; + _Bool userShortScrubberEnabled = shortScrubberEnabled; + if ([SCIUtils getBoolPref:@"reels_show_scrubber"]) { + userMinSec = 0; + userDuration = 0; + userShortScrubberEnabled = true; + } + + return %orig(set, userTapPauseEnabled, controls, previewThumbEnabled, userMinSec, seekSec, tapSec, userDuration, userShortScrubberEnabled); +} +%end + +%hook IGSundialFeedViewController +- (void)_refreshReelsWithParamsForNetworkRequest:(NSInteger)arg1 userDidPullToRefresh:(BOOL)arg2 { + if ([SCIUtils getBoolPref:@"prevent_doom_scrolling"]) { + IGRefreshControl *_refreshControl = MSHookIvar(self, "_refreshControl"); + [self refreshControlDidEndFinishLoadingAnimation:_refreshControl]; + + return; + } + + if ([SCIUtils getBoolPref:@"refresh_reel_confirm"]) { + NSLog(@"[SCInsta] Reel refresh triggered"); + + [SCIUtils showConfirmation:^(void) { %orig(arg1, arg2); } + cancelHandler:^(void) { + IGRefreshControl *_refreshControl = MSHookIvar(self, "_refreshControl"); + [self refreshControlDidEndFinishLoadingAnimation:_refreshControl]; + } + title:@"Refresh Reels"]; + } else { + return %orig(arg1, arg2); + } +} +%end + +// * Disable volume/mute button triggering unmutes +%hook IGAudioStatusAnnouncer +- (void)_muteSwitchStateChanged:(id)changed { + if (![SCIUtils getBoolPref:@"disable_auto_unmuting_reels"]) { + %orig(changed); + } +} +- (void)_didPressVolumeButton:(id)button { + if (![SCIUtils getBoolPref:@"disable_auto_unmuting_reels"]) { + %orig(button); + } +} +- (void)_didUnplugHeadphones:(id)headphones { + if (![SCIUtils getBoolPref:@"disable_auto_unmuting_reels"]) { + %orig(headphones); + } +} +%end \ No newline at end of file diff --git a/src/Features/StoriesAndMessages/DisableInstantsCreation.x b/src/Features/StoriesAndMessages/DisableInstantsCreation.x new file mode 100644 index 0000000..4787ca8 --- /dev/null +++ b/src/Features/StoriesAndMessages/DisableInstantsCreation.x @@ -0,0 +1,58 @@ +#import "../../Utils.h" + +#define QUICKSNAPENABLED(orig) return [SCIUtils getBoolPref:@"disable_instants_creation"] ? false : orig; + +// Demangled name: IGQuickSnapExperimentation.IGQuickSnapExperimentationHelper +%hook _TtC26IGQuickSnapExperimentation32IGQuickSnapExperimentationHelper ++ (_Bool)isQuicksnapEnabled:(id)enabled { + QUICKSNAPENABLED(%orig); +} ++ (_Bool)isQuicksnapEnabledInFeed:(id)feed { + QUICKSNAPENABLED(%orig); +} ++ (_Bool)isQuicksnapEnabledInInbox:(id)inbox { + QUICKSNAPENABLED(%orig); +} ++ (_Bool)isQuicksnapEnabledInStories:(id)stories { + QUICKSNAPENABLED(%orig); +} ++ (_Bool)isQuicksnapEnabledInNotesTray:(id)tray { + QUICKSNAPENABLED(%orig); +} ++ (_Bool)isQuicksnapEnabledInNotesTrayWithPeek:(id)peek { + QUICKSNAPENABLED(%orig); +} ++ (_Bool)isQuicksnapEnabledInNotesTrayWithPog:(id)pog { + QUICKSNAPENABLED(%orig); +} ++ (_Bool)isQuicksnapNotesTrayEmptyPogEnabled:(id)enabled { + QUICKSNAPENABLED(%orig); +} +// + (_Bool)isStoriesSpringEnabled:(id)enabled { +// return true; +// } +// + (_Bool)shouldEnableScreenshotBlocking:(id)blocking { +// return false; +// } +// + (_Bool)areFiltersEnabled:(id)enabled { +// return true; +// } +// + (_Bool)isBottomsheetCustomAudienceEnabled:(id)enabled { +// return true; +// } +// + (_Bool)isVideoCaptureEnabled:(id)enabled { +// return true; +// } +%end + +// %hook IGDirectNotesTrayRowCell +// - (_Bool)isQuicksnapPeekVisible { +// return true; +// } +// %end + +// %hook IGDirectNotesTrayRowSectionController +// - (_Bool)isQuicksnapPeekVisible { +// return true; +// } +// %end \ No newline at end of file diff --git a/src/Features/StoriesAndMessages/DisableStorySeen.x b/src/Features/StoriesAndMessages/DisableStorySeen.x new file mode 100644 index 0000000..765cab0 --- /dev/null +++ b/src/Features/StoriesAndMessages/DisableStorySeen.x @@ -0,0 +1,245 @@ +#import "../../Utils.h" +#import "../../InstagramHeaders.h" + +// Bypass flag: when YES, all hooks let calls through (for manual mark as seen) +static BOOL sciSeenBypassActive = NO; + +static BOOL sciShouldBlockSeen() { + if (sciSeenBypassActive) return NO; + return [SCIUtils getBoolPref:@"no_seen_receipt"]; +} + +// Block story seen receipts by intercepting all known upload/send paths +%hook IGStorySeenStateUploader +- (id)initWithUserSessionPK:(id)arg1 networker:(id)arg2 { + if (sciShouldBlockSeen()) { + NSLog(@"[SCInsta] Blocked story seen uploader init"); + return nil; + } + return %orig; +} +- (void)uploadSeenStateWithMedia:(id)arg1 { + if (sciShouldBlockSeen()) return; + %orig; +} +- (void)uploadSeenState { + if (sciShouldBlockSeen()) return; + %orig; +} +- (void)_uploadSeenState:(id)arg1 { + if (sciShouldBlockSeen()) return; + %orig; +} +- (void)sendSeenReceipt:(id)arg1 { + if (sciShouldBlockSeen()) return; + %orig; +} +- (id)networker { + if (sciShouldBlockSeen()) return nil; + return %orig; +} +%end + +// Block seen tracking on fullscreen section controller +%hook IGStoryFullscreenSectionController +- (void)markItemAsSeen:(id)arg1 { + if (sciShouldBlockSeen()) return; + %orig; +} +- (void)_markItemAsSeen:(id)arg1 { + if (sciShouldBlockSeen()) return; + %orig; +} +- (void)storySeenStateDidChange:(id)arg1 { + if (sciShouldBlockSeen()) return; + %orig; +} +- (void)sendSeenRequestForCurrentItem { + if (sciShouldBlockSeen()) return; + %orig; +} +- (void)markCurrentItemAsSeen { + if (sciShouldBlockSeen()) return; + %orig; +} +%end + +// Block seen on viewer controller +%hook IGStoryViewerViewController +- (void)markAsSeen { + if (sciShouldBlockSeen()) return; + %orig; +} +- (void)markStoryAsSeen:(id)arg1 { + if (sciShouldBlockSeen()) return; + %orig; +} +- (void)_markCurrentStoryAsSeen { + if (sciShouldBlockSeen()) return; + %orig; +} +- (void)markCurrentMediaAsSeen { + if (sciShouldBlockSeen()) return; + %orig; +} +%end + +// Block local visual seen state updates on the story tray +// This prevents the colored ring from turning grey after viewing +%hook IGStoryTrayViewModel +- (void)markAsSeen { + if (sciShouldBlockSeen()) return; + %orig; +} +- (void)setHasUnseenMedia:(BOOL)arg1 { + if (sciShouldBlockSeen()) { + // Always keep as unseen visually + %orig(YES); + return; + } + %orig; +} +- (BOOL)hasUnseenMedia { + if (sciShouldBlockSeen()) return YES; + return %orig; +} +- (void)setIsSeen:(BOOL)arg1 { + if (sciShouldBlockSeen()) { + %orig(NO); + return; + } + %orig; +} +- (BOOL)isSeen { + if (sciShouldBlockSeen()) return NO; + return %orig; +} +%end + +// Also try to block on the story item model level +%hook IGStoryItem +- (void)setHasSeen:(BOOL)arg1 { + if (sciShouldBlockSeen()) { + %orig(NO); + return; + } + %orig; +} +- (BOOL)hasSeen { + if (sciShouldBlockSeen()) return NO; + return %orig; +} +%end + +// Manual "mark as seen" button on story overlay +%hook IGStoryFullscreenOverlayView +- (void)didMoveToSuperview { + %orig; + + if (!sciShouldBlockSeen()) return; + if ([self viewWithTag:1339]) return; + + UIButton *seenBtn = [UIButton buttonWithType:UIButtonTypeCustom]; + seenBtn.tag = 1339; + + UIImageSymbolConfiguration *config = [UIImageSymbolConfiguration configurationWithPointSize:14 weight:UIImageSymbolWeightMedium]; + UIImage *icon = [UIImage systemImageNamed:@"eye" withConfiguration:config]; + [seenBtn setImage:icon forState:UIControlStateNormal]; + [seenBtn setTitle:@" Mark seen" forState:UIControlStateNormal]; + [seenBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; + seenBtn.titleLabel.font = [UIFont systemFontOfSize:11 weight:UIFontWeightMedium]; + seenBtn.tintColor = [UIColor whiteColor]; + seenBtn.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.4]; + seenBtn.layer.cornerRadius = 14; + seenBtn.clipsToBounds = YES; + seenBtn.contentEdgeInsets = UIEdgeInsetsMake(6, 10, 6, 12); + + seenBtn.translatesAutoresizingMaskIntoConstraints = NO; + [seenBtn addTarget:self action:@selector(sciMarkSeenTapped:) forControlEvents:UIControlEventTouchUpInside]; + [self addSubview:seenBtn]; + + // Bottom right, moved up to avoid overlapping existing buttons + [NSLayoutConstraint activateConstraints:@[ + [seenBtn.bottomAnchor constraintEqualToAnchor:self.safeAreaLayoutGuide.bottomAnchor constant:-110], + [seenBtn.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-12], + [seenBtn.heightAnchor constraintEqualToConstant:28] + ]]; +} + +%new - (void)sciMarkSeenTapped:(UIButton *)sender { + // Haptic feedback + UIImpactFeedbackGenerator *haptic = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium]; + [haptic impactOccurred]; + + // Visual feedback + [UIView animateWithDuration:0.1 animations:^{ + sender.transform = CGAffineTransformMakeScale(0.85, 0.85); + sender.alpha = 0.6; + } completion:^(BOOL finished) { + [UIView animateWithDuration:0.15 animations:^{ + sender.transform = CGAffineTransformIdentity; + sender.alpha = 1.0; + }]; + }]; + + // Enable bypass so all our hooks let the calls through + sciSeenBypassActive = YES; + + BOOL didMark = NO; + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + // Try all view controllers in responder chain + UIResponder *responder = self; + while (responder) { + // IGStoryViewerViewController + if ([responder isKindOfClass:NSClassFromString(@"IGStoryViewerViewController")]) { + SEL selectors[] = { + @selector(markAsSeen), @selector(markStoryAsSeen:), + @selector(_markCurrentStoryAsSeen), @selector(markCurrentMediaAsSeen) + }; + for (int i = 0; i < 4; i++) { + if ([responder respondsToSelector:selectors[i]]) { + NSLog(@"[SCInsta] Manual seen: calling %@ on IGStoryViewerViewController", NSStringFromSelector(selectors[i])); + if (selectors[i] == @selector(markStoryAsSeen:)) { + [responder performSelector:selectors[i] withObject:nil]; + } else { + [responder performSelector:selectors[i]]; + } + didMark = YES; + } + } + } + // IGStoryFullscreenSectionController (might be in responder chain as next responder of a child VC) + if ([responder isKindOfClass:NSClassFromString(@"IGStoryFullscreenSectionController")]) { + SEL selectors[] = { + @selector(markItemAsSeen:), @selector(markCurrentItemAsSeen), + @selector(sendSeenRequestForCurrentItem) + }; + for (int i = 0; i < 3; i++) { + if ([responder respondsToSelector:selectors[i]]) { + NSLog(@"[SCInsta] Manual seen: calling %@ on IGStoryFullscreenSectionController", NSStringFromSelector(selectors[i])); + if (selectors[i] == @selector(markItemAsSeen:)) { + [responder performSelector:selectors[i] withObject:nil]; + } else { + [responder performSelector:selectors[i]]; + } + didMark = YES; + } + } + } + responder = [responder nextResponder]; + } + +#pragma clang diagnostic pop + + // Re-enable blocking + sciSeenBypassActive = NO; + + if (didMark) { + [SCIUtils showToastForDuration:1.5 title:@"Marked as seen"]; + } else { + [SCIUtils showToastForDuration:2.0 title:@"Could not mark as seen" subtitle:@"Method not found"]; + } +} +%end diff --git a/src/Features/StoriesAndMessages/DisableTypingStatus.x b/src/Features/StoriesAndMessages/DisableTypingStatus.x new file mode 100644 index 0000000..b8e2251 --- /dev/null +++ b/src/Features/StoriesAndMessages/DisableTypingStatus.x @@ -0,0 +1,9 @@ +#import "../../Utils.h" + +%hook IGDirectTypingStatusService +- (void)updateOutgoingStatusIsActive:(_Bool)active threadKey:(id)key threadMetadata:(id)metadata typingStatusType:(long long)type { + if ([SCIUtils getBoolPref:@"disable_typing_status"]) return; + + return %orig(active, key, metadata, type); +} +%end \ No newline at end of file diff --git a/src/Features/StoriesAndMessages/KeepDeletedMessages.x b/src/Features/StoriesAndMessages/KeepDeletedMessages.x new file mode 100644 index 0000000..014b66d --- /dev/null +++ b/src/Features/StoriesAndMessages/KeepDeletedMessages.x @@ -0,0 +1,22 @@ +#import "../../Utils.h" +#import "../../InstagramHeaders.h" + +%hook IGDirectRealtimeIrisThreadDelta ++ (id)removeItemWithMessageId:(id)arg1 { + if ([SCIUtils getBoolPref:@"keep_deleted_message"]) { + arg1 = NULL; + } + + return %orig(arg1); +} +%end + +%hook IGDirectMessageUpdate ++ (id)removeMessageWithMessageId:(id)arg1{ + if ([SCIUtils getBoolPref:@"keep_deleted_message"]) { + arg1 = NULL; + } + + return %orig(arg1); +} +%end \ No newline at end of file diff --git a/src/Features/StoriesAndMessages/SeenButtons.x b/src/Features/StoriesAndMessages/SeenButtons.x new file mode 100644 index 0000000..4a8ab14 --- /dev/null +++ b/src/Features/StoriesAndMessages/SeenButtons.x @@ -0,0 +1,96 @@ +#import "../../InstagramHeaders.h" +#import "../../Tweak.h" +#import "../../Utils.h" + +// Seen buttons (in DMs) +// - Enables no seen for messages +// - Enables unlimited views of DM visual messages +%hook IGTallNavigationBarView +- (void)setRightBarButtonItems:(NSArray *)items { + NSMutableArray *new_items = [[items filteredArrayUsingPredicate: + [NSPredicate predicateWithBlock:^BOOL(UIView *value, NSDictionary *_) { + if ([SCIUtils getBoolPref:@"hide_reels_blend"]) { + return ![value.accessibilityIdentifier isEqualToString:@"blend-button"]; + } + + return true; + }] + ] mutableCopy]; + + // Messages seen + if ([SCIUtils getBoolPref:@"remove_lastseen"]) { + UIBarButtonItem *seenButton = [[UIBarButtonItem alloc] initWithImage:[UIImage systemImageNamed:@"checkmark.message"] style:UIBarButtonItemStylePlain target:self action:@selector(seenButtonHandler:)]; + [new_items addObject:seenButton]; + } + + // DM visual messages viewed + if ([SCIUtils getBoolPref:@"unlimited_replay"]) { + UIBarButtonItem *dmVisualMsgsViewedButton = [[UIBarButtonItem alloc] initWithImage:[UIImage systemImageNamed:@"photo.badge.checkmark"] style:UIBarButtonItemStylePlain target:self action:@selector(dmVisualMsgsViewedButtonHandler:)]; + [new_items addObject:dmVisualMsgsViewedButton]; + + if (dmVisualMsgsViewedButtonEnabled) { + [dmVisualMsgsViewedButton setTintColor:SCIUtils.SCIColor_Primary]; + } else { + [dmVisualMsgsViewedButton setTintColor:UIColor.labelColor]; + } + } + + %orig([new_items copy]); +} + +// Messages seen button +%new - (void)seenButtonHandler:(UIBarButtonItem *)sender { + UIViewController *nearestVC = [SCIUtils nearestViewControllerForView:self]; + if ([nearestVC isKindOfClass:%c(IGDirectThreadViewController)]) { + [(IGDirectThreadViewController *)nearestVC markLastMessageAsSeen]; + + [SCIUtils showToastForDuration:2.5 title:@"Marked messages as seen"]; + } +} +// DM visual messages viewed button +%new - (void)dmVisualMsgsViewedButtonHandler:(UIBarButtonItem *)sender { + if (dmVisualMsgsViewedButtonEnabled) { + dmVisualMsgsViewedButtonEnabled = false; + [sender setTintColor:UIColor.labelColor]; + + [SCIUtils showToastForDuration:4.5 title:@"Visual messages can be replayed without expiring"]; + } + else { + dmVisualMsgsViewedButtonEnabled = true; + [sender setTintColor:SCIUtils.SCIColor_Primary]; + + [SCIUtils showToastForDuration:4.5 title:@"Visual messages will now expire after viewing"]; + } +} +%end + +// Messages seen logic +%hook IGDirectThreadViewListAdapterDataSource +- (BOOL)shouldUpdateLastSeenMessage { + if ([SCIUtils getBoolPref:@"remove_lastseen"]) { + return false; + } + + return %orig; +} +%end + +// DM stories viewed logic +%hook IGDirectVisualMessageViewerEventHandler +- (void)visualMessageViewerController:(id)arg1 didBeginPlaybackForVisualMessage:(id)arg2 atIndex:(NSInteger)arg3 { + if ([SCIUtils getBoolPref:@"unlimited_replay"]) { + // Check if dm stories should be marked as viewed + if (dmVisualMsgsViewedButtonEnabled) { + %orig; + } + } +} +- (void)visualMessageViewerController:(id)arg1 didEndPlaybackForVisualMessage:(id)arg2 atIndex:(NSInteger)arg3 mediaCurrentTime:(CGFloat)arg4 forNavType:(NSInteger)arg5 { + if ([SCIUtils getBoolPref:@"unlimited_replay"]) { + // Check if dm stories should be marked as viewed + if (dmVisualMsgsViewedButtonEnabled) { + %orig; + } + } +} +%end \ No newline at end of file diff --git a/src/Features/StoriesAndMessages/VisualMsgModifier.x b/src/Features/StoriesAndMessages/VisualMsgModifier.x new file mode 100644 index 0000000..31ce8ff --- /dev/null +++ b/src/Features/StoriesAndMessages/VisualMsgModifier.x @@ -0,0 +1,21 @@ +#import "../../Utils.h" + +%hook IGDirectVisualMessage +- (NSInteger)viewMode { + NSInteger mode = %orig; + + // * Modes * + // 0 - View Once + // 1 - Replayable + + if ([SCIUtils getBoolPref:@"disable_view_once_limitations"]) { + if (mode == 0) { + mode = 1; + + NSLog(@"[SCInsta] Modifying visual message from read-once to replayable"); + } + } + + return mode; +} +%end \ No newline at end of file diff --git a/src/InstagramHeaders.h b/src/InstagramHeaders.h new file mode 100644 index 0000000..90fa0f6 --- /dev/null +++ b/src/InstagramHeaders.h @@ -0,0 +1,616 @@ +#import +#include +#import +#import "../modules/JGProgressHUD/JGProgressHUD.h" + +#ifdef __cplusplus +#define _Bool bool +#endif + +@interface NSURL () +- (id)normalizedURL; // method provided by Instagram app +@end + +@interface IGActionableConfirmationToastViewModel : NSObject { + NSString *_text_annotatedTitleText; + NSString *_text_annotatedSubtitleText; +} +@end + +@interface IGActionableConfirmationToastPresenter : NSObject +- (void)showAlertWithViewModel:(id)model isAnimated:(_Bool)animated animationDuration:(double)duration presentationPriority:(long long)priority tapActionBlock:(id)tap presentedHandler:(id)presented dismissedHandler:(id)dismissed; +- (void)hideAlert; +@end + +@interface IGRootViewController : UIViewController +- (IGActionableConfirmationToastPresenter *)toastPresenter; + +- (void)addHandleLongPress; // new +- (void)handleLongPress:(UILongPressGestureRecognizer *)sender; // new +@end + +@interface IGViewController : UIViewController +- (void)_superPresentViewController:(UIViewController *)viewController animated:(BOOL)animated completion:(id)completion; +@end + +@interface IGMainFeedAppHeaderController : UIViewController +- (void)_superPresentViewController:(UIViewController *)viewController animated:(BOOL)animated completion:(id)completion; // new +@end + +@interface IGShimmeringGridView : UIView +@end + +@interface IGExploreGridViewController : IGViewController +@end + +@interface UIImage () +- (NSString *)ig_imageName; +@end + +@interface IGProfileMenuSheetViewController : IGViewController +@end + +@interface IGTabBar: UIView +@end + +@interface IGTabBarController : UIViewController +@end + +@interface IGTableViewCell: UITableViewCell +- (id)initWithReuseIdentifier:(NSString *)identifier; +@end + +@interface IGProfileSheetTableViewCell : IGTableViewCell +@end + +@interface IGTallNavigationBarView : UIView +@end + +@interface UIView (RCTViewUnmounting) +@property(retain, nonatomic) UIViewController *viewController; +- (UIView *)_rootView; +@end + +@interface IGImageSpecifier : NSObject +@property(readonly, nonatomic) NSURL *url; +@end + +@interface IGVideo : NSObject +- (id)sortedVideoURLsBySize; // Before Instagram v398 +- (id)allVideoURLs; // After Instagram v398 +@end + +@interface IGPhoto : NSObject +- (id)imageURLForWidth:(CGFloat)width; +@end + +@interface IGBaseMedia : NSObject +@property (retain, nonatomic) id explorePostInFeed; +@end + +@interface IGMedia : IGBaseMedia +@property(readonly) IGVideo *video; +@property(readonly) IGPhoto *photo; +@end + +@interface IGPostItem : NSObject +@property(readonly) IGVideo *video; +@property(readonly) IGPhoto *photo; +@end + +@interface IGPageMediaView : UIView +@property(readonly) NSMutableArray *items; +- (IGPostItem *)currentMediaItem; +@end + +@interface IGFeedItem : NSObject +@property long long likeCount; +@property(readonly) IGVideo *video; +- (BOOL)isSponsored; +- (BOOL)isSponsoredApp; +@end + +@interface IGImageView : UIImageView +@property(retain, nonatomic) IGImageSpecifier *imageSpecifier; +@end + +@interface IGFeedItemPagePhotoCell : UICollectionViewCell +@property (nonatomic, strong) id post; +@property (nonatomic, strong) IGPostItem *pagePhotoPost; +@end + +@interface IGProfilePicturePreviewViewController : UIViewController +{ + IGImageView *_profilePictureView; +} +@property (nonatomic, strong) JGProgressHUD *hud; +- (void)addHandleLongPress; // new +- (void)handleLongPress:(UILongPressGestureRecognizer *)sender; // new +@end + +@interface IGFeedItemMediaCell : UICollectionViewCell +@property(retain, nonatomic) IGMedia *post; +- (UIImage *)mediaCellCurrentlyDisplayedImage; +@end + +@interface IGFeedItemPhotoCell : IGFeedItemMediaCell +@end + +@interface IGFeedItemPhotoCellConfiguration : NSObject +@end + +@interface IGFeedPhotoView : UIView +@property (nonatomic, strong) id delegate; + +- (void)addLongPressGestureRecognizer; // new +- (void)sciAddDownloadButton; // new +- (void)handleLongPress:(UILongPressGestureRecognizer *)sender; // new +@end + +@interface IGModernFeedVideoCell : UIView +- (id)mediaCellFeedItem; +- (void)addLongPressGestureRecognizer; // new +- (void)sciAddDownloadButton; // new +- (void)handleLongPress:(UILongPressGestureRecognizer *)sender; // new +@end + +@interface IGSundialViewerVideoCell : UIView +@property(readonly, nonatomic) IGMedia *video; + +- (void)addLongPressGestureRecognizer; // new +@end + +@interface IGSundialViewerPhotoView : UIView +- (void)addLongPressGestureRecognizer; // new +@end + +@interface IGImageProgressView : UIView +@property(retain, nonatomic) IGImageSpecifier *imageSpecifier; +@end + +@interface IGStatefulVideoPlayer : NSObject +@end + +@interface IGStoryPhotoView : UIView +- (id)item; + +- (void)addLongPressGestureRecognizer; // new +@end + +@interface IGStoryFullscreenSectionController : NSObject +@property (nonatomic, strong, readwrite) IGMedia *currentStoryItem; +@end + +@interface IGStoryVideoView : UIView +@property (nonatomic, weak, readwrite) IGStoryFullscreenSectionController *captionDelegate; + +- (void)addLongPressGestureRecognizer; // new +@end + +@interface IGStoryModernVideoView : UIView +@property (nonatomic, readonly) IGMedia *item; + +- (void)addLongPressGestureRecognizer; // new +@end + +@interface IGStoryFullscreenOverlayView : UIView +@property (nonatomic, weak, readwrite) id gestureDelegate; +- (id)gestureDelegate; +- (void)addLongPressGestureRecognizer; // new +@end + +@interface IGDirectVisualMessageViewerController : UIViewController +@end + +@interface IGDirectVisualMessageViewerViewModeAwareDataSource : NSObject +@end + +@interface IGDirectVisualMessage : NSObject +- (id)rawVideo; +@end + +@interface IGUser : NSObject +@property NSInteger followStatus; +@property(copy) NSString *username; +@property BOOL followsCurrentUser; +@end + +@interface IGFollowController : NSObject +@property IGUser *user; +@end + +@interface IGCoreTextView : UIView +@property(nonatomic, strong) NSString *text; +- (void)addHandleLongPress; // new +- (void)handleLongPress:(UILongPressGestureRecognizer *)sender; // new +@end + +@interface IGUserSession : NSObject +@property (readonly, nonatomic) IGUser *user; +@end + +@interface IGWindow : UIWindow +@property (nonatomic) __weak IGUserSession *userSession; +@end + +@interface IGShakeWindow : UIWindow +@property (nonatomic) __weak IGUserSession *userSession; +@end + +@interface IGStyledString : NSObject +@property (retain, nonatomic) NSMutableAttributedString *attributedString; +- (void)appendString:(id)arg1; +@end + +@interface IGInstagramAppDelegate : NSObject +@end + +@interface IGDirectInboxSearchAIAgentsPillsContainerCell : UIView +@end + +@interface IGTapButton : UIButton +@end + +@interface IGLabel : UILabel +@end + +@interface IGLabelItemViewModel : NSObject +- (id)labelTitle; +- (id)uniqueIdentifier; +@end + +@interface IGDirectInboxSuggestedThreadCellViewModel : NSObject +@end + +@interface IGDirectInboxHeaderCellViewModel : NSObject +- (id)title; +@end + +@interface IGSearchResultViewModel : NSObject +- (id)title; +- (NSUInteger)itemType; +@end + +@interface IGDirectShareRecipient : NSObject +- (NSString *)threadName; +- (BOOL)isBroadcastChannel; +@end + +@interface IGDirectRecipientCellViewModel : NSObject +- (id)recipient; +- (NSInteger)sectionType; +@end + +@interface IGDirectInboxSearchAIAgentsSuggestedPromptRowCell : UIView +@end + +@interface IGDSSegmentedPillBarView : UIView +- (id)delegate; +@end + +@interface IGImageWithAccessoryButton : IGTapButton +- (void)addLongPressGestureRecognizer; // new +- (void)handleLongPress:(UILongPressGestureRecognizer *)gr; // new +@end + +@interface IGHomeFeedHeaderViewController +- (void)headerDidLongPressLogo:(id)arg1; +@end + +@interface IGSearchBarDonutButton : UIView +@end + +@interface IGAnimatablePlaceholderTextField : UITextField +@end + +@interface IGDirectCommandSystemViewModel : NSObject +- (id)row; +@end + +@interface IGDirectCommandSystemRow : NSObject +@end + +@interface IGDirectCommandSystemResult : NSObject +- (id)title; +- (id)commandString; +@end + +@interface IGGrowingTextView : UIView +- (id)placeholderText; +- (void)setPlaceholderText:(id)arg1; +@end + +@interface IGUnifiedVideoCollectionView : UIScrollView +@end + +@interface IGBadgedNavigationButton : UIView +- (void)addLongPressGestureRecognizer; // new +@end + +@interface IGSearchBar : UIView +- (NSObject *)sanitizePlaceholderForConfig:(NSObject *)config; // new +@end + +@interface IGSearchBarConfig : NSObject +@end + +@interface IGDirectComposer : UIView +- (NSObject *)patchConfig:(NSObject *)config; // new +@end + +@interface IGDirectComposerConfig : NSObject +@end + +@interface IGAnimatablePlaceholderTextFieldContainer : UIView +@end + +@interface IGDirectInboxConfig : NSObject +@end + +@interface IGDirectMediaPickerConfig : NSObject +@end + +@interface IGDirectMediaPickerGalleryConfig : NSObject +@end + +@interface IGStoryEyedropperToggleButton : UIControl +@property (nonatomic, strong, readwrite) UIColor *color; + +- (void)setPushedDown:(BOOL)pushedDown; + +- (void)addLongPressGestureRecognizer; // new +@end + +@interface IGStoryTextEntryViewController : UIViewController +- (void)textViewControllerDidUpdateWithColor:(id)color colorSource:(NSInteger)source; +@end + +@interface IGStoryColorPaletteView : UIView +@end + +@interface IGProfilePictureImageView : UIView +@property (nonatomic, readonly) IGUser *userGQL; + +- (void)addLongPressGestureRecognizer; // new +@end + +@interface IGImageRequest : NSObject +- (id)url; +@end + +@interface IGDiscoveryGridItem : NSObject +- (id)model; +@end + +@interface IGStoryTextEntryControlsOverlayView : UIView + +@property (readonly, nonatomic) NSMutableArray *animationTypes; +@property (readonly, nonatomic) NSMutableArray *effectTypes; + +- (void)reloadData; + +@end + +@interface _TtC27IGGalleryDestinationToolbar31IGGalleryDestinationToolbarView : UIView +@property(nonatomic, copy, readwrite) NSArray *tools; +@end + +@interface IGSundialViewerVerticalUFI : UIView +- (void)_didTapLikeButton:(id)arg1; +- (void)_didTapRepostButton:(id)arg1; +@end + +@interface IGMainAppSurfaceIntent : NSObject +- (id)tabStringFromSurfaceIntent; +@end + +@interface IGSundialFeedViewController : UIViewController +- (void)refreshControlDidEndFinishLoadingAnimation:(id)arg1; +@end + +@interface IGRefreshControl : UIControl +@end + +@interface IGDirectThreadViewDrawingViewController : UIViewController +- (void)drawingControls:controls didSelectColor:color; +@end + +@interface IGSundialViewerNavigationBarOld : UIView +@end + +@interface IGUFIInteractionCountsView : UIView +@end + +@interface IGFeedItemUFICell : UIView +- (void)UFIButtonBarDidTapOnRepost:(id)arg1; +@end + +@interface IGNotesCreationFeatureSupportModel : NSObject +@end + +@interface IGNotesCustomThemeCreationModel : NSObject ++ (id)defaultModelForExpressiveEmojiType:(id)arg1; +@end + +@interface IGDirectNotesComposerViewController : UIViewController +- (void)notesBubbleEditorViewControllerDidUpdateWithCustomThemeCreationModel:(id)model; +@end + +@interface _TtC20IGDirectNotesUISwift41IGDirectNotesBubbleEditorColorPaletteView : UIView +@property (nonatomic, copy) UIColor *backgroundColor; // new +@property (nonatomic, copy) UIColor *textColor; // new +@property (nonatomic, copy) NSString *emojiText; // new + +- (void)presentColorPicker:(NSString *)target; // new +- (void)applySCICustomTheme:(NSString *)target; // new +@end + +@interface _TtC20IGDirectNotesUISwift39IGDirectNotesBubbleEditorViewController : UIViewController +@property (nonatomic) IGDirectNotesComposerViewController *delegate; +@end + +@interface IGDSBottomButtonsView : UIView +- (void)setPrimaryButtonEnabled:(BOOL)enabled; +- (void)setSecondaryButtonEnabled:(BOOL)enabled; +@end + +@interface IGStoryTrayViewModel : NSObject +@property (nonatomic, readonly) NSString *pk; +@property (nonatomic, readonly) BOOL isUnseenNux; +@end + +@interface _TtC32IGSundialOrganicCTAContainerView32IGSundialOrganicCTAContainerView : UIView +@end + +@interface IGCommentThreadViewController : UIViewController +@end + +@interface IGSeeAllItemConfiguration : NSObject +@property (readonly, nonatomic) long long destination; +@end + +@interface IGDSMenuItem : NSObject +@end + +@interface IGDirectThreadViewController : UIViewController +- (void)markLastMessageAsSeen; +@end + +@interface IGTabBarButton : UIButton +- (void)addHandleLongPress; // new +@end + +@interface IGStoryFullscreenDefaultFooterView : NSObject +@end + +@interface IGDirectThreadThemePickerOption : NSObject +@end + +@interface IGCreationActionBarButton : UIButton +@end + +@interface IGCreationActionBarLabeledButton : NSObject +@property (readonly, nonatomic) IGCreationActionBarButton *button; +@end + + + +///////////////////////////////////////////////////////////////////////////// + + + +static BOOL is_iPad() { + if ([(NSString *)[UIDevice currentDevice].model hasPrefix:@"iPad"]) { + return YES; + } + return NO; +} + + + +///////////////////////////////////////////////////////////////////////////// + + + +static UIViewController * _Nullable _topMostController(UIViewController * _Nonnull cont) { + UIViewController *topController = cont; + while (topController.presentedViewController) { + topController = topController.presentedViewController; + } + if ([topController isKindOfClass:[UINavigationController class]]) { + UIViewController *visible = ((UINavigationController *)topController).visibleViewController; + if (visible) { + topController = visible; + } + } + return (topController != cont ? topController : nil); +} +static UIViewController * _Nonnull topMostController() { + UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController; + UIViewController *next = nil; + while ((next = _topMostController(topController)) != nil) { + topController = next; + } + return topController; +} + +@class FLEXAlert, FLEXAlertAction; + +typedef void (^FLEXAlertReveal)(void); +typedef void (^FLEXAlertBuilder)(FLEXAlert *make); +typedef FLEXAlert * _Nonnull (^FLEXAlertStringProperty)(NSString * _Nullable); +typedef FLEXAlert * _Nonnull (^FLEXAlertStringArg)(NSString * _Nullable); +typedef FLEXAlert * _Nonnull (^FLEXAlertTextField)(void(^configurationHandler)(UITextField *textField)); +typedef FLEXAlertAction * _Nonnull (^FLEXAlertAddAction)(NSString *title); +typedef FLEXAlertAction * _Nonnull (^FLEXAlertActionStringProperty)(NSString * _Nullable); +typedef FLEXAlertAction * _Nonnull (^FLEXAlertActionProperty)(void); +typedef FLEXAlertAction * _Nonnull (^FLEXAlertActionBOOLProperty)(BOOL); +typedef FLEXAlertAction * _Nonnull (^FLEXAlertActionHandler)(void(^handler)(NSArray *strings)); + +@interface FLEXAlert : NSObject + +// Shows a simple alert with one button which says "Dismiss" ++ (void)showAlert:(NSString * _Nullable)title message:(NSString * _Nullable)message from:(UIViewController *)viewController; + +// Shows a simple alert with no buttons and only a title, for half a second ++ (void)showQuickAlert:(NSString *)title from:(UIViewController *)viewController; + +// Construct and display an alert ++ (void)makeAlert:(FLEXAlertBuilder)block showFrom:(UIViewController *)viewController; +// Construct and display an action sheet-style alert ++ (void)makeSheet:(FLEXAlertBuilder)block + showFrom:(UIViewController *)viewController + source:(id)viewOrBarItem; + +// Construct an alert ++ (UIAlertController *)makeAlert:(FLEXAlertBuilder)block; +// Construct an action sheet-style alert ++ (UIAlertController *)makeSheet:(FLEXAlertBuilder)block; + +// Set the alert's title. +/// +// Call in succession to append strings to the title. +@property (nonatomic, readonly) FLEXAlertStringProperty title; +// Set the alert's message. +/// +// Call in succession to append strings to the message. +@property (nonatomic, readonly) FLEXAlertStringProperty message; +// Add a button with a given title with the default style and no action. +@property (nonatomic, readonly) FLEXAlertAddAction button; +// Add a text field with the given (optional) placeholder text. +@property (nonatomic, readonly) FLEXAlertStringArg textField; +// Add and configure the given text field. +/// +// Use this if you need to more than set the placeholder, such as +// supply a delegate, make it secure entry, or change other attributes. +@property (nonatomic, readonly) FLEXAlertTextField configuredTextField; + +@end + +@interface FLEXAlertAction : NSObject + +// Set the action's title. +/// +// Call in succession to append strings to the title. +@property (nonatomic, readonly) FLEXAlertActionStringProperty title; +// Make the action destructive. It appears with red text. +@property (nonatomic, readonly) FLEXAlertActionProperty destructiveStyle; +// Make the action cancel-style. It appears with a bolder font. +@property (nonatomic, readonly) FLEXAlertActionProperty cancelStyle; +// Enable or disable the action. Enabled by default. +@property (nonatomic, readonly) FLEXAlertActionBOOLProperty enabled; +// Give the button an action. The action takes an array of text field strings. +@property (nonatomic, readonly) FLEXAlertActionHandler handler; +// Access the underlying UIAlertAction, should you need to change it while +// the encompassing alert is being displayed. For example, you may want to +// enable or disable a button based on the input of some text fields in the alert. +// Do not call this more than once per instance. +@property (nonatomic, readonly) UIAlertAction *action; + +@end +@interface FLEXManager : NSObject ++ (instancetype)sharedManager; +- (void)showExplorer; +- (void)hideExplorer; +- (void)toggleExplorer; +@end \ No newline at end of file diff --git a/src/QuickLook.h b/src/QuickLook.h new file mode 100644 index 0000000..31ec00a --- /dev/null +++ b/src/QuickLook.h @@ -0,0 +1,10 @@ +#import +#import + +@interface QuickLookDelegate : NSObject + +@property (nonatomic, strong) NSArray *previewItemURLs; + +- (instancetype)initWithPreviewItemURLs:(NSArray *)urls; + +@end \ No newline at end of file diff --git a/src/QuickLook.m b/src/QuickLook.m new file mode 100644 index 0000000..379ee35 --- /dev/null +++ b/src/QuickLook.m @@ -0,0 +1,29 @@ +#import "QuickLook.h" + +@implementation QuickLookDelegate + +- (instancetype)initWithPreviewItemURLs:(NSArray *)urls { + self = [super init]; + if (self) { + _previewItemURLs = [urls copy]; + } + return self; +} + +/* * QLPreviewControllerDataSource Protocol * */ + +- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller { + return self.previewItemURLs.count; +} + +- (id)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index { + return self.previewItemURLs[index]; +} + +/* QLPreviewControllerDelegate Protocol */ + +// - (void)previewControllerWillDismiss:(QLPreviewController *)controller {} + +// - (void)previewControllerDidDismiss:(QLPreviewController *)controller {} + +@end \ No newline at end of file diff --git a/src/Settings/SCISetting.h b/src/Settings/SCISetting.h new file mode 100644 index 0000000..5a45749 --- /dev/null +++ b/src/Settings/SCISetting.h @@ -0,0 +1,105 @@ +#import +#import +#import "SCISymbol.h" + +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, SCITableCell) { + SCITableCellStatic, + SCITableCellLink, + SCITableCellSwitch, + SCITableCellStepper, + SCITableCellButton, + SCITableCellMenu, + SCITableCellNavigation, +}; + +/// + +@interface SCISetting : NSObject + +@property (nonatomic, readonly) SCITableCell type; + +@property (nonatomic, strong) NSString *title; +@property (nonatomic, strong) NSString *subtitle; + +@property (nonatomic, strong, nullable) SCISymbol *icon; +@property (nonatomic, strong) NSString *defaultsKey; + +@property (nonatomic, strong) NSURL *url; +@property (nonatomic, strong) NSURL *imageUrl; + +@property (nonatomic) BOOL requiresRestart; + +@property (nonatomic) double min; +@property (nonatomic) double max; +@property (nonatomic) double step; +@property (nonatomic, copy) NSString *label; +@property (nonatomic, copy) NSString *singularLabel; + +@property (nonatomic, copy) void (^action)(void); + +@property (nonatomic, strong) UIMenu *baseMenu; + +@property (nonatomic, strong) NSArray *navSections; +@property (nonatomic, strong) UIViewController *navViewController; + ++ (instancetype)staticCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + icon:(nullable SCISymbol *)icon; + ++ (instancetype)linkCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + icon:(nullable SCISymbol *)icon + url:(NSString *)url; + ++ (instancetype)linkCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + imageUrl:(NSString *)imageUrl + url:(NSString *)url; + ++ (instancetype)switchCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + defaultsKey:(NSString *)defaultsKey; + ++ (instancetype)switchCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + defaultsKey:(NSString *)defaultsKey + requiresRestart:(BOOL)requiresRestart; + ++ (instancetype)stepperCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + defaultsKey:(NSString *)defaultsKey + min:(double)min + max:(double)max + step:(double)step + label:(NSString *)label + singularLabel:(NSString *)singularLabel; + ++ (instancetype)buttonCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + icon:(nullable SCISymbol *)icon + action:(void (^)(void))action; + ++ (instancetype)menuCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + menu:(UIMenu *)menu; + ++ (instancetype)navigationCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + icon:(nullable SCISymbol *)icon + navSections:(NSArray *)navSections; + ++ (instancetype)navigationCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + icon:(nullable SCISymbol *)icon + viewController:(UIViewController *)viewController; + + +# pragma mark - Instance methods + +- (UIMenu *)menuForButton:(UIButton *)button; + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/Settings/SCISetting.m b/src/Settings/SCISetting.m new file mode 100644 index 0000000..193e60c --- /dev/null +++ b/src/Settings/SCISetting.m @@ -0,0 +1,245 @@ +#import "SCISetting.h" + +@interface SCISetting () + +@property (nonatomic, readwrite) SCITableCell type; + +- (instancetype)initWithType:(SCITableCell)type NS_DESIGNATED_INITIALIZER; +- (instancetype)init NS_UNAVAILABLE; + +@end + +/// + +@implementation SCISetting + +// MARK: - - initWithType + +- (instancetype)initWithType:(SCITableCell)type { + self = [super init]; + + if (self) { + self.type = type; + } + + return self; +} + + +// MARK: - + staticCellWithTitle + ++ (instancetype)staticCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + icon:(nullable SCISymbol *)icon +{ + SCISetting *setting = [[self alloc] initWithType:SCITableCellStatic]; + + setting.title = title; + setting.subtitle = subtitle; + setting.icon = icon; + + return setting; +} + +// MARK: - + linkCellWithTitle + ++ (instancetype)linkCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + icon:(nullable SCISymbol *)icon + url:(NSString *)url +{ + SCISetting *setting = [[self alloc] initWithType:SCITableCellLink]; + + setting.title = title; + setting.subtitle = subtitle; + setting.icon = icon; + setting.url = [NSURL URLWithString:url]; + + return setting; +} + ++ (instancetype)linkCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + imageUrl:(NSString *)imageUrl + url:(NSString *)url +{ + SCISetting *setting = [[self alloc] initWithType:SCITableCellLink]; + + setting.title = title; + setting.subtitle = subtitle; + + setting.imageUrl = [NSURL URLWithString:imageUrl]; + setting.url = [NSURL URLWithString:url]; + + return setting; +} + +// MARK: - + switchCellWithTitle + ++ (instancetype)switchCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + defaultsKey:(NSString *)defaultsKey +{ + SCISetting *setting = [[self alloc] initWithType:SCITableCellSwitch]; + + setting.title = title; + setting.subtitle = subtitle; + setting.defaultsKey = defaultsKey; + + return setting; +} + ++ (instancetype)switchCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + defaultsKey:(NSString *)defaultsKey + requiresRestart:(BOOL)requiresRestart +{ + SCISetting *setting = [[self alloc] initWithType:SCITableCellSwitch]; + + setting.title = title; + setting.subtitle = subtitle; + setting.defaultsKey = defaultsKey; + setting.requiresRestart = requiresRestart; + + return setting; +} + +// MARK: - + stepperCellWithTitle + ++ (instancetype)stepperCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + defaultsKey:(NSString *)defaultsKey + min:(double)min + max:(double)max + step:(double)step + label:(NSString *)label + singularLabel:(NSString *)singularLabel +{ + SCISetting *setting = [[self alloc] initWithType:SCITableCellStepper]; + + setting.title = title; + setting.subtitle = subtitle; + setting.defaultsKey = defaultsKey; + + setting.min = min; + setting.max = max; + setting.step = step; + setting.label = label; + setting.singularLabel = singularLabel; + + return setting; +} + +// MARK: - + buttonCellWithTitle + ++ (instancetype)buttonCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + icon:(nullable SCISymbol *)icon + action:(void (^)(void))action +{ + SCISetting *setting = [[self alloc] initWithType:SCITableCellButton]; + + setting.title = title; + setting.subtitle = subtitle; + + setting.icon = icon; + setting.action = action; + + return setting; +} + +# pragma mark + menuCellWithTitle + ++ (instancetype)menuCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + menu:(UIMenu *)menu +{ + SCISetting *setting = [[self alloc] initWithType:SCITableCellMenu]; + + setting.title = title; + setting.subtitle = subtitle; + + setting.baseMenu = menu; + + return setting; +} + +// MARK: - + navigationCellWithTitle + ++ (instancetype)navigationCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + icon:(nullable SCISymbol *)icon + navSections:(NSArray *)navSections +{ + SCISetting *setting = [[self alloc] initWithType:SCITableCellNavigation]; + + setting.title = title; + setting.subtitle = subtitle; + + setting.icon = icon; + setting.navSections = navSections; + + return setting; +} + ++ (instancetype)navigationCellWithTitle:(NSString *)title + subtitle:(NSString *)subtitle + icon:(nullable SCISymbol *)icon + viewController:(UIViewController *)viewController +{ + SCISetting *setting = [[self alloc] initWithType:SCITableCellNavigation]; + + setting.title = title; + setting.subtitle = subtitle; + + setting.icon = icon; + setting.navViewController = viewController; + + return setting; +} + + +// MARK: - Instance methods + +- (UIMenu *)menuForButton:(UIButton *)button { + return [self submenuForButton:button submenu:self.baseMenu]; +} + +- (UIMenu *)submenuForButton:(UIButton *)button submenu:(UIMenu*)submenu { + NSMutableArray *children = [NSMutableArray array]; + + for (id obj in submenu.children) { + // Handle recursive submenus + if ([obj isKindOfClass:[UIMenu class]]) { + [children addObject:[self submenuForButton:button submenu:(UIMenu *)obj]]; + continue; + } + else if (![obj isKindOfClass:[UICommand class]]) { + continue; + } + + UICommand *child = obj; + + NSString *saved = [[NSUserDefaults standardUserDefaults] stringForKey:child.propertyList[@"defaultsKey"]]; + + UICommand *command = [UICommand commandWithTitle:child.title + image:child.image + action:child.action + propertyList:child.propertyList]; + + if ([child.propertyList[@"value"] isEqualToString:saved]) { + command.state = YES; + + [button setTitle:command.title forState:UIControlStateNormal]; + } + else { + command.state = NO; + } + + [children addObject:command]; + } + + return [UIMenu menuWithTitle:submenu.title image:nil identifier:nil options:submenu.options children:children]; +} + +@end diff --git a/src/Settings/SCISettingsViewController.h b/src/Settings/SCISettingsViewController.h new file mode 100644 index 0000000..cfada86 --- /dev/null +++ b/src/Settings/SCISettingsViewController.h @@ -0,0 +1,17 @@ +#import +#import +#import "TweakSettings.h" +#import "SCISetting.h" +#import "SCISymbol.h" +#import "../Utils.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface SCISettingsViewController : UIViewController + +- (instancetype)initWithTitle:(NSString *)title sections:(NSArray *)sections reduceMargin:(BOOL)reduceMargin; +- (instancetype)init; + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/Settings/SCISettingsViewController.m b/src/Settings/SCISettingsViewController.m new file mode 100644 index 0000000..cb211c9 --- /dev/null +++ b/src/Settings/SCISettingsViewController.m @@ -0,0 +1,356 @@ +#import "SCISettingsViewController.h" + +static char rowStaticRef[] = "row"; + +@interface SCISettingsViewController () + +@property (nonatomic, strong) UITableView *tableView; +@property (nonatomic, copy) NSArray *sections; +@property (nonatomic) BOOL reduceMargin; + +@end + +/// + +@implementation SCISettingsViewController + +- (instancetype)initWithTitle:(NSString *)title sections:(NSArray *)sections reduceMargin:(BOOL)reduceMargin { + self = [super init]; + + if (self) { + self.title = title; + self.reduceMargin = reduceMargin; + + // Exclude development cells from release builds + NSMutableArray *mutableSections = [sections mutableCopy]; + + [mutableSections enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSDictionary *section, NSUInteger index, BOOL *stop) { + + if ([section[@"header"] hasPrefix:@"_"] && [section[@"footer"] hasPrefix:@"_"]) { + if (![[SCIUtils IGVersionString] isEqualToString:@"0.0.0"]) { + [mutableSections removeObjectAtIndex:index]; + } + } + + else if ([section[@"header"] isEqualToString:@"Experimental"]) { + if (![[SCIUtils IGVersionString] hasSuffix:@"-dev"]) { + [mutableSections removeObjectAtIndex:index]; + } + } + + }]; + + self.sections = [mutableSections copy]; + } + + + return self; +} + +- (instancetype)init { + return [self initWithTitle:[SCITweakSettings title] sections:[SCITweakSettings sections] reduceMargin:YES]; +} + +- (void)viewDidLoad { + [super viewDidLoad]; + + self.navigationController.navigationBar.prefersLargeTitles = NO; + self.view.backgroundColor = UIColor.systemBackgroundColor; + + self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleInsetGrouped]; + self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + self.tableView.dataSource = self; + self.tableView.contentInset = UIEdgeInsetsMake(self.reduceMargin ? -30 : -10, 0, 0, 0); + self.tableView.delegate = self; + + [self.view addSubview:self.tableView]; +} + +- (void)viewWillDisappear:(BOOL)animated { + [super viewWillDisappear:animated]; + + if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"SCInstaFirstRun"] isEqualToString:SCIVersionString]) { + UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"SCInsta Settings Info" + message:@"In the future: Hold down on the three lines at the top right of your profile page, to re-open SCInsta settings." + preferredStyle:UIAlertControllerStyleAlert]; + + [alert addAction:[UIAlertAction actionWithTitle:@"I understand!" + style:UIAlertActionStyleDefault + handler:nil]]; + + UIViewController *presenter = self.presentingViewController; + [presenter presentViewController:alert animated:YES completion:nil]; + + // Done with first-time setup for this version + [[NSUserDefaults standardUserDefaults] setValue:SCIVersionString forKey:@"SCInstaFirstRun"]; + } +} + +// MARK: - UITableViewDataSource + +- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { + SCISetting *row = self.sections[indexPath.section][@"rows"][indexPath.row]; + if (!row) return nil; + + UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil]; + UIListContentConfiguration *cellContentConfig = cell.defaultContentConfiguration; + + cellContentConfig.text = row.title; + + // Subtitle + if (row.subtitle.length) { + cellContentConfig.secondaryText = row.subtitle; + cellContentConfig.textToSecondaryTextVerticalPadding = 4.5; + } + + // Icon + if (row.icon != nil) { + cellContentConfig.image = [row.icon image]; + cellContentConfig.imageProperties.tintColor = row.icon.color; + } + + // Image url + if (row.imageUrl != nil) { + [self loadImageFromURL:row.imageUrl atIndexPath:indexPath forTableView:tableView]; + + cellContentConfig.imageToTextPadding = 14; + } + + switch (row.type) { + case SCITableCellStatic: { + cell.selectionStyle = UITableViewCellSelectionStyleNone; + break; + } + + case SCITableCellLink: { + cellContentConfig.textProperties.color = [UIColor systemBlueColor]; + cellContentConfig.textProperties.font = [UIFont systemFontOfSize:[UIFont preferredFontForTextStyle:UIFontTextStyleBody].pointSize + weight:UIFontWeightMedium]; + + cell.selectionStyle = UITableViewCellSelectionStyleDefault; + + UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage systemImageNamed:@"safari"]]; + imageView.tintColor = [UIColor systemGray3Color]; + cell.accessoryView = imageView; + + break; + } + + case SCITableCellSwitch: { + UISwitch *toggle = [UISwitch new]; + toggle.on = [[NSUserDefaults standardUserDefaults] boolForKey:row.defaultsKey]; + toggle.onTintColor = [SCIUtils SCIColor_Primary]; + + objc_setAssociatedObject(toggle, rowStaticRef, row, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + [toggle addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged]; + + cell.accessoryView = toggle; + cell.selectionStyle = UITableViewCellSelectionStyleNone; + break; + } + + case SCITableCellStepper: { + UIStepper *stepper = [UIStepper new]; + stepper.minimumValue = row.min; + stepper.maximumValue = row.max; + stepper.stepValue = row.step; + stepper.value = [[NSUserDefaults standardUserDefaults] doubleForKey:row.defaultsKey]; + + objc_setAssociatedObject(stepper, rowStaticRef, row, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + + [stepper addTarget:self + action:@selector(stepperChanged:) + forControlEvents:UIControlEventValueChanged]; + + // Template subtitle + if (row.subtitle.length) { + cellContentConfig.secondaryText = [self formatString:row.subtitle withValue:stepper.value label:row.label singularLabel:row.singularLabel]; + } + + cell.accessoryView = stepper; + cell.selectionStyle = UITableViewCellSelectionStyleNone; + break; + } + + case SCITableCellButton: { + cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; + break; + } + + case SCITableCellMenu: { + UIButton *menuButton = [UIButton buttonWithType:UIButtonTypeSystem]; + [menuButton setTitle:@"•••" forState:UIControlStateNormal]; + menuButton.menu = [row menuForButton:menuButton]; + menuButton.showsMenuAsPrimaryAction = YES; + menuButton.titleLabel.font = [UIFont systemFontOfSize:[UIFont preferredFontForTextStyle:UIFontTextStyleBody].pointSize + weight:UIFontWeightMedium]; + + UIButtonConfiguration *config = menuButton.configuration ?: [UIButtonConfiguration plainButtonConfiguration]; + menuButton.configuration.contentInsets = NSDirectionalEdgeInsetsMake(8, 8, 8, 8); + menuButton.configuration = config; + + [menuButton sizeToFit]; + + cell.accessoryView = menuButton; + cell.selectionStyle = UITableViewCellSelectionStyleNone; + break; + } + + case SCITableCellNavigation: { + cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; + break; + } + } + + cell.contentConfiguration = cellContentConfig; + + return cell; +} + +- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { + return [self.sections[section][@"rows"] count]; +} + +- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { + return self.sections[section][@"header"]; +} + +- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { + return self.sections[section][@"footer"]; +} + +- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { + return self.sections.count; +} + +// MARK: - UITableViewDelegate + +- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { + SCISetting *row = self.sections[indexPath.section][@"rows"][indexPath.row]; + if (!row) return; + + if (row.type == SCITableCellLink) { + [[UIApplication sharedApplication] openURL:row.url options:@{} completionHandler:nil]; + } + else if (row.type == SCITableCellButton) { + if (row.action != nil) { + row.action(); + } + } + else if (row.type == SCITableCellNavigation) { + if (row.navSections.count > 0) { + UIViewController *vc = [[SCISettingsViewController alloc] initWithTitle:row.title sections:row.navSections reduceMargin:NO]; + vc.title = row.title; + [self.navigationController pushViewController:vc animated:YES]; + } + else if (row.navViewController) { + [self.navigationController pushViewController:row.navViewController animated:YES]; + } + } + + [tableView deselectRowAtIndexPath:indexPath animated:YES]; +} + +// MARK: - Actions + +- (void)switchChanged:(UISwitch *)sender { + SCISetting *row = objc_getAssociatedObject(sender, rowStaticRef); + [[NSUserDefaults standardUserDefaults] setBool:sender.isOn forKey:row.defaultsKey]; + + NSLog(@"Switch changed: %@", sender.isOn ? @"ON" : @"OFF"); + + if (row.requiresRestart) { + [SCIUtils showRestartConfirmation]; + } +} + +- (void)stepperChanged:(UIStepper *)sender { + SCISetting *row = objc_getAssociatedObject(sender, rowStaticRef); + [[NSUserDefaults standardUserDefaults] setDouble:sender.value forKey:row.defaultsKey]; + + NSLog(@"Stepper changed: %f", sender.value); + + [self reloadCellForView:sender]; +} + +- (void)menuChanged:(UICommand *)command { + NSDictionary *properties = command.propertyList; + + [[NSUserDefaults standardUserDefaults] setValue:properties[@"value"] forKey:properties[@"defaultsKey"]]; + + NSLog(@"Menu changed: %@", command.propertyList[@"value"]); + + [self reloadCellForView:command.sender animated:YES]; + + if (properties[@"requiresRestart"]) { + [SCIUtils showRestartConfirmation]; + } +} + +// MARK: - Helper + +- (NSString *)formatString:(NSString *)template withValue:(double)value label:(NSString *)label singularLabel:(NSString *)singularLabel { + // Singular or plural labels + NSString *applicableLabel = fabs(value - 1.0) < 0.00001 ? singularLabel : label; + + // Force value to 0 to prevent it being -0 + if (fabs(value) < 0.00001) { + value = 0.0; + } + + // Get correct decimal value based on step value + NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; + formatter.numberStyle = NSNumberFormatterDecimalStyle; + formatter.minimumFractionDigits = 0; + formatter.maximumFractionDigits = [SCIUtils decimalPlacesInDouble:value]; + + NSString *stringValue = [formatter stringFromNumber:@(value)]; + + return [NSString stringWithFormat:template, stringValue, applicableLabel]; +} + +- (void)reloadCellForView:(UIView *)view animated:(BOOL)animated { + UITableViewCell *cell = (UITableViewCell *)view.superview; + while (cell && ![cell isKindOfClass:[UITableViewCell class]]) { + cell = (UITableViewCell *)cell.superview; + } + if (!cell) return; + + NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; + if (!indexPath) return; + + [self.tableView reloadRowsAtIndexPaths:@[indexPath] + withRowAnimation:animated ? UITableViewRowAnimationAutomatic : UITableViewRowAnimationNone]; +} +- (void)reloadCellForView:(UIView *)view { + [self reloadCellForView:view animated:NO]; +} + +- (void)loadImageFromURL:(NSURL *)url atIndexPath:(NSIndexPath *)indexPath forTableView:(UITableView *)tableView +{ + if (!url) return; + + NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) + { + if (!data || error) return; + + UIImage *image = [UIImage imageWithData:data]; + if (!image) return; + + dispatch_async(dispatch_get_main_queue(), ^{ + UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; + if (!cell) return; + + UIListContentConfiguration *config = (UIListContentConfiguration *)cell.contentConfiguration; + config.image = image; + config.imageProperties.maximumSize = CGSizeMake(45, 45); + cell.contentConfiguration = config; + }); + }]; + + [task resume]; +} + +@end diff --git a/src/Settings/SCISymbol.h b/src/Settings/SCISymbol.h new file mode 100644 index 0000000..8b68845 --- /dev/null +++ b/src/Settings/SCISymbol.h @@ -0,0 +1,21 @@ +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface SCISymbol : NSObject + +@property (nonatomic, copy, readonly) NSString *name; +@property (nonatomic, copy, readonly) UIColor *color; +@property (nonatomic, readonly) CGFloat size; +@property (nonatomic, readonly) UIImageSymbolWeight weight; + +- (UIImage *)image; + ++ (instancetype)symbolWithName:(NSString *)name; ++ (instancetype)symbolWithName:(NSString *)name color:(UIColor *)color; ++ (instancetype)symbolWithName:(NSString *)name color:(UIColor *)color size:(CGFloat)size; ++ (instancetype)symbolWithName:(NSString *)name color:(UIColor *)color size:(CGFloat)size weight:(UIImageSymbolWeight)weight; + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/Settings/SCISymbol.m b/src/Settings/SCISymbol.m new file mode 100644 index 0000000..f050beb --- /dev/null +++ b/src/Settings/SCISymbol.m @@ -0,0 +1,87 @@ +#import "SCISymbol.h" + +@interface SCISymbol () + +@property (nonatomic, copy, readwrite) NSString *name; +@property (nonatomic, copy, readwrite) UIColor *color; +@property (nonatomic, readwrite) CGFloat size; +@property (nonatomic, readwrite) UIImageSymbolWeight weight; + +- (instancetype)init; + +@end + +/// + +@implementation SCISymbol + +// MARK: - Instance methods + +- (instancetype)init { + self = [super init]; + + if (self) { + self.name = @""; + self.color = [UIColor labelColor]; + self.weight = UIImageSymbolWeightRegular; + self.size = 15.0; + } + + return self; +} + +- (UIImage *)image { + UIImage *symbol = [UIImage systemImageNamed:self.name]; + + if (self.size || (self.size && self.weight)) { + UIImageSymbolConfiguration *symbolConfig = [UIImageSymbolConfiguration configurationWithTextStyle:UIFontTextStyleTitle1]; + symbolConfig = [symbolConfig configurationByApplyingConfiguration: + [UIImageSymbolConfiguration configurationWithPointSize:self.size weight:self.weight]]; + + return [symbol imageWithConfiguration:symbolConfig]; + } + + return symbol; +} + +// MARK: - Class methods + ++ (instancetype)symbolWithName:(NSString *)name { + SCISymbol *symbol = [[self alloc] init]; + + symbol.name = name; + + return symbol; +} + ++ (instancetype)symbolWithName:(NSString *)name color:(UIColor *)color { + SCISymbol *symbol = [[self alloc] init]; + + symbol.name = name; + symbol.color = color; + + return symbol; +} + ++ (instancetype)symbolWithName:(NSString *)name color:(UIColor *)color size:(CGFloat)size { + SCISymbol *symbol = [[self alloc] init]; + + symbol.name = name; + symbol.color = color; + symbol.size = size; + + return symbol; +} + ++ (instancetype)symbolWithName:(NSString *)name color:(UIColor *)color size:(CGFloat)size weight:(UIImageSymbolWeight)weight { + SCISymbol *symbol = [[self alloc] init]; + + symbol.name = name; + symbol.color = color; + symbol.size = size; + symbol.weight = weight; + + return symbol; +} + +@end diff --git a/src/Settings/TweakSettings.h b/src/Settings/TweakSettings.h new file mode 100644 index 0000000..7932f93 --- /dev/null +++ b/src/Settings/TweakSettings.h @@ -0,0 +1,17 @@ +#import +#import "SCISetting.h" +#import "SCISymbol.h" +#import "../Utils.h" +#import "../Tweak.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface SCITweakSettings : NSObject + ++ (NSArray *)sections; ++ (NSString *)title; ++ (NSDictionary *)menus; + +@end + +NS_ASSUME_NONNULL_END diff --git a/src/Settings/TweakSettings.m b/src/Settings/TweakSettings.m new file mode 100644 index 0000000..49a064a --- /dev/null +++ b/src/Settings/TweakSettings.m @@ -0,0 +1,520 @@ +#import "TweakSettings.h" + +@implementation SCITweakSettings + +// MARK: - Sections + +/// +/// This returns an array of sections, with each section consisting of a dictionary +/// +/// `"title"`: The section title (leave blank for no title) +/// +/// `"rows"`: An array of **SCISetting** classes, potentially containing a "navigationCellWithTitle" initializer to allow for nested setting pages. +/// +/// `"footer`: The section footer (leave blank for no footer) + ++ (NSArray *)sections { + return @[ + @{ + @"header": @"", + @"rows": @[ + [SCISetting linkCellWithTitle:@"Donate" subtitle:@"Consider donating to support this tweak's development!" icon:[SCISymbol symbolWithName:@"heart.circle.fill" color:[UIColor systemPinkColor] size:20.0] url:@"https://ko-fi.com/SoCuul"] + ] + }, + @{ + @"header": @"", + @"rows": @[ + [SCISetting navigationCellWithTitle:@"General" + subtitle:@"" + icon:[SCISymbol symbolWithName:@"gear"] + navSections:@[@{ + @"header": @"", + @"rows": @[ + [SCISetting switchCellWithTitle:@"Hide ads" subtitle:@"Removes all ads from the Instagram app" defaultsKey:@"hide_ads"], + [SCISetting switchCellWithTitle:@"Hide Meta AI" subtitle:@"Hides the meta ai buttons/functionality within the app" defaultsKey:@"hide_meta_ai"], + [SCISetting switchCellWithTitle:@"Copy description" subtitle:@"Copy description text fields by long-pressing on them" defaultsKey:@"copy_description"], + [SCISetting switchCellWithTitle:@"Do not save recent searches" subtitle:@"Search bars will no longer save your recent searches" defaultsKey:@"no_recent_searches"], + [SCISetting switchCellWithTitle:@"Use detailed color picker" subtitle:@"Long press on the eyedropper tool in stories to customize the text color more precisely" defaultsKey:@"detailed_color_picker"], + [SCISetting switchCellWithTitle:@"Enable liquid glass buttons" subtitle:@"Enables experimental liquid glass buttons within the app" defaultsKey:@"liquid_glass_buttons" requiresRestart:YES], + [SCISetting switchCellWithTitle:@"Enable liquid glass surfaces" subtitle:@"Enables liquid glass for other elements, such as menus" defaultsKey:@"liquid_glass_surfaces" requiresRestart:YES], + [SCISetting switchCellWithTitle:@"Enable teen app icons" subtitle:@"When enabled, hold down on the Instagram logo to change the app icon" defaultsKey:@"teen_app_icons" requiresRestart:YES] + ] + }, + @{ + @"header": @"Notes", + @"rows": @[ + [SCISetting switchCellWithTitle:@"Hide notes tray" subtitle:@"Hides the notes tray in the dm inbox" defaultsKey:@"hide_notes_tray"], + [SCISetting switchCellWithTitle:@"Hide friends map" subtitle:@"Hides the friends map icon in the notes tray" defaultsKey:@"hide_friends_map"], + [SCISetting switchCellWithTitle:@"Enable note theming" subtitle:@"Enables the ability to use the notes theme picker" defaultsKey:@"enable_notes_customization"], + [SCISetting switchCellWithTitle:@"Custom note themes" subtitle:@"Provides an option to set custom emojis and background/text colors" defaultsKey:@"custom_note_themes"], + ] + }, + @{ + @"header": @"Focus/distractions", + @"rows": @[ + [SCISetting switchCellWithTitle:@"No suggested users" subtitle:@"Hides all suggested users for you to follow, outside your feed" defaultsKey:@"no_suggested_users"], + [SCISetting switchCellWithTitle:@"No suggested chats" subtitle:@"Hides the suggested broadcast channels in direct messages" defaultsKey:@"no_suggested_chats"], + [SCISetting switchCellWithTitle:@"Hide explore posts grid" subtitle:@"Hides the grid of suggested posts on the explore/search tab" defaultsKey:@"hide_explore_grid"], + [SCISetting switchCellWithTitle:@"Hide trending searches" subtitle:@"Hides the trending searches under the explore search bar" defaultsKey:@"hide_trending_searches"], + ] + }] + ], + [SCISetting navigationCellWithTitle:@"Feed" + subtitle:@"" + icon:[SCISymbol symbolWithName:@"rectangle.stack"] + navSections:@[@{ + @"header": @"", + @"rows": @[ + [SCISetting switchCellWithTitle:@"Hide stories tray" subtitle:@"Hides the story tray at the top and within your feed" defaultsKey:@"hide_stories_tray"], + [SCISetting switchCellWithTitle:@"Hide entire feed" subtitle:@"Removes all content from your home feed, including posts" defaultsKey:@"hide_entire_feed"], + [SCISetting switchCellWithTitle:@"No suggested posts" subtitle:@"Removes suggested posts from your feed" defaultsKey:@"no_suggested_post"], + [SCISetting switchCellWithTitle:@"No suggested for you" subtitle:@"Hides suggested accounts for you to follow" defaultsKey:@"no_suggested_account"], + [SCISetting switchCellWithTitle:@"No suggested reels" subtitle:@"Hides suggested reels to watch" defaultsKey:@"no_suggested_reels"], + [SCISetting switchCellWithTitle:@"No suggested threads posts" subtitle:@"Hides suggested threads posts" defaultsKey:@"no_suggested_threads"], + [SCISetting switchCellWithTitle:@"Disable video autoplay" subtitle:@"Prevents videos on your feed from playing automatically" defaultsKey:@"disable_feed_autoplay"] + ] + }] + ], + [SCISetting navigationCellWithTitle:@"Reels" + subtitle:@"" + icon:[SCISymbol symbolWithName:@"film.stack"] + navSections:@[@{ + @"header": @"", + @"rows": @[ + [SCISetting menuCellWithTitle:@"Tap Controls" subtitle:@"Change what happens when you tap on a reel" menu:[self menus][@"reels_tap_control"]], + [SCISetting switchCellWithTitle:@"Always show progress scrubber" subtitle:@"Forces the progress bar to appear on every reel" defaultsKey:@"reels_show_scrubber"], + [SCISetting switchCellWithTitle:@"Disable auto-unmuting reels" subtitle:@"Prevents reels from unmuting when the volume/silent button is pressed" defaultsKey:@"disable_auto_unmuting_reels" requiresRestart:YES], + [SCISetting switchCellWithTitle:@"Confirm reel refresh" subtitle:@"Shows an alert when you trigger a reels refresh" defaultsKey:@"refresh_reel_confirm"], + ] + }, + @{ + @"header": @"Hiding", + @"rows": @[ + [SCISetting switchCellWithTitle:@"Hide reels header" subtitle:@"Hides the top navigation bar when watching reels" defaultsKey:@"hide_reels_header"], + [SCISetting switchCellWithTitle:@"Hide reels blend button" subtitle:@"Hides the button in DMs to open a reels blend" defaultsKey:@"hide_reels_blend"] + ] + }, + @{ + @"header": @"Limits", + @"rows": @[ + [SCISetting switchCellWithTitle:@"Disable scrolling reels" subtitle:@"Prevents reels from being scrolled to the next video" defaultsKey:@"disable_scrolling_reels" requiresRestart:YES], + [SCISetting switchCellWithTitle:@"Prevent doom scrolling" subtitle:@"Limits the amount of reels available to scroll at any given time, and prevents refreshing" defaultsKey:@"prevent_doom_scrolling"], + [SCISetting stepperCellWithTitle:@"Doom scrolling limit" subtitle:@"Only loads %@ %@" defaultsKey:@"doom_scrolling_reel_count" min:1 max:100 step:1 label:@"reels" singularLabel:@"reel"] + ] + }] + ], + [SCISetting navigationCellWithTitle:@"Saving" + subtitle:@"" + icon:[SCISymbol symbolWithName:@"tray.and.arrow.down"] + navSections:@[@{ + @"header": @"", + @"rows": @[ + [SCISetting switchCellWithTitle:@"Download feed posts" subtitle:@"Long-press with finger(s) to download posts in the home tab" defaultsKey:@"dw_feed_posts"], + [SCISetting switchCellWithTitle:@"Download reels" subtitle:@"Long-press with finger(s) on a reel to download" defaultsKey:@"dw_reels"], + [SCISetting switchCellWithTitle:@"Download stories" subtitle:@"Long-press with finger(s) while viewing someone's story to download" defaultsKey:@"dw_story"], + [SCISetting switchCellWithTitle:@"Save profile picture" subtitle:@"On someone's profile, click their profile picture to enlarge it, then hold to download" defaultsKey:@"save_profile"] + ] + }, + @{ + @"header": @"Download method", + @"rows": @[ + [SCISetting menuCellWithTitle:@"Download method" subtitle:@"How to trigger downloads" menu:[self menus][@"dw_method"]], + [SCISetting menuCellWithTitle:@"Save action" subtitle:@"What happens after downloading" menu:[self menus][@"dw_save_action"]], + [SCISetting switchCellWithTitle:@"Confirm before download" subtitle:@"Show a confirmation dialog before starting a download" defaultsKey:@"dw_confirm"] + ] + }, + @{ + @"header": @"Customize gestures", + @"footer": @"Only applies when download method is set to \"Long-press gesture\"", + @"rows": @[ + [SCISetting stepperCellWithTitle:@"Finger count for long-press" subtitle:@"Downloads with %@ %@" defaultsKey:@"dw_finger_count" min:1 max:5 step:1 label:@"fingers" singularLabel:@"finger"], + [SCISetting stepperCellWithTitle:@"Long-press hold time" subtitle:@"Press finger(s) for %@ %@" defaultsKey:@"dw_finger_duration" min:0 max:10 step:0.25 label:@"sec" singularLabel:@"sec"] + ] + }] + ], + [SCISetting navigationCellWithTitle:@"Stories and messages" + subtitle:@"" + icon:[SCISymbol symbolWithName:@"rectangle.portrait.on.rectangle.portrait.angled"] + navSections:@[@{ + @"header": @"Messages", + @"rows": @[ + [SCISetting switchCellWithTitle:@"Keep deleted messages" subtitle:@"Saves deleted messages in chat conversations" defaultsKey:@"keep_deleted_message"], + [SCISetting switchCellWithTitle:@"Manually mark messages as seen" subtitle:@"Adds a button to DM threads, which will mark messages as seen" defaultsKey:@"remove_lastseen"], + [SCISetting switchCellWithTitle:@"Disable typing status" subtitle:@"Prevents the typing indicator from being shown to others when you're typing in DMs" defaultsKey:@"disable_typing_status"], + ] + }, + @{ + @"header": @"Visual messages & stories", + @"rows": @[ + [SCISetting switchCellWithTitle:@"Unlimited replay of visual messages" subtitle:@"Replays direct visual messages normal/once stories unlimited times (toggle with image check icon)" defaultsKey:@"unlimited_replay"], + [SCISetting switchCellWithTitle:@"Disable view-once limitations" subtitle:@"Makes view-once messages behave like normal visual messages (loopable/pauseable)" defaultsKey:@"disable_view_once_limitations"], + [SCISetting switchCellWithTitle:@"Disable screenshot detection" subtitle:@"Removes the screenshot-prevention features for visual messages in DMs" defaultsKey:@"remove_screenshot_alert"], + [SCISetting switchCellWithTitle:@"Disable story seen receipt" subtitle:@"Hides the notification for others when you view their story" defaultsKey:@"no_seen_receipt"], + [SCISetting switchCellWithTitle:@"Disable instants creation" subtitle:@"Hides the functionality to create/send instants" defaultsKey:@"disable_instants_creation" requiresRestart:YES] + ] + }] + ], + [SCISetting navigationCellWithTitle:@"Navigation" + subtitle:@"" + icon:[SCISymbol symbolWithName:@"hand.draw.fill"] + navSections:@[@{ + @"header": @"", + @"rows": @[ + [SCISetting menuCellWithTitle:@"Icon order" subtitle:@"The order of the icons on the bottom navigation bar" menu:[self menus][@"nav_icon_ordering"]], + [SCISetting menuCellWithTitle:@"Swipe between tabs" subtitle:@"Lets you swipe to switch between navigation bar tabs" menu:[self menus][@"swipe_nav_tabs"]], + ] + }, + @{ + @"header": @"Hiding tabs", + @"rows": @[ + [SCISetting switchCellWithTitle:@"Hide feed tab" subtitle:@"Hides the feed/home tab on the bottom navigation bar" defaultsKey:@"hide_feed_tab" requiresRestart:YES], + [SCISetting switchCellWithTitle:@"Hide explore tab" subtitle:@"Hides the explore/search tab on the bottom navigation bar" defaultsKey:@"hide_explore_tab" requiresRestart:YES], + [SCISetting switchCellWithTitle:@"Hide reels tab" subtitle:@"Hides the reels tab on the bottom navigation bar" defaultsKey:@"hide_reels_tab" requiresRestart:YES], + [SCISetting switchCellWithTitle:@"Hide create tab" subtitle:@"Hides the create tab on the bottom navigation bar" defaultsKey:@"hide_create_tab" requiresRestart:YES] + ] + }] + ], + [SCISetting navigationCellWithTitle:@"Confirm actions" + subtitle:@"" + icon:[SCISymbol symbolWithName:@"checkmark"] + navSections:@[@{ + @"header": @"", + @"rows": @[ + [SCISetting switchCellWithTitle:@"Confirm like: Posts/Stories" subtitle:@"Shows an alert when you click the like button on posts or stories to confirm the like" defaultsKey:@"like_confirm"], + [SCISetting switchCellWithTitle:@"Confirm like: Reels" subtitle:@"Shows an alert when you click the like button on reels to confirm the like" defaultsKey:@"like_confirm_reels"] + ] + }, + @{ + @"header": @"", + @"rows": @[ + [SCISetting switchCellWithTitle:@"Confirm follow" subtitle:@"Shows an alert when you click the follow button to confirm the follow" defaultsKey:@"follow_confirm"], + [SCISetting switchCellWithTitle:@"Confirm repost" subtitle:@"Shows an alert when you click the repost button to confirm before resposting" defaultsKey:@"repost_confirm"], + [SCISetting switchCellWithTitle:@"Confirm call" subtitle:@"Shows an alert when you click the audio/video call button to confirm before calling" defaultsKey:@"call_confirm"], + [SCISetting switchCellWithTitle:@"Confirm voice messages" subtitle:@"Shows an alert to confirm before sending a voice message" defaultsKey:@"voice_message_confirm"], + [SCISetting switchCellWithTitle:@"Confirm follow requests" subtitle:@"Shows an alert when you accept/decline a follow request" defaultsKey:@"follow_request_confirm"], + [SCISetting switchCellWithTitle:@"Confirm shh mode" subtitle:@"Shows an alert to confirm before toggling disappearing messages" defaultsKey:@"shh_mode_confirm"], + [SCISetting switchCellWithTitle:@"Confirm posting comment" subtitle:@"Shows an alert when you click the post comment button to confirm" defaultsKey:@"post_comment_confirm"], + [SCISetting switchCellWithTitle:@"Confirm changing theme" subtitle:@"Shows an alert when you change a chat theme to confirm" defaultsKey:@"change_direct_theme_confirm"], + [SCISetting switchCellWithTitle:@"Confirm sticker interaction" subtitle:@"Shows an alert when you click a sticker on someone's story to confirm the action" defaultsKey:@"sticker_interact_confirm"] + ] + }] + ] + ] + }, + @{ + @"header": @"", + @"rows": @[ + // [SCISetting navigationCellWithTitle:@"Experimental" + // subtitle:@"" + // icon:[SCISymbol symbolWithName:@"testtube.2"] + // navSections:@[@{ + // @"header": @"Warning", + // @"footer": @"These features are unstable and cause the Instagram app to crash unexpectedly.\n\nUse at your own risk!" + // }, + // @{ + // @"header": @"", + // @"rows": @[ + + // ] + // } + // ] + // ], + [SCISetting navigationCellWithTitle:@"Debug" + subtitle:@"" + icon:[SCISymbol symbolWithName:@"ladybug"] + navSections:@[@{ + @"header": @"FLEX", + @"rows": @[ + [SCISetting switchCellWithTitle:@"Enable FLEX gesture" subtitle:@"Allows you to hold 5 fingers on the screen to open the FLEX explorer" defaultsKey:@"flex_instagram"], + [SCISetting switchCellWithTitle:@"Open FLEX on app launch" subtitle:@"Automatically opens the FLEX explorer when the app launches" defaultsKey:@"flex_app_launch"], + [SCISetting switchCellWithTitle:@"Open FLEX on app focus" subtitle:@"Automatically opens the FLEX explorer when the app is focused" defaultsKey:@"flex_app_start"] + ] + }, + @{ + @"header": @"SCInsta", + @"rows": @[ + [SCISetting switchCellWithTitle:@"Enable tweak settings quick-access" subtitle:@"Allows you to hold on the home tab to open the SCInsta settings" defaultsKey:@"settings_shortcut" requiresRestart:YES], + [SCISetting switchCellWithTitle:@"Show tweak settings on app launch" subtitle:@"Automatically opens the SCInsta settings when the app launches" defaultsKey:@"tweak_settings_app_launch"], + [SCISetting buttonCellWithTitle:@"Reset onboarding completion state" + subtitle:@"" + icon:nil + action:^(void) { [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SCInstaFirstRun"]; [SCIUtils showRestartConfirmation];} + ], + ] + }, + @{ + @"header": @"Instagram", + @"rows": @[ + [SCISetting switchCellWithTitle:@"Disable safe mode" subtitle:@"Makes Instagram not reset settings after subsequent crashes (at your own risk)" defaultsKey:@"disable_safe_mode"] + ] + }, + @{ + @"header": @"_ Example", + @"rows": @[ + [SCISetting staticCellWithTitle:@"Static Cell" subtitle:@"" icon:[SCISymbol symbolWithName:@"tablecells"]], + [SCISetting switchCellWithTitle:@"Switch Cell" subtitle:@"Tap the switch" defaultsKey:@"test_switch_cell"], + [SCISetting switchCellWithTitle:@"Switch Cell (Restart)" subtitle:@"Tap the switch" defaultsKey:@"test_switch_cell_restart" requiresRestart:YES], + [SCISetting stepperCellWithTitle:@"Stepper cell" subtitle:@"I have %@%@" defaultsKey:@"test_stepper_cell" min:-10 max:1000 step:5.5 label:@"$" singularLabel:@"$"], + [SCISetting linkCellWithTitle:@"Link Cell" subtitle:@"Using icon" icon:[SCISymbol symbolWithName:@"link" color:[UIColor systemTealColor] size:20.0] url:@"https://google.com"], + [SCISetting linkCellWithTitle:@"Link Cell" subtitle:@"Using image" imageUrl:@"https://i.imgur.com/c9CbytZ.png" url:@"https://google.com"], + [SCISetting buttonCellWithTitle:@"Button Cell" + subtitle:@"" + icon:[SCISymbol symbolWithName:@"oval.inset.filled"] + action:^(void) { [SCIUtils showConfirmation:^(void){}]; } + ], + [SCISetting menuCellWithTitle:@"Menu Cell" subtitle:@"Change the value on the right" menu:[self menus][@"test"]], + [SCISetting navigationCellWithTitle:@"Navigation Cell" + subtitle:@"" + icon:[SCISymbol symbolWithName:@"rectangle.stack"] + navSections:@[@{ + @"header": @"", + @"rows": @[] + }] + ] + ], + @"footer": @"_ Example" + } + ] + ] + ] + }, + @{ + @"header": @"Credits", + @"rows": @[ + [SCISetting linkCellWithTitle:@"Developer" subtitle:@"SoCuul" imageUrl:@"https://i.imgur.com/c9CbytZ.png" url:@"https://socuul.dev"], + [SCISetting linkCellWithTitle:@"View Repo" subtitle:@"View the tweak's source code on GitHub" imageUrl:@"https://i.imgur.com/BBUNzeP.png" url:@"https://github.com/SoCuul/SCInsta"] + ], + @"footer": [NSString stringWithFormat:@"SCInsta %@\n\nInstagram v%@", SCIVersionString, [SCIUtils IGVersionString]] + } + ]; +} + + +// MARK: - Title + +/// +/// This is the title displayed on the initial settings page view controller +/// + ++ (NSString *)title { + return @"SCInsta Settings"; +} + + +// MARK: - Menus + +/// +/// This returns a dictionary where each key corresponds to a certain menu that can be displayed. +/// Each "propertyList" item is an NSDictionary containing the following items: +/// +/// `"defaultsKey"`: The key to save the selected value under in NSUserDefaults +/// +/// `"value"`: A unique string corresponding to the menu item which is selected +/// +/// `"requiresRestart"`: (optional) Causes a popup to appear detailing you have to restart to use these features +/// + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wundeclared-selector" + ++ (NSDictionary *)menus { + return @{ + @"dw_save_action": [UIMenu menuWithChildren:@[ + [UICommand commandWithTitle:@"Share sheet" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"dw_save_action", + @"value": @"share" + } + ], + [UICommand commandWithTitle:@"Save to Photos" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"dw_save_action", + @"value": @"photos" + } + ] + ]], + + @"dw_method": [UIMenu menuWithChildren:@[ + [UICommand commandWithTitle:@"Download button" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"dw_method", + @"value": @"button", + @"requiresRestart": @YES + } + ], + [UICommand commandWithTitle:@"Long-press gesture" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"dw_method", + @"value": @"gesture", + @"requiresRestart": @YES + } + ] + ]], + + @"reels_tap_control": [UIMenu menuWithChildren:@[ + [UICommand commandWithTitle:@"Default" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"reels_tap_control", + @"value": @"default", + @"requiresRestart": @YES + } + ], + [UIMenu menuWithTitle:@"" + image:nil + identifier:nil + options:UIMenuOptionsDisplayInline + children:@[ + [UICommand commandWithTitle:@"Pause/Play" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"reels_tap_control", + @"value": @"pause", + @"requiresRestart": @YES + } + ], + [UICommand commandWithTitle:@"Mute/Unmute" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"reels_tap_control", + @"value": @"mute", + @"requiresRestart": @YES + } + ] + ] + ] + ]], + + @"nav_icon_ordering": [UIMenu menuWithChildren:@[ + [UICommand commandWithTitle:@"Default" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"nav_icon_ordering", + @"value": @"default", + @"requiresRestart": @YES + } + ], + [UIMenu menuWithTitle:@"" + image:nil + identifier:nil + options:UIMenuOptionsDisplayInline + children:@[ + [UICommand commandWithTitle:@"Classic" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"nav_icon_ordering", + @"value": @"classic", + @"requiresRestart": @YES + } + ], + [UICommand commandWithTitle:@"Standard" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"nav_icon_ordering", + @"value": @"standard", + @"requiresRestart": @YES + } + ], + [UICommand commandWithTitle:@"Alternate" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"nav_icon_ordering", + @"value": @"alternate", + @"requiresRestart": @YES + } + ] + ] + ] + ]], + @"swipe_nav_tabs": [UIMenu menuWithChildren:@[ + [UICommand commandWithTitle:@"Default" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"swipe_nav_tabs", + @"value": @"default", + @"requiresRestart": @YES + } + ], + [UIMenu menuWithTitle:@"" + image:nil + identifier:nil + options:UIMenuOptionsDisplayInline + children:@[ + [UICommand commandWithTitle:@"Enabled" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"swipe_nav_tabs", + @"value": @"enabled", + @"requiresRestart": @YES + } + ], + [UICommand commandWithTitle:@"Disabled" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"swipe_nav_tabs", + @"value": @"disabled", + @"requiresRestart": @YES + } + ] + ] + ] + ]], + + @"test": [UIMenu menuWithChildren:@[ + [UIMenu menuWithTitle:@"" + image:nil + identifier:nil + options:UIMenuOptionsDisplayInline + children:@[ + [UICommand commandWithTitle:@"ABC" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"test_menu_cell", + @"value": @"abc" + } + ], + [UICommand commandWithTitle:@"123" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"test_menu_cell", + @"value": @"123" + } + ] + ] + ], + [UICommand commandWithTitle:@"Requires restart" + image:nil + action:@selector(menuChanged:) + propertyList:@{ + @"defaultsKey": @"test_menu_cell", + @"value": @"requires_restart", + @"requiresRestart": @YES + } + ], + ]] + }; +} + +#pragma clang diagnostic pop + +@end diff --git a/src/Tweak.h b/src/Tweak.h new file mode 100644 index 0000000..d4479f6 --- /dev/null +++ b/src/Tweak.h @@ -0,0 +1,7 @@ +#import + +// * Tweak version * +extern NSString *SCIVersionString; + +// Variables that work across features +extern BOOL dmVisualMsgsViewedButtonEnabled; // Whether story dm unlimited views button is enabled \ No newline at end of file diff --git a/src/Tweak.x b/src/Tweak.x new file mode 100644 index 0000000..93c93f9 --- /dev/null +++ b/src/Tweak.x @@ -0,0 +1,718 @@ +#import +#import "InstagramHeaders.h" +#import "Tweak.h" +#import "Utils.h" + +/////////////////////////////////////////////////////////// + +// Screenshot handlers + +#define VOID_HANDLESCREENSHOT(orig) [SCIUtils getBoolPref:@"remove_screenshot_alert"] ? nil : orig; +#define NONVOID_HANDLESCREENSHOT(orig) return VOID_HANDLESCREENSHOT(orig) + +/////////////////////////////////////////////////////////// + +// * Tweak version * +NSString *SCIVersionString = @"v1.1.2"; + +// Variables that work across features +BOOL dmVisualMsgsViewedButtonEnabled = false; + +// Tweak first-time setup +%hook IGInstagramAppDelegate +- (_Bool)application:(UIApplication *)application willFinishLaunchingWithOptions:(id)arg2 { + // Default SCInsta config + NSDictionary *sciDefaults = @{ + @"hide_ads": @(YES), + @"copy_description": @(YES), + @"detailed_color_picker": @(YES), + @"remove_screenshot_alert": @(YES), + @"call_confirm": @(YES), + @"keep_deleted_message": @(YES), + @"dw_feed_posts": @(YES), + @"dw_reels": @(YES), + @"dw_story": @(YES), + @"save_profile": @(YES), + @"dw_method": @"button", + @"dw_confirm": @(YES), + @"dw_save_action": @"share", + @"dw_finger_count": @(3), + @"dw_finger_duration": @(0.5), + @"reels_tap_control": @"default", + @"nav_icon_ordering": @"default", + @"swipe_nav_tabs": @"default", + @"enable_notes_customization": @(YES), + @"custom_note_themes": @(YES), + @"disable_auto_unmuting_reels": @(YES), + @"doom_scrolling_reel_count": @(1) + }; + [[NSUserDefaults standardUserDefaults] registerDefaults:sciDefaults]; + + // Override instagram defaults + if ([SCIUtils getBoolPref:@"liquid_glass_buttons"]) { + [[NSUserDefaults standardUserDefaults] setValue:@(YES) forKey:@"instagram.override.project.lucent.navigation"]; + } + else { + [[NSUserDefaults standardUserDefaults] setValue:@(NO) forKey:@"instagram.override.project.lucent.navigation"]; + } + + return %orig; +} +- (_Bool)application:(UIApplication *)application didFinishLaunchingWithOptions:(id)arg2 { + %orig; + + // Open settings for first-time users + double openDelay = [SCIUtils getBoolPref:@"tweak_settings_app_launch"] ? 0.0 : 5.0; + + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(openDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + if ( + ![[[NSUserDefaults standardUserDefaults] objectForKey:@"SCInstaFirstRun"] isEqualToString:SCIVersionString] + || [SCIUtils getBoolPref:@"tweak_settings_app_launch"] + ) { + NSLog(@"[SCInsta] First run, initializing"); + + // Display settings modal on screen + NSLog(@"[SCInsta] Displaying SCInsta first-time settings modal"); + [SCIUtils showSettingsVC:[self window]]; + } + }); + + NSLog(@"[SCInsta] Cleaning cache..."); + [SCIUtils cleanCache]; + + if ([SCIUtils getBoolPref:@"flex_app_launch"]) { + [[objc_getClass("FLEXManager") sharedManager] showExplorer]; + } + + return true; +} + +- (void)applicationDidBecomeActive:(id)arg1 { + %orig; + + if ([SCIUtils getBoolPref:@"flex_app_start"]) { + [[objc_getClass("FLEXManager") sharedManager] showExplorer]; + } +} +%end + +%hook IGDSLauncherConfig +- (_Bool)isLiquidGlassInAppNotificationEnabled { + return [SCIUtils liquidGlassEnabledBool:%orig]; +} +- (_Bool)isLiquidGlassContextMenuEnabled{ + return [SCIUtils liquidGlassEnabledBool:%orig]; +} +- (_Bool)isLiquidGlassToastEnabled { + return [SCIUtils liquidGlassEnabledBool:%orig]; +} +- (_Bool)isLiquidGlassToastPeekEnabled { + return [SCIUtils liquidGlassEnabledBool:%orig]; +} +- (_Bool)isLiquidGlassAlertDialogEnabled { + return [SCIUtils liquidGlassEnabledBool:%orig]; +} +%end + +// Disable sending modded insta bug reports +%hook IGWindow +- (void)showDebugMenu { + return; +} +%end + +%hook IGBugReportUploader +- (id)initWithNetworker:(id)arg1 + pandoGraphQLService:(id)arg2 + analyticsLogger:(id)arg3 + userDefaults:(id)arg4 + launcherSetProvider:(id)arg5 +shouldPersistLastBugReportId:(id)arg6 +{ + return nil; +} +%end + +// Disable anti-screenshot feature on visual messages +%hook IGStoryViewerContainerView +- (void)setShouldBlockScreenshot:(BOOL)arg1 viewModel:(id)arg2 { VOID_HANDLESCREENSHOT(%orig); } +%end + +// Disable screenshot logging/detection +%hook IGDirectVisualMessageViewerSession +- (id)visualMessageViewerController:(id)arg1 didDetectScreenshotForVisualMessage:(id)arg2 atIndex:(NSInteger)arg3 { NONVOID_HANDLESCREENSHOT(%orig); } +%end + +%hook IGDirectVisualMessageReplayService +- (id)visualMessageViewerController:(id)arg1 didDetectScreenshotForVisualMessage:(id)arg2 atIndex:(NSInteger)arg3 { NONVOID_HANDLESCREENSHOT(%orig); } +%end + +%hook IGDirectVisualMessageReportService +- (id)visualMessageViewerController:(id)arg1 didDetectScreenshotForVisualMessage:(id)arg2 atIndex:(NSInteger)arg3 { NONVOID_HANDLESCREENSHOT(%orig); } +%end + +%hook IGDirectVisualMessageScreenshotSafetyLogger +- (id)initWithUserSession:(id)arg1 entryPoint:(NSInteger)arg2 { + if ([SCIUtils getBoolPref:@"remove_screenshot_alert"]) { + NSLog(@"[SCInsta] Disable visual message screenshot safety logger"); + return nil; + } + + return %orig; +} +%end + +%hook IGScreenshotObserver +- (id)initForController:(id)arg1 { NONVOID_HANDLESCREENSHOT(%orig); } +%end + +%hook IGScreenshotObserverDelegate +- (void)screenshotObserverDidSeeScreenshotTaken:(id)arg1 { VOID_HANDLESCREENSHOT(%orig); } +- (void)screenshotObserverDidSeeActiveScreenCapture:(id)arg1 event:(NSInteger)arg2 { VOID_HANDLESCREENSHOT(%orig); } +%end + +%hook IGDirectMediaViewerViewController +- (void)screenshotObserverDidSeeScreenshotTaken:(id)arg1 { VOID_HANDLESCREENSHOT(%orig); } +- (void)screenshotObserverDidSeeActiveScreenCapture:(id)arg1 event:(NSInteger)arg2 { VOID_HANDLESCREENSHOT(%orig); } +%end + +%hook IGStoryViewerViewController +- (void)screenshotObserverDidSeeScreenshotTaken:(id)arg1 { VOID_HANDLESCREENSHOT(%orig); } +- (void)screenshotObserverDidSeeActiveScreenCapture:(id)arg1 event:(NSInteger)arg2 { VOID_HANDLESCREENSHOT(%orig); } +%end + +%hook IGSundialFeedViewController +- (void)screenshotObserverDidSeeScreenshotTaken:(id)arg1 { VOID_HANDLESCREENSHOT(%orig); } +- (void)screenshotObserverDidSeeActiveScreenCapture:(id)arg1 event:(NSInteger)arg2 { VOID_HANDLESCREENSHOT(%orig); } +%end + +%hook IGDirectVisualMessageViewerController +- (void)screenshotObserverDidSeeScreenshotTaken:(id)arg1 { VOID_HANDLESCREENSHOT(%orig); } +- (void)screenshotObserverDidSeeActiveScreenCapture:(id)arg1 event:(NSInteger)arg2 { VOID_HANDLESCREENSHOT(%orig); } +%end + +///////////////////////////////////////////////////////////////////////////// + +// Hide items + +// Direct suggested chats (in search bar) +%hook IGDirectInboxSearchListAdapterDataSource +- (id)objectsForListAdapter:(id)arg1 { + NSArray *originalObjs = %orig(); + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (id obj in originalObjs) { + BOOL shouldHide = NO; + + // Section header + if ([obj isKindOfClass:%c(IGLabelItemViewModel)]) { + + // Broadcast channels + if ([[obj valueForKey:@"uniqueIdentifier"] isEqualToString:@"channels"]) { + if ([SCIUtils getBoolPref:@"no_suggested_chats"]) { + NSLog(@"[SCInsta] Hiding suggested chats (header)"); + + shouldHide = YES; + } + } + + // Ask Meta AI + else if ([[obj valueForKey:@"labelTitle"] isEqualToString:@"Ask Meta AI"]) { + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + NSLog(@"[SCInsta] Hiding meta ai suggested chats (header)"); + + shouldHide = YES; + } + } + + // AI + else if ([[obj valueForKey:@"labelTitle"] isEqualToString:@"AI"]) { + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + NSLog(@"[SCInsta] Hiding ai suggested chats (header)"); + + shouldHide = YES; + } + } + + } + + // AI agents section + else if ( + [obj isKindOfClass:%c(IGDirectInboxSearchAIAgentsPillsSectionViewModel)] + || [obj isKindOfClass:%c(IGDirectInboxSearchAIAgentsSuggestedPromptViewModel)] + || [obj isKindOfClass:%c(IGDirectInboxSearchAIAgentsSuggestedPromptLoggingViewModel)] + ) { + + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + NSLog(@"[SCInsta] Hiding suggested chats (ai agents)"); + + shouldHide = YES; + } + + } + + // Recipients list + else if ([obj isKindOfClass:%c(IGDirectRecipientCellViewModel)]) { + + // Broadcast channels + if ([[obj recipient] isBroadcastChannel]) { + if ([SCIUtils getBoolPref:@"no_suggested_chats"]) { + NSLog(@"[SCInsta] Hiding suggested chats (broadcast channels recipient)"); + + shouldHide = YES; + } + } + + // Meta AI (special section types) + else if (([obj sectionType] == 20) || [obj sectionType] == 18) { + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + NSLog(@"[SCInsta] Hiding meta ai suggested chats (meta ai recipient)"); + + shouldHide = YES; + } + } + + // Meta AI (catch-all) + else if ([[[obj recipient] threadName] isEqualToString:@"Meta AI"]) { + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + NSLog(@"[SCInsta] Hiding meta ai suggested chats (meta ai recipient)"); + + shouldHide = YES; + } + } + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + + } + + return [filteredObjs copy]; +} +%end + +// Direct suggested chats (thread creation view) +%hook IGDirectThreadCreationViewController +- (id)objectsForListAdapter:(id)arg1 { + NSArray *originalObjs = %orig(); + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (id obj in originalObjs) { + BOOL shouldHide = NO; + + // Meta AI suggested user in direct new message view + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + + if ([obj isKindOfClass:%c(IGDirectCreateChatCellViewModel)]) { + + // "AI Chats" + if ([[obj valueForKey:@"title"] isEqualToString:@"AI chats"]) { + NSLog(@"[SCInsta] Hiding meta ai: direct thread creation ai chats section"); + + shouldHide = YES; + } + + } + + else if ([obj isKindOfClass:%c(IGDirectRecipientCellViewModel)]) { + + // Meta AI suggested user + if ([[[obj recipient] threadName] isEqualToString:@"Meta AI"]) { + NSLog(@"[SCInsta] Hiding meta ai: direct thread creation ai suggestion"); + + shouldHide = YES; + } + + } + + } + + // Invite friends to insta contacts upsell + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + if ([obj isKindOfClass:%c(IGContactInvitesSearchUpsellViewModel)]) { + NSLog(@"[SCInsta] Hiding suggested users: invite contacts upsell"); + + shouldHide = YES; + } + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + } + + return [filteredObjs copy]; +} +%end + +// Direct suggested chats (inbox view) +%hook IGDirectInboxListAdapterDataSource +- (id)objectsForListAdapter:(id)arg1 { + NSArray *originalObjs = %orig(); + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (id obj in originalObjs) { + BOOL shouldHide = NO; + + // Section header + if ([obj isKindOfClass:%c(IGDirectInboxHeaderCellViewModel)]) { + + // "Suggestions" header + if ([[obj title] isEqualToString:@"Suggestions"]) { + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + NSLog(@"[SCInsta] Hiding suggested chats (header: messages tab)"); + + shouldHide = YES; + } + } + + // "Accounts to follow/message" header + else if ([[obj title] hasPrefix:@"Accounts to"]) { + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + NSLog(@"[SCInsta] Hiding suggested users: (header: inbox view)"); + + shouldHide = YES; + } + } + + } + + // Suggested recipients + else if ([obj isKindOfClass:%c(IGDirectInboxSuggestedThreadCellViewModel)]) { + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + NSLog(@"[SCInsta] Hiding suggested chats (recipients: channels tab)"); + + shouldHide = YES; + } + } + + // "Accounts to follow" recipients + else if ([obj isKindOfClass:%c(IGDiscoverPeopleItemConfiguration)] || [obj isKindOfClass:%c(IGDiscoverPeopleConnectionItemConfiguration)]) { + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + NSLog(@"[SCInsta] Hiding suggested chats: (recipients: inbox view)"); + + shouldHide = YES; + } + } + + // Hide notes tray + else if ([obj isKindOfClass:%c(IGDirectNotesTrayRowViewModel)]) { + if ([SCIUtils getBoolPref:@"hide_notes_tray"]) { + NSLog(@"[SCInsta] Hiding notes tray"); + + shouldHide = YES; + } + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + + } + + return [filteredObjs copy]; +} +%end + +// Explore page results +%hook IGSearchListKitDataSource +- (id)objectsForListAdapter:(id)arg1 { + NSArray *originalObjs = %orig(); + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (id obj in originalObjs) { + BOOL shouldHide = NO; + + // Meta AI + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + + // Section header + if ([obj isKindOfClass:%c(IGLabelItemViewModel)]) { + + // "Ask Meta AI" search results header + if ([[obj valueForKey:@"labelTitle"] isEqualToString:@"Ask Meta AI"]) { + shouldHide = YES; + } + + } + + // Empty search bar upsell view + else if ([obj isKindOfClass:%c(IGSearchNullStateUpsellViewModel)]) { + shouldHide = YES; + } + + // Meta AI search suggestions + else if ([obj isKindOfClass:%c(IGSearchResultNestedGroupViewModel)]) { + shouldHide = YES; + } + + // Meta AI suggested search results + else if ([obj isKindOfClass:%c(IGSearchResultViewModel)]) { + + // itemType 6 is meta ai suggestions + if ([obj itemType] == 6) { + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + shouldHide = YES; + } + + } + + // Meta AI user account in search results + else if ([[[obj title] string] isEqualToString:@"meta.ai"]) { + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + shouldHide = YES; + } + } + + } + + } + + // No suggested users + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + + // Section header + if ([obj isKindOfClass:%c(IGLabelItemViewModel)]) { + + // "Suggested for you" search results header + if ([[obj valueForKey:@"labelTitle"] isEqualToString:@"Suggested for you"]) { + shouldHide = YES; + } + + } + + // Instagram users + else if ([obj isKindOfClass:%c(IGDiscoverPeopleItemConfiguration)]) { + shouldHide = YES; + } + + // See all suggested users + else if ([obj isKindOfClass:%c(IGSeeAllItemConfiguration)] && ((IGSeeAllItemConfiguration *)obj).destination == 4) { + shouldHide = YES; + } + + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + + } + + return [filteredObjs copy]; +} +%end + +// Story tray +%hook IGMainStoryTrayDataSource +- (id)allItemsForTrayUsingCachedValue:(BOOL)cached { + NSArray *originalObjs = %orig(cached); + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (IGStoryTrayViewModel *obj in originalObjs) { + BOOL shouldHide = NO; + + if ([SCIUtils getBoolPref:@"no_suggested_users"]) { + if ([obj isKindOfClass:%c(IGStoryTrayViewModel)]) { + NSNumber *type = [((IGStoryTrayViewModel *)obj) valueForKey:@"type"]; + + // 8/9 looks to be the types for recommended stories + if ([type isEqual:@(8)] || [type isEqual:@(9)]) { + NSLog(@"[SCInsta] Hiding suggested users: story tray"); + + shouldHide = YES; + + } + } + } + + if ([SCIUtils getBoolPref:@"hide_ads"]) { + // "New!" account id is 3538572169 + if ([obj isKindOfClass:%c(IGStoryTrayViewModel)] && (obj.isUnseenNux == YES || [obj.pk isEqualToString:@"3538572169"])) { + NSLog(@"[SCInsta] Removing ads: story tray"); + + shouldHide = YES; + } + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + } + + return [filteredObjs copy]; +} +%end + +// Story tray expanded footer (Suggested accounts to follow) +%hook IGStoryTraySectionController +- (void)storyTrayControllerShowSUPOGEducationBump { + if ([SCIUtils getBoolPref:@"no_suggested_users"]) return; + + return %orig(); +} +%end + +// Modern IGDS app menus +%hook IGDSMenu +- (id)initWithMenuItems:(NSArray *)originalObjs edr:(BOOL)edr headerLabelText:(id)headerLabelText { + NSMutableArray *filteredObjs = [NSMutableArray arrayWithCapacity:[originalObjs count]]; + + for (id obj in originalObjs) { + BOOL shouldHide = NO; + + // Meta AI + if ( + [[obj valueForKey:@"title"] isEqualToString:@"AI images"] + || [[obj valueForKey:@"title"] isEqualToString:@"Meta AI"] + ) { + + if ([SCIUtils getBoolPref:@"hide_meta_ai"]) { + NSLog(@"[SCInsta] Hiding meta ai from IGDS menu"); + + shouldHide = YES; + } + + } + + // Populate new objs array + if (!shouldHide) { + [filteredObjs addObject:obj]; + } + + } + + return %orig([filteredObjs copy], edr, headerLabelText); +} +%end + +///////////////////////////////////////////////////////////////////////////// + +// Confirm buttons + +%hook IGFeedItemUFICell +- (void)UFIButtonBarDidTapOnLike:(id)arg1 { + if ([SCIUtils getBoolPref:@"like_confirm"]) { + NSLog(@"[SCInsta] Confirm post like triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } + else { + return %orig; + } +} + +- (void)UFIButtonBarDidTapOnRepost:(id)arg1 { + if ([SCIUtils getBoolPref:@"repost_confirm"]) { + NSLog(@"[SCInsta] Confirm repost triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } + else { + return %orig; + } +} + +- (void)UFIButtonBarDidLongPressOnRepost:(id)arg1 { + if ([SCIUtils getBoolPref:@"repost_confirm"]) { + NSLog(@"[SCInsta] Confirm repost triggered (long press ignored)"); + } + else { + return %orig; + } +} +- (void)UFIButtonBarDidLongPressOnRepost:(id)arg1 withGestureRecognizer:(id)arg2 { + if ([SCIUtils getBoolPref:@"repost_confirm"]) { + NSLog(@"[SCInsta] Confirm repost triggered (long press ignored)"); + } + else { + return %orig; + } +} +%end + +%hook IGSundialViewerVerticalUFI +- (void)_didTapLikeButton:(id)arg1 { + if ([SCIUtils getBoolPref:@"like_confirm_reels"]) { + NSLog(@"[SCInsta] Confirm reels like triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } + else { + return %orig; + } +} + +- (void)_didLongPressLikeButton:(id)arg1 { + if ([SCIUtils getBoolPref:@"like_confirm_reels"]) { + NSLog(@"[SCInsta] Confirm repost triggered (long press ignored)"); + } + else { + return %orig; + } +} + +- (void)_didTapRepostButton:(id)arg1 { + if ([SCIUtils getBoolPref:@"repost_confirm"]) { + NSLog(@"[SCInsta] Confirm repost triggered"); + + [SCIUtils showConfirmation:^(void) { %orig; }]; + } + else { + return %orig; + } +} + +- (void)_didLongPressRepostButton:(id)arg1 { + if ([SCIUtils getBoolPref:@"repost_confirm"]) { + NSLog(@"[SCInsta] Confirm repost triggered (long press ignored)"); + } + else { + return %orig; + } +} +%end + +///////////////////////////////////////////////////////////////////////////// + +// FLEX explorer gesture handler +%hook IGRootViewController +- (void)viewDidLoad { + %orig; + + // Recognize 5-finger long press + UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)]; + longPress.minimumPressDuration = 1; + longPress.numberOfTouchesRequired = 5; + [self.view addGestureRecognizer:longPress]; +} +%new - (void)handleLongPress:(UILongPressGestureRecognizer *)sender { + if (sender.state != UIGestureRecognizerStateBegan) return; + + if ([SCIUtils getBoolPref:@"flex_instagram"]) { + [[objc_getClass("FLEXManager") sharedManager] showExplorer]; + } +} +%end + +// Disable safe mode (defaults reset upon subsequent crashes) +%hook IGSafeModeChecker +- (id)initWithInstacrashCounterProvider:(void *)provider crashThreshold:(unsigned long long)threshold { + if ([SCIUtils getBoolPref:@"disable_safe_mode"]) return nil; + + return %orig(provider, threshold); +} +- (unsigned long long)crashCount { + if ([SCIUtils getBoolPref:@"disable_safe_mode"]) { + return 0; + } + + return %orig; +} +%end diff --git a/src/Utils.h b/src/Utils.h new file mode 100644 index 0000000..91dc661 --- /dev/null +++ b/src/Utils.h @@ -0,0 +1,83 @@ +#import +#import +#import +#import +#import + +#import "../modules/JGProgressHUD/JGProgressHUD.h" + +#import "InstagramHeaders.h" +#import "QuickLook.h" + +#import "Settings/SCISettingsViewController.h" + +#define SCILog(fmt, ...) \ + do { \ + NSString *tmpStr = [NSString stringWithFormat:(fmt), ##__VA_ARGS__]; \ + os_log(OS_LOG_DEFAULT, "[SCInsta Test] %{public}s", tmpStr.UTF8String); \ + } while(0) + +#define SCILogId(prefix, obj) os_log(OS_LOG_DEFAULT, "[SCInsta Test] %{public}@: %{public}@", prefix, obj); + +@interface SCIUtils : NSObject + ++ (BOOL)getBoolPref:(NSString *)key; ++ (double)getDoublePref:(NSString *)key; ++ (NSString *)getStringPref:(NSString *)key; + ++ (_Bool)liquidGlassEnabledBool:(_Bool)fallback; + ++ (void)cleanCache; + +// Displaying View Controllers ++ (void)showQuickLookVC:(NSArray *)items; ++ (void)showShareVC:(id)item; ++ (void)showSettingsVC:(UIWindow *)window; + +// Colours ++ (UIColor *)SCIColor_Primary; + +// Errors ++ (NSError *)errorWithDescription:(NSString *)errorDesc; ++ (NSError *)errorWithDescription:(NSString *)errorDesc code:(NSInteger)errorCode; + ++ (JGProgressHUD *)showErrorHUDWithDescription:(NSString *)errorDesc; ++ (JGProgressHUD *)showErrorHUDWithDescription:(NSString *)errorDesc dismissAfterDelay:(CGFloat)dismissDelay; + +// Media ++ (NSURL *)getPhotoUrl:(IGPhoto *)photo; ++ (NSURL *)getPhotoUrlForMedia:(IGMedia *)media; + ++ (NSURL *)getVideoUrl:(IGVideo *)video; ++ (NSURL *)getVideoUrlForMedia:(IGMedia *)media; + +// View Controllers ++ (UIViewController *)viewControllerForView:(UIView *)view; ++ (UIViewController *)viewControllerForAncestralView:(UIView *)view; ++ (UIViewController *)nearestViewControllerForView:(UIView *)view; + +// Functions ++ (NSString *)IGVersionString; ++ (BOOL)isNotch; + ++ (BOOL)existingLongPressGestureRecognizerForView:(UIView *)view; + +// Alerts ++ (BOOL)showConfirmation:(void(^)(void))okHandler title:(NSString *)title; ++ (BOOL)showConfirmation:(void(^)(void))okHandler cancelHandler:(void(^)(void))cancelHandler title:(NSString *)title; ++ (BOOL)showConfirmation:(void(^)(void))okHandler; ++ (BOOL)showConfirmation:(void(^)(void))okHandler cancelHandler:(void(^)(void))cancelHandler; ++ (void)showRestartConfirmation; + +// Toasts ++ (void)showToastForDuration:(double)duration title:(NSString *)title; ++ (void)showToastForDuration:(double)duration title:(NSString *)title subtitle:(NSString *)subtitle; + +// Math ++ (NSUInteger)decimalPlacesInDouble:(double)value; + +// Ivars ++ (id)getIvarForObj:(id)obj name:(const char *)name; ++ (void)setIvarForObj:(id)obj name:(const char *)name value:(id)value; + +@end \ No newline at end of file diff --git a/src/Utils.m b/src/Utils.m new file mode 100644 index 0000000..4314f9a --- /dev/null +++ b/src/Utils.m @@ -0,0 +1,338 @@ +#import "Utils.h" + +@implementation SCIUtils + ++ (BOOL)getBoolPref:(NSString *)key { + if (![key length] || [[NSUserDefaults standardUserDefaults] objectForKey:key] == nil) return false; + + return [[NSUserDefaults standardUserDefaults] boolForKey:key]; +} ++ (double)getDoublePref:(NSString *)key { + if (![key length] || [[NSUserDefaults standardUserDefaults] objectForKey:key] == nil) return 0; + + return [[NSUserDefaults standardUserDefaults] doubleForKey:key]; +} ++ (NSString *)getStringPref:(NSString *)key { + if (![key length] || [[NSUserDefaults standardUserDefaults] objectForKey:key] == nil) return @""; + + return [[NSUserDefaults standardUserDefaults] stringForKey:key]; +} + ++ (_Bool)liquidGlassEnabledBool:(_Bool)fallback { + BOOL setting = [SCIUtils getBoolPref:@"liquid_glass_surfaces"]; + return setting ? true : fallback; +} + ++ (void)cleanCache { + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSMutableArray *deletionErrors = [NSMutableArray array]; + + // Temp folder + // * disabled bc app crashed trying to delete certain files inside it + // todo: remove the above disclaimer if this new code doesn't cause crashing + NSArray *tempFolderContents = [fileManager contentsOfDirectoryAtURL:[NSURL fileURLWithPath:NSTemporaryDirectory()] includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsHiddenFiles error:nil]; + + for (NSURL *fileURL in tempFolderContents) { + NSError *cacheItemDeletionError; + [fileManager removeItemAtURL:fileURL error:&cacheItemDeletionError]; + + if (cacheItemDeletionError) [deletionErrors addObject:cacheItemDeletionError]; + } + + // Analytics folder + NSString *analyticsFolder = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"Application Support/com.burbn.instagram/analytics"]; + NSArray *analyticsFolderContents = [fileManager contentsOfDirectoryAtURL:[[NSURL alloc] initFileURLWithPath:analyticsFolder] includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsHiddenFiles error:nil]; + + for (NSURL *fileURL in analyticsFolderContents) { + NSError *cacheItemDeletionError; + [fileManager removeItemAtURL:fileURL error:&cacheItemDeletionError]; + + if (cacheItemDeletionError) [deletionErrors addObject:cacheItemDeletionError]; + } + + // Caches folder + NSString *cachesFolder = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"Caches"]; + NSArray *cachesFolderContents = [fileManager contentsOfDirectoryAtURL:[[NSURL alloc] initFileURLWithPath:cachesFolder] includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsHiddenFiles error:nil]; + + for (NSURL *fileURL in cachesFolderContents) { + NSError *cacheItemDeletionError; + [fileManager removeItemAtURL:fileURL error:&cacheItemDeletionError]; + + if (cacheItemDeletionError) [deletionErrors addObject:cacheItemDeletionError]; + } + + // Log errors + if (deletionErrors.count > 1) { + + for (NSError *error in deletionErrors) { + NSLog(@"[SCInsta] File Deletion Error: %@", error); + } + + } + +} + +// Displaying View Controllers ++ (void)showQuickLookVC:(NSArray *)items { + UIViewController *topVC = topMostController(); + if (!topVC) { + NSLog(@"[SCInsta] No view controller available to present QuickLook"); + return; + } + + QLPreviewController *previewController = [[QLPreviewController alloc] init]; + QuickLookDelegate *quickLookDelegate = [[QuickLookDelegate alloc] initWithPreviewItemURLs:items]; + + previewController.dataSource = quickLookDelegate; + + [topVC presentViewController:previewController animated:true completion:nil]; +} ++ (void)showShareVC:(id)item { + UIViewController *topVC = topMostController(); + if (!topVC) { + NSLog(@"[SCInsta] No view controller available to present share sheet"); + return; + } + + UIActivityViewController *acVC = [[UIActivityViewController alloc] initWithActivityItems:@[item] applicationActivities:nil]; + if (is_iPad()) { + acVC.popoverPresentationController.sourceView = topVC.view; + acVC.popoverPresentationController.sourceRect = CGRectMake(topVC.view.bounds.size.width / 2.0, topVC.view.bounds.size.height / 2.0, 1.0, 1.0); + } + [topVC presentViewController:acVC animated:true completion:nil]; +} ++ (void)showSettingsVC:(UIWindow *)window { + UIViewController *rootController = [window rootViewController]; + SCISettingsViewController *settingsViewController = [SCISettingsViewController new]; + UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:settingsViewController]; + + [rootController presentViewController:navigationController animated:YES completion:nil]; +} + +// Colours ++ (UIColor *)SCIColor_Primary { + return [UIColor colorWithRed:0/255.0 green:152/255.0 blue:254/255.0 alpha:1]; +}; + +// Errors ++ (NSError *)errorWithDescription:(NSString *)errorDesc { + return [self errorWithDescription:errorDesc code:1]; +} ++ (NSError *)errorWithDescription:(NSString *)errorDesc code:(NSInteger)errorCode { + NSError *error = [ NSError errorWithDomain:@"com.socuul.scinsta" code:errorCode userInfo:@{ NSLocalizedDescriptionKey: errorDesc } ]; + return error; +} + ++ (JGProgressHUD *)showErrorHUDWithDescription:(NSString *)errorDesc { + return [self showErrorHUDWithDescription:errorDesc dismissAfterDelay:4.0]; +} ++ (JGProgressHUD *)showErrorHUDWithDescription:(NSString *)errorDesc dismissAfterDelay:(CGFloat)dismissDelay { + JGProgressHUD *hud = [[JGProgressHUD alloc] init]; + hud.textLabel.text = errorDesc; + hud.indicatorView = [[JGProgressHUDErrorIndicatorView alloc] init]; + + UIView *hudView = topMostController().view; + if (!hudView) hudView = [UIApplication sharedApplication].keyWindow; + if (hudView) { + [hud showInView:hudView]; + [hud dismissAfterDelay:dismissDelay]; + } else { + NSLog(@"[SCInsta] No valid view for error HUD: %@", errorDesc); + } + + return hud; +} + +// Media ++ (NSURL *)getPhotoUrl:(IGPhoto *)photo { + if (!photo) return nil; + + // Get highest quality photo link + NSURL *photoUrl = [photo imageURLForWidth:100000.00]; + + return photoUrl; +} ++ (NSURL *)getPhotoUrlForMedia:(IGMedia *)media { + if (!media) return nil; + + IGPhoto *photo = media.photo; + + return [SCIUtils getPhotoUrl:photo]; +} ++ (NSURL *)getVideoUrl:(IGVideo *)video { + if (!video) return nil; + + // The past (pre v398) + if ([video respondsToSelector:@selector(sortedVideoURLsBySize)]) { + NSArray *sorted = [video sortedVideoURLsBySize]; + NSString *urlString = sorted.firstObject[@"url"]; + return urlString.length ? [NSURL URLWithString:urlString] : nil; + } + + // The present (post v398) + if ([video respondsToSelector:@selector(allVideoURLs)]) { + return [[video allVideoURLs] anyObject]; + } + + return nil; +} ++ (NSURL *)getVideoUrlForMedia:(IGMedia *)media { + if (!media) return nil; + + IGVideo *video = media.video; + if (!video) return nil; + + return [SCIUtils getVideoUrl:video]; +} + +// View Controllers ++ (UIViewController *)viewControllerForView:(UIView *)view { + NSString *viewDelegate = @"viewDelegate"; + if ([view respondsToSelector:NSSelectorFromString(viewDelegate)]) { + return [view valueForKey:viewDelegate]; + } + + return nil; +} + ++ (UIViewController *)viewControllerForAncestralView:(UIView *)view { + NSString *_viewControllerForAncestor = @"_viewControllerForAncestor"; + if ([view respondsToSelector:NSSelectorFromString(_viewControllerForAncestor)]) { + return [view valueForKey:_viewControllerForAncestor]; + } + + return nil; +} + ++ (UIViewController *)nearestViewControllerForView:(UIView *)view { + return [self viewControllerForView:view] ?: [self viewControllerForAncestralView:view]; +} + +// Functions ++ (NSString *)IGVersionString { + return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]; +}; ++ (BOOL)isNotch { + return [[[UIApplication sharedApplication] keyWindow] safeAreaInsets].bottom > 0; +}; + ++ (BOOL)existingLongPressGestureRecognizerForView:(UIView *)view { + NSArray *allRecognizers = view.gestureRecognizers; + + for (UIGestureRecognizer *recognizer in allRecognizers) { + if ([[recognizer class] isSubclassOfClass:[UILongPressGestureRecognizer class]]) { + return YES; + } + } + + return NO; +} + +// Alerts ++ (BOOL)showConfirmation:(void(^)(void))okHandler title:(NSString *)title { + UIAlertController* alert = [UIAlertController alertControllerWithTitle:title message:@"Are you sure?" preferredStyle:UIAlertControllerStyleAlert]; + [alert addAction:[UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { + okHandler(); + }]]; + [alert addAction:[UIAlertAction actionWithTitle:@"No!" style:UIAlertActionStyleCancel handler:nil]]; + + [topMostController() presentViewController:alert animated:YES completion:nil]; + + return nil; +}; ++ (BOOL)showConfirmation:(void(^)(void))okHandler cancelHandler:(void(^)(void))cancelHandler title:(NSString *)title { + UIAlertController* alert = [UIAlertController alertControllerWithTitle:title message:@"Are you sure?" preferredStyle:UIAlertControllerStyleAlert]; + [alert addAction:[UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { + okHandler(); + }]]; + [alert addAction:[UIAlertAction actionWithTitle:@"No!" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { + if (cancelHandler != nil) { + cancelHandler(); + } + }]]; + + [topMostController() presentViewController:alert animated:YES completion:nil]; + + return nil; +}; ++ (BOOL)showConfirmation:(void(^)(void))okHandler { + return [self showConfirmation:okHandler title:nil]; +}; ++ (BOOL)showConfirmation:(void(^)(void))okHandler cancelHandler:(void(^)(void))cancelHandler { + return [self showConfirmation:okHandler cancelHandler:cancelHandler title:nil]; +} ++ (void)showRestartConfirmation { + UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Restart required" message:@"You must restart the app to apply this change" preferredStyle:UIAlertControllerStyleAlert]; + [alert addAction:[UIAlertAction actionWithTitle:@"Restart" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { + exit(0); + }]]; + [alert addAction:[UIAlertAction actionWithTitle:@"Later" style:UIAlertActionStyleCancel handler:nil]]; + + [topMostController() presentViewController:alert animated:YES completion:nil]; +}; + +// Toasts ++ (void)showToastForDuration:(double)duration title:(NSString *)title { + [SCIUtils showToastForDuration:duration title:title subtitle:nil]; +} ++ (void)showToastForDuration:(double)duration title:(NSString *)title subtitle:(NSString *)subtitle { + // Root VC + Class rootVCClass = NSClassFromString(@"IGRootViewController"); + + UIViewController *topMostVC = topMostController(); + if (![topMostVC isKindOfClass:rootVCClass]) return; + + IGRootViewController *rootVC = (IGRootViewController *)topMostVC; + + // Presenter + IGActionableConfirmationToastPresenter *toastPresenter = [rootVC toastPresenter]; + if (toastPresenter == nil) return; + + // View Model + Class modelClass = NSClassFromString(@"IGActionableConfirmationToastViewModel"); + IGActionableConfirmationToastViewModel *model = [modelClass new]; + + [model setValue:title forKey:@"text_annotatedTitleText"]; + [model setValue:subtitle forKey:@"text_annotatedSubtitleText"]; + + // Show new toast, after clearing existing one + [toastPresenter hideAlert]; + [toastPresenter showAlertWithViewModel:model isAnimated:true animationDuration:duration presentationPriority:0 tapActionBlock:nil presentedHandler:nil dismissedHandler:nil]; +} + +// Math ++ (NSUInteger)decimalPlacesInDouble:(double)value { + NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; + [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; + [formatter setMaximumFractionDigits:15]; // Allow enough digits for double precision + [formatter setMinimumFractionDigits:0]; + [formatter setDecimalSeparator:@"."]; // Force dot for internal logic, then respect locale for final display if needed + + NSString *stringValue = [formatter stringFromNumber:@(value)]; + + // Find decimal separator + NSRange decimalRange = [stringValue rangeOfString:formatter.decimalSeparator]; + + if (decimalRange.location == NSNotFound) { + return 0; + } else { + return stringValue.length - (decimalRange.location + decimalRange.length); + } +} + +// Ivars ++ (id)getIvarForObj:(id)obj name:(const char *)name { + Ivar ivar = class_getInstanceVariable(object_getClass(obj), name); + if (!ivar) return nil; + + return object_getIvar(obj, ivar); +} ++ (void)setIvarForObj:(id)obj name:(const char *)name value:(id)value { + Ivar ivar = class_getInstanceVariable(object_getClass(obj), name); + if (!ivar) return; + + object_setIvarWithStrongDefault(obj, ivar, value); +} + + +@end \ No newline at end of file