commit 2a4ee357cec46eb6edfb102a16db0cfe20f81af0 Author: John Doe <222520099+haumlab@users.noreply.github.com> Date: Thu Dec 25 02:14:09 2025 +0000 Migrate to FlatBuffers and unify Mobile/TV modules diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml new file mode 100644 index 0000000..ff8091a --- /dev/null +++ b/.github/workflows/android.yml @@ -0,0 +1,123 @@ +name: Android CI + +on: + push: + branches: [ main ] + tags: + - 'v*' + pull_request: + branches: [ main ] + release: + types: [ published, created, edited ] + workflow_dispatch: + +permissions: + contents: write + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + cache: gradle + + - name: Grant execute permission for gradlew + run: chmod +x gradlew + + - name: Decode Keystore + run: | + echo "${{ secrets.KEYSTORE_BASE64 }}" | base64 -d > ${{ github.workspace }}/release.keystore + + - name: Build Release APKs + run: ./gradlew assembleRelease + + - name: Sign Mobile APK + env: + KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }} + KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }} + KEY_ALIAS: ${{ secrets.KEY_ALIAS }} + run: | + $ANDROID_HOME/build-tools/34.0.0/apksigner sign --ks ${{ github.workspace }}/release.keystore \ + --ks-key-alias "$KEY_ALIAS" \ + --ks-pass "pass:$KEYSTORE_PASSWORD" \ + --key-pass "pass:$KEY_PASSWORD" \ + --out mobile/build/outputs/apk/release/mobile-release.apk \ + mobile/build/outputs/apk/release/mobile-release-unsigned.apk + + - name: Sign TV APK + env: + KEYSTORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }} + KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }} + KEY_ALIAS: ${{ secrets.KEY_ALIAS }} + run: | + $ANDROID_HOME/build-tools/34.0.0/apksigner sign --ks ${{ github.workspace }}/release.keystore \ + --ks-key-alias "$KEY_ALIAS" \ + --ks-pass "pass:$KEYSTORE_PASSWORD" \ + --key-pass "pass:$KEY_PASSWORD" \ + --out tv/build/outputs/apk/release/tv-release.apk \ + tv/build/outputs/apk/release/tv-release-unsigned.apk + + - name: Upload Mobile APK + uses: actions/upload-artifact@v4 + with: + name: mobile-release + path: mobile/build/outputs/apk/release/mobile-release.apk + + - name: Upload TV APK + uses: actions/upload-artifact@v4 + with: + name: tv-release + path: tv/build/outputs/apk/release/tv-release.apk + + - name: Get version + id: get_version + run: | + if [[ $GITHUB_REF == refs/tags/* ]]; then + echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT + echo "IS_TAG=true" >> $GITHUB_OUTPUT + else + echo "VERSION=latest" >> $GITHUB_OUTPUT + echo "IS_TAG=false" >> $GITHUB_OUTPUT + fi + + - name: Create Release (Tag) + if: startsWith(github.ref, 'refs/tags/') + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ steps.get_version.outputs.VERSION }} + draft: false + prerelease: false + files: | + mobile/build/outputs/apk/release/mobile-release.apk + tv/build/outputs/apk/release/tv-release.apk + + - name: Create Release (Latest) + if: github.ref == 'refs/heads/main' + uses: softprops/action-gh-release@v2 + with: + tag_name: latest + name: Latest Build + body: | + **Automated development build** from `${{ github.sha }}` + + This is a pre-release build from the main branch and may be unstable. + + **[View Changelog](https://github.com/haumlab/hyperion-android-reborn/blob/main/CHANGELOG.md)** for recent changes. + + --- + ### Downloads + - **mobile-release.apk** - For phones and tablets + - **tv-release.apk** - For Android TV devices + draft: false + prerelease: true + files: | + mobile/build/outputs/apk/release/mobile-release.apk + tv/build/outputs/apk/release/tv-release.apk diff --git a/.gitignore b/.gitignore new file mode 100755 index 0000000..9701502 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +/.idea/caches +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/AndroidProjectSystem.xml b/.idea/AndroidProjectSystem.xml new file mode 100644 index 0000000..4a53bee --- /dev/null +++ b/.idea/AndroidProjectSystem.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..30aa626 --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..b86273d --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/deploymentTargetSelector.xml b/.idea/deploymentTargetSelector.xml new file mode 100644 index 0000000..758e93f --- /dev/null +++ b/.idea/deploymentTargetSelector.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100755 index 0000000..e6de06a --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,21 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/markdown.xml b/.idea/markdown.xml new file mode 100644 index 0000000..c61ea33 --- /dev/null +++ b/.idea/markdown.xml @@ -0,0 +1,8 @@ + + + + + + \ No newline at end of file diff --git a/.idea/migrations.xml b/.idea/migrations.xml new file mode 100644 index 0000000..f8051a6 --- /dev/null +++ b/.idea/migrations.xml @@ -0,0 +1,10 @@ + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100755 index 0000000..4237920 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml new file mode 100755 index 0000000..72f00ed --- /dev/null +++ b/.idea/runConfigurations.xml @@ -0,0 +1,20 @@ + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..5b040a7 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,100 @@ + + + +# [v2.0.1] +### Changes +- APKs are now signed + +--- + +# [v2.0] +### Changes +- Full Android 12+ (API 31+) compatibility +- Migrated from Android Support Library to AndroidX +- Updated to Gradle 8.4 and Android Gradle Plugin 8.2.1 +- Updated to Kotlin 1.9.22 +- Updated target SDK to 34 (Android 14) +- Added foreground service type declaration for media projection +- Added POST_NOTIFICATIONS permission for Android 13+ +- Replaced deprecated AsyncTask with ExecutorService/Handler pattern +- Removed ButterKnife dependency (TV app) +- Updated Konfetti library to v2.0.4 +- Updated Protobuf to 3.25.1 with protobuf-javalite +- Changed default message priority to 100 +- Added proper PendingIntent immutability flags for Android 12+ + +### Fixed +- FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION error on Android 12+ +- PendingIntent mutability crash on Android 12+ +- Notification permission handling for Android 13+ +- Resource reference issues with AGP 8.x namespace changes + +## [v1.0] +### Changes + + +- OLD +## [v1.0] + +- Arabic translation + +### Fixed +- Possible NPE when stopping the grabber + +## [v0.5-beta] +### Changes +- Added the ability to send only the average color of the screen +- French translation +- Norwegian translation +- Czech translation +- German translation +- Dutch translation +- Partial Russian translation +- Partial Spanish translation +- Removed openGL grabber option +- Added toggle grabber activity shortcut +- LEDs will now be cleared when rebooting or shutting down + +### Fixed +- Lights now clear (if running) when shutting down +- Assertion bug in TV settings +- Possible null intent when starting grabber +- OOM bug + +## [v0.4-alpha] +### Changes +- Start grabber on device boot +- Added some eye candy for when grabber is started +- General UI tweaks (tv & mobile) +- Reconnect behavior implemented for mobile build +- New connection wizard +- New settings/connection page (tv build) +- Quick settings tile to toggle grabber (mobile build) +- Screen orientation change updates grabber +- Configurable grabber image quality +- Pressing the notification will now return to the app's main activity + +### Fixed +- Grabber would fail to resume when waking device +- OpenGL grabber sometimes halting immediately after starting screen grab +- Default grabber failing to send data the first time it is turned on +- Grabber not stopping when the host is unreachable +- Aspect ratio of grabbed image being slightly off +- OOM bug + +## [v0.3-alpha] +### Changes +- Leanback launcher support (tv build) +- Revised layout (tv build) +- Reconnect if connection is lost to hyperion server (tv build) + +## [v0.2-alpha] +### Changes +- App Icon +- Fancy toggle button +- Bug fixes +- New Grabber (old grabber can be enabled in the settings) + +### Known Bugs +- OpenGL grabber will sometimes hang when started, making the lights unresponsive. Quitting the app and starting again generally fixes the problem. +- New grabber fails to send any data the first time it is initialized. Turning off and back on one more time seems to fix the problem. diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..0a96941 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Dave Anderson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d87e2c9 --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ + +logosz + + +# Hyperion Android Reborn +Screen grabber for hyperion, updated for **Android 12** and **beyond**. + +This application will send the content of the android screen to a hyperion instance to handle the image. + +Info about hyperion can be found on their website: +https://hyperion-project.org/ + +--- + +# Download +Both **TV** and **Mobile** apps are within [releases page](https://github.com/haumlab/hyperion-android-reborn/releases) diff --git a/app/.gitignore b/app/.gitignore new file mode 100755 index 0000000..796b96d --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle b/app/build.gradle new file mode 100755 index 0000000..a5961d6 --- /dev/null +++ b/app/build.gradle @@ -0,0 +1,50 @@ +plugins { + id 'com.android.application' + id 'kotlin-android' +} + +apply from: project(':common').projectDir.absolutePath + '/variables.gradle' + +android { + namespace 'com.hyperion.grabber' + compileSdk 34 + + defaultConfig { + applicationId "com.hyperion.grabber" + minSdk 21 + targetSdk 34 + versionCode 2013 + versionName "2.0" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + + compileOptions { + targetCompatibility JavaVersion.VERSION_17 + sourceCompatibility JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = '17' + } +} + +dependencies { + implementation fileTree(include: ['*.jar'], dir: 'libs') + api project(path: ':common') + implementation "androidx.appcompat:appcompat:1.6.1" + implementation "androidx.core:core-ktx:1.12.0" + implementation "androidx.constraintlayout:constraintlayout:2.1.4" + implementation "androidx.preference:preference-ktx:1.2.1" + implementation "androidx.localbroadcastmanager:localbroadcastmanager:1.1.0" + + implementation "androidx.leanback:leanback:1.0.0" + implementation "androidx.leanback:leanback-preference:1.0.0" + implementation 'nl.dionsegijn:konfetti-xml:2.0.4' + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" +} \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100755 index 0000000..f1b4245 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100755 index 0000000..1ce0762 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/java/com/hyperion/grabber/AppCompatPreferenceActivity.java b/app/src/main/java/com/hyperion/grabber/AppCompatPreferenceActivity.java new file mode 100755 index 0000000..02dd69f --- /dev/null +++ b/app/src/main/java/com/hyperion/grabber/AppCompatPreferenceActivity.java @@ -0,0 +1,118 @@ +package com.hyperion.grabber; + +import android.content.res.Configuration; +import android.os.Bundle; +import android.preference.PreferenceActivity; +import androidx.annotation.LayoutRes; +import androidx.annotation.Nullable; +import androidx.core.app.NavUtils; +import androidx.appcompat.app.ActionBar; +import androidx.appcompat.app.AppCompatDelegate; +import androidx.appcompat.widget.Toolbar; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; + +/** + * A {@link android.preference.PreferenceActivity} which implements and proxies the necessary calls + * to be used with AppCompat. + */ +public abstract class AppCompatPreferenceActivity extends PreferenceActivity { + + private AppCompatDelegate mDelegate; + + @Override + protected void onCreate(Bundle savedInstanceState) { + getDelegate().installViewFactory(); + getDelegate().onCreate(savedInstanceState); + super.onCreate(savedInstanceState); + getSupportActionBar().setDisplayShowHomeEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + } + + @Override + protected void onPostCreate(Bundle savedInstanceState) { + super.onPostCreate(savedInstanceState); + getDelegate().onPostCreate(savedInstanceState); + } + + public ActionBar getSupportActionBar() { + return getDelegate().getSupportActionBar(); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + if (item.getItemId() == android.R.id.home) { + NavUtils.navigateUpFromSameTask(this); + return true; + } + return super.onOptionsItemSelected(item); + } + + @Override + public MenuInflater getMenuInflater() { + return getDelegate().getMenuInflater(); + } + + @Override + public void setContentView(@LayoutRes int layoutResID) { + getDelegate().setContentView(layoutResID); + } + + @Override + public void setContentView(View view) { + getDelegate().setContentView(view); + } + + @Override + public void setContentView(View view, ViewGroup.LayoutParams params) { + getDelegate().setContentView(view, params); + } + + @Override + public void addContentView(View view, ViewGroup.LayoutParams params) { + getDelegate().addContentView(view, params); + } + + @Override + protected void onPostResume() { + super.onPostResume(); + getDelegate().onPostResume(); + } + + @Override + protected void onTitleChanged(CharSequence title, int color) { + super.onTitleChanged(title, color); + getDelegate().setTitle(title); + } + + @Override + public void onConfigurationChanged(Configuration newConfig) { + super.onConfigurationChanged(newConfig); + getDelegate().onConfigurationChanged(newConfig); + } + + @Override + protected void onStop() { + super.onStop(); + getDelegate().onStop(); + } + + @Override + protected void onDestroy() { + super.onDestroy(); + getDelegate().onDestroy(); + } + + public void invalidateOptionsMenu() { + getDelegate().invalidateOptionsMenu(); + } + + private AppCompatDelegate getDelegate() { + if (mDelegate == null) { + mDelegate = AppCompatDelegate.create(this, null); + } + return mDelegate; + } +} diff --git a/app/src/main/java/com/hyperion/grabber/FadingImageView.java b/app/src/main/java/com/hyperion/grabber/FadingImageView.java new file mode 100644 index 0000000..7004ae2 --- /dev/null +++ b/app/src/main/java/com/hyperion/grabber/FadingImageView.java @@ -0,0 +1,74 @@ +package com.hyperion.grabber; + +import android.content.Context; +import android.content.res.Resources; +import android.util.AttributeSet; +import android.util.TypedValue; + +public class FadingImageView extends androidx.appcompat.widget.AppCompatImageView { + private Context c; + + public FadingImageView(Context c, AttributeSet attrs, int defStyle) { + super(c, attrs, defStyle); + this.c = c; + init(); + } + + public FadingImageView(Context c, AttributeSet attrs) { + super(c, attrs); + this.c = c; + init(); + } + + public FadingImageView(Context c) { + super(c); + this.c = c; + init(); + } + + private void init() { + this.setHorizontalFadingEdgeEnabled(true); + this.setVerticalFadingEdgeEnabled(true); + this.setEdgeLength(80); + } + + public void setEdgeLength(int length) { + this.setFadingEdgeLength(getPixels(length)); + } + + @Override + protected float getLeftFadingEdgeStrength() { + return 1.0f; + } + + @Override + protected float getRightFadingEdgeStrength() { + return 1.0f; + } + + @Override + protected float getTopFadingEdgeStrength() { + return 1.0f; + } + + @Override + protected float getBottomFadingEdgeStrength() { + return 1.0f; + } + + @Override + public boolean hasOverlappingRendering() { + return true; + } + + @Override + public boolean onSetAlpha(int alpha) { + return false; + } + + private int getPixels(int dipValue) { + Resources r = c.getResources(); + return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, + dipValue, r.getDisplayMetrics()); + } +} \ No newline at end of file diff --git a/app/src/main/java/com/hyperion/grabber/HyperionGrabberTileService.java b/app/src/main/java/com/hyperion/grabber/HyperionGrabberTileService.java new file mode 100644 index 0000000..9265fb6 --- /dev/null +++ b/app/src/main/java/com/hyperion/grabber/HyperionGrabberTileService.java @@ -0,0 +1,147 @@ +package com.hyperion.grabber; + +import android.app.ActivityManager; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.os.Build; +import android.os.Handler; +import android.service.quicksettings.Tile; +import android.service.quicksettings.TileService; +import androidx.annotation.RequiresApi; +import androidx.core.app.TaskStackBuilder; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import android.text.TextUtils; +import android.widget.Toast; + +import com.hyperion.grabber.common.BootActivity; +import com.hyperion.grabber.common.HyperionScreenService; +import com.hyperion.grabber.common.util.Preferences; + +@RequiresApi(api = Build.VERSION_CODES.N) +public class HyperionGrabberTileService extends TileService { + private final int REMOVE_LISTENER_DELAY = 1000 * 10; // 10 second delay to remove listener + private static boolean mIsListening = false; + private Handler mHandle = new Handler(); + + private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + Tile tile = getQsTile(); + boolean running = intent.getBooleanExtra(HyperionScreenService.BROADCAST_TAG, false); + String error = intent.getStringExtra(HyperionScreenService.BROADCAST_ERROR); + tile.setState(running ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE); + tile.updateTile(); + if (error != null) { + Toast.makeText(getBaseContext(), error, Toast.LENGTH_LONG).show(); + } + } + }; + + @Override + public void onStartListening() { + super.onStartListening(); + mHandle.removeCallbacksAndMessages(null); + if (!mIsListening) { + LocalBroadcastManager.getInstance(this).registerReceiver( + mMessageReceiver, new IntentFilter(HyperionScreenService.BROADCAST_FILTER)); + mIsListening = true; + } + if (isServiceRunning()) { + Intent intent = new Intent(this, HyperionScreenService.class); + intent.setAction(HyperionScreenService.GET_STATUS); + startService(intent); + } else { + Tile tile = getQsTile(); + tile.setState(Tile.STATE_INACTIVE); + tile.updateTile(); + } + } + + @Override + public void onStopListening() { + super.onTileRemoved(); + mHandle.postDelayed(unregisterReceiverRunner, REMOVE_LISTENER_DELAY); + } + + @Override + public void onDestroy() { + super.onDestroy(); + mIsListening = false; + } + + @Override + public void onClick() { + Tile tile = getQsTile(); + tile.updateTile(); + int tileState = tile.getState(); + if (tileState == Tile.STATE_ACTIVE) { + Intent intent = new Intent(this, HyperionScreenService.class); + intent.setAction(HyperionScreenService.ACTION_EXIT); + startService(intent); + } else { + Runnable runner = () -> { + + boolean setupStarted = startSetupIfNeeded(); + + if (!setupStarted){ + final Intent i = new Intent(this, BootActivity.class); + i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION + |Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS + |Intent.FLAG_ACTIVITY_NO_HISTORY); + startActivity(i); + } + + }; + if (isLocked()) { + unlockAndRun(runner); + } else { + runner.run(); + } + } + } + + private boolean isServiceRunning() { + ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); + assert manager != null; + for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { + if (HyperionScreenService.class.getName().equals(service.service.getClassName())) { + return true; + } + } + return false; + } + + private Runnable unregisterReceiverRunner = () -> { + LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver); + mIsListening = false; + }; + + public static boolean isListening() { return mIsListening; } + + /** Starts the Settings Activity if connection settings are missing + * + * @return true if setup was started + */ + private boolean startSetupIfNeeded(){ + Preferences preferences = new Preferences(getApplicationContext()); + if (TextUtils.isEmpty(preferences.getString(com.hyperion.grabber.common.R.string.pref_key_host, null)) || preferences.getInt(com.hyperion.grabber.common.R.string.pref_key_port, -1) == -1){ + Intent settingsIntent = new Intent(this, SettingsActivity.class); + settingsIntent.putExtra(SettingsActivity.EXTRA_SHOW_TOAST_KEY, SettingsActivity.EXTRA_SHOW_TOAST_SETUP_REQUIRED_FOR_QUICK_TILE); + settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + + // Use TaskStackBuilder to make sure the MainActivity opens when the SettingsActivity is closed + TaskStackBuilder.create(this) + .addNextIntentWithParentStack(settingsIntent) + .startActivities(); + + Intent closeIntent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); + sendBroadcast(closeIntent); + + return true; + } + + return false; + } +} diff --git a/app/src/main/java/com/hyperion/grabber/MainActivity.java b/app/src/main/java/com/hyperion/grabber/MainActivity.java new file mode 100755 index 0000000..1a5282b --- /dev/null +++ b/app/src/main/java/com/hyperion/grabber/MainActivity.java @@ -0,0 +1,241 @@ +package com.hyperion.grabber; + +import android.Manifest; +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; +import android.app.Activity; +import android.app.ActivityManager; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.pm.PackageManager; +import android.graphics.Color; +import android.media.projection.MediaProjectionManager; +import android.os.Build; +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import androidx.appcompat.app.AppCompatActivity; +import android.os.Bundle; +import android.util.Log; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.widget.ImageView; +import android.widget.Toast; + +import com.hyperion.grabber.common.BootActivity; +import com.hyperion.grabber.common.HyperionScreenService; + +public class MainActivity extends AppCompatActivity implements ImageView.OnClickListener, + ImageView.OnFocusChangeListener { + public static final int REQUEST_MEDIA_PROJECTION = 1; + private static final int REQUEST_NOTIFICATION_PERMISSION = 2; + private static final String TAG = "DEBUG"; + private boolean mRecorderRunning = false; + private static MediaProjectionManager mMediaProjectionManager; + private Intent mPendingProjectionData = null; + private int mPendingResultCode = 0; + + private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + boolean checked = intent.getBooleanExtra(HyperionScreenService.BROADCAST_TAG, false); + mRecorderRunning = checked; + String error = intent.getStringExtra(HyperionScreenService.BROADCAST_ERROR); + if (error != null && + (Build.VERSION.SDK_INT < Build.VERSION_CODES.N || + !HyperionGrabberTileService.isListening())) { + Toast.makeText(getBaseContext(), error, Toast.LENGTH_LONG).show(); + } + setImageViews(checked, checked); + } + }; + + @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + mMediaProjectionManager = (MediaProjectionManager) + getSystemService(Context.MEDIA_PROJECTION_SERVICE); + + ImageView iv = findViewById(R.id.power_toggle); + iv.setOnClickListener(this); + iv.setOnFocusChangeListener(this); + iv.setFocusable(true); + iv.requestFocus(); + + View settingsButton = findViewById(R.id.settingsButton); + if (settingsButton != null) { + settingsButton.setOnClickListener(v -> { + Intent intent = new Intent(this, SettingsActivity.class); + startActivity(intent); + }); + } + + setImageViews(mRecorderRunning, false); + + LocalBroadcastManager.getInstance(this).registerReceiver( + mMessageReceiver, new IntentFilter(HyperionScreenService.BROADCAST_FILTER)); + checkForInstance(); + + // Request notification permission for Android 13+ + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + requestNotificationPermission(); + } + } + + private void requestNotificationPermission() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) + != PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions(this, + new String[]{Manifest.permission.POST_NOTIFICATIONS}, + REQUEST_NOTIFICATION_PERMISSION); + } + } + } + + @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) + @Override + public void onClick(View view) { + if (!mRecorderRunning) { + startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), + REQUEST_MEDIA_PROJECTION); + } else { + stopScreenRecorder(); + } + mRecorderRunning = !mRecorderRunning; + } + + @Override + public void onFocusChange(View view, boolean focused) { + if (focused) { + ((ImageView) view).setColorFilter(Color.argb(255, 0, 0, 150)); + } else { + ((ImageView) view).setColorFilter(Color.argb(255, 0, 0, 0)); + } + } + + @RequiresApi(api = Build.VERSION_CODES.M) + @Override + public void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == REQUEST_MEDIA_PROJECTION) { + if (resultCode != Activity.RESULT_OK) { + Toast.makeText(this, com.hyperion.grabber.common.R.string.toast_must_give_permission, Toast.LENGTH_SHORT).show(); + if (mRecorderRunning) { + stopScreenRecorder(); + } + setImageViews(false, true); + return; + } + Log.i(TAG, "Starting screen capture"); + startScreenRecorder(resultCode, (Intent) data.clone()); + mRecorderRunning = true; + } + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (requestCode == REQUEST_NOTIFICATION_PERMISSION) { + if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) { + Toast.makeText(this, "Notification permission is needed for the foreground service", Toast.LENGTH_LONG).show(); + } + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + super.onCreateOptionsMenu(menu); + MenuInflater inflater = getMenuInflater(); + inflater.inflate(R.menu.options_menu, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + if (item.getItemId() == R.id.settings) { + Intent intent = new Intent(this, SettingsActivity.class); + startActivity(intent); + } + return super.onOptionsItemSelected(item); + } + + private void checkForInstance() { + if (isServiceRunning()) { + Intent intent = new Intent(this, HyperionScreenService.class); + intent.setAction(HyperionScreenService.GET_STATUS); + startService(intent); + } + } + + public void startScreenRecorder(int resultCode, Intent data) { + BootActivity.startScreenRecorder(this, resultCode, data); + } + + public void stopScreenRecorder() { + if (mRecorderRunning) { + Intent intent = new Intent(this, HyperionScreenService.class); + intent.setAction(HyperionScreenService.ACTION_EXIT); + startService(intent); + } + } + + private void setImageViews(boolean running, boolean animated) { + View rainbow = findViewById(R.id.sweepGradientView); + View message = findViewById(R.id.grabberStartedText); + View buttonImage = findViewById(R.id.power_toggle); + if (running) { + if (animated){ + fadeView(rainbow, true); + fadeView(message, true); + } else { + rainbow.setVisibility(View.VISIBLE); + message.setVisibility(View.VISIBLE); + } + buttonImage.setAlpha((float) 1); + } else { + if (animated){ + fadeView(rainbow, false); + fadeView(message, false); + } else { + rainbow.setVisibility(View.INVISIBLE); + message.setVisibility(View.INVISIBLE); + } + buttonImage.setAlpha((float) 0.25); + } + } + + private boolean isServiceRunning() { + ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); + assert manager != null; + for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { + if (HyperionScreenService.class.getName().equals(service.service.getClassName())) { + return true; + } + } + return false; + } + + private void fadeView(View view, boolean visible){ + float alpha = visible ? 1f : 0f; + int endVisibility = visible ? View.VISIBLE : View.INVISIBLE; + view.setVisibility(View.VISIBLE); + view.animate() + .alpha(alpha) + .setListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + view.setVisibility(endVisibility); + } + }) + .start(); + } +} diff --git a/app/src/main/java/com/hyperion/grabber/SettingsActivity.java b/app/src/main/java/com/hyperion/grabber/SettingsActivity.java new file mode 100755 index 0000000..981e732 --- /dev/null +++ b/app/src/main/java/com/hyperion/grabber/SettingsActivity.java @@ -0,0 +1,158 @@ +package com.hyperion.grabber; + +import android.annotation.TargetApi; +import android.content.Intent; +import android.os.Build; +import android.os.Bundle; +import android.preference.Preference; +import android.preference.PreferenceActivity; +import android.preference.PreferenceFragment; +import android.preference.PreferenceManager; +import androidx.appcompat.app.ActionBar; +import android.view.MenuItem; +import android.widget.Toast; +import java.lang.reflect.Field; + +/** + * A {@link PreferenceActivity} that presents a set of application settings. On + * handset devices, settings are presented as a single list. On tablets, + * settings are split by category, with category headers shown to the left of + * the list of settings. + *

+ * See + * Android Design: Settings for design guidelines and the Settings + * API Guide for more information on developing a Settings UI. + */ +public class SettingsActivity extends AppCompatPreferenceActivity { + public static final String EXTRA_SHOW_TOAST_KEY = "extra_show_toast_key"; + public static final int EXTRA_SHOW_TOAST_SETUP_REQUIRED_FOR_QUICK_TILE = 1; + + + /** + * A preference value change listener that updates the preference's summary + * to reflect its new value. + */ + private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = (preference, value) -> { + final int prefResourceID = getResourceId(preference.getKey(), com.hyperion.grabber.common.R.string.class); + + // verify we have a valid int value for the following preference keys + if (prefResourceID == com.hyperion.grabber.common.R.string.pref_key_port || + prefResourceID == com.hyperion.grabber.common.R.string.pref_key_reconnect_delay || + prefResourceID == com.hyperion.grabber.common.R.string.pref_key_priority || + prefResourceID == com.hyperion.grabber.common.R.string.pref_key_x_led || + prefResourceID == com.hyperion.grabber.common.R.string.pref_key_y_led || + prefResourceID == com.hyperion.grabber.common.R.string.pref_key_framerate) { + try { + Integer.parseInt(value.toString()); + } catch (NumberFormatException e) { + e.printStackTrace(); + return false; + } + } + + String stringValue = value.toString(); + preference.setSummary(stringValue); + + return true; + }; + + /** + * Returns the resource ID of the provided string + */ + public static int getResourceId(String resourceName, Class c) { + try { + Field idField = c.getDeclaredField(resourceName); + return idField.getInt(idField); + } catch (Exception e) { + e.printStackTrace(); + } + return -1; + } + + /** + * Binds a preference's summary to its value. More specifically, when the + * preference's value is changed, its summary (line of text below the + * preference title) is updated to reflect the value. The summary is also + * immediately updated upon calling this method. The exact display format is + * dependent on the type of preference. + * + * @see #sBindPreferenceSummaryToValueListener + */ + private static void bindPreferenceSummaryToValue(Preference preference) { + if (preference == null) return; + // Set the listener to watch for value changes. + preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener); + + // Trigger the listener immediately with the preference's + // current value. + sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, + PreferenceManager + .getDefaultSharedPreferences(preference.getContext()) + .getString(preference.getKey(), "")); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + getFragmentManager().beginTransaction().replace(android.R.id.content, + new GeneralPreferenceFragment()).commit(); + + Bundle extras = getIntent().getExtras(); + if (extras != null && extras.containsKey(EXTRA_SHOW_TOAST_KEY)){ + if (extras.getInt(EXTRA_SHOW_TOAST_KEY) == EXTRA_SHOW_TOAST_SETUP_REQUIRED_FOR_QUICK_TILE){ + Toast.makeText(getApplicationContext(), R.string.quick_tile_toast_setup_required, Toast.LENGTH_SHORT).show(); + } + } + + setupActionBar(); + } + + /** + * Set up the {@link android.app.ActionBar}, if the API is available. + */ + private void setupActionBar() { + ActionBar actionBar = getSupportActionBar(); + if (actionBar != null) { + // Show the Up button in the action bar. + actionBar.setDisplayHomeAsUpEnabled(true); + } + } + + /** + * This fragment shows general preferences only. It is used when the + * activity is showing a two-pane settings UI. + */ + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + public static class GeneralPreferenceFragment extends PreferenceFragment { + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + addPreferencesFromResource(com.hyperion.grabber.common.R.xml.pref_general); + setHasOptionsMenu(true); + + // Bind the summaries of EditText/List/Dialog/Ringtone preferences + // to their values. When their values change, their summaries are + // updated to reflect the new value, per the Android Design + // guidelines. + bindPreferenceSummaryToValue(findPreference(getString(com.hyperion.grabber.common.R.string.pref_key_host))); + bindPreferenceSummaryToValue(findPreference(getString(com.hyperion.grabber.common.R.string.pref_key_port))); + bindPreferenceSummaryToValue(findPreference(getString(com.hyperion.grabber.common.R.string.pref_key_priority))); + bindPreferenceSummaryToValue(findPreference(getString(com.hyperion.grabber.common.R.string.pref_key_framerate))); + bindPreferenceSummaryToValue(findPreference(getString(com.hyperion.grabber.common.R.string.pref_key_reconnect_delay))); + bindPreferenceSummaryToValue(findPreference(getString(com.hyperion.grabber.common.R.string.pref_key_x_led))); + bindPreferenceSummaryToValue(findPreference(getString(com.hyperion.grabber.common.R.string.pref_key_y_led))); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + int id = item.getItemId(); + if (id == android.R.id.home) { + startActivity(new Intent(getActivity(), SettingsActivity.class)); + return true; + } + return super.onOptionsItemSelected(item); + } + } +} diff --git a/app/src/main/java/com/hyperion/grabber/tv/activities/LeanbackActivity.java b/app/src/main/java/com/hyperion/grabber/tv/activities/LeanbackActivity.java new file mode 100644 index 0000000..9bfa4ad --- /dev/null +++ b/app/src/main/java/com/hyperion/grabber/tv/activities/LeanbackActivity.java @@ -0,0 +1,10 @@ +package com.hyperion.grabber.tv.activities; + +import androidx.fragment.app.FragmentActivity; + +public abstract class LeanbackActivity extends FragmentActivity { + @Override + public boolean onSearchRequested() { + return false; + } +} diff --git a/app/src/main/java/com/hyperion/grabber/tv/activities/MainActivity.java b/app/src/main/java/com/hyperion/grabber/tv/activities/MainActivity.java new file mode 100644 index 0000000..d962a94 --- /dev/null +++ b/app/src/main/java/com/hyperion/grabber/tv/activities/MainActivity.java @@ -0,0 +1,284 @@ +package com.hyperion.grabber.tv.activities; + +import android.Manifest; +import android.animation.Animator; +import android.animation.AnimatorListenerAdapter; +import android.app.Activity; +import android.app.ActivityManager; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; +import android.content.pm.PackageManager; +import android.graphics.Color; +import android.media.projection.MediaProjectionManager; +import android.os.Build; +import android.os.Bundle; +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; +import androidx.core.app.ActivityCompat; +import androidx.core.app.ActivityOptionsCompat; +import androidx.core.content.ContextCompat; +import androidx.localbroadcastmanager.content.LocalBroadcastManager; +import androidx.appcompat.app.AppCompatDelegate; +import android.util.Log; +import android.view.View; +import android.widget.ImageButton; +import android.widget.ImageView; +import android.widget.Toast; + +import com.hyperion.grabber.common.BootActivity; +import com.hyperion.grabber.common.HyperionScreenService; +import com.hyperion.grabber.common.util.Preferences; +import com.hyperion.grabber.R; + +public class MainActivity extends LeanbackActivity implements ImageView.OnClickListener, + ImageView.OnFocusChangeListener { + public static final int REQUEST_MEDIA_PROJECTION = 1; + public static final int REQUEST_INITIAL_SETUP = 2; + private static final int REQUEST_NOTIFICATION_PERMISSION = 3; + public static final String BROADCAST_ERROR = "SERVICE_ERROR"; + public static final String BROADCAST_TAG = "SERVICE_STATUS"; + public static final String BROADCAST_FILTER = "SERVICE_FILTER"; + private static final String TAG = "DEBUG"; + private boolean mRecorderRunning = false; + private static MediaProjectionManager mMediaProjectionManager; + + private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + boolean checked = intent.getBooleanExtra(BROADCAST_TAG, false); + mRecorderRunning = checked; + String error = intent.getStringExtra(BROADCAST_ERROR); + if (error != null) { + Toast.makeText(getBaseContext(), error, Toast.LENGTH_SHORT).show(); + } + setImageViews(checked, true); + } + }; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + if (!initIfConfigured()){ + startSetup(); + } + + // Request notification permission for Android 13+ + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + requestNotificationPermission(); + } + } + + private void requestNotificationPermission() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) + != PackageManager.PERMISSION_GRANTED) { + ActivityCompat.requestPermissions(this, + new String[]{Manifest.permission.POST_NOTIFICATIONS}, + REQUEST_NOTIFICATION_PERMISSION); + } + } + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults); + if (requestCode == REQUEST_NOTIFICATION_PERMISSION) { + if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) { + Toast.makeText(this, "Notification permission is needed for the foreground service", Toast.LENGTH_LONG).show(); + } + } + } + + /** @return whether the activity was initialized */ + private boolean initIfConfigured() { + // Do we have a valid server config? + Preferences preferences = new Preferences(getApplicationContext()); + String host = preferences.getString(com.hyperion.grabber.common.R.string.pref_key_host, null); + int port = preferences.getInt(com.hyperion.grabber.common.R.string.pref_key_port, -1); + + if (host == null || port == -1){ + return false; + } + + initActivity(); + return true; + } + + private void startSetup() { + // Start onboarding (setup) + Intent intent = new Intent(this, NetworkScanActivity.class); + startActivityForResult(intent, REQUEST_INITIAL_SETUP); + } + + // Prepare activity for display + private void initActivity() { + // assume the recorder is not running until we are notified otherwise + mRecorderRunning = false; + + setContentView(R.layout.activity_main); + AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); + mMediaProjectionManager = (MediaProjectionManager) + getSystemService(Context.MEDIA_PROJECTION_SERVICE); + + ImageView iv = findViewById(R.id.power_toggle); + iv.setOnClickListener(this); + iv.setOnFocusChangeListener(this); + iv.setFocusable(true); + iv.requestFocus(); + + ImageButton ib = findViewById(R.id.settingsButton); + ib.setOnClickListener(this); + ib.setOnFocusChangeListener(this); + ib.setFocusable(true); + + setImageViews(mRecorderRunning, false); + + LocalBroadcastManager.getInstance(this).registerReceiver( + mMessageReceiver, new IntentFilter(BROADCAST_FILTER)); + + // request an update on the running status + checkForInstance(); + } + + @Override + public void onClick(View view) { + int id = view.getId(); + if (id == R.id.power_toggle) { + if (!mRecorderRunning) { + startActivityForResult(mMediaProjectionManager.createScreenCaptureIntent(), + REQUEST_MEDIA_PROJECTION); + } else { + stopScreenRecorder(); + } + mRecorderRunning = !mRecorderRunning; + } else if (id == R.id.settingsButton) { + startSettings(); + } + } + + @Override + public void onFocusChange(View view, boolean focused) { + int clr = Color.argb(255, 0, 0, 150); + if (!focused) { + clr = Color.argb(255, 0, 0, 0); + } + int id = view.getId(); + if (id == R.id.power_toggle) { + ((ImageView) view).setColorFilter(clr); + } else if (id == R.id.settingsButton) { + ((ImageButton) view).setColorFilter(clr); + } + } + + @RequiresApi(api = Build.VERSION_CODES.M) + @Override + public void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == REQUEST_INITIAL_SETUP){ + if (resultCode == RESULT_OK){ + if (!initIfConfigured()){ + startSetup(); + } + } else { + finish(); + } + + return; + } + if (requestCode == REQUEST_MEDIA_PROJECTION) { + if (resultCode != Activity.RESULT_OK) { + Toast.makeText(this, com.hyperion.grabber.common.R.string.toast_must_give_permission, Toast.LENGTH_SHORT).show(); + if (mRecorderRunning) { + stopScreenRecorder(); + } + setImageViews(false, true); + return; + } + Log.i(TAG, "Starting screen capture"); + startScreenRecorder(resultCode, (Intent) data.clone()); + mRecorderRunning = true; + } + } + + private void startSettings() { + stopScreenRecorder(); + Intent intent = new Intent(this, ManualSetupActivity.class); + Bundle bundle = + ActivityOptionsCompat.makeSceneTransitionAnimation(this) + .toBundle(); + startActivity(intent, bundle); + } + + private void checkForInstance() { + if (isServiceRunning()) { + Intent intent = new Intent(this, HyperionScreenService.class); + intent.setAction(HyperionScreenService.GET_STATUS); + startService(intent); + } + } + + private void setImageViews(boolean running, boolean animated) { + View rainbow = findViewById(R.id.sweepGradientView); + View message = findViewById(R.id.grabberStartedText); + if (running) { + if (animated){ + fadeView(rainbow, true); + fadeView(message, true); + } else { + rainbow.setVisibility(View.VISIBLE); + message.setVisibility(View.VISIBLE); + } + } else { + if (animated){ + fadeView(rainbow, false); + fadeView(message, false); + } else { + rainbow.setVisibility(View.INVISIBLE); + message.setVisibility(View.INVISIBLE); + } + } + } + + public void startScreenRecorder(int resultCode, Intent data) { + BootActivity.startScreenRecorder(this, resultCode, data); + } + + public void stopScreenRecorder() { + if (mRecorderRunning) { + Intent intent = new Intent(this, HyperionScreenService.class); + intent.setAction(HyperionScreenService.ACTION_EXIT); + startService(intent); + } + } + + private boolean isServiceRunning() { + ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); + assert manager != null; + for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { + if (HyperionScreenService.class.getName().equals(service.service.getClassName())) { + return true; + } + } + return false; + } + + private void fadeView(View view, boolean visible){ + float alpha = visible ? 1f : 0f; + int endVisibility = visible ? View.VISIBLE : View.INVISIBLE; + view.setVisibility(View.VISIBLE); + view.animate() + .alpha(alpha) + .setListener(new AnimatorListenerAdapter() { + @Override + public void onAnimationEnd(Animator animation) { + view.setVisibility(endVisibility); + } + }) + .start(); + + + } +} diff --git a/app/src/main/java/com/hyperion/grabber/tv/activities/ManualSetupActivity.java b/app/src/main/java/com/hyperion/grabber/tv/activities/ManualSetupActivity.java new file mode 100644 index 0000000..22dfc2e --- /dev/null +++ b/app/src/main/java/com/hyperion/grabber/tv/activities/ManualSetupActivity.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2014 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.hyperion.grabber.tv.activities; + +import android.os.Bundle; +import androidx.leanback.app.GuidedStepSupportFragment; +import androidx.fragment.app.FragmentActivity; + +import com.hyperion.grabber.tv.fragments.settings.BasicSettingsStepFragment; + +/** + * Allows to set all preferences manually + */ +public class ManualSetupActivity extends FragmentActivity { + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + if (null == savedInstanceState) { + GuidedStepSupportFragment.addAsRoot(this, new BasicSettingsStepFragment(), android.R.id.content); + } + } +} diff --git a/app/src/main/java/com/hyperion/grabber/tv/activities/NetworkScanActivity.java b/app/src/main/java/com/hyperion/grabber/tv/activities/NetworkScanActivity.java new file mode 100644 index 0000000..0660319 --- /dev/null +++ b/app/src/main/java/com/hyperion/grabber/tv/activities/NetworkScanActivity.java @@ -0,0 +1,105 @@ +package com.hyperion.grabber.tv.activities; + +import android.annotation.SuppressLint; +import android.content.Intent; +import android.os.Bundle; +import androidx.annotation.Nullable; +import android.view.Gravity; +import android.view.View; +import android.widget.Button; +import android.widget.ProgressBar; +import android.widget.TextView; + +import com.hyperion.grabber.common.network.NetworkScanner; +import com.hyperion.grabber.common.util.HyperionScannerTask; +import com.hyperion.grabber.R; + + +public class NetworkScanActivity extends LeanbackActivity implements HyperionScannerTask.Listener { + private boolean isScanning = false; + + private Button startScanButton; + private Button manualSetupButton; + private ProgressBar progressBar; + private TextView descriptionText; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_network_scan); + + startScanButton = findViewById(R.id.startScanButton); + manualSetupButton = findViewById(R.id.manualSetupButton); + progressBar = findViewById(R.id.progressBar); + descriptionText = findViewById(R.id.scannerDescriptionText); + + // only if back was pressed on this Activity will we not be configured when we finish + setResult(RESULT_OK); + + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == MainActivity.REQUEST_INITIAL_SETUP){ + if (resultCode == RESULT_OK){ + // when the setup completed successfully, we completed successfully. + setResult(RESULT_OK); + finish(); + } + } + } + + public void onClick(View v){ + if (v.getId() == R.id.startScanButton){ + if (!isScanning){ + new HyperionScannerTask(this).execute(); + } + + } else if (v.getId() == R.id.manualSetupButton){ + Intent intent = new Intent(this, ManualSetupActivity.class); + startActivityForResult(intent, MainActivity.REQUEST_INITIAL_SETUP); + } + + } + + @Override + public void onBackPressed() { + setResult(RESULT_CANCELED); + super.onBackPressed(); + } + + @SuppressLint("StringFormatInvalid") + @Override + public void onScannerProgress(float progress) { + if (!isScanning){ + isScanning = true; + startScanButton.setText(com.hyperion.grabber.common.R.string.scanner_scan_in_progress_button); + descriptionText.setGravity(Gravity.CENTER); + descriptionText.setText(getString(com.hyperion.grabber.common.R.string.scanner_scan_in_progress_text, "\uD83D\uDD75️")); // todo: 🕵️ + } + + progressBar.setProgress(Math.round(progress * 100)); + } + + @SuppressLint("StringFormatInvalid") + @Override + public void onScannerCompleted(@Nullable String foundIpAddress) { + isScanning = false; + + if (foundIpAddress == null){ + startScanButton.setText(com.hyperion.grabber.common.R.string.scanner_retry_button); + manualSetupButton.requestFocus(); + descriptionText.setText(getString(com.hyperion.grabber.common.R.string.scanner_no_results, "\uD83D\uDE29")); // 😩 + } else { + Intent intent = new Intent(this, ScanResultActivity.class); + intent.putExtra(ScanResultActivity.EXTRA_RESULT_HOST_NAME, foundIpAddress); + + intent.putExtra(ScanResultActivity.EXTRA_RESULT_PORT, String.valueOf(NetworkScanner.PORT)); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(intent); + finish(); // Finish the current activity + } + } + +} diff --git a/app/src/main/java/com/hyperion/grabber/tv/activities/ScanResultActivity.java b/app/src/main/java/com/hyperion/grabber/tv/activities/ScanResultActivity.java new file mode 100644 index 0000000..753c0e6 --- /dev/null +++ b/app/src/main/java/com/hyperion/grabber/tv/activities/ScanResultActivity.java @@ -0,0 +1,204 @@ +package com.hyperion.grabber.tv.activities; + +import android.animation.Animator; +import android.animation.AnimatorSet; +import android.animation.ObjectAnimator; +import android.content.Intent; +import android.graphics.Color; +import android.os.Bundle; +import android.view.View; +import android.view.animation.DecelerateInterpolator; +import android.widget.TextView; + +import com.hyperion.grabber.common.network.HyperionFlatBuffers; +import com.hyperion.grabber.common.util.Preferences; +import com.hyperion.grabber.R; + +import java.io.IOException; +import java.util.Random; + +import nl.dionsegijn.konfetti.xml.KonfettiView; +import nl.dionsegijn.konfetti.core.Party; +import nl.dionsegijn.konfetti.core.PartyFactory; +import nl.dionsegijn.konfetti.core.emitter.Emitter; +import nl.dionsegijn.konfetti.core.emitter.EmitterConfig; +import nl.dionsegijn.konfetti.core.models.Shape; +import nl.dionsegijn.konfetti.core.models.Size; + +import java.util.concurrent.TimeUnit; + +/** Shows the result of a network scan and allows to save the result to Preferences */ +public class ScanResultActivity extends LeanbackActivity { + public static final String EXTRA_RESULT_HOST_NAME = "EXTRA_RESULT_HOST_NAME"; + public static final String EXTRA_RESULT_PORT = "EXTRA_RESULT_PORT"; + + + private KonfettiView konfettiView; + private TextView descriptionText; + private TextView hostNameText; + private TextView emojiText; + private String hostName; + private int port; + + private final int ORANGE = Color.rgb(253, 104, 40); + private final int[] COLORS = {Color.RED, Color.BLUE, Color.CYAN, Color.GREEN, Color.YELLOW, ORANGE}; + /** the amount of variation in R, G, B components of a confetti burst */ + private final int BURST_COLOR_SPREAD = 200; + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_scan_result); + + konfettiView = findViewById(R.id.konfetti); + descriptionText = findViewById(R.id.scanResultDescriptionText); + hostNameText = findViewById(R.id.scanResultHostName); + emojiText = findViewById(R.id.scanResultEmojiText); + + emojiText.setText("\uD83D\uDC4F"); // 👏Clapping Hands + String partyPopper = "\uD83C\uDF89"; + descriptionText.setText(getResources().getString(com.hyperion.grabber.common.R.string.scan_result_description, partyPopper)); + Bundle extras = getIntent().getExtras(); + if (extras != null){ + hostName = extras.getString(EXTRA_RESULT_HOST_NAME); + port = Integer.parseInt(extras.getString(EXTRA_RESULT_PORT)); + hostNameText.setText(hostName); + } else { + hostNameText.setText(com.hyperion.grabber.common.R.string.error_no_host_name_extra); + } + + // Animate the appearance of the scan result + Animator fadeInAnimator = ObjectAnimator.ofFloat(hostNameText, "alpha", 0f, 1f); + Animator scaleXAnimator = ObjectAnimator + .ofFloat(hostNameText, "scaleX", .8f, 1f); + Animator scaleYAnimator = ObjectAnimator + .ofFloat(hostNameText, "scaleY", .8f, 1f); + AnimatorSet hostNameSet = new AnimatorSet(); + hostNameSet.playTogether(fadeInAnimator, scaleXAnimator, scaleYAnimator); + hostNameSet.setInterpolator(new DecelerateInterpolator()); + hostNameSet.setDuration(6000L); + hostNameSet.start(); + + konfettiView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { + @Override + public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { + startKonfetti(); + konfettiView.removeOnLayoutChangeListener(this); + } + }); + + + + } + + @Override + protected void onPause() { + super.onPause(); + setHyperionColor(hostName, port, Color.BLACK); + + } + + @Override + protected void onResume() { + super.onResume(); + setHyperionColor(hostName, port, Color.MAGENTA); + } + + public void onClick(View v){ + if (v.getId() == R.id.confirmButton){ + saveResult(); + + Intent intent = new Intent(this, MainActivity.class); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); + startActivity(intent); + finish(); // call this to finish the current activity + } else if (v.getId() == R.id.changeColorButton){ + int color = COLORS[new Random().nextInt(COLORS.length)]; + setHyperionColor(hostName, port, color); + burstKonfetti(color); + } + } + + /** Save scan result to Preferences */ + private void saveResult() { + Preferences prefs = new Preferences(getApplicationContext()); + prefs.putString(com.hyperion.grabber.common.R.string.pref_key_host, hostName); + prefs.putInt(com.hyperion.grabber.common.R.string.pref_key_port, port); + } + + private void startKonfetti() { + EmitterConfig emitterConfig = new Emitter(Long.MAX_VALUE, TimeUnit.MILLISECONDS).perSecond(300); + Party party = new PartyFactory(emitterConfig) + .colors(java.util.Arrays.asList(Color.YELLOW, Color.GREEN, Color.MAGENTA)) + .setSpeedBetween(1f, 5f) + .fadeOutEnabled(true) + .timeToLive(400L) + .shapes(java.util.Arrays.asList(Shape.Square.INSTANCE, Shape.Circle.INSTANCE)) + .sizes(java.util.Arrays.asList(new Size(12, 5f, 0f))) + .position(-50f, konfettiView.getWidth() + 50f, -50f, -50f) + .build(); + konfettiView.start(party); + } + + /** Start a one-shot burst of confetti from a random location of a single color + * + * @param color a color int such as Color.RED, NOT a color resource + */ + private void burstKonfetti(int color){ + int r = Color.red(color); + int g = Color.green(color); + int b = Color.blue(color); + + Random random = new Random(); + java.util.List variations = new java.util.ArrayList<>(); + int halfSpread = BURST_COLOR_SPREAD / 2; + for (int i = 0; i < 10; i++) { + variations.add(Color.rgb( + colorComponentClamp(r - halfSpread + random.nextInt(BURST_COLOR_SPREAD)), + colorComponentClamp(g - halfSpread + random.nextInt(BURST_COLOR_SPREAD)), + colorComponentClamp(b - halfSpread + random.nextInt(BURST_COLOR_SPREAD)) + )); + } + + float posX = (float) (Math.random() * konfettiView.getWidth()); + float posY = (float) (Math.random() * konfettiView.getHeight()); + + EmitterConfig emitterConfig = new Emitter(100, TimeUnit.MILLISECONDS).max(100); + Party party = new PartyFactory(emitterConfig) + .colors(variations) + .setSpeedBetween(1f, 5f) + .fadeOutEnabled(true) + .timeToLive(400L) + .shapes(java.util.Arrays.asList(Shape.Square.INSTANCE, Shape.Circle.INSTANCE)) + .sizes(java.util.Arrays.asList(new Size(12, 5f, 0f))) + .position(posX, posY) + .build(); + konfettiView.start(party); + } + + /** A color int , or Color.BLACK to clear */ + private void setHyperionColor(String hostName, int port, int color){ + new Thread(() -> { + try { + HyperionFlatBuffers hyperion = new HyperionFlatBuffers(hostName, port, 50); + if (hyperion.isConnected()){ + if (color == Color.BLACK){ + hyperion.clear(50); + } else { + hyperion.setColor(color, 50); + } + } + hyperion.disconnect(); + } catch (IOException e) { + e.printStackTrace(); + } + }).start(); + } + + /** [0 -255] */ + private static int colorComponentClamp(int value){ + return Math.min(255, Math.max(0, value)); + } + +} diff --git a/app/src/main/java/com/hyperion/grabber/tv/fragments/settings/BasicSettingsStepFragment.kt b/app/src/main/java/com/hyperion/grabber/tv/fragments/settings/BasicSettingsStepFragment.kt new file mode 100644 index 0000000..869ad16 --- /dev/null +++ b/app/src/main/java/com/hyperion/grabber/tv/fragments/settings/BasicSettingsStepFragment.kt @@ -0,0 +1,335 @@ +package com.hyperion.grabber.tv.fragments.settings + +import android.app.Activity +import android.content.Context +import android.graphics.Color +import android.os.Bundle +import androidx.leanback.widget.GuidanceStylist +import androidx.leanback.widget.GuidedAction +import android.widget.Toast +import com.hyperion.grabber.common.network.HyperionFlatBuffers +import com.hyperion.grabber.R +import com.hyperion.grabber.common.R as CommonR +import java.lang.ref.WeakReference +import java.net.UnknownHostException +import java.util.concurrent.Executors + +internal class BasicSettingsStepFragment : SettingsStepBaseFragment() { + + /** The amount of times the connection was tested */ + private var testCounter = 0 + + override fun onProvideTheme(): Int { + return R.style.Theme_HyperionGrabber_GuidedStep_First + } + + override fun onCreateGuidance(savedInstanceState: Bundle?): GuidanceStylist.Guidance { + val title = getString(R.string.guidedstep_basic_settings_title) + val description = getString(R.string.guidedstep_basic_settings_description) + val icon = activity?.getDrawable(R.drawable.ic_qr_android_tv_remote_short) + return GuidanceStylist.Guidance(title, description, null, icon) + } + + override fun onCreateActions(actions: MutableList, savedInstanceState: Bundle?) { + + val enterHost = GuidedAction.Builder(context) + .id(ACTION_HOST_NAME) + .title(getString(CommonR.string.pref_title_host)) + .description(prefs.getString(CommonR.string.pref_key_host, null)) + .descriptionEditable(true) + .build() + + val enterPort = unSignedNumberAction( + ACTION_PORT, + getString(CommonR.string.pref_title_port), + prefs.getInt(CommonR.string.pref_key_port).toString() + ) + + val enterHorizontalLEDCount = unSignedNumberAction( + ACTION_X_LED_COUNT, + getString(CommonR.string.pref_title_x_led), + prefs.getInt(CommonR.string.pref_key_x_led).toString() + ) + + val enterVerticalLEDCount = unSignedNumberAction( + ACTION_Y_LED_COUNT, + getString(CommonR.string.pref_title_y_led), + prefs.getInt(CommonR.string.pref_key_y_led).toString() + ) + + val startOnBootEnabled = prefs.getBoolean(CommonR.string.pref_key_boot) + + val startOnBoot = GuidedAction.Builder(context) + .id(ACTION_START_ON_BOOT) + .title(getString(CommonR.string.pref_title_boot)) + .description(CommonR.string.pref_summary_boot) + .checkSetId(GuidedAction.CHECKBOX_CHECK_SET_ID) + .checked(startOnBootEnabled) + .build() + + val advancedInfo = GuidedAction.Builder(context) + .title(R.string.guidedstep_section_advanced_title) + .description(R.string.guidedstep_section_advanced_description) + .multilineDescription(true) + .focusable(false) + .infoOnly(true) + .enabled(false) + .build() + + val priority = unSignedNumberAction( + ACTION_MESSAGE_PRIORITY, + getString(CommonR.string.pref_title_priority), + prefs.getString(CommonR.string.pref_key_priority, "100") + ) + + val reconnectEnabled = prefs.getBoolean(CommonR.string.pref_key_reconnect) + + val reconnect = GuidedAction.Builder(context) + .id(ACTION_RECONNECT) + .title(getString(CommonR.string.pref_title_reconnect)) + .checkSetId(GuidedAction.CHECKBOX_CHECK_SET_ID) + .checked(reconnectEnabled) + .build() + + val reconnectDelay = unSignedNumberAction( + ACTION_RECONNECT_DELAY, + getString(CommonR.string.pref_title_reconnect_delay), + prefs.getInt(CommonR.string.pref_key_reconnect_delay).toString() + ) + + val reconnectDescription = + if (prefs.contains(CommonR.string.pref_key_reconnect)){ + if (reconnectEnabled){ + CommonR.string.enabled + } else { + CommonR.string.disabled + } + } else { + CommonR.string.pref_summary_reconnect + } + + + val reconnectGroup = GuidedAction.Builder(context) + .id(ACTION_RECONNECT_GROUP) + .title(getString(CommonR.string.pref_title_reconnect)) + .description(reconnectDescription) + .subActions(listOf(reconnect, reconnectDelay)) + .build() + + val frameRateLabels = resources.getStringArray(CommonR.array.pref_list_framerate) + val frameRateValues = resources.getStringArray(CommonR.array.pref_list_framerate_values) + + val selectedCaptureRate = prefs.getString(CommonR.string.pref_key_framerate, "30") + + val captureRateDescription = + if (prefs.contains(CommonR.string.pref_key_framerate)){ + frameRateLabels[frameRateValues.indexOf(selectedCaptureRate)] + } else { + getString(CommonR.string.pref_summary_framerate) + } + + val captureRate = radioListAction( + ACTION_CAPTURE_RATE, + getString(CommonR.string.pref_title_framerate), + captureRateDescription, + ACTION_CAPTURE_RATE_SET_ID, + frameRateLabels, + frameRateValues, + selectedCaptureRate + ) + + val averageColor = GuidedAction.Builder(context) + .id(ACTION_AVERAGE_COLOR) + .title(getString(CommonR.string.pref_title_use_avg_color)) + .description(CommonR.string.pref_summary_use_avg_color) + .checkSetId(GuidedAction.CHECKBOX_CHECK_SET_ID) + .checked(prefs.getBoolean(CommonR.string.pref_key_use_avg_color)) + .build() + + actions.add(enterHost) + actions.add(enterPort) + actions.add(enterHorizontalLEDCount) + actions.add(enterVerticalLEDCount) + actions.add(startOnBoot) + actions.add(advancedInfo) + actions.add(priority) + actions.add(reconnectGroup) + actions.add(captureRate) + actions.add(averageColor) + + } + + override fun onCreateButtonActions(actions: MutableList, savedInstanceState: Bundle?) { + actions.add(continueAction()) + actions.add(GuidedAction.Builder(context) + .id(ACTION_TEST) + .title(getString(R.string.guidedstep_test)) + .description(R.string.guidedstep_test_description) + .build() + + ) + actions.add(backAction()) + } + + override fun onGuidedActionClicked(action: GuidedAction) { + if (action.id == SettingsStepBaseFragment.CONTINUE) { + + try { + val host = assertStringValue(ACTION_HOST_NAME) + val port = assertIntValue(ACTION_PORT) + val xLED = assertIntValue(ACTION_X_LED_COUNT) + val yLED = assertIntValue(ACTION_Y_LED_COUNT) + val startOnBootEnabled = findActionById(ACTION_START_ON_BOOT).isChecked + val priority = assertIntValue(ACTION_MESSAGE_PRIORITY) + val frameRate = assertSubActionValue(ACTION_CAPTURE_RATE, String::class.java) + val reconnect = findSubActionById(ACTION_RECONNECT)!!.isChecked + val reconnectDelay = assertIntValue(ACTION_RECONNECT_DELAY) + val useAverageColor = findActionById(ACTION_AVERAGE_COLOR)!!.isChecked + + prefs.putString(CommonR.string.pref_key_host, host) + prefs.putInt(CommonR.string.pref_key_port, port) + prefs.putInt(CommonR.string.pref_key_x_led, xLED) + prefs.putInt(CommonR.string.pref_key_y_led, yLED) + prefs.putBoolean(CommonR.string.pref_key_boot, startOnBootEnabled) + prefs.putInt(CommonR.string.pref_key_priority, priority) + prefs.putInt(CommonR.string.pref_key_reconnect_delay, reconnectDelay) + prefs.putString(CommonR.string.pref_key_framerate, frameRate) + prefs.putBoolean(CommonR.string.pref_key_reconnect, reconnect) + prefs.putBoolean(CommonR.string.pref_key_use_avg_color, useAverageColor) + + val activity = activity + activity?.setResult(Activity.RESULT_OK) + finishGuidedStepSupportFragments() + + } catch (ignored: AssertionError) { + } + + return + + } else if (action.id == ACTION_TEST){ + val colorIdx = testCounter % TEST_COLORS.size + val color = TEST_COLORS[colorIdx] + testCounter++ + + try { + val host = assertStringValue(ACTION_HOST_NAME) + val port = assertIntValue(ACTION_PORT) + val priority = assertIntValue(ACTION_MESSAGE_PRIORITY) + testHyperionColor(host, port, priority, color) + } catch (ignored: AssertionError) { + } + + return + + } + + super.onGuidedActionClicked(action) + } + + override fun onSubGuidedActionClicked(action: GuidedAction): Boolean { + when { + action.id == ACTION_RECONNECT -> { + val newDescription = if(action.isChecked){ + getString(CommonR.string.enabled) + } else getString(CommonR.string.disabled) + + findActionById(ACTION_RECONNECT_GROUP) + .description = newDescription + notifyActionIdChanged(ACTION_RECONNECT_GROUP) + + + + return !action.isChecked + } + action is ValueGuidedAction && action.parentId != null -> { + findActionById(action.parentId).description = action.title + notifyActionIdChanged(action.parentId) + } + } + + + return super.onSubGuidedActionClicked(action) + } + + /** tries to connect to Hyperion and sets the given color for 5 seconds */ + private fun testHyperionColor(hostName: String, port: Int, priority: Int, color: Int) { + TestTask(requireContext()).execute(TestSpec(hostName, port, priority, color)) + } + + companion object { + private const val ACTION_HOST_NAME = 100L + private const val ACTION_PORT = 110L + private const val ACTION_START_ON_BOOT = 120L + private const val ACTION_X_LED_COUNT = 130L + private const val ACTION_Y_LED_COUNT = 140L + private const val ACTION_RECONNECT_GROUP = 200L + private const val ACTION_RECONNECT = 210L + private const val ACTION_RECONNECT_DELAY = 220L + private const val ACTION_MESSAGE_PRIORITY = 300L + private const val ACTION_CAPTURE_RATE = 400L + private const val ACTION_CAPTURE_RATE_SET_ID = 1500 + private const val ACTION_AVERAGE_COLOR = 600L + + + private const val ACTION_TEST = 700L + + private val TEST_COLORS = intArrayOf(Color.RED, Color.GREEN, Color.BLUE, Color.WHITE) + + /** + * Tries to connect to Hyperion and set all LEDs to a single color + */ + class TestTask(context: Context) { + private val contextRef = WeakReference(context) + private val executor = Executors.newSingleThreadExecutor() + private val mainHandler = android.os.Handler(android.os.Looper.getMainLooper()) + + fun execute(spec: TestSpec) { + executor.execute { + val result = doInBackground(spec) + mainHandler.post { onPostExecute(result) } + } + } + + private fun doInBackground(spec: TestSpec): Int { + try { + val (host, port, priority, color) = spec + val hyperion = HyperionFlatBuffers(host, port, priority) + if (hyperion.isConnected) { + hyperion.setColor(color, priority, 3000) + } else { + return RESULT_UNREACHABLE + } + hyperion.disconnect() + return RESULT_OK + } catch (e: UnknownHostException) { + return RESULT_UNREACHABLE + } catch (e: Exception){ + return RESULT_UNKNOWN_ERROR + } + } + + private fun onPostExecute(result: Int) { + contextRef.get()?.run { + val messageRes = when(result){ + RESULT_OK -> R.string.guidedstep_test_success + RESULT_UNREACHABLE -> R.string.guidedstep_test_host_unreachable + else -> R.string.guidedstep_test_unknown_error + } + + Toast.makeText(this, messageRes, Toast.LENGTH_SHORT).show() + } + } + + companion object { + const val RESULT_OK = 1 + const val RESULT_UNREACHABLE = -1 + const val RESULT_UNKNOWN_ERROR = -100 + } + } + + data class TestSpec(val host: String, val port: Int, val priority: Int, val color: Int) + + } + + +} diff --git a/app/src/main/java/com/hyperion/grabber/tv/fragments/settings/SettingsStepBaseFragment.kt b/app/src/main/java/com/hyperion/grabber/tv/fragments/settings/SettingsStepBaseFragment.kt new file mode 100644 index 0000000..3c2cf01 --- /dev/null +++ b/app/src/main/java/com/hyperion/grabber/tv/fragments/settings/SettingsStepBaseFragment.kt @@ -0,0 +1,208 @@ +package com.hyperion.grabber.tv.fragments.settings + +import android.content.Context +import android.os.Bundle +import androidx.leanback.app.GuidedStepSupportFragment +import androidx.leanback.widget.GuidanceStylist +import androidx.leanback.widget.GuidedAction +import android.text.InputType +import android.widget.Toast +import com.hyperion.grabber.common.util.Preferences +import com.hyperion.grabber.R +import com.hyperion.grabber.common.R as CommonR + +/** Base class for Settings Fragments. Defines utilities for creating [GuidedAction]s and + * assertions on action values + */ +internal abstract class SettingsStepBaseFragment : GuidedStepSupportFragment() { + + lateinit var prefs: Preferences + + override fun onCreate(savedInstanceState: Bundle?) { + prefs = Preferences(requireContext()) + super.onCreate(savedInstanceState) + + } + + override fun onCreateGuidanceStylist(): GuidanceStylist { + return SettingsStepStylist() + } + + /** Default implementation handles backAction only*/ + override fun onGuidedActionClicked(action: GuidedAction) { + if (action.id == BACK) { + finishGuidedStepSupportFragments() + } + } + + protected fun continueAction(): GuidedAction { + return GuidedAction.Builder(context) + .id(CONTINUE) + .title(getString(R.string.guidedstep_save)) + .description(R.string.guidedstep_letsdoit) + .build() + } + + protected fun backAction(): GuidedAction { + return GuidedAction.Builder(context) + .id(BACK) + .title(getString(R.string.guidedstep_cancel)) + .description(R.string.guidedstep_nevermind) + .build() + } + + protected fun unSignedNumberAction(id: Long, title: String, description: CharSequence?): GuidedAction { + return GuidedAction.Builder(context) + .id(id) + .title(title) + .description(description) + .descriptionEditable(true) + .descriptionInputType(InputType.TYPE_CLASS_NUMBER) + .descriptionEditInputType(InputType.TYPE_CLASS_NUMBER) + .build() + + } + + protected fun radioListAction(id: Long, title: String, description: String?, setId: Int, optionLabels: Array, optionValues: Array, selected: Any?): GuidedAction { + val subActions = optionLabels.zip(optionValues).map { + ValueGuidedAction.Companion.Builder(requireContext()) + .parentId(id) + .checkSetId(setId) + .title(it.first) + .value(it.second) + .checked(it.second == selected) + .build() + } + + + return GuidedAction.Builder(context) + .id(id) + .title(title) + .description(description) + .subActions(subActions) + .build() + + } + + /** makes sure a value is filled for the GuidedAction and + * returns that value. If it is not filled, a toast is shown and this + * fun @throws a [AssertionError] + */ + @Throws(AssertionError::class) + protected fun assertStringValue(actionId: Long): String { + with(stringValueForAction(actionId)){ + if (isEmpty()){ + notifyRequired(actionId) + throw AssertionError("$actionId has no value") + } + return this + } + } + + /** makes sure a value is filled for the GuidedAction and + * returns that value. If it is not filled, a toast is shown and this + * fun @throws a [AssertionError] + */ + @Throws(AssertionError::class) + protected fun assertIntValue(actionId: Long): Int { + return assertStringValue(actionId).let{ + try { + Integer.parseInt(it) + } catch (ignored: Exception){ + showToast(getString(CommonR.string.pref_error_invalid_field, it, getString(CommonR.string.pref_title_reconnect_delay))) + throw AssertionError("$actionId is not a valid int") + } + } + } + + protected fun findActionByIdRecursive(actionId: Long) = + findActionById(actionId) ?: findSubActionById(actionId) + + + protected fun findSubActionById(subActionId: Long): GuidedAction? { + actions.forEach { mainAction -> + mainAction.subActions?.find { + if (it.id == subActionId) { + return it + } else false + } + } + + return null + } + + /** makes sure a value is filled for the GuidedAction and + * returns that value. If it is not filled, a toast is shown and this + * fun @throws an [AssertionError] + */ + protected fun assertSubActionValue(actionId: Long, type: Class): T { + with(findActionByIdRecursive(actionId)!!){ + val selected = subActions.find { it.isChecked } + + if (selected is ValueGuidedAction){ + return selected.value as T + } + + if (selected == null) { + notifyRequired(actionId) + throw AssertionError("$actionId has no value") + } + return selected.title.toString() as T + } + } + + protected fun notifyActionIdChanged(id: Long){ + notifyActionChanged(findActionPositionById(id)) + } + + /** Returns empty string if not set */ + private fun stringValueForAction(actionId: Long): String = + findActionByIdRecursive(actionId)?.description?.toString() ?: "" + + + protected fun showToast(message: CharSequence){ + Toast.makeText(activity, message, Toast.LENGTH_SHORT).show() + } + + private fun notifyRequired(actionId: Long){ + showToast(getString(CommonR.string.pref_error_missing_field, findActionById(actionId).title)) + } + + companion object { + const val CONTINUE = -1303L + const val BACK = -1304L + } + + class ValueGuidedAction( + val value: Any? = null, + val parentId: Long? = null + ) : GuidedAction() { + + companion object { + class Builder(context: Context) : GuidedAction.BuilderBase(context){ + var value: Any? = null + var parentId: Long? = null + + fun value(value: Any?): Builder { + this.value = value + return this + } + + fun parentId(parentId: Long?): Builder { + this.parentId = parentId + return this + } + + fun build(): ValueGuidedAction{ + val action = ValueGuidedAction(value, parentId) + applyValues(action) + + return action + } + + } + } + } + + +} diff --git a/app/src/main/java/com/hyperion/grabber/tv/fragments/settings/SettingsStepStylist.kt b/app/src/main/java/com/hyperion/grabber/tv/fragments/settings/SettingsStepStylist.kt new file mode 100644 index 0000000..c6cde8b --- /dev/null +++ b/app/src/main/java/com/hyperion/grabber/tv/fragments/settings/SettingsStepStylist.kt @@ -0,0 +1,10 @@ +package com.hyperion.grabber.tv.fragments.settings + +import androidx.leanback.widget.GuidanceStylist +import com.hyperion.grabber.R + +class SettingsStepStylist : GuidanceStylist() { + override fun onProvideLayoutId(): Int { + return R.layout.settings_guidance + } +} \ No newline at end of file diff --git a/app/src/main/java/com/hyperion/grabber/tv/views/SettingsRelativeLayout.java b/app/src/main/java/com/hyperion/grabber/tv/views/SettingsRelativeLayout.java new file mode 100644 index 0000000..267cc1e --- /dev/null +++ b/app/src/main/java/com/hyperion/grabber/tv/views/SettingsRelativeLayout.java @@ -0,0 +1,83 @@ +package com.hyperion.grabber.tv.views; + +import android.content.Context; +import android.content.res.TypedArray; +import android.graphics.drawable.Drawable; +import androidx.leanback.widget.GuidanceStylist; +import android.util.AttributeSet; +import android.view.View; +import android.widget.ImageView; +import android.widget.RelativeLayout; + +/** + * Relative layout implementation that lays out child views based on provided keyline percent( + * distance of TitleView baseline from the top). + * + * Repositioning child views in PreDraw callback in {@link GuidanceStylist} was interfering with + * fragment transition. To avoid that, we do that in the onLayout pass. + * + * Nino: Copied from Leanback code, changed to align icon bottom with description bottom + */ +class SettingsRelativeLayout extends RelativeLayout { + private float mTitleKeylinePercent; + + public SettingsRelativeLayout(Context context) { + this(context, null); + } + + public SettingsRelativeLayout(Context context, AttributeSet attrs) { + this(context, attrs, 0); + } + + public SettingsRelativeLayout(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + mTitleKeylinePercent = getKeyLinePercent(context); + } + + public static float getKeyLinePercent(Context context) { + TypedArray ta = context.getTheme().obtainStyledAttributes( + androidx.leanback.R.styleable.LeanbackGuidedStepTheme); + float percent = ta.getFloat(androidx.leanback.R.styleable.LeanbackGuidedStepTheme_guidedStepKeyline, 40); + ta.recycle(); + return percent; + } + + @Override + protected void onLayout(boolean changed, int l, int t, int r, int b) { + super.onLayout(changed, l, t, r, b); + + View mTitleView = getRootView().findViewById(androidx.leanback.R.id.guidance_title); + View mBreadcrumbView = getRootView().findViewById(androidx.leanback.R.id.guidance_breadcrumb); + View mDescriptionView = getRootView().findViewById( + androidx.leanback.R.id.guidance_description); + ImageView mIconView = getRootView().findViewById(androidx.leanback.R.id.guidance_icon); + int mTitleKeylinePixels = (int) (getMeasuredHeight() * mTitleKeylinePercent / 100); + + if (mTitleView != null && mTitleView.getParent() == this) { + int titleViewBaseline = mTitleView.getBaseline(); + int mBreadcrumbViewHeight = mBreadcrumbView == null ? 0 : mBreadcrumbView.getMeasuredHeight(); + int guidanceTextContainerTop = mTitleKeylinePixels + - titleViewBaseline - mBreadcrumbViewHeight - mTitleView.getPaddingTop(); + int offset = guidanceTextContainerTop - (mBreadcrumbView == null ? 0 : mBreadcrumbView.getTop()); + + if (mBreadcrumbView != null && mBreadcrumbView.getParent() == this) { + mBreadcrumbView.offsetTopAndBottom(offset); + } + + mTitleView.offsetTopAndBottom(offset); + + if (mDescriptionView != null && mDescriptionView.getParent() == this) { + mDescriptionView.offsetTopAndBottom(offset); + } + } + + if (mIconView != null && mIconView.getParent() == this) { + Drawable drawable = mIconView.getDrawable(); + if (drawable != null && mDescriptionView != null) { + int iconOffset = mDescriptionView.getBottom() - mIconView.getBottom(); + mIconView.offsetTopAndBottom( + iconOffset); + } + } + } +} diff --git a/app/src/main/res/drawable-v21/round_rectangle_background.xml b/app/src/main/res/drawable-v21/round_rectangle_background.xml new file mode 100644 index 0000000..bcee9c7 --- /dev/null +++ b/app/src/main/res/drawable-v21/round_rectangle_background.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable-xhdpi/ic_qr_android_tv_remote_short.png b/app/src/main/res/drawable-xhdpi/ic_qr_android_tv_remote_short.png new file mode 100644 index 0000000..f51de51 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_qr_android_tv_remote_short.png differ diff --git a/app/src/main/res/drawable/banner.png b/app/src/main/res/drawable/banner.png new file mode 100644 index 0000000..b842977 Binary files /dev/null and b/app/src/main/res/drawable/banner.png differ diff --git a/app/src/main/res/drawable/ic_network_scan.xml b/app/src/main/res/drawable/ic_network_scan.xml new file mode 100644 index 0000000..d3edacb --- /dev/null +++ b/app/src/main/res/drawable/ic_network_scan.xml @@ -0,0 +1,11 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_settings_ethernet_white_128dp.xml b/app/src/main/res/drawable/ic_settings_ethernet_white_128dp.xml new file mode 100644 index 0000000..9d8e8c6 --- /dev/null +++ b/app/src/main/res/drawable/ic_settings_ethernet_white_128dp.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..63c869d --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/activity_network_scan.xml b/app/src/main/res/layout/activity_network_scan.xml new file mode 100644 index 0000000..29f77f3 --- /dev/null +++ b/app/src/main/res/layout/activity_network_scan.xml @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + + +