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 @@
+
+
+
+
+# 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 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/activity_scan_result.xml b/app/src/main/res/layout/activity_scan_result.xml
new file mode 100644
index 0000000..c0a0ab1
--- /dev/null
+++ b/app/src/main/res/layout/activity_scan_result.xml
@@ -0,0 +1,124 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/settings_guidance.xml b/app/src/main/res/layout/settings_guidance.xml
new file mode 100644
index 0000000..563e6dc
--- /dev/null
+++ b/app/src/main/res/layout/settings_guidance.xml
@@ -0,0 +1,46 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/menu/options_menu.xml b/app/src/main/res/menu/options_menu.xml
new file mode 100644
index 0000000..ed76d33
--- /dev/null
+++ b/app/src/main/res/menu/options_menu.xml
@@ -0,0 +1,5 @@
+
+
\ No newline at end of file
diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml
new file mode 100644
index 0000000..8beebe6
--- /dev/null
+++ b/app/src/main/res/values-ar/strings.xml
@@ -0,0 +1,22 @@
+
+
+
+ تلميح
+ قم بتنزيل تطبيق Android TV Remote الرسمي على هاتفك لإدخال الأرقام والنصوص بسهولة
+ اختبار الاتصال
+ إعدادات متقدمة
+ يمكن أن تترك الإعدادات أدناه بأمان في الإعدادات الافتراضية
+ حفظ
+ اختبار
+ تألق
+ النتيجة: حسنًا. المصابيح لا تضيء؟ جرب قيمة أولوية أقل
+ النتيجة: تعذر الاتصال. يرجى التحقق من المضيف والمنفذ
+ النتيجة: خطأ غير معروف
+ استمر
+ دعونا نفعل ذلك
+ لا بأس
+ إلغاء
+ مطلوب
+
+ Hyperion Grabber (Toggle)
+
diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml
new file mode 100644
index 0000000..a77d535
--- /dev/null
+++ b/app/src/main/res/values-cs/strings.xml
@@ -0,0 +1,20 @@
+
+
+
+ Tip
+ Stáhněte si oficiální aplikaci Android TV Remote do telefonu pro snadné zadávání čísel a textu
+ Test připojení
+ Pokročilé nastavení
+ Níže uvedená nastavení mohou být bezpečně ponechána na výchozích hodnotách
+ Uložit
+ Test
+ Rozsvítit
+ Výsledek: OK. LED nesvítí? Zkuste nižší hodnotu priority
+ Výsledek: Nelze se připojit. Zkontrolujte prosím položky Host a Port
+ Výsledek: neznámá chyba
+ Pokračovat
+ Pojďme na to
+ Nevadí
+ Zrušit
+ Vyžadováno
+
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
new file mode 100644
index 0000000..9088848
--- /dev/null
+++ b/app/src/main/res/values-de/strings.xml
@@ -0,0 +1,22 @@
+
+
+
+ Tip
+ Lade dir die offizielle Android TV App auf dein Smartphone um Zahlen und Text besser eingeben zu können
+ Verbindungstest
+ Erweiterte Einstellungen
+ Die nachfolgenden Einstellungen können auf ihren Standardwerten belassen werden
+ Speichern
+ Test
+ Licht an
+ Ergebnis: OK. LEDs leuchten nicht? Versuch es mit einer niedrigeren Priorität
+ Ergebnis: Verbindungsfehler. Bitte überprüfe IP und Port Nummer
+ Ergebnis: Unbekannter Fehler
+ Weiter
+ So soll es sein
+ Vergiss es
+ Abbrechen
+ Benötigt
+
+ Hyperion Grabber (Umschalten)
+
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
new file mode 100644
index 0000000..86fcb4a
--- /dev/null
+++ b/app/src/main/res/values-es/strings.xml
@@ -0,0 +1,14 @@
+
+
+
+ Consejo
+ Prueba de conexión
+ Configuración avanzada
+ Guardar
+ Prueba
+ Resultado: No se pudo conectar. Por favor, compruebe el host y el puerto
+ Resultado: error desconocido
+ Continuar
+ No importa
+ Cancelar
+
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
new file mode 100644
index 0000000..6a153e3
--- /dev/null
+++ b/app/src/main/res/values-fr/strings.xml
@@ -0,0 +1,20 @@
+
+
+
+ Astuce
+ Téléchargez l\'application officielle \"Android TV Remote\" sur votre téléphone pour une saisie simplifié des numéros et du texte.
+ Test de connexion
+ Paramètres avancés
+ Les paramètres ci-dessous peuvent être laissés à leurs valeurs par défaut
+ Sauvegarder
+ Tester
+ Allumer
+ Résultat: OK. Les LEDs ne s\'allument pas? Essayez une valeur de priorité inférieure
+ Résultat : Impossible de se connecter. Veuillez vérifier l\'hôte et le port
+ Résultat : erreur inconnue
+ Continuer
+ Allons-y
+ Cela ne fait rien
+ Annuler
+ Obligatoire
+
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
new file mode 100644
index 0000000..ccb3632
--- /dev/null
+++ b/app/src/main/res/values-it/strings.xml
@@ -0,0 +1,20 @@
+
+
+
+ Suggerimento
+ Scarica l\'app ufficiale Android TV Remote sul telefono per inserire facilmente numeri e testo
+ Test di connessione
+ Impostazioni avanzate
+ Le impostazioni seguenti per sicurezza possono essere lasciate ai loro valori predefiniti
+ Salva
+ Test
+ Brilla
+ Risultato: OK. I LED non si accendono? Prova un valore di priorità più basso
+ Risultato: impossibile connettersi. Si prega di controllare l\'host e la porta
+ Risultato: errore sconosciuto
+ Continua
+ Facciamolo
+ Non importa
+ Annulla
+ Obbligatorio
+
diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml
new file mode 100644
index 0000000..dd87889
--- /dev/null
+++ b/app/src/main/res/values-nl/strings.xml
@@ -0,0 +1,20 @@
+
+
+
+ Tip
+ Download de officiële Android TV Remote app op uw telefoon om nummers en tekst eenvoudig in te voeren
+ Verbindingstest
+ Geavanceerde instellingen
+ De onderstaande instellingen staan voor de meeste situaties al goed
+ Opslaan
+ Test
+ Laat ze stralen
+ Resultaat: OK. Lichten de LED\'s niet op? Probeer een lagere prioriteitswaarde
+ Resultaat: Kon geen verbinding maken. Controleer de host en poort
+ Resultaat: onbekende fout
+ Doorgaan
+ Lekker bezig!
+ Laat maar
+ Annuleren
+ Vereist
+
diff --git a/app/src/main/res/values-no/strings.xml b/app/src/main/res/values-no/strings.xml
new file mode 100644
index 0000000..8ab4a0e
--- /dev/null
+++ b/app/src/main/res/values-no/strings.xml
@@ -0,0 +1,20 @@
+
+
+
+ Tips
+ Last ned den offisielle Android TV Remote appen på telefonen for enkel inntasting av tall og tekst
+ Test tilkoblingen
+ Avanserte innstillinger
+ Innstillingene nedenfor kan trygt kjøres på sine standardverdier
+ Lagre
+ Test
+ Kjør på
+ Resultat: OK. Ingen lys? Prøv en lavere prioritetsverdi
+ Resultat: Kunne ikke koble til. Vennligst sjekk vertsnavn og port
+ Resultat: ukjent feil
+ Fortsett
+ La oss gjøre det
+ Glem det
+ Avbryt
+ Påkrevd
+
diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml
new file mode 100644
index 0000000..9a78aa1
--- /dev/null
+++ b/app/src/main/res/values-ru/strings.xml
@@ -0,0 +1,12 @@
+
+
+ Проверка соединения
+ Дополнительные параметры
+ Сохранить
+ Тест
+ Да будет свет
+ Результат: неизвестная ошибка
+ Продолжать
+ Отмена
+ Требуется
+
diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml
new file mode 100644
index 0000000..e989a8a
--- /dev/null
+++ b/app/src/main/res/values/colors.xml
@@ -0,0 +1,13 @@
+
+
+ #607D8B
+ #455A64
+ #324249
+ #303030
+ #CFD8DC
+ #FF5722
+ #212121
+ #757575
+ #FFFFFF
+ #BDBDBD
+
\ No newline at end of file
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
new file mode 100755
index 0000000..4be2295
--- /dev/null
+++ b/app/src/main/res/values/strings.xml
@@ -0,0 +1,25 @@
+
+
+
+ Tip
+ Download the official Android TV Remote app on your phone for easy entry of numbers and text
+ Connection test
+ Advanced settings
+ The settings below can safely be left at their defaults
+ Save
+ Test
+ Shine on
+ Result: OK. LEDs not lighting up? Try a lower priority value
+ Result: Could not connect. Please check host and port
+ Result: unknown error
+ Continue
+ Let\'s do it
+ Never mind
+ Cancel
+ Required
+
+ Hyperion Grabber (Toggle)
+ Settings
+ Hyperion Grabber
+ Please complete the setup in the app first
+
diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml
new file mode 100644
index 0000000..b67400c
--- /dev/null
+++ b/app/src/main/res/values/styles.xml
@@ -0,0 +1,47 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/test/java/com/hyperion/grabber/ExampleUnitTest.java b/app/src/test/java/com/hyperion/grabber/ExampleUnitTest.java
new file mode 100755
index 0000000..7297288
--- /dev/null
+++ b/app/src/test/java/com/hyperion/grabber/ExampleUnitTest.java
@@ -0,0 +1,17 @@
+package com.hyperion.grabber;
+
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ * Example local unit test, which will execute on the development machine (host).
+ *
+ * @see Testing documentation
+ */
+public class ExampleUnitTest {
+ @Test
+ public void addition_isCorrect() throws Exception {
+ assertEquals(4, 2 + 2);
+ }
+}
\ No newline at end of file
diff --git a/build.gradle b/build.gradle
new file mode 100755
index 0000000..bb57199
--- /dev/null
+++ b/build.gradle
@@ -0,0 +1,27 @@
+// Top-level build file where you can add configuration options common to all sub-projects/modules.
+
+buildscript {
+ ext.kotlin_version = '1.9.22'
+
+ repositories {
+ google()
+ mavenCentral()
+ }
+ dependencies {
+ classpath 'com.android.tools.build:gradle:8.2.1'
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
+ // NOTE: Do not place your application dependencies here; they belong
+ // in the individual module build.gradle files
+ }
+}
+
+allprojects {
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+task clean(type: Delete) {
+ delete rootProject.buildDir
+}
diff --git a/common/.gitignore b/common/.gitignore
new file mode 100644
index 0000000..796b96d
--- /dev/null
+++ b/common/.gitignore
@@ -0,0 +1 @@
+/build
diff --git a/common/build.gradle b/common/build.gradle
new file mode 100644
index 0000000..3ddfc49
--- /dev/null
+++ b/common/build.gradle
@@ -0,0 +1,49 @@
+plugins {
+ id 'com.android.library'
+ id 'kotlin-android'
+}
+
+apply from: project(':common').projectDir.absolutePath + '/variables.gradle'
+
+android {
+ namespace 'com.hyperion.grabber.common'
+ compileSdk 34
+
+ defaultConfig {
+ minSdk 21
+ targetSdk 34
+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+ vectorDrawables.useSupportLibrary = true
+ multiDexEnabled true
+ }
+
+ 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')
+ implementation "androidx.core:core-ktx:1.12.0"
+ implementation "androidx.appcompat:appcompat:1.6.1"
+ implementation "androidx.constraintlayout:constraintlayout:2.1.4"
+ implementation "androidx.preference:preference-ktx:1.2.1"
+ implementation "androidx.localbroadcastmanager:localbroadcastmanager:1.1.0"
+ implementation 'com.google.flatbuffers:flatbuffers-java:23.5.26'
+ testImplementation 'junit:junit:4.13.2'
+ androidTestImplementation 'androidx.test:runner:1.5.2'
+ androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
+ implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
+}
diff --git a/common/src/main/AndroidManifest.xml b/common/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..e5e75b0
--- /dev/null
+++ b/common/src/main/AndroidManifest.xml
@@ -0,0 +1,44 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/common/src/main/flatbuffers/hyperion_reply.fbs b/common/src/main/flatbuffers/hyperion_reply.fbs
new file mode 100644
index 0000000..c80d1b6
--- /dev/null
+++ b/common/src/main/flatbuffers/hyperion_reply.fbs
@@ -0,0 +1,9 @@
+namespace hyperionnet;
+
+table Reply {
+ error:string;
+ video:int = -1;
+ registered:int = -1;
+}
+
+root_type Reply;
diff --git a/common/src/main/flatbuffers/hyperion_request.fbs b/common/src/main/flatbuffers/hyperion_request.fbs
new file mode 100644
index 0000000..06bd54a
--- /dev/null
+++ b/common/src/main/flatbuffers/hyperion_request.fbs
@@ -0,0 +1,46 @@
+namespace hyperionnet;
+
+// A priority value of -1 clears all priorities
+table Register {
+ origin:string (required);
+ priority:int;
+}
+
+table RawImage {
+ data:[ubyte];
+ width:int = -1;
+ height:int = -1;
+}
+
+table NV12Image {
+ data_y:[ubyte];
+ data_uv:[ubyte];
+ width:int;
+ height:int;
+ stride_y:int = 0;
+ stride_uv:int = 0;
+}
+
+union ImageType {RawImage, NV12Image}
+
+table Image {
+ data:ImageType (required);
+ duration:int = -1;
+}
+
+table Clear {
+ priority:int;
+}
+
+table Color {
+ data:int = -1;
+ duration:int = -1;
+}
+
+union Command {Color, Image, Clear, Register}
+
+table Request {
+ command:Command (required);
+}
+
+root_type Request;
diff --git a/common/src/main/java/com/hyperion/grabber/BootActivity.java b/common/src/main/java/com/hyperion/grabber/BootActivity.java
new file mode 100644
index 0000000..408f418
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/BootActivity.java
@@ -0,0 +1,51 @@
+package com.hyperion.grabber.common;
+
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.media.projection.MediaProjectionManager;
+import android.os.Build;
+import android.os.Bundle;
+import androidx.annotation.Nullable;
+import androidx.annotation.RequiresApi;
+import androidx.appcompat.app.AppCompatActivity;
+
+public class BootActivity extends AppCompatActivity {
+ public static final int REQUEST_MEDIA_PROJECTION = 1;
+
+ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
+ @Override
+ protected void onCreate(@Nullable Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ MediaProjectionManager manager = (MediaProjectionManager)
+ getSystemService(Context.MEDIA_PROJECTION_SERVICE);
+ if (manager != null) {
+ startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
+ } else {
+ finish();
+ }
+ }
+
+ @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) {
+ startScreenRecorder(this, resultCode, data);
+ }
+ finish();
+ }
+ }
+
+ public static void startScreenRecorder(Context context, int resultCode, Intent data) {
+ Intent intent = new Intent(context, HyperionScreenService.class);
+ intent.setAction(HyperionScreenService.ACTION_START);
+ intent.putExtra(HyperionScreenService.EXTRA_RESULT_CODE, resultCode);
+ intent.putExtras(data);
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ context.startForegroundService(intent);
+ } else {
+ context.startService(intent);
+ }
+ }
+}
diff --git a/common/src/main/java/com/hyperion/grabber/HyperionGrabberBootReceiver.java b/common/src/main/java/com/hyperion/grabber/HyperionGrabberBootReceiver.java
new file mode 100644
index 0000000..c18c17c
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/HyperionGrabberBootReceiver.java
@@ -0,0 +1,28 @@
+package com.hyperion.grabber.common;
+
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Build;
+import androidx.annotation.RequiresApi;
+
+import com.hyperion.grabber.common.util.Preferences;
+
+public class HyperionGrabberBootReceiver extends BroadcastReceiver {
+ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
+ Preferences preferences = new Preferences(context);
+ if (preferences.getBoolean(R.string.pref_key_boot)) {
+ final Intent i = new Intent(context, BootActivity.class);
+ i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION
+ |Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
+ |Intent.FLAG_ACTIVITY_NO_HISTORY
+ |Intent.FLAG_ACTIVITY_NEW_TASK);
+
+ context.startActivity(i);
+ }
+ }
+ }
+}
diff --git a/common/src/main/java/com/hyperion/grabber/HyperionNotification.java b/common/src/main/java/com/hyperion/grabber/HyperionNotification.java
new file mode 100644
index 0000000..0adbee7
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/HyperionNotification.java
@@ -0,0 +1,108 @@
+package com.hyperion.grabber.common;
+
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.drawable.Icon;
+import android.os.Build;
+import androidx.annotation.RequiresApi;
+import androidx.core.app.NotificationCompat;
+
+public class HyperionNotification {
+ private final String NOTIFICATION_CHANNEL_ID = "com.hyperion.grabber.notification";
+ private final String NOTIFICATION_CHANNEL_LABEL;
+ private final String NOTIFICATION_TITLE;
+ private final String NOTIFICATION_DESCRIPTION;
+ private final int PENDING_INTENT_REQUEST_CODE = 0;
+ private final NotificationManager mNotificationManager;
+ private final Context mContext;
+ private Notification.Action mAction = null;
+
+ HyperionNotification (Context ctx, NotificationManager manager) {
+ mNotificationManager = manager;
+ mContext = ctx;
+ NOTIFICATION_TITLE = mContext.getString(R.string.app_name);
+ NOTIFICATION_DESCRIPTION = mContext.getString(R.string.notification_description);
+ NOTIFICATION_CHANNEL_LABEL = mContext.getString(R.string.notification_channel_label);
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ mNotificationManager.createNotificationChannel(makeChannel());
+ }
+ }
+
+ private int getPendingIntentFlags() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ return PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE;
+ } else {
+ return PendingIntent.FLAG_UPDATE_CURRENT;
+ }
+ }
+
+ public void setAction(int code, String label, Intent intent) {
+ PendingIntent pendingIntent = PendingIntent.getService(mContext, code,
+ intent, getPendingIntentFlags());
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+ mAction = new Notification.Action.Builder(
+ Icon.createWithResource(mContext, R.drawable.ic_notification_icon),
+ label,
+ pendingIntent
+ ).build();
+ } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
+ mAction = new Notification.Action.Builder(
+ R.drawable.ic_notification_icon,
+ label,
+ pendingIntent
+ ).build();
+ }
+ }
+
+ public Notification buildNotification() {
+ PendingIntent pIntent = null;
+ Intent intent = mContext.getPackageManager().getLaunchIntentForPackage(mContext.getPackageName());
+ if (intent != null) {
+ intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
+ pIntent = PendingIntent.getActivity(mContext, PENDING_INTENT_REQUEST_CODE,
+ intent, getPendingIntentFlags());
+ }
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ Notification.Builder builder = new Notification.Builder(mContext, NOTIFICATION_CHANNEL_ID)
+ .setOngoing(true)
+ .setSmallIcon(R.drawable.ic_notification_icon)
+ .setContentTitle(NOTIFICATION_TITLE)
+ .setContentText(NOTIFICATION_DESCRIPTION);
+ if (mAction != null) {
+ builder.addAction(mAction);
+ }
+ if (pIntent != null) {
+ builder.setContentIntent(pIntent);
+ }
+ return builder.build();
+ } else {
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
+ .setVibrate(null)
+ .setSound(null)
+ .setOngoing(true)
+ .setPriority(NotificationCompat.PRIORITY_MAX)
+ .setSmallIcon(R.drawable.ic_notification_icon)
+ .setContentTitle(NOTIFICATION_TITLE)
+ .setContentText(NOTIFICATION_DESCRIPTION);
+ if (pIntent != null) {
+ builder.setContentIntent(pIntent);
+ }
+ return builder.build();
+ }
+ }
+
+ @RequiresApi(api = Build.VERSION_CODES.O)
+ private NotificationChannel makeChannel() {
+ NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
+ NOTIFICATION_CHANNEL_LABEL, NotificationManager.IMPORTANCE_DEFAULT);
+ notificationChannel.setDescription(NOTIFICATION_CHANNEL_LABEL);
+ notificationChannel.enableVibration(false);
+ notificationChannel.setSound(null,null);
+ return notificationChannel;
+ }
+}
diff --git a/common/src/main/java/com/hyperion/grabber/HyperionScreenEncoder.java b/common/src/main/java/com/hyperion/grabber/HyperionScreenEncoder.java
new file mode 100755
index 0000000..6dcc19b
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/HyperionScreenEncoder.java
@@ -0,0 +1,352 @@
+package com.hyperion.grabber.common;
+
+import android.annotation.TargetApi;
+import android.graphics.PixelFormat;
+import android.hardware.display.DisplayManager;
+import android.hardware.display.VirtualDisplay;
+import android.media.Image;
+import android.media.ImageReader;
+import android.media.MediaCodec;
+import android.media.projection.MediaProjection;
+import android.os.Build;
+import android.os.Handler;
+import android.os.HandlerThread;
+import androidx.annotation.RequiresApi;
+import android.util.Log;
+
+import com.hyperion.grabber.common.network.HyperionThread;
+import com.hyperion.grabber.common.util.BorderProcessor;
+import com.hyperion.grabber.common.util.HyperionGrabberOptions;
+
+import java.nio.ByteBuffer;
+
+public class HyperionScreenEncoder extends HyperionScreenEncoderBase {
+ private static final String TAG = "HyperionScreenEncoder";
+ private static final boolean DEBUG = false;
+
+ private static final int MAX_IMAGE_READER_IMAGES = 2;
+
+ private static final int MAX_CAPTURE_WIDTH = 128;
+ private static final int MAX_CAPTURE_HEIGHT = 72;
+
+ private VirtualDisplay mVirtualDisplay;
+ private ImageReader mImageReader;
+ private HandlerThread mCaptureThread;
+ private Handler mCaptureHandler;
+ private volatile boolean mRunning = false;
+
+ private int mCaptureWidth;
+ private int mCaptureHeight;
+
+ @TargetApi(Build.VERSION_CODES.LOLLIPOP)
+ HyperionScreenEncoder(final HyperionThread.HyperionThreadListener listener,
+ final MediaProjection projection, final int width, final int height,
+ final int density, HyperionGrabberOptions options) {
+ super(listener, projection, width, height, density, options);
+
+ // Calculate capture dimensions maintaining aspect ratio
+ // Use very small resolution to minimize HDR tonemapping overhead
+ float aspectRatio = (float) width / height;
+ if (aspectRatio >= 1.0f) {
+ // Landscape
+ mCaptureWidth = Math.min(MAX_CAPTURE_WIDTH, getGrabberWidth());
+ mCaptureHeight = Math.max(1, (int) (mCaptureWidth / aspectRatio));
+ } else {
+ // Portrait
+ mCaptureHeight = Math.min(MAX_CAPTURE_HEIGHT, getGrabberHeight());
+ mCaptureWidth = Math.max(1, (int) (mCaptureHeight * aspectRatio));
+ }
+
+ // Ensure dimensions are even (required by some devices)
+ mCaptureWidth = (mCaptureWidth / 2) * 2;
+ mCaptureHeight = (mCaptureHeight / 2) * 2;
+ if (mCaptureWidth < 2) mCaptureWidth = 2;
+ if (mCaptureHeight < 2) mCaptureHeight = 2;
+
+ if (DEBUG) {
+ Log.d(TAG, "Capture dimensions: " + mCaptureWidth + "x" + mCaptureHeight);
+ }
+
+ try {
+ prepare();
+ } catch (MediaCodec.CodecException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @TargetApi(Build.VERSION_CODES.M)
+ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
+ private void prepare() throws MediaCodec.CodecException {
+ if (DEBUG) Log.d(TAG, "Preparing encoder");
+
+ mCaptureThread = new HandlerThread(TAG + "-Capture", android.os.Process.THREAD_PRIORITY_BACKGROUND);
+ mCaptureThread.start();
+ mCaptureHandler = new Handler(mCaptureThread.getLooper());
+
+ int displayFlags = DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC;
+
+ mImageReader = ImageReader.newInstance(
+ mCaptureWidth,
+ mCaptureHeight,
+ PixelFormat.RGBA_8888,
+ MAX_IMAGE_READER_IMAGES
+ );
+
+ mVirtualDisplay = mMediaProjection.createVirtualDisplay(
+ TAG,
+ mCaptureWidth, mCaptureHeight, mDensity,
+ displayFlags,
+ mImageReader.getSurface(),
+ mDisplayCallback,
+ mHandler);
+
+ startCaptureLoop();
+ }
+
+ private void startCaptureLoop() {
+ mRunning = true;
+ setCapturing(true);
+
+ final long frameIntervalNs = 1_000_000_000L / mFrameRate;
+
+ mCaptureHandler.post(new Runnable() {
+ @Override
+ public void run() {
+ if (!mRunning || !isCapturing()) {
+ return;
+ }
+
+ long startTime = System.nanoTime();
+
+ Image img = null;
+ try {
+ img = mImageReader.acquireLatestImage();
+ if (img != null) {
+ sendImage(img);
+ }
+ } catch (Exception e) {
+ if (DEBUG) Log.w(TAG, "Frame capture error: " + e.getMessage());
+ } finally {
+ if (img != null) {
+ try {
+ img.close();
+ } catch (Exception ignored) {}
+ }
+ }
+
+ long elapsed = System.nanoTime() - startTime;
+ long delayMs = Math.max(1, (frameIntervalNs - elapsed) / 1_000_000L);
+
+ if (mRunning && mCaptureHandler != null) {
+ mCaptureHandler.postDelayed(this, delayMs);
+ }
+ }
+ });
+ }
+
+ @Override
+ public void stopRecording() {
+ if (DEBUG) Log.i(TAG, "stopRecording Called");
+ mRunning = false;
+ setCapturing(false);
+
+ if (mCaptureHandler != null) {
+ mCaptureHandler.removeCallbacksAndMessages(null);
+ }
+
+ if (mVirtualDisplay != null) {
+ mVirtualDisplay.release();
+ mVirtualDisplay = null;
+ }
+
+ if (mCaptureThread != null) {
+ mCaptureThread.quitSafely();
+ mCaptureThread = null;
+ mCaptureHandler = null;
+ }
+
+ mHandler.getLooper().quit();
+ clearAndDisconnect();
+
+ if (mImageReader != null) {
+ mImageReader.close();
+ mImageReader = null;
+ }
+ }
+
+ @Override
+ public void resumeRecording() {
+ if (DEBUG) Log.i(TAG, "resumeRecording Called");
+ if (!isCapturing() && mImageReader != null) {
+ startCaptureLoop();
+ }
+ }
+
+ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
+ @Override
+ public void setOrientation(int orientation) {
+ if (mVirtualDisplay != null && orientation != mCurrentOrientation) {
+ mCurrentOrientation = orientation;
+
+ int temp = mCaptureWidth;
+ mCaptureWidth = mCaptureHeight;
+ mCaptureHeight = temp;
+
+ mRunning = false;
+ setCapturing(false);
+
+ if (mCaptureHandler != null) {
+ mCaptureHandler.removeCallbacksAndMessages(null);
+ }
+
+ mVirtualDisplay.resize(mCaptureWidth, mCaptureHeight, mDensity);
+
+ if (mImageReader != null) {
+ mImageReader.close();
+ }
+
+ mImageReader = ImageReader.newInstance(
+ mCaptureWidth,
+ mCaptureHeight,
+ PixelFormat.RGBA_8888,
+ MAX_IMAGE_READER_IMAGES
+ );
+
+ mVirtualDisplay.setSurface(mImageReader.getSurface());
+ startCaptureLoop();
+ }
+ }
+
+ private VirtualDisplay.Callback mDisplayCallback = new VirtualDisplay.Callback() {
+ @Override
+ public void onPaused() {
+ if (DEBUG) Log.d(TAG, "VirtualDisplay paused");
+ mRunning = false;
+ setCapturing(false);
+ }
+
+ @RequiresApi(api = Build.VERSION_CODES.KITKAT_WATCH)
+ @Override
+ public void onResumed() {
+ if (DEBUG) Log.d(TAG, "VirtualDisplay resumed");
+ if (!mRunning) {
+ startCaptureLoop();
+ }
+ }
+
+ @Override
+ public void onStopped() {
+ if (DEBUG) Log.d(TAG, "VirtualDisplay stopped");
+ mRunning = false;
+ setCapturing(false);
+ }
+ };
+
+ private byte[] getPixels(ByteBuffer buffer, int width, int height, int rowStride,
+ int pixelStride, int firstX, int firstY) {
+ int effectiveWidth = width - firstX * 2;
+ int effectiveHeight = height - firstY * 2;
+
+ if (effectiveWidth <= 0 || effectiveHeight <= 0) {
+ effectiveWidth = width;
+ effectiveHeight = height;
+ firstX = 0;
+ firstY = 0;
+ }
+
+ byte[] pixels = new byte[effectiveWidth * effectiveHeight * 3];
+ int pixelIndex = 0;
+
+ for (int y = firstY; y < height - firstY; y++) {
+ int rowOffset = y * rowStride;
+ for (int x = firstX; x < width - firstX; x++) {
+ int offset = rowOffset + x * pixelStride;
+ pixels[pixelIndex++] = (byte) (buffer.get(offset) & 0xff); // R
+ pixels[pixelIndex++] = (byte) (buffer.get(offset + 1) & 0xff); // G
+ pixels[pixelIndex++] = (byte) (buffer.get(offset + 2) & 0xff); // B
+ }
+ }
+
+ return pixels;
+ }
+
+ private byte[] getAverageColor(ByteBuffer buffer, int width, int height, int rowStride,
+ int pixelStride, int firstX, int firstY) {
+ long totalRed = 0, totalGreen = 0, totalBlue = 0;
+ int pixelCount = 0;
+
+ int startY = Math.max(0, firstY);
+ int endY = Math.min(height, height - firstY);
+ int startX = Math.max(0, firstX);
+ int endX = Math.min(width, width - firstX);
+
+ for (int y = startY; y < endY; y++) {
+ int rowOffset = y * rowStride;
+ for (int x = startX; x < endX; x++) {
+ int offset = rowOffset + x * pixelStride;
+ totalRed += buffer.get(offset) & 0xff;
+ totalGreen += buffer.get(offset + 1) & 0xff;
+ totalBlue += buffer.get(offset + 2) & 0xff;
+ pixelCount++;
+ }
+ }
+
+ byte[] avgColor = new byte[3];
+ if (pixelCount > 0) {
+ avgColor[0] = (byte) (totalRed / pixelCount);
+ avgColor[1] = (byte) (totalGreen / pixelCount);
+ avgColor[2] = (byte) (totalBlue / pixelCount);
+ }
+
+ return avgColor;
+ }
+
+ private void sendImage(Image img) {
+ if (img == null) return;
+
+ Image.Plane[] planes = img.getPlanes();
+ if (planes == null || planes.length == 0) return;
+
+ Image.Plane plane = planes[0];
+ ByteBuffer buffer = plane.getBuffer();
+ if (buffer == null) return;
+
+ int width = img.getWidth();
+ int height = img.getHeight();
+ int pixelStride = plane.getPixelStride();
+ int rowStride = plane.getRowStride();
+ int firstX = 0;
+ int firstY = 0;
+
+ if (mRemoveBorders || mAvgColor) {
+ mBorderProcessor.parseBorder(buffer, width, height, rowStride, pixelStride);
+ BorderProcessor.BorderObject border = mBorderProcessor.getCurrentBorder();
+ if (border != null && border.isKnown()) {
+ firstX = border.getHorizontalBorderIndex();
+ firstY = border.getVerticalBorderIndex();
+ }
+ }
+
+ try {
+ if (mAvgColor) {
+ mListener.sendFrame(
+ getAverageColor(buffer, width, height, rowStride, pixelStride, firstX, firstY),
+ 1,
+ 1
+ );
+ } else {
+ int effectiveWidth = width - firstX * 2;
+ int effectiveHeight = height - firstY * 2;
+ if (effectiveWidth > 0 && effectiveHeight > 0) {
+ mListener.sendFrame(
+ getPixels(buffer, width, height, rowStride, pixelStride, firstX, firstY),
+ effectiveWidth,
+ effectiveHeight
+ );
+ }
+ }
+ } catch (Exception e) {
+ if (DEBUG) Log.w(TAG, "Error sending frame: " + e.getMessage());
+ }
+ }
+}
diff --git a/common/src/main/java/com/hyperion/grabber/HyperionScreenEncoderBase.java b/common/src/main/java/com/hyperion/grabber/HyperionScreenEncoderBase.java
new file mode 100644
index 0000000..bdefa33
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/HyperionScreenEncoderBase.java
@@ -0,0 +1,144 @@
+package com.hyperion.grabber.common;
+
+import android.content.res.Configuration;
+import android.media.projection.MediaProjection;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.Process;
+import android.util.Log;
+
+import com.hyperion.grabber.common.network.HyperionThread;
+import com.hyperion.grabber.common.util.BorderProcessor;
+import com.hyperion.grabber.common.util.HyperionGrabberOptions;
+
+public class HyperionScreenEncoderBase {
+ static final boolean DEBUG = false;
+ private static final String TAG = "ScreenEncoderBase";
+ private final int CLEAR_COMMAND_DELAY_MS = 100;
+ private final int INIT_ORIENTATION;
+
+ final boolean mRemoveBorders = false; // enables detecting borders for standard grabbing - disabled for now
+ final boolean mAvgColor;
+ final int mWidthScaled;
+ final int mFrameRate;
+ final int mHeightScaled;
+ final int mDensity;
+ boolean mIsCapturing = false;
+ int mCurrentOrientation;
+
+ BorderProcessor mBorderProcessor;
+ Handler mHandler;
+ MediaProjection mMediaProjection;
+ HyperionThread.HyperionThreadListener mListener;
+
+ HyperionScreenEncoderBase(final HyperionThread.HyperionThreadListener listener,
+ final MediaProjection projection, int width, int height,
+ final int density, HyperionGrabberOptions options) {
+ if (DEBUG) Log.d(TAG, "Encoder starting");
+
+ mListener = listener;
+ mMediaProjection = projection;
+ mDensity = density;
+ mFrameRate = options.getFrameRate();
+ mAvgColor = options.useAverageColor();
+
+ int blackThreshold = options.getBlackThreshold();
+ mBorderProcessor = new BorderProcessor(blackThreshold);
+
+ mCurrentOrientation = INIT_ORIENTATION = width > height ? Configuration.ORIENTATION_LANDSCAPE :
+ Configuration.ORIENTATION_PORTRAIT;
+
+ if (DEBUG) {
+ Log.d(TAG, "Density: " + String.valueOf(mDensity));
+ Log.d(TAG, "Frame Rate: " + String.valueOf(mFrameRate));
+ Log.d(TAG, "Original Width: " + String.valueOf(width));
+ Log.d(TAG, "Original Height: " + String.valueOf(height));
+ Log.d(TAG, "Average Color Only: " + String.valueOf(mAvgColor));
+ Log.d(TAG, "Black Pixel Threshold: " + String.valueOf(blackThreshold));
+ }
+
+ int divisor = options.findDivisor(width, height);
+
+ mHeightScaled = (height / divisor);
+ mWidthScaled = (width / divisor);
+
+ if (DEBUG) {
+ Log.d(TAG, "Common Divisor: " + String.valueOf(divisor));
+ Log.d(TAG, "Scaled Width: " + String.valueOf(mWidthScaled));
+ Log.d(TAG, "Scaled Height: " + String.valueOf(mHeightScaled));
+ }
+
+ final HandlerThread thread = new HandlerThread(TAG, Process.THREAD_PRIORITY_DISPLAY);
+ thread.start();
+ mHandler = new Handler(thread.getLooper());
+
+ if (DEBUG) Log.d(TAG, "Encoder ready");
+ }
+
+ private Runnable clearAndDisconnectRunner = new Runnable() {
+ public void run() {
+ if (DEBUG) Log.d(TAG, "Clearing LEDs and disconnecting");
+ try {
+ Thread.sleep(CLEAR_COMMAND_DELAY_MS);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ mListener.clear();
+ mListener.disconnect();
+ }
+ };
+
+ private Runnable clearLightsRunner = new Runnable() {
+ public void run() {
+ if (DEBUG) Log.d(TAG, "Clearing LEDs");
+ try {
+ Thread.sleep(CLEAR_COMMAND_DELAY_MS);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ mListener.clear();
+ }
+ };
+
+ public void clearLights() {
+ new Thread(clearLightsRunner).start();
+ }
+
+ void clearAndDisconnect() {
+ new Thread(clearAndDisconnectRunner).start();
+ }
+
+ public boolean isCapturing() {
+ return mIsCapturing;
+ }
+
+ public void setCapturing(boolean isCapturing) {
+ mIsCapturing = isCapturing;
+ }
+
+ public void sendStatus() {
+ if (mListener != null) {
+ mListener.sendStatus(isCapturing());
+ }
+ }
+
+ public void stopRecording() {
+ throw new RuntimeException("Stub!");
+ }
+
+ public void resumeRecording() {
+ throw new RuntimeException("Stub!");
+ }
+
+ int getGrabberWidth() {
+ return INIT_ORIENTATION != mCurrentOrientation ? mHeightScaled : mWidthScaled;
+ }
+
+ int getGrabberHeight() {
+ return INIT_ORIENTATION != mCurrentOrientation ? mWidthScaled : mHeightScaled;
+ }
+
+ public void setOrientation(int orientation) {
+ mCurrentOrientation = orientation;
+ }
+}
\ No newline at end of file
diff --git a/common/src/main/java/com/hyperion/grabber/HyperionScreenService.java b/common/src/main/java/com/hyperion/grabber/HyperionScreenService.java
new file mode 100644
index 0000000..ed50f1f
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/HyperionScreenService.java
@@ -0,0 +1,340 @@
+package com.hyperion.grabber.common;
+
+import android.annotation.TargetApi;
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.Service;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.ServiceInfo;
+import android.media.projection.MediaProjection;
+import android.media.projection.MediaProjectionManager;
+import android.os.Build;
+import android.os.IBinder;
+import androidx.annotation.Nullable;
+import androidx.annotation.RequiresApi;
+import androidx.core.app.ServiceCompat;
+import androidx.localbroadcastmanager.content.LocalBroadcastManager;
+import android.util.DisplayMetrics;
+import android.util.Log;
+import android.view.WindowManager;
+
+import com.hyperion.grabber.common.network.HyperionThread;
+import com.hyperion.grabber.common.util.HyperionGrabberOptions;
+import com.hyperion.grabber.common.util.Preferences;
+
+import java.util.Objects;
+
+public class HyperionScreenService extends Service {
+ 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 boolean DEBUG = false;
+ private static final String TAG = "HyperionScreenService";
+
+ private static final String BASE = "com.hyperion.grabber.service.";
+ public static final String ACTION_START = BASE + "ACTION_START";
+ public static final String ACTION_STOP = BASE + "ACTION_STOP";
+ public static final String ACTION_EXIT = BASE + "ACTION_EXIT";
+ public static final String GET_STATUS = BASE + "ACTION_STATUS";
+ public static final String EXTRA_RESULT_CODE = BASE + "EXTRA_RESULT_CODE";
+ private static final int NOTIFICATION_ID = 1;
+ private static final int NOTIFICATION_EXIT_INTENT_ID = 2;
+
+ private boolean RECONNECT = false;
+ private boolean hasConnected = false;
+ private MediaProjectionManager mMediaProjectionManager;
+ private HyperionThread mHyperionThread;
+ private static MediaProjection _mediaProjection;
+ private int mFrameRate;
+ private int mHorizontalLEDCount;
+ private int mVerticalLEDCount;
+ private boolean mSendAverageColor;
+ private HyperionScreenEncoder mHyperionEncoder;
+ private NotificationManager mNotificationManager;
+ private String mStartError = null;
+
+ HyperionThreadBroadcaster mReceiver = new HyperionThreadBroadcaster() {
+ @Override
+ public void onConnected() {
+ Log.d(TAG, "CONNECTED TO HYPERION INSTANCE");
+ hasConnected = true;
+ notifyActivity();
+ }
+
+ @Override
+ public void onConnectionError(int errorID, String error) {
+ Log.e(TAG, "COULD NOT CONNECT TO HYPERION INSTANCE");
+ if (error != null) Log.e(TAG, error);
+ if (!hasConnected) {
+ mStartError = getResources().getString(R.string.error_server_unreachable);
+ haltStartup();
+ }
+ if (RECONNECT && hasConnected) {
+ Log.e(TAG, "AUTOMATIC RECONNECT ENABLED. CONNECTING ...");
+ } else if (!RECONNECT && hasConnected) {
+ mStartError = getResources().getString(R.string.error_connection_lost);
+ stopSelf();
+ }
+ }
+
+ @Override
+ public void onReceiveStatus(boolean isCapturing) {
+ if (DEBUG) Log.v(TAG, "Received grabber status, notifying activity. Status: " +
+ String.valueOf(isCapturing));
+ notifyActivity();
+ }
+ };
+
+ BroadcastReceiver mEventReceiver = new BroadcastReceiver() {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ switch (Objects.requireNonNull(intent.getAction())) {
+ case Intent.ACTION_SCREEN_ON:
+ if (DEBUG) Log.v(TAG, "ACTION_SCREEN_ON intent received");
+ if (mHyperionEncoder != null && !isCapturing()) {
+ if (DEBUG) Log.v(TAG, "Encoder not grabbing, attempting to restart");
+ mHyperionEncoder.resumeRecording();
+ }
+ notifyActivity();
+ break;
+ case Intent.ACTION_SCREEN_OFF:
+ if (DEBUG) Log.v(TAG, "ACTION_SCREEN_OFF intent received");
+ if (mHyperionEncoder != null) {
+ if (DEBUG) Log.v(TAG, "Clearing current light data");
+ mHyperionEncoder.clearLights();
+ }
+ break;
+ case Intent.ACTION_CONFIGURATION_CHANGED:
+ if (DEBUG) Log.v(TAG, "ACTION_CONFIGURATION_CHANGED intent received");
+ if (mHyperionEncoder != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+ if (DEBUG) Log.v(TAG, "Configuration changed, checking orientation");
+ mHyperionEncoder.setOrientation(getResources().getConfiguration().orientation);
+ }
+ break;
+ case Intent.ACTION_SHUTDOWN:
+ case Intent.ACTION_REBOOT:
+ if (DEBUG) Log.v(TAG, "ACTION_SHUTDOWN|ACTION_REBOOT intent received");
+ stopScreenRecord();
+ break;
+ }
+ }
+ };
+
+ @Override
+ public void onCreate() {
+ mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
+ super.onCreate();
+ }
+
+ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
+ private boolean prepared() {
+ Preferences prefs = new Preferences(getBaseContext());
+ String host = prefs.getString(R.string.pref_key_host, null);
+ int port = prefs.getInt(R.string.pref_key_port, -1);
+ String priority = prefs.getString(R.string.pref_key_priority, "100");
+ mFrameRate = prefs.getInt(R.string.pref_key_framerate);
+ mHorizontalLEDCount = prefs.getInt(R.string.pref_key_x_led);
+ mVerticalLEDCount = prefs.getInt(R.string.pref_key_y_led);
+ mSendAverageColor = prefs.getBoolean(R.string.pref_key_use_avg_color);
+ RECONNECT = prefs.getBoolean(R.string.pref_key_reconnect);
+ int delay = prefs.getInt(R.string.pref_key_reconnect_delay);
+
+ if (host == null || Objects.equals(host, "0.0.0.0") || Objects.equals(host, "")) {
+ mStartError = getResources().getString(R.string.error_empty_host);
+ return false;
+ }
+ if (port == -1) {
+ mStartError = getResources().getString(R.string.error_empty_port);
+ return false;
+ }
+ if (mHorizontalLEDCount <= 0 || mVerticalLEDCount <= 0) {
+ mStartError = getResources().getString(R.string.error_invalid_led_counts);
+ return false;
+ }
+ mMediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
+ mHyperionThread = new HyperionThread(mReceiver, host, port, Integer.parseInt(priority), RECONNECT, delay);
+ mHyperionThread.start();
+ mStartError = null;
+ return true;
+ }
+
+ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
+ @Override
+ public int onStartCommand(Intent intent, int flags, int startId) {
+ if (DEBUG) Log.v(TAG, "Start command received");
+ super.onStartCommand(intent, flags, startId);
+ if (intent == null || intent.getAction() == null) {
+ String nullItem = (intent == null ? "intent" : "action");
+ if (DEBUG) Log.v(TAG, "Null " + nullItem + " provided to start command");
+ } else {
+ final String action = intent.getAction();
+ if (DEBUG) Log.v(TAG, "Start command action: " + String.valueOf(action));
+ switch (action) {
+ case ACTION_START:
+ if (mHyperionThread == null) {
+ boolean isPrepared = prepared();
+ if (isPrepared) {
+ // For Android 12+, we must start foreground with mediaProjection type BEFORE getting MediaProjection
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ ServiceCompat.startForeground(this, NOTIFICATION_ID, getNotification(),
+ ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
+ } else {
+ startForeground(NOTIFICATION_ID, getNotification());
+ }
+
+ startScreenRecord(intent);
+
+ IntentFilter intentFilter = new IntentFilter();
+ intentFilter.addAction(Intent.ACTION_SCREEN_ON);
+ intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
+ intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
+ intentFilter.addAction(Intent.ACTION_REBOOT);
+ intentFilter.addAction(Intent.ACTION_SHUTDOWN);
+
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
+ registerReceiver(mEventReceiver, intentFilter, Context.RECEIVER_NOT_EXPORTED);
+ } else {
+ registerReceiver(mEventReceiver, intentFilter);
+ }
+ } else {
+ haltStartup();
+ }
+ }
+ break;
+ case ACTION_STOP:
+ stopScreenRecord();
+ break;
+ case GET_STATUS:
+ notifyActivity();
+ break;
+ case ACTION_EXIT:
+ stopSelf();
+ break;
+ }
+ }
+ return START_STICKY;
+ }
+
+ @Nullable
+ @Override
+ public IBinder onBind(Intent intent) {
+ return null;
+ }
+
+ @Override
+ public void onDestroy() {
+ if (DEBUG) Log.v(TAG, "Ending service");
+
+ try {
+ unregisterReceiver(mEventReceiver);
+ } catch (Exception e) {
+ if (DEBUG) Log.v(TAG, "Wake receiver not registered");
+ }
+
+ stopScreenRecord();
+ stopForeground(true);
+ notifyActivity();
+
+ super.onDestroy();
+ }
+
+ private void haltStartup() {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
+ ServiceCompat.startForeground(this, NOTIFICATION_ID, getNotification(),
+ ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
+ } else {
+ startForeground(NOTIFICATION_ID, getNotification());
+ }
+ stopSelf();
+ }
+
+ private Intent buildExitButton() {
+ Intent notificationIntent = new Intent(this, this.getClass());
+ notificationIntent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
+ notificationIntent.setAction(ACTION_EXIT);
+ return notificationIntent;
+ }
+
+ public Notification getNotification() {
+ HyperionNotification notification = new HyperionNotification(this, mNotificationManager);
+ String label = getString(R.string.notification_exit_button);
+ notification.setAction(NOTIFICATION_EXIT_INTENT_ID, label, buildExitButton());
+ return notification.buildNotification();
+ }
+
+ @TargetApi(Build.VERSION_CODES.LOLLIPOP)
+ private void startScreenRecord(final Intent intent) {
+ if (DEBUG) Log.v(TAG, "Start screen recorder");
+ final int resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, 0);
+ // get MediaProjection
+ final MediaProjection projection = mMediaProjectionManager.getMediaProjection(resultCode, intent);
+ WindowManager window = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
+ if (projection != null && window != null) {
+ _mediaProjection = projection;
+ final DisplayMetrics metrics = new DisplayMetrics();
+ window.getDefaultDisplay().getRealMetrics(metrics);
+ final int density = metrics.densityDpi;
+ HyperionGrabberOptions options = new HyperionGrabberOptions(mHorizontalLEDCount,
+ mVerticalLEDCount, mFrameRate, mSendAverageColor);
+ if (DEBUG) Log.v(TAG, "Starting the recorder");
+ mHyperionEncoder = new HyperionScreenEncoder(mHyperionThread.getReceiver(),
+ projection, metrics.widthPixels, metrics.heightPixels,
+ density, options);
+ mHyperionEncoder.sendStatus();
+ }
+ }
+
+ private void stopScreenRecord() {
+ if (DEBUG) Log.v(TAG, "Stop screen recorder");
+ RECONNECT = false;
+ mNotificationManager.cancel(NOTIFICATION_ID);
+ if (mHyperionEncoder != null) {
+ if (DEBUG) Log.v(TAG, "Stopping the current encoder");
+ mHyperionEncoder.stopRecording();
+ }
+ releaseResource();
+ if (mHyperionThread != null) {
+ mHyperionThread.interrupt();
+ }
+ }
+
+ @TargetApi(Build.VERSION_CODES.LOLLIPOP)
+ public void releaseResource() {
+ if (_mediaProjection != null) {
+ _mediaProjection.stop();
+ _mediaProjection = null;
+ }
+ }
+
+ boolean isCapturing() {
+ return mHyperionEncoder != null && mHyperionEncoder.isCapturing();
+ }
+
+ boolean isCommunicating() {
+ return isCapturing() && hasConnected;
+ }
+
+ private void notifyActivity() {
+ Intent intent = new Intent(BROADCAST_FILTER);
+ intent.putExtra(BROADCAST_TAG, isCommunicating());
+ intent.putExtra(BROADCAST_ERROR, mStartError);
+ if (DEBUG) {
+ Log.v(TAG, "Sending status broadcast - communicating: " +
+ String.valueOf(isCommunicating()));
+ if (mStartError != null) {
+ Log.v(TAG, "Startup error: " + mStartError);
+ }
+ }
+ LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
+ }
+
+ public interface HyperionThreadBroadcaster {
+// void onResponse(String response);
+ void onConnected();
+ void onConnectionError(int errorHash, String errorString);
+ void onReceiveStatus(boolean isCapturing);
+ }
+}
diff --git a/common/src/main/java/com/hyperion/grabber/ToggleActivity.java b/common/src/main/java/com/hyperion/grabber/ToggleActivity.java
new file mode 100644
index 0000000..0b86898
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/ToggleActivity.java
@@ -0,0 +1,97 @@
+package com.hyperion.grabber.common;
+
+import android.app.Activity;
+import android.app.ActivityManager;
+import android.content.Context;
+import android.content.Intent;
+import android.media.projection.MediaProjectionManager;
+import android.os.Build;
+import android.os.Bundle;
+import androidx.annotation.Nullable;
+import androidx.annotation.RequiresApi;
+import androidx.appcompat.app.AppCompatActivity;
+
+public class ToggleActivity extends AppCompatActivity {
+ public static final int REQUEST_MEDIA_PROJECTION = 1;
+
+ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
+ @Override
+ protected void onCreate(@Nullable Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ boolean serviceRunning = checkForInstance();
+
+ if (serviceRunning) {
+ stopService();
+ finish();
+ } else {
+ requestPermission();
+ }
+
+ }
+
+ @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) {
+ startScreenRecorder(this, resultCode, data);
+ }
+
+ finish();
+
+ }
+ }
+
+ private static void startScreenRecorder(Context context, int resultCode, Intent data) {
+ Intent intent = new Intent(context, HyperionScreenService.class);
+ intent.setAction(HyperionScreenService.ACTION_START);
+ intent.putExtra(HyperionScreenService.EXTRA_RESULT_CODE, resultCode);
+ intent.putExtras(data);
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ context.startForegroundService(intent);
+ } else {
+ context.startService(intent);
+ }
+ }
+
+ /** @return whether the service is running */
+ private boolean checkForInstance() {
+ if (isServiceRunning()) {
+ Intent intent = new Intent(this, HyperionScreenService.class);
+ intent.setAction(HyperionScreenService.GET_STATUS);
+ startService(intent);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ 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;
+ }
+
+ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
+ private void requestPermission(){
+ MediaProjectionManager manager = (MediaProjectionManager)
+ getSystemService(Context.MEDIA_PROJECTION_SERVICE);
+ if (manager != null) {
+ startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION);
+ }
+ }
+
+ /** stop recording & stop service */
+
+ private void stopService() {
+ Intent stopIntent = new Intent(ToggleActivity.this, HyperionScreenService.class);
+ stopIntent.setAction(HyperionScreenService.ACTION_EXIT);
+ startService(stopIntent);
+ }
+}
diff --git a/common/src/main/java/com/hyperion/grabber/network/HyperionClient.java b/common/src/main/java/com/hyperion/grabber/network/HyperionClient.java
new file mode 100644
index 0000000..363ee59
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/network/HyperionClient.java
@@ -0,0 +1,14 @@
+package com.hyperion.grabber.common.network;
+
+import java.io.IOException;
+
+public interface HyperionClient {
+ boolean isConnected();
+ void disconnect() throws IOException;
+ void clear(int priority) throws IOException;
+ void clearAll() throws IOException;
+ void setColor(int color, int priority) throws IOException;
+ void setColor(int color, int priority, int duration_ms) throws IOException;
+ void setImage(byte[] data, int width, int height, int priority) throws IOException;
+ void setImage(byte[] data, int width, int height, int priority, int duration_ms) throws IOException;
+}
diff --git a/common/src/main/java/com/hyperion/grabber/network/HyperionFlatBuffers.java b/common/src/main/java/com/hyperion/grabber/network/HyperionFlatBuffers.java
new file mode 100644
index 0000000..65b1c4f
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/network/HyperionFlatBuffers.java
@@ -0,0 +1,137 @@
+package com.hyperion.grabber.common.network;
+
+import com.google.flatbuffers.FlatBufferBuilder;
+import hyperionnet.Clear;
+import hyperionnet.Color;
+import hyperionnet.Command;
+import hyperionnet.Image;
+import hyperionnet.ImageType;
+import hyperionnet.RawImage;
+import hyperionnet.Register;
+import hyperionnet.Reply;
+import hyperionnet.Request;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.nio.ByteBuffer;
+
+public class HyperionFlatBuffers implements HyperionClient {
+ private final int TIMEOUT = 1000;
+ private final Socket mSocket;
+ private final int mPriority;
+ private final FlatBufferBuilder mBuilder;
+
+ public HyperionFlatBuffers(String address, int port, int priority) throws IOException {
+ mSocket = new Socket();
+ mSocket.connect(new InetSocketAddress(address, port), TIMEOUT);
+ mPriority = priority;
+ mBuilder = new FlatBufferBuilder(1024);
+ register();
+ }
+
+ private void register() throws IOException {
+ mBuilder.clear();
+ int originOffset = mBuilder.createString("HyperionAndroidGrabber");
+ int registerOffset = Register.createRegister(mBuilder, originOffset, mPriority);
+ int requestOffset = Request.createRequest(mBuilder, Command.Register, registerOffset);
+ Request.finishRequestBuffer(mBuilder, requestOffset);
+ sendRequest(mBuilder.dataBuffer());
+ }
+
+ @Override
+ public boolean isConnected() {
+ return mSocket != null && mSocket.isConnected();
+ }
+
+ @Override
+ public void disconnect() throws IOException {
+ if (isConnected()) {
+ mSocket.close();
+ }
+ }
+
+ @Override
+ public void clear(int priority) throws IOException {
+ mBuilder.clear();
+ int clearOffset = Clear.createClear(mBuilder, priority);
+ int requestOffset = Request.createRequest(mBuilder, Command.Clear, clearOffset);
+ Request.finishRequestBuffer(mBuilder, requestOffset);
+ sendRequest(mBuilder.dataBuffer());
+ }
+
+ @Override
+ public void clearAll() throws IOException {
+ clear(-1);
+ }
+
+ @Override
+ public void setColor(int color, int priority) throws IOException {
+ setColor(color, priority, -1);
+ }
+
+ @Override
+ public void setColor(int color, int priority, int duration_ms) throws IOException {
+ mBuilder.clear();
+ int colorOffset = Color.createColor(mBuilder, color, duration_ms);
+ int requestOffset = Request.createRequest(mBuilder, Command.Color, colorOffset);
+ Request.finishRequestBuffer(mBuilder, requestOffset);
+ sendRequest(mBuilder.dataBuffer());
+ }
+
+ @Override
+ public void setImage(byte[] data, int width, int height, int priority) throws IOException {
+ setImage(data, width, height, priority, -1);
+ }
+
+ @Override
+ public void setImage(byte[] data, int width, int height, int priority, int duration_ms) throws IOException {
+ mBuilder.clear();
+ int dataOffset = RawImage.createDataVector(mBuilder, data);
+ int rawImageOffset = RawImage.createRawImage(mBuilder, dataOffset, width, height);
+ int imageOffset = Image.createImage(mBuilder, ImageType.RawImage, rawImageOffset, duration_ms);
+ int requestOffset = Request.createRequest(mBuilder, Command.Image, imageOffset);
+ Request.finishRequestBuffer(mBuilder, requestOffset);
+ sendRequest(mBuilder.dataBuffer());
+ }
+
+ private void sendRequest(ByteBuffer bb) throws IOException {
+ if (isConnected()) {
+ int size = bb.remaining();
+ byte[] header = new byte[4];
+ header[0] = (byte)((size >> 24) & 0xFF);
+ header[1] = (byte)((size >> 16) & 0xFF);
+ header[2] = (byte)((size >> 8) & 0xFF);
+ header[3] = (byte)((size ) & 0xFF);
+
+ OutputStream output = mSocket.getOutputStream();
+ output.write(header);
+
+ byte[] data = new byte[bb.remaining()];
+ bb.get(data);
+ output.write(data);
+ output.flush();
+
+ receiveReply();
+ }
+ }
+
+ private void receiveReply() throws IOException {
+ // We don't really need to parse the reply for now, but we should consume it
+ // to keep the socket clean.
+ if (mSocket.getInputStream().available() >= 4) {
+ byte[] header = new byte[4];
+ int read = mSocket.getInputStream().read(header, 0, 4);
+ if (read == 4) {
+ int size = ((header[0] & 0xFF) << 24) | ((header[1] & 0xFF) << 16) | ((header[2] & 0xFF) << 8) | (header[3] & 0xFF);
+ if (size > 0) {
+ byte[] data = new byte[size];
+ mSocket.getInputStream().read(data, 0, size);
+ // Reply reply = Reply.getRootAsReply(ByteBuffer.wrap(data));
+ }
+ }
+ }
+ }
+}
diff --git a/common/src/main/java/com/hyperion/grabber/network/HyperionThread.java b/common/src/main/java/com/hyperion/grabber/network/HyperionThread.java
new file mode 100644
index 0000000..22ff48f
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/network/HyperionThread.java
@@ -0,0 +1,124 @@
+package com.hyperion.grabber.common.network;
+
+import com.hyperion.grabber.common.HyperionScreenService;
+
+import java.io.IOException;
+
+public class HyperionThread extends Thread {
+
+ private String HOST;
+ private int PORT;
+ private int PRIORITY;
+ private final int FRAME_DURATION = -1;
+ private boolean RECONNECT = false;
+ private boolean HAS_CONNECTED = false;
+ private int RECONNECT_DELAY;
+ private HyperionClient mHyperion;
+
+ HyperionScreenService.HyperionThreadBroadcaster mSender;
+ HyperionThreadListener mReceiver = new HyperionThreadListener() {
+ @Override
+ public void sendFrame(byte[] data, int width, int height) {
+ if (mHyperion != null && mHyperion.isConnected()) {
+ try {
+ mHyperion.setImage(data, width, height, PRIORITY, FRAME_DURATION);
+ } catch (IOException e) {
+ mSender.onConnectionError(e.hashCode(), e.getMessage());
+ e.printStackTrace();
+ if (RECONNECT && HAS_CONNECTED) {
+ reconnectDelay(RECONNECT_DELAY);
+ try {
+ mHyperion = createClient();
+ } catch (IOException i) {
+ i.printStackTrace();
+ }
+ }
+ }
+ }
+ }
+
+ @Override
+ public void clear() {
+ if (mHyperion != null && mHyperion.isConnected()) {
+ try {
+ mHyperion.clear(PRIORITY);
+ } catch (IOException e) {
+ mSender.onConnectionError(e.hashCode(), e.getMessage());
+ e.printStackTrace();
+ }
+ }
+ }
+
+ @Override
+ public void disconnect() {
+ if (mHyperion != null) {
+ try {
+ mHyperion.disconnect();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ @Override
+ public void sendStatus(boolean isGrabbing) {
+ if (mSender != null) {
+ mSender.onReceiveStatus(isGrabbing);
+ }
+ }
+ };
+
+ public HyperionThread(HyperionScreenService.HyperionThreadBroadcaster listener, final String host,
+ final int port, final int priority, final boolean reconnect, final int delay){
+ HOST = host;
+ PORT = port;
+ PRIORITY = priority;
+ RECONNECT = reconnect;
+ RECONNECT_DELAY = delay * 1000;
+ mSender = listener;
+ }
+
+ public HyperionThreadListener getReceiver() {return mReceiver;}
+
+ private HyperionClient createClient() throws IOException {
+ return new HyperionFlatBuffers(HOST, PORT, PRIORITY);
+ }
+
+ @Override
+ public void run(){
+ do {
+ try {
+ mHyperion = createClient();
+ } catch (IOException e) {
+ mSender.onConnectionError(e.hashCode(), e.getMessage());
+ e.printStackTrace();
+ if (RECONNECT && HAS_CONNECTED) {
+ reconnectDelay(RECONNECT_DELAY);
+ }
+ } finally {
+ if (mHyperion != null && mSender != null && mHyperion.isConnected()) {
+ HAS_CONNECTED = true;
+ mSender.onConnected();
+ break;
+ }
+ }
+ } while (RECONNECT && HAS_CONNECTED);
+ }
+
+ public void reconnectDelay(long t) {
+ try {
+ Thread.sleep(t);
+ } catch (InterruptedException e) {
+ RECONNECT = false;
+ HAS_CONNECTED = false;
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ public interface HyperionThreadListener {
+ void sendFrame(byte[] data, int width, int height);
+ void clear();
+ void disconnect();
+ void sendStatus(boolean isGrabbing);
+ }
+}
diff --git a/common/src/main/java/com/hyperion/grabber/network/NetworkScanner.java b/common/src/main/java/com/hyperion/grabber/network/NetworkScanner.java
new file mode 100644
index 0000000..e0e07f7
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/network/NetworkScanner.java
@@ -0,0 +1,171 @@
+package com.hyperion.grabber.common.network;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.annotation.WorkerThread;
+import android.util.Log;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.NetworkInterface;
+import java.net.Socket;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+/** Scans the local network for running Hyperion servers
+ * Created by nino on 27-5-18.
+ */
+
+public class NetworkScanner {
+ public static final int PORT = 19400;
+ /** The amount of milliseconds we try to connect to a given ip before giving up */
+ private static final int ATTEMPT_TIMEOUT_MS = 50;
+
+ private final String[] ipsToTry;
+ private int lastTriedIndex = -1;
+
+
+ public NetworkScanner() {
+
+ ipsToTry = getIPsToTry();
+ }
+
+
+ /** Scan the next ip address in the list of addresses to try
+ *
+ * @return the hostname (or an ip represented as String) when a Hyperion server was found
+ */
+ @Nullable
+ @WorkerThread
+ public String tryNext(){
+
+ if (!hasNextAttempt()){
+ throw new IllegalStateException("No more ip addresses to try");
+ }
+
+ Socket socket = new Socket();
+ String ip = ipsToTry[++lastTriedIndex];
+ try {
+ socket.connect(new InetSocketAddress(ip, PORT), ATTEMPT_TIMEOUT_MS);
+
+ if (socket.isConnected()){
+ socket.close();
+ return ip;
+ }
+
+ } catch(Exception e) {
+ return null;
+ }
+
+
+ return null;
+
+ }
+
+ /** An indication of how many of the total ip's have been tried
+ *
+ * @return progress in in the range [0.0 .. 1.0]
+ */
+ public float getProgress() {
+ if (ipsToTry.length == 0){
+ return 1f;
+ }
+
+ return lastTriedIndex / (float)ipsToTry.length;
+ }
+
+ /** True if not all ip's have been tried yet
+ *
+ */
+ public boolean hasNextAttempt(){
+ return ipsToTry.length > 0 && lastTriedIndex + 1 < ipsToTry.length;
+ }
+
+ /**
+ * Get IP addresses for non-localhost interfaces
+ * @param useIPv4 true=return ipv4, false=return ipv6
+ * @return a list of found addresses (may be empty)
+ *
+ * https://stackoverflow.com/a/13007325
+ */
+ @NonNull
+ private static List getIPAddresses(boolean useIPv4) {
+ List foundAddresses = new ArrayList<>();
+ try {
+ List interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
+ for (NetworkInterface intf : interfaces) {
+ List addrs = Collections.list(intf.getInetAddresses());
+ for (InetAddress addr : addrs) {
+ if (!addr.isLoopbackAddress()) {
+ String sAddr = addr.getHostAddress();
+ //boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
+ boolean isIPv4 = sAddr.indexOf(':')<0;
+
+ if (useIPv4) {
+ if (isIPv4)
+ foundAddresses.add(sAddr);
+ } else {
+ if (!isIPv4) {
+ int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
+ String v6Addr = delim < 0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
+ foundAddresses.add(v6Addr);
+ }
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ // for now eat exceptions
+ Log.e("HYPERION SCANNER", "Could not get ip address", e);
+ }
+ return foundAddresses;
+ }
+
+ private String[] getIPsToTry(){
+ try {
+ List localIpV4Addresses = getIPAddresses(true);
+ String[] allIpsToTry = new String[localIpV4Addresses.size() * 254];
+
+ for (int localIpIdx = 0; localIpIdx < localIpV4Addresses.size(); localIpIdx++) {
+ String localIpV4Address = localIpV4Addresses.get(localIpIdx);
+ String[] ipsToTry = new String[254];
+
+ String[] ipParts = localIpV4Address.split("\\.");
+
+ String ipPrefix = ipParts[0] + "." + ipParts[1] + "." + ipParts[2] + ".";
+ for (int i = 1; i< 255 ; i++){
+ ipsToTry[i-1] = ipPrefix + i;
+ }
+
+ int localNumberInSubnet = Integer.parseInt(ipParts[3]);
+
+ // sort in such a way that ips close to the local ip will be tried first
+ Arrays.sort(ipsToTry, (lhs, rhs) -> {
+ int lhsNumberInSubnet = Integer.parseInt(lhs.split("\\.")[3]);
+ int rhsNumberInSubnet = Integer.parseInt(rhs.split("\\.")[3]);
+ int lhsDistance = Math.abs(lhsNumberInSubnet - localNumberInSubnet);
+ int rhsDistance = Math.abs(rhsNumberInSubnet - localNumberInSubnet);
+ return lhsDistance - rhsDistance;
+ });
+
+ for (int i = 0; i < ipsToTry.length; i++) {
+ // interleave with previously found ip addresses
+ int allIndex = (localIpV4Addresses.size() * i) + localIpIdx;
+ allIpsToTry[allIndex] = ipsToTry[i];
+ }
+
+
+ }
+
+
+ return allIpsToTry;
+ } catch (Exception e){
+ // for now eat exceptions
+ Log.e("HYPERION SCANNER", "Error while building list of subnet ip's", e);
+ return new String[]{};
+ }
+ }
+}
diff --git a/common/src/main/java/com/hyperion/grabber/util/BorderProcessor.java b/common/src/main/java/com/hyperion/grabber/util/BorderProcessor.java
new file mode 100644
index 0000000..d5fc255
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/util/BorderProcessor.java
@@ -0,0 +1,186 @@
+package com.hyperion.grabber.common.util;
+
+import java.nio.ByteBuffer;
+import java.util.Objects;
+
+public class BorderProcessor {
+
+ private final int MAX_INCONSISTENT_FRAME_COUNT = 10;
+ private final int MAX_UNKNOWN_FRAME_COUNT = 600;
+ private final int BORDER_CHANGE_FRAME_COUNT = 50;
+
+ private final int BLACK_THRESHOLD; // unit to detect how black a pixel is [0..255]
+ private BorderObject mPreviousBorder;
+ private BorderObject mCurrentBorder;
+ private int mConsistentFrames = 0;
+ private int mInconsistentFrames = 0;
+
+ public BorderProcessor(int blackThreshold) {
+ BLACK_THRESHOLD = blackThreshold;
+ }
+
+ public BorderObject getCurrentBorder() { return mCurrentBorder; }
+
+ private void checkNewBorder(BorderObject newBorder) {
+ if (mPreviousBorder != null && mPreviousBorder.equals(newBorder)) {
+ ++mConsistentFrames;
+ mInconsistentFrames = 0;
+ } else {
+ ++mInconsistentFrames;
+
+ if (mInconsistentFrames <= MAX_INCONSISTENT_FRAME_COUNT) {
+ return;
+ }
+
+ mPreviousBorder = newBorder;
+ mConsistentFrames = 0;
+ }
+
+ if (mCurrentBorder != null && mCurrentBorder.equals(newBorder)) {
+ mInconsistentFrames = 0;
+ return;
+ }
+
+ if (!newBorder.isKnown()) {
+ if (mConsistentFrames == MAX_UNKNOWN_FRAME_COUNT) {
+ mCurrentBorder = newBorder;
+ }
+ } else {
+ if (mCurrentBorder == null || !mCurrentBorder.isKnown() ||
+ mConsistentFrames == BORDER_CHANGE_FRAME_COUNT) {
+ mCurrentBorder = newBorder;
+ }
+ }
+ }
+
+ public void parseBorder(ByteBuffer buffer, int width, int height, int rowStride,
+ int pixelStride) {
+ checkNewBorder( findBorder(buffer, width, height, rowStride, pixelStride) );
+ }
+
+ private BorderObject findBorder(ByteBuffer buffer, int width, int height, int rowStride,
+ int pixelStride) {
+
+ int width33percent = width / 3;
+ int width66percent = width33percent * 2;
+ int height33percent = height / 3;
+ int height66percent = height33percent * 2;
+ int yCenter = height / 2;
+ int xCenter = width / 2;
+ int firstNonBlackYPixelIndex = -1;
+ int firstNonBlackXPixelIndex = -1;
+
+ // placeholders for the RGB values of each of the 3 pixel positions we check
+ int p1R, p1G, p1B, p2R, p2G, p2B, p3R, p3G, p3B;
+
+ // positions in the byte array that represent 33%, 66%, and center.
+ // used when parsing both the X and Y axis of the image
+ int pos33percent, pos66percent, posCentered;
+
+ buffer.position(0).mark();
+
+ // iterate through the X axis until we either hit 33% of the image width or a non-black pixel
+ for (int x = 0; x < width33percent; x++) {
+
+ // RGB values at 33% height - to left of image
+ pos33percent = (height33percent * rowStride) + (x * pixelStride);
+ p1R = buffer.get(pos33percent) & 0xff;
+ p1G = buffer.get(pos33percent + 1) & 0xff;
+ p1B = buffer.get(pos33percent + 2) & 0xff;
+
+ // RGB values at 66% height - to left of image
+ pos66percent = (height66percent * rowStride) + (x * pixelStride);
+ p2R = buffer.get(pos66percent) & 0xff;
+ p2G = buffer.get(pos66percent + 1) & 0xff;
+ p2B = buffer.get(pos66percent + 2) & 0xff;
+
+ // RGB values at center Y - to right of image
+ posCentered = (yCenter * rowStride) + ((width - x - 1) * pixelStride);
+ p3R = buffer.get(posCentered) & 0xff;
+ p3G = buffer.get(posCentered + 1) & 0xff;
+ p3B = buffer.get(posCentered + 2) & 0xff;
+
+ // check if any of our RGB values DO NOT evaluate as black
+ if (!isBlack(p1R,p1G,p1B) || !isBlack(p2R,p2G,p2B) || !isBlack(p3R,p3G,p3B)) {
+ firstNonBlackXPixelIndex = x;
+ break;
+ }
+ }
+
+ buffer.reset();
+
+ // iterate through the Y axis until we either hit 33% of the image height or a non-black pixel
+ for (int y = 0; y < height33percent; y++) {
+
+ // RGB values at 33% width - top of image
+ pos33percent = (width33percent * pixelStride) + (y * rowStride);
+ p1R = buffer.get(pos33percent) & 0xff;
+ p1G = buffer.get(pos33percent + 1) & 0xff;
+ p1B = buffer.get(pos33percent + 2) & 0xff;
+
+ // RGB values at 66% width - top of image
+ pos66percent = (width66percent * pixelStride) + (y * rowStride);
+ p2R = buffer.get(pos66percent) & 0xff;
+ p2G = buffer.get(pos66percent + 1) & 0xff;
+ p2B = buffer.get(pos66percent + 2) & 0xff;
+
+ // RGB values at center X - bottom of image
+ posCentered = (xCenter * pixelStride) + ((height - y - 1) * rowStride);
+ p3R = buffer.get(posCentered) & 0xff;
+ p3G = buffer.get(posCentered + 1) & 0xff;
+ p3B = buffer.get(posCentered + 2) & 0xff;
+
+ // check if any of our RGB values DO NOT evaluate as black
+ if (!isBlack(p1R,p1G,p1B) || !isBlack(p2R,p2G,p2B) || !isBlack(p3R,p3G,p3B)) {
+ firstNonBlackYPixelIndex = y;
+ break;
+ }
+ }
+
+ return new BorderObject(firstNonBlackXPixelIndex, firstNonBlackYPixelIndex);
+ }
+
+ private boolean isBlack(int red, int green, int blue) {
+ return red < BLACK_THRESHOLD && green < BLACK_THRESHOLD && blue < BLACK_THRESHOLD;
+ }
+
+ public static class BorderObject {
+ private boolean isKnown;
+ private int horizontalBorderIndex;
+ private int verticalBorderIndex;
+
+ BorderObject(int horizontalBorderIndex, int verticalBorderIndex) {
+ this.horizontalBorderIndex = horizontalBorderIndex;
+ this.verticalBorderIndex = verticalBorderIndex;
+ this.isKnown = this.horizontalBorderIndex != -1 && this.verticalBorderIndex != -1;
+ }
+
+ public boolean isKnown() { return isKnown; }
+ public int getHorizontalBorderIndex() { return horizontalBorderIndex; }
+ public int getVerticalBorderIndex() { return verticalBorderIndex; }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ BorderObject that = (BorderObject) o;
+ return isKnown == that.isKnown &&
+ horizontalBorderIndex == that.horizontalBorderIndex &&
+ verticalBorderIndex == that.verticalBorderIndex;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(isKnown, horizontalBorderIndex, verticalBorderIndex);
+ }
+
+ @Override
+ public String toString() {
+ return "BorderObject{" +
+ "isKnown=" + isKnown +
+ ", horizontalBorderIndex=" + horizontalBorderIndex +
+ ", verticalBorderIndex=" + verticalBorderIndex +
+ '}';
+ }
+ }
+}
diff --git a/common/src/main/java/com/hyperion/grabber/util/HyperionGrabberOptions.java b/common/src/main/java/com/hyperion/grabber/util/HyperionGrabberOptions.java
new file mode 100644
index 0000000..f618183
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/util/HyperionGrabberOptions.java
@@ -0,0 +1,84 @@
+package com.hyperion.grabber.common.util;
+
+import android.util.Log;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.ListIterator;
+
+public class HyperionGrabberOptions {
+ private static final boolean DEBUG = false;
+ private static final String TAG = "HyperionGrabberOptions";
+
+ private final int MINIMUM_IMAGE_PACKET_SIZE; // how many bytes the minimal acceptable image quality is
+ private final int FRAME_RATE;
+ private final boolean USE_AVERAGE_COLOR;
+ private final int BLACK_THRESHOLD = 5; // The limit each RGB value must be under to be considered a black pixel [0-255]
+
+ public HyperionGrabberOptions(int horizontalLED, int verticalLED, int frameRate, boolean useAvgColor) {
+
+ /*
+ * To determine the minimal acceptable image packet size we take the count of the width & height
+ * of the LED pixels (that the user is driving via their hyperion server) and multiply them
+ * together and then by 3 (1 for each color in RGB). This will give us the count of the bytes
+ * that the minimal acceptable quality should be equal to or greater than.
+ **/
+ MINIMUM_IMAGE_PACKET_SIZE = horizontalLED * verticalLED * 3;
+ FRAME_RATE = frameRate;
+ USE_AVERAGE_COLOR = useAvgColor;
+
+ if (DEBUG) {
+ Log.d(TAG, "Horizontal LED Count: " + String.valueOf(horizontalLED));
+ Log.d(TAG, "Vertical LED Count: " + String.valueOf(verticalLED));
+ Log.d(TAG, "Minimum Image Packet: " + String.valueOf(MINIMUM_IMAGE_PACKET_SIZE));
+ }
+ }
+
+ public int getFrameRate() { return FRAME_RATE; }
+
+ public boolean useAverageColor() { return USE_AVERAGE_COLOR; }
+
+ /**
+ * returns the divisor best suited to be used to meet the minimum image packet size
+ * Since we only want to scale using whole numbers, we need to find what common divisors
+ * are available for the given width & height. We will check those divisors to find the smallest
+ * number (that we can divide our screen dimensions by) that would meet the minimum image
+ * packet size required to match the count of the LEDs on the destination hyperion server.
+ * @param width The original width of the device screen
+ * @param height The original height of the device screen
+ * @return int The divisor bes suited to scale the screen dimensions by
+ **/
+ public int findDivisor(int width, int height) {
+ List divisors = getCommonDivisors(width, height);
+ if (DEBUG) Log.d(TAG, "Available Divisors: " + divisors.toString());
+ ListIterator it = divisors.listIterator(divisors.size());
+
+ // iterate backwards since the divisors are listed largest to smallest
+ while (it.hasPrevious()) {
+ int i = (int) it.previous();
+
+ // check if the image packet size for this divisor is >= the minimum image packet size
+ // like above we multiply the dimensions together and then by 3 for each byte in RGB
+ if ((width / i) * (height / i) * 3 >= MINIMUM_IMAGE_PACKET_SIZE)
+ return i;
+ }
+ return 1;
+ }
+
+ /**
+ * gets a list of all the common divisors [large to small] for the given integers.
+ * @param num1 The first integer to find a whole number divisor for
+ * @param num2 The second integer to find a whole number divisor for
+ * @return List A list of the common divisors [large to small] that match the provided integers
+ **/
+ private static List getCommonDivisors(int num1, int num2) {
+ List list = new ArrayList<>();
+ int min = Math.min(num1, num2);
+ for (int i = 1; i <= min / 2; i++)
+ if (num1 % i == 0 && num2 % i == 0)
+ list.add(i);
+ if (num1 % min == 0 && num2 % min == 0) list.add(min);
+ return list;
+ }
+
+ public int getBlackThreshold() { return BLACK_THRESHOLD; }
+}
diff --git a/common/src/main/java/com/hyperion/grabber/util/HyperionScannerTask.java b/common/src/main/java/com/hyperion/grabber/util/HyperionScannerTask.java
new file mode 100644
index 0000000..5cbe0d1
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/util/HyperionScannerTask.java
@@ -0,0 +1,74 @@
+package com.hyperion.grabber.common.util;
+
+import android.os.Handler;
+import android.os.Looper;
+import androidx.annotation.Nullable;
+import android.util.Log;
+
+import com.hyperion.grabber.common.network.NetworkScanner;
+
+import java.lang.ref.WeakReference;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+
+/**
+ * Starts a network scan for a running Hyperion server
+ * and posts progress and results
+ */
+public class HyperionScannerTask {
+ private WeakReference weakListener;
+ private ExecutorService executor = Executors.newSingleThreadExecutor();
+ private Handler mainHandler = new Handler(Looper.getMainLooper());
+
+ public HyperionScannerTask(Listener listener){
+ weakListener = new WeakReference<>(listener);
+ }
+
+ public void execute() {
+ executor.execute(() -> {
+ String result = doInBackground();
+ mainHandler.post(() -> onPostExecute(result));
+ });
+ }
+
+ private String doInBackground() {
+ Log.d("Hyperion scanner", "starting scan");
+ NetworkScanner networkScanner = new NetworkScanner();
+
+ String result;
+ while (networkScanner.hasNextAttempt()){
+ result = networkScanner.tryNext();
+
+ if (result != null){
+ return result;
+ }
+
+ final float progress = networkScanner.getProgress();
+ mainHandler.post(() -> onProgressUpdate(progress));
+ }
+
+ return null;
+ }
+
+ private void onProgressUpdate(Float value) {
+ Log.d("Hyperion scanner", "scan progress: " + value);
+ if(weakListener.get() != null){
+ weakListener.get().onScannerProgress(value);
+ }
+ }
+
+ private void onPostExecute(String result) {
+ Log.d("Hyperion scanner", "scan result: " + result);
+ if(weakListener.get() != null){
+ weakListener.get().onScannerCompleted(result);
+ }
+ }
+
+ public interface Listener {
+
+ void onScannerProgress(float progress);
+ void onScannerCompleted(@Nullable String foundIpAddress);
+
+ }
+}
\ No newline at end of file
diff --git a/common/src/main/java/com/hyperion/grabber/util/Preferences.kt b/common/src/main/java/com/hyperion/grabber/util/Preferences.kt
new file mode 100644
index 0000000..b4f26e0
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/util/Preferences.kt
@@ -0,0 +1,85 @@
+package com.hyperion.grabber.common.util
+
+import android.content.Context
+import android.content.res.Resources
+import androidx.preference.PreferenceManager
+import androidx.annotation.StringRes
+
+/** Wrapper around SharedPreferences which allows for default values defined in Resources
+ * Main purpose is that defaults are defined in a centralized location and that preferences are
+ * accessed through a unified interface */
+class Preferences(context: Context) {
+
+ private val preferences = PreferenceManager.getDefaultSharedPreferences(context)
+ private val resources = context.resources
+
+ fun contains(@StringRes keyResourceId: Int): Boolean = preferences.contains(key(keyResourceId))
+
+ fun getString(@StringRes keyResourceId: Int, default: String? = null): String? {
+ return preferences.getString(key(keyResourceId), default)
+ }
+
+ fun putString(@StringRes keyResourceId: Int, value: String){
+ val edit = preferences.edit()
+ edit.putString(key(keyResourceId), value)
+ edit.apply()
+ }
+
+ fun getInt(@StringRes keyResourceId: Int): Int {
+ val default = defaultKey(keyResourceId, "integer").let {
+ if (it == 0){
+ 0
+ } else {
+ try {
+ resources.getInteger(it)
+ } catch (e: Resources.NotFoundException) {
+ 0
+ }
+ }
+ }
+
+ return getInt(keyResourceId, default)
+ }
+
+ fun getInt(@StringRes keyResourceId: Int, default: Int = 0): Int {
+ return getString(keyResourceId)?.let { Integer.parseInt(it) } ?: default
+ }
+
+ fun putInt(@StringRes keyResourceId: Int, value: Int){
+ putString(keyResourceId, value.toString())
+ }
+
+ fun getBoolean(@StringRes keyResourceId: Int): Boolean {
+ val default = defaultKey(keyResourceId, "bool").let {
+ if (it == 0){
+ false
+ } else {
+ try {
+ resources.getBoolean(it)
+ } catch (e: Resources.NotFoundException) {
+ false
+ }
+ }
+ }
+
+ return preferences.getBoolean(key(keyResourceId), default)
+ }
+
+ fun getBoolean(@StringRes keyResourceId: Int, default: Boolean): Boolean =
+ preferences.getBoolean(key(keyResourceId), default)
+
+ fun putBoolean(@StringRes keyResourceId: Int, value: Boolean){
+ val edit = preferences.edit()
+ edit.putBoolean(key(keyResourceId), value)
+ edit.apply()
+ }
+
+ private fun key(keyResourceId: Int) = resources.getString(keyResourceId)
+
+ /** @return 0 if not found, resource id otherwise */
+ private fun defaultKey(keyResourceId: Int, type: String): Int {
+ val defaultKeyName = resources.getResourceEntryName(keyResourceId).replace("pref_key_", "pref_default_")
+ return resources.getIdentifier(defaultKeyName, type, resources.getResourcePackageName(keyResourceId))
+ }
+
+}
\ No newline at end of file
diff --git a/common/src/main/java/com/hyperion/grabber/views/SweepGradientView.java b/common/src/main/java/com/hyperion/grabber/views/SweepGradientView.java
new file mode 100644
index 0000000..2c345cc
--- /dev/null
+++ b/common/src/main/java/com/hyperion/grabber/views/SweepGradientView.java
@@ -0,0 +1,69 @@
+package com.hyperion.grabber.common.views;
+
+import android.content.Context;
+import android.graphics.Canvas;
+import android.graphics.Color;
+import android.graphics.Matrix;
+import android.graphics.Paint;
+import android.graphics.Rect;
+import android.graphics.SweepGradient;
+import androidx.annotation.Nullable;
+import android.util.AttributeSet;
+import android.view.View;
+
+/**
+ * Created by nino on 26-5-18.
+ */
+
+public class SweepGradientView extends View{
+
+ Paint paint;
+ final int[] colors = {Color.RED, Color.MAGENTA, Color.BLUE, Color.CYAN, Color.GREEN, Color.YELLOW, Color.RED};
+ final float[] positions = {0f, 1/6f, 2/6f, 3/6f, 4/6f, 5/6f, 6/6f};
+
+ SweepGradient gradient;
+
+ Rect viewBounds = new Rect();
+
+ Matrix gradientMatrix = new Matrix();
+
+ float rotate = 0f;
+
+ public SweepGradientView(Context context) {
+ this(context, null);
+ }
+
+ public SweepGradientView(Context context, @Nullable AttributeSet attrs) {
+ this(context, attrs, 0);
+ }
+
+ public SweepGradientView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
+ super(context, attrs, defStyleAttr);
+
+ paint = new Paint();
+ paint.setShader(gradient);
+ }
+
+
+
+ @Override
+ protected void onDraw(Canvas canvas) {
+
+ gradientMatrix.postRotate(rotate++, viewBounds.width()/2, viewBounds.height()/2);
+ gradient.setLocalMatrix(gradientMatrix);
+
+ paint.setShader(gradient);
+ canvas.drawRect(viewBounds, paint);
+ gradientMatrix.reset();
+ invalidate();
+
+ }
+
+ @Override
+ protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
+ super.onMeasure(widthMeasureSpec, heightMeasureSpec);
+ viewBounds.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
+
+ gradient = new SweepGradient(viewBounds.centerX(), viewBounds.centerY(), colors, positions);
+ }
+}
diff --git a/common/src/main/java/hyperionnet/Clear.java b/common/src/main/java/hyperionnet/Clear.java
new file mode 100644
index 0000000..61a70cf
--- /dev/null
+++ b/common/src/main/java/hyperionnet/Clear.java
@@ -0,0 +1,28 @@
+package hyperionnet;
+
+import com.google.flatbuffers.Constants;
+import com.google.flatbuffers.FlatBufferBuilder;
+import com.google.flatbuffers.Table;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+@SuppressWarnings("unused")
+public final class Clear extends Table {
+ public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
+ public static Clear getRootAsClear(ByteBuffer _bb) { return getRootAsClear(_bb, new Clear()); }
+ public static Clear getRootAsClear(ByteBuffer _bb, Clear obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
+ public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
+ public Clear __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
+
+ public int priority() { int o = __offset(4); return o != 0 ? bb.getInt(o + bb_pos) : 0; }
+
+ public static int createClear(FlatBufferBuilder builder, int priority) {
+ builder.startTable(1);
+ Clear.addPriority(builder, priority);
+ return Clear.endClear(builder);
+ }
+
+ public static void startClear(FlatBufferBuilder builder) { builder.startTable(1); }
+ public static void addPriority(FlatBufferBuilder builder, int priority) { builder.addInt(0, priority, 0); }
+ public static int endClear(FlatBufferBuilder builder) { return builder.endTable(); }
+}
diff --git a/common/src/main/java/hyperionnet/Color.java b/common/src/main/java/hyperionnet/Color.java
new file mode 100644
index 0000000..af96a78
--- /dev/null
+++ b/common/src/main/java/hyperionnet/Color.java
@@ -0,0 +1,31 @@
+package hyperionnet;
+
+import com.google.flatbuffers.Constants;
+import com.google.flatbuffers.FlatBufferBuilder;
+import com.google.flatbuffers.Table;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+@SuppressWarnings("unused")
+public final class Color extends Table {
+ public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
+ public static Color getRootAsColor(ByteBuffer _bb) { return getRootAsColor(_bb, new Color()); }
+ public static Color getRootAsColor(ByteBuffer _bb, Color obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
+ public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
+ public Color __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
+
+ public int data() { int o = __offset(4); return o != 0 ? bb.getInt(o + bb_pos) : -1; }
+ public int duration() { int o = __offset(6); return o != 0 ? bb.getInt(o + bb_pos) : -1; }
+
+ public static int createColor(FlatBufferBuilder builder, int data, int duration) {
+ builder.startTable(2);
+ Color.addDuration(builder, duration);
+ Color.addData(builder, data);
+ return Color.endColor(builder);
+ }
+
+ public static void startColor(FlatBufferBuilder builder) { builder.startTable(2); }
+ public static void addData(FlatBufferBuilder builder, int data) { builder.addInt(0, data, -1); }
+ public static void addDuration(FlatBufferBuilder builder, int duration) { builder.addInt(1, duration, -1); }
+ public static int endColor(FlatBufferBuilder builder) { return builder.endTable(); }
+}
diff --git a/common/src/main/java/hyperionnet/Command.java b/common/src/main/java/hyperionnet/Command.java
new file mode 100644
index 0000000..db38863
--- /dev/null
+++ b/common/src/main/java/hyperionnet/Command.java
@@ -0,0 +1,14 @@
+package hyperionnet;
+
+@SuppressWarnings("unused")
+public final class Command {
+ private Command() { }
+ public static final byte NONE = 0;
+ public static final byte Color = 1;
+ public static final byte Image = 2;
+ public static final byte Clear = 3;
+ public static final byte Register = 4;
+
+ public static final String[] names = { "NONE", "Color", "Image", "Clear", "Register", };
+ public static String name(int e) { return names[e]; }
+}
diff --git a/common/src/main/java/hyperionnet/Image.java b/common/src/main/java/hyperionnet/Image.java
new file mode 100644
index 0000000..f95e3d8
--- /dev/null
+++ b/common/src/main/java/hyperionnet/Image.java
@@ -0,0 +1,38 @@
+package hyperionnet;
+
+import com.google.flatbuffers.Constants;
+import com.google.flatbuffers.FlatBufferBuilder;
+import com.google.flatbuffers.Table;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+@SuppressWarnings("unused")
+public final class Image extends Table {
+ public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
+ public static Image getRootAsImage(ByteBuffer _bb) { return getRootAsImage(_bb, new Image()); }
+ public static Image getRootAsImage(ByteBuffer _bb, Image obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
+ public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
+ public Image __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
+
+ public byte dataType() { int o = __offset(4); return o != 0 ? bb.get(o + bb_pos) : 0; }
+ public Table data(Table obj) { int o = __offset(6); return o != 0 ? __union(obj, o + bb_pos) : null; }
+ public int duration() { int o = __offset(8); return o != 0 ? bb.getInt(o + bb_pos) : -1; }
+
+ public static int createImage(FlatBufferBuilder builder, byte data_type, int dataOffset, int duration) {
+ builder.startTable(3);
+ Image.addDuration(builder, duration);
+ Image.addData(builder, dataOffset);
+ Image.addDataType(builder, data_type);
+ return Image.endImage(builder);
+ }
+
+ public static void startImage(FlatBufferBuilder builder) { builder.startTable(3); }
+ public static void addDataType(FlatBufferBuilder builder, byte dataType) { builder.addByte(0, dataType, 0); }
+ public static void addData(FlatBufferBuilder builder, int dataOffset) { builder.addOffset(1, dataOffset, 0); }
+ public static void addDuration(FlatBufferBuilder builder, int duration) { builder.addInt(2, duration, -1); }
+ public static int endImage(FlatBufferBuilder builder) {
+ int o = builder.endTable();
+ builder.required(o, 6); // data
+ return o;
+ }
+}
diff --git a/common/src/main/java/hyperionnet/ImageType.java b/common/src/main/java/hyperionnet/ImageType.java
new file mode 100644
index 0000000..08aa1b1
--- /dev/null
+++ b/common/src/main/java/hyperionnet/ImageType.java
@@ -0,0 +1,12 @@
+package hyperionnet;
+
+@SuppressWarnings("unused")
+public final class ImageType {
+ private ImageType() { }
+ public static final byte NONE = 0;
+ public static final byte RawImage = 1;
+ public static final byte NV12Image = 2;
+
+ public static final String[] names = { "NONE", "RawImage", "NV12Image", };
+ public static String name(int e) { return names[e]; }
+}
diff --git a/common/src/main/java/hyperionnet/RawImage.java b/common/src/main/java/hyperionnet/RawImage.java
new file mode 100644
index 0000000..29a6bad
--- /dev/null
+++ b/common/src/main/java/hyperionnet/RawImage.java
@@ -0,0 +1,38 @@
+package hyperionnet;
+
+import com.google.flatbuffers.BaseVector;
+import com.google.flatbuffers.Constants;
+import com.google.flatbuffers.FlatBufferBuilder;
+import com.google.flatbuffers.Table;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+@SuppressWarnings("unused")
+public final class RawImage extends Table {
+ public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
+ public static RawImage getRootAsRawImage(ByteBuffer _bb) { return getRootAsRawImage(_bb, new RawImage()); }
+ public static RawImage getRootAsRawImage(ByteBuffer _bb, RawImage obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
+ public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
+ public RawImage __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
+
+ public int data(int j) { int o = __offset(4); return o != 0 ? bb.get(__vector(o) + j * 1) & 0xFF : 0; }
+ public int dataLength() { int o = __offset(4); return o != 0 ? __vector_len(o) : 0; }
+ public ByteBuffer dataAsByteBuffer() { return __vector_as_bytebuffer(4, 1); }
+ public int width() { int o = __offset(6); return o != 0 ? bb.getInt(o + bb_pos) : -1; }
+ public int height() { int o = __offset(8); return o != 0 ? bb.getInt(o + bb_pos) : -1; }
+
+ public static int createRawImage(FlatBufferBuilder builder, int dataOffset, int width, int height) {
+ builder.startTable(3);
+ RawImage.addHeight(builder, height);
+ RawImage.addWidth(builder, width);
+ RawImage.addData(builder, dataOffset);
+ return RawImage.endRawImage(builder);
+ }
+
+ public static void startRawImage(FlatBufferBuilder builder) { builder.startTable(3); }
+ public static void addData(FlatBufferBuilder builder, int dataOffset) { builder.addOffset(0, dataOffset, 0); }
+ public static int createDataVector(FlatBufferBuilder builder, byte[] data) { return builder.createByteVector(data); }
+ public static void addWidth(FlatBufferBuilder builder, int width) { builder.addInt(1, width, -1); }
+ public static void addHeight(FlatBufferBuilder builder, int height) { builder.addInt(2, height, -1); }
+ public static int endRawImage(FlatBufferBuilder builder) { return builder.endTable(); }
+}
diff --git a/common/src/main/java/hyperionnet/Register.java b/common/src/main/java/hyperionnet/Register.java
new file mode 100644
index 0000000..2121c41
--- /dev/null
+++ b/common/src/main/java/hyperionnet/Register.java
@@ -0,0 +1,38 @@
+package hyperionnet;
+
+import com.google.flatbuffers.BaseVector;
+import com.google.flatbuffers.Constants;
+import com.google.flatbuffers.FlatBufferBuilder;
+import com.google.flatbuffers.Table;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+@SuppressWarnings("unused")
+public final class Register extends Table {
+ public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
+ public static Register getRootAsRegister(ByteBuffer _bb) { return getRootAsRegister(_bb, new Register()); }
+ public static Register getRootAsRegister(ByteBuffer _bb, Register obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
+ public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
+ public Register __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
+
+ public String origin() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; }
+ public ByteBuffer originAsByteBuffer() { return __vector_as_bytebuffer(4, 1); }
+ public ByteBuffer originInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); }
+ public int priority() { int o = __offset(6); return o != 0 ? bb.getInt(o + bb_pos) : 0; }
+
+ public static int createRegister(FlatBufferBuilder builder, int originOffset, int priority) {
+ builder.startTable(2);
+ Register.addPriority(builder, priority);
+ Register.addOrigin(builder, originOffset);
+ return Register.endRegister(builder);
+ }
+
+ public static void startRegister(FlatBufferBuilder builder) { builder.startTable(2); }
+ public static void addOrigin(FlatBufferBuilder builder, int originOffset) { builder.addOffset(0, originOffset, 0); }
+ public static void addPriority(FlatBufferBuilder builder, int priority) { builder.addInt(1, priority, 0); }
+ public static int endRegister(FlatBufferBuilder builder) {
+ int o = builder.endTable();
+ builder.required(o, 4); // origin
+ return o;
+ }
+}
diff --git a/common/src/main/java/hyperionnet/Reply.java b/common/src/main/java/hyperionnet/Reply.java
new file mode 100644
index 0000000..05b3bbe
--- /dev/null
+++ b/common/src/main/java/hyperionnet/Reply.java
@@ -0,0 +1,35 @@
+package hyperionnet;
+
+import com.google.flatbuffers.Constants;
+import com.google.flatbuffers.FlatBufferBuilder;
+import com.google.flatbuffers.Table;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+@SuppressWarnings("unused")
+public final class Reply extends Table {
+ public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
+ public static Reply getRootAsReply(ByteBuffer _bb) { return getRootAsReply(_bb, new Reply()); }
+ public static Reply getRootAsReply(ByteBuffer _bb, Reply obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
+ public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
+ public Reply __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
+
+ public String error() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; }
+ public int video() { int o = __offset(6); return o != 0 ? bb.getInt(o + bb_pos) : -1; }
+ public int registered() { int o = __offset(8); return o != 0 ? bb.getInt(o + bb_pos) : -1; }
+
+ public static int createReply(FlatBufferBuilder builder, int errorOffset, int video, int registered) {
+ builder.startTable(3);
+ Reply.addRegistered(builder, registered);
+ Reply.addVideo(builder, video);
+ Reply.addError(builder, errorOffset);
+ return Reply.endReply(builder);
+ }
+
+ public static void startReply(FlatBufferBuilder builder) { builder.startTable(3); }
+ public static void addError(FlatBufferBuilder builder, int errorOffset) { builder.addOffset(0, errorOffset, 0); }
+ public static void addVideo(FlatBufferBuilder builder, int video) { builder.addInt(1, video, -1); }
+ public static void addRegistered(FlatBufferBuilder builder, int registered) { builder.addInt(2, registered, -1); }
+ public static int endReply(FlatBufferBuilder builder) { return builder.endTable(); }
+ public static void finishReplyBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset); }
+}
diff --git a/common/src/main/java/hyperionnet/Request.java b/common/src/main/java/hyperionnet/Request.java
new file mode 100644
index 0000000..6011a9f
--- /dev/null
+++ b/common/src/main/java/hyperionnet/Request.java
@@ -0,0 +1,36 @@
+package hyperionnet;
+
+import com.google.flatbuffers.Constants;
+import com.google.flatbuffers.FlatBufferBuilder;
+import com.google.flatbuffers.Table;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+@SuppressWarnings("unused")
+public final class Request extends Table {
+ public static void ValidateVersion() { Constants.FLATBUFFERS_23_5_26(); }
+ public static Request getRootAsRequest(ByteBuffer _bb) { return getRootAsRequest(_bb, new Request()); }
+ public static Request getRootAsRequest(ByteBuffer _bb, Request obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); }
+ public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); }
+ public Request __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; }
+
+ public byte commandType() { int o = __offset(4); return o != 0 ? bb.get(o + bb_pos) : 0; }
+ public Table command(Table obj) { int o = __offset(6); return o != 0 ? __union(obj, o + bb_pos) : null; }
+
+ public static int createRequest(FlatBufferBuilder builder, byte command_type, int commandOffset) {
+ builder.startTable(2);
+ Request.addCommand(builder, commandOffset);
+ Request.addCommandType(builder, command_type);
+ return Request.endRequest(builder);
+ }
+
+ public static void startRequest(FlatBufferBuilder builder) { builder.startTable(2); }
+ public static void addCommandType(FlatBufferBuilder builder, byte commandType) { builder.addByte(0, commandType, 0); }
+ public static void addCommand(FlatBufferBuilder builder, int commandOffset) { builder.addOffset(1, commandOffset, 0); }
+ public static int endRequest(FlatBufferBuilder builder) {
+ int o = builder.endTable();
+ builder.required(o, 6); // command
+ return o;
+ }
+ public static void finishRequestBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset); }
+}
diff --git a/common/src/main/res/drawable-v24/ic_launcher_foreground.xml b/common/src/main/res/drawable-v24/ic_launcher_foreground.xml
new file mode 100644
index 0000000..95f8fdc
--- /dev/null
+++ b/common/src/main/res/drawable-v24/ic_launcher_foreground.xml
@@ -0,0 +1,19 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/common/src/main/res/drawable/ic_info_white_24dp.xml b/common/src/main/res/drawable/ic_info_white_24dp.xml
new file mode 100644
index 0000000..1a83498
--- /dev/null
+++ b/common/src/main/res/drawable/ic_info_white_24dp.xml
@@ -0,0 +1,5 @@
+
+
+
diff --git a/common/src/main/res/drawable/ic_launcher_background.xml b/common/src/main/res/drawable/ic_launcher_background.xml
new file mode 100644
index 0000000..e1c9bd9
--- /dev/null
+++ b/common/src/main/res/drawable/ic_launcher_background.xml
@@ -0,0 +1,237 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/common/src/main/res/drawable/ic_notification_icon.xml b/common/src/main/res/drawable/ic_notification_icon.xml
new file mode 100644
index 0000000..94b27ff
--- /dev/null
+++ b/common/src/main/res/drawable/ic_notification_icon.xml
@@ -0,0 +1,10 @@
+
+
+
+
\ No newline at end of file
diff --git a/common/src/main/res/drawable/ic_power_black_72dp.xml b/common/src/main/res/drawable/ic_power_black_72dp.xml
new file mode 100644
index 0000000..1f63fce
--- /dev/null
+++ b/common/src/main/res/drawable/ic_power_black_72dp.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/common/src/main/res/drawable/ic_settings_black_72dp.xml b/common/src/main/res/drawable/ic_settings_black_72dp.xml
new file mode 100644
index 0000000..cfa8cca
--- /dev/null
+++ b/common/src/main/res/drawable/ic_settings_black_72dp.xml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/common/src/main/res/drawable/ic_toggle_image_middle.xml b/common/src/main/res/drawable/ic_toggle_image_middle.xml
new file mode 100644
index 0000000..e2db00e
--- /dev/null
+++ b/common/src/main/res/drawable/ic_toggle_image_middle.xml
@@ -0,0 +1,31 @@
+
+
+
+
+
+
+
diff --git a/common/src/main/res/drawable/image_button_background.xml b/common/src/main/res/drawable/image_button_background.xml
new file mode 100644
index 0000000..63f8f32
--- /dev/null
+++ b/common/src/main/res/drawable/image_button_background.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/common/src/main/res/drawable/pill_background.xml b/common/src/main/res/drawable/pill_background.xml
new file mode 100644
index 0000000..f848327
--- /dev/null
+++ b/common/src/main/res/drawable/pill_background.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/common/src/main/res/drawable/round_rectangle_background.xml b/common/src/main/res/drawable/round_rectangle_background.xml
new file mode 100644
index 0000000..3d1bc9d
--- /dev/null
+++ b/common/src/main/res/drawable/round_rectangle_background.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/common/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/common/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 0000000..eca70cf
--- /dev/null
+++ b/common/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/common/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/common/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
new file mode 100644
index 0000000..eca70cf
--- /dev/null
+++ b/common/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/common/src/main/res/mipmap-hdpi/ic_launcher.png b/common/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100755
index 0000000..2eb0b78
Binary files /dev/null and b/common/src/main/res/mipmap-hdpi/ic_launcher.png differ
diff --git a/common/src/main/res/mipmap-hdpi/ic_launcher_round.png b/common/src/main/res/mipmap-hdpi/ic_launcher_round.png
new file mode 100644
index 0000000..4d001c3
Binary files /dev/null and b/common/src/main/res/mipmap-hdpi/ic_launcher_round.png differ
diff --git a/common/src/main/res/mipmap-mdpi/ic_launcher.png b/common/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100755
index 0000000..f0fe46b
Binary files /dev/null and b/common/src/main/res/mipmap-mdpi/ic_launcher.png differ
diff --git a/common/src/main/res/mipmap-mdpi/ic_launcher_round.png b/common/src/main/res/mipmap-mdpi/ic_launcher_round.png
new file mode 100644
index 0000000..b63f49e
Binary files /dev/null and b/common/src/main/res/mipmap-mdpi/ic_launcher_round.png differ
diff --git a/common/src/main/res/mipmap-xhdpi/ic_launcher.png b/common/src/main/res/mipmap-xhdpi/ic_launcher.png
new file mode 100755
index 0000000..043c110
Binary files /dev/null and b/common/src/main/res/mipmap-xhdpi/ic_launcher.png differ
diff --git a/common/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/common/src/main/res/mipmap-xhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..34cdf3d
Binary files /dev/null and b/common/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ
diff --git a/common/src/main/res/mipmap-xxhdpi/ic_launcher.png b/common/src/main/res/mipmap-xxhdpi/ic_launcher.png
new file mode 100755
index 0000000..df1f856
Binary files /dev/null and b/common/src/main/res/mipmap-xxhdpi/ic_launcher.png differ
diff --git a/common/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/common/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..b5514cd
Binary files /dev/null and b/common/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ
diff --git a/common/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/common/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 0000000..3970e32
Binary files /dev/null and b/common/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ
diff --git a/common/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/common/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..460d8b5
Binary files /dev/null and b/common/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ
diff --git a/common/src/main/res/values-ar/strings.xml b/common/src/main/res/values-ar/strings.xml
new file mode 100644
index 0000000..85cf070
--- /dev/null
+++ b/common/src/main/res/values-ar/strings.xml
@@ -0,0 +1,68 @@
+
+
+
+ - 10 لقطة في الثانية
+ - 15 لقطة في الثانية
+ - 24 لقطة في الثانية
+ - 30 لقطة في الثانية
+ - 60 لقطة في الثانية
+
+ هايبريون جرابر
+ الإعدادات
+ تمكين
+ تعطيل
+
+ خروج
+
+ مرحبا!
+ Hyperion Grabber يمكنه بحث الشبكة الخاصة بك لتشغيل خوادم, حتى أنك لن تضطر إلى عزف مع جهاز التحكم عن بعد لكمة في عنوان ip.
+ بدء البحث
+ البحث عن شبكة المحلية الخاصة بك لتشغيل هايبريون خوادم %s
+ يتم البحث
+ لم يتم العثور على نتائج %s
+ إعادة المحاولة
+ الإعداد اليدوي
+
+ و الفائز هو…
+ للاحتفال ، قمنا بتحويل جميع المصابيح الخاصة بك إلى اللون الأرجواني %s
+ أحبها!
+ أنا أكره الارجوان
+
+ الاتصال
+ هايبريون المضيف
+ المضيف الخاص بك هايبريون سبيل المثال يعمل على
+ منفذ Hyperion Protobuf
+ على protobuf المنفذ الخاص هايبريون سبيل المثال
+ العد العمودي LED
+ العد العمودي لمصابيح LED على جهازك
+ العد الأفقية LED
+ العد الأفقى لمصابيح LED على جهازك
+ أولوية الرسالة
+ رسالة القناة الأولوية لاستخدام
+ إعادة الاتصال
+ تلقائي إعادة الاتصال إلى hyperion على الاتصال المفقود
+ إعادة الاتصال من التأخير
+ عدد ثواني الانتظار قبل محاولة إعادة الاتصال
+
+ التقاط
+ معدل التقاط
+ لقطة في الثانية حيث يتم إرسال البيانات إلى هايبريون
+
+ العام
+ بدء التقاط الشاشة عند بدء تشغيل الجهاز
+ الاستيلاء على التمهيد
+ %s ينبغي أن لا تكون فارغه
+ %s غير صالح لـ %s
+ اعدادات المضيف ينبغي أن لا تكون فارغه
+ إعداد المنفذ يجب أن لا يكون فارغاً
+ عدد LED أفقي وعمودي يجب أن تكون مجموعة أكبر من 0
+ لا يمكن الاتصال هايبريون الخادم. التحقق من الإعدادات الخاصة بك وتأكد من هايبريون يعمل
+ تم فقد الاتصال بخادم hyperion الخاص بك ، الآن قم بإيقاف grabber
+ يجب منح إذن لتسجيل بيانات الشاشة.
+ اضغط على \"رجوع\" لإغلاق التطبيق. سيستمر إرسال محتوى الشاشة إلى Hyperion
+ هذا غريب ، من المتوقع اسم مضيف هنا
+ اشعارات Hyperion Grabber
+ حاليا الاستيلاء على محتوى الشاشة
+ إرسال متوسط لون الشاشة
+ يرسل متوسط لون شاشة الجهاز الخاص بك بدلا من صورة منه
+
diff --git a/common/src/main/res/values-cs/strings.xml b/common/src/main/res/values-cs/strings.xml
new file mode 100644
index 0000000..99e9ea7
--- /dev/null
+++ b/common/src/main/res/values-cs/strings.xml
@@ -0,0 +1,68 @@
+
+
+
+ - 10 fps
+ - 15 fps
+ - 24 fps
+ - 30 fps
+ - 60 fps
+
+ Hyperion Grabber
+ Nastavení
+ Povoleno
+ Zakázáno
+
+ Ukončit
+
+ Ahoj!
+ Hyperion Grabber může vyhledat spuštěné Hyperion servery ve vaší lokální síti, abyste nemuseli zadávat IP adresu vaším dálkovým ovladačem.
+ Spustit hledání
+ Hledání spuštěných Hyperion serverů ve vaší lokální síti %s
+ Hledání...
+ Nebyly nalezeny žádné výsledky %s
+ opakovat
+ Ruční nastavení
+
+ A vítězem se stává...
+ Abychom to oslavili, nastavili jsme všechny LED na fialovou %s
+ Miluju to!
+ Nesnáším fialovou
+
+ Připojení
+ Hyperion Host
+ Host, ne kterém je spuštěn váš Hyperion server
+ Hyperion Protobuf Port
+ Protobuf port vašeho Hyperion serveru
+ Vertikální počet LED
+ Vertikální počet LED na vašem pásku
+ Horizontální počet LED
+ Horizontální počet LED na vašem pásku
+ Priorita komunikace
+ Priorita kanálu, který se použije pro odesílání dat
+ Znovu připojit
+ Automatické opětovné připojení k Hyperion serveru při ztrátě připojení
+ Zpoždění opětovného připojení
+ Kolik vteřin čekat před pokusem o opětovné připojení
+
+ Zachytávání obsahu
+ Frekvence snímání
+ Počet snímků za sekundu, ve kterém chcete odesílat data na Hyperionu
+
+ Obecné
+ Spustit grabování při spuštení zařízení
+ Grabování při Bootu
+ %s by neměl být prázdný
+ %s neplatí pro %s
+ Pole nastavení Host by nemělo být prázdné
+ Pole nastavení portu by nemělo být prázdné
+ Horizontální a vertikální počet LED musí být nastaven a větší než 0
+ Nelze se připojit k Hyperion serveru. Zkontrolujte vaše nastavení a ujistěte se, že je Hyperion spuštěn
+ Spojení s vaším Hyperion serverem bylo ztraceno, grabber se nyní ukončuje
+ K zaznamenávání dat na obrazovce musí být uděleno oprávnění.
+ Stikněte Zpět pro uzavření aplikace. Obsah obrazovky se bude nadále odesílat do Hyperionu.
+ Zvláštní, tady má být hostname
+ Hyperion Grabber notifikace
+ Momentálně se grabuje obsah obrazovky
+ Odeslat průměrnou barvu obrazovky
+ Odesílá průměrnou barvu obrazovky vašeho zařízení namísto přesného obrazu
+
diff --git a/common/src/main/res/values-de/strings.xml b/common/src/main/res/values-de/strings.xml
new file mode 100644
index 0000000..e1d9964
--- /dev/null
+++ b/common/src/main/res/values-de/strings.xml
@@ -0,0 +1,68 @@
+
+
+
+ - 10 fps
+ - 15 fps
+ - 24 fps
+ - 30 fps
+ - 60 fps
+
+ Hyperion Grabber
+ Einstellungen
+ Einschalten
+ Ausschalten
+
+ Beenden
+
+ Hallo!
+ Hyperion Grabber kann im Netzwerk nach Servern suchen, so dass Du nicht die IP-Adresse deines Servers manuell eingeben musst.
+ Suche starten
+ Suche nach lokalen Hyperion Servers läuft %s
+ Suche…
+ Kein Server gefunden %s
+ Wiederholen
+ Manuelle Einstellung
+
+ Und der Gewinner ist …
+ Jetzt müssten alle deine LEDs Lila aufleuchten %s
+ Ich liebe es!
+ Bitte kein Lila
+
+ Verbindung
+ IP Adresse
+ Die IP Adresse auf dem dein Hyperion Server läuft
+ Port Nummer
+ Die PROTO Port Nummer von deinem Hyperion Server
+ Vertikale LEDs
+ Die vertikale Anzahl deiner LEDs
+ Horizontale LEDs
+ Die horizontale Anzahl deiner LEDs
+ Priorität
+ Die Priorität vom Hyperion Grabber
+ Verbindungswiederholung
+ Die Verbindung zum Hyperion Server bei Verlust automatisch wiederherstellen
+ Verzögerung
+ Die Sekundenanzahl zwischen den Verbindungswiederholungen
+
+ Aufnahme
+ Aufnahmefrequenz
+ Wie schnell neue Bilder an den Server gesendet werden sollen
+
+ Allgemein
+ Hyperion Grabber mit Android starten
+ Autostart
+ %s sollte nicht leer sein
+ %s passt nicht zur %s
+ Die IP Adresse darf nicht leer sein
+ Die Port Nummer darf nicht leer sein
+ Die Anzahl der horizontalen oder vertikalen LEDs müssen größer als 0 sein
+ Eine Verbindung zum Hyperion Server konnte nicht hergestellt werden. Bitte überprüfe deine Einstellungen und stelle sicher, dass dein Hyperion Server läuft
+ Die Verbindung zum Hyperion Server wurde getrennt. Die Bilderfassung wir angehalten.
+ Bitte erlaube die Bilderfassung.
+ Du kannst Hyperion Grabber mit der Zurück-Taste verlassen. Der Bildschirminhalt wird im Hintergrund an deinen Hyperion Server gesendet.
+ Eigentlich sollte hier eine IP Adresse eingegeben werden
+ Hyperion Grabber Benachrichtigungen
+ Bildschirminhalt wird übertragen
+ Durchschnittliche Bildschirmfarbe senden
+ Es wird die durchschnittliche Farbe jedes Bildes berechnet und deine LEDs leuchten alle nach dieser berechneten Farbe.
+
diff --git a/common/src/main/res/values-es/strings.xml b/common/src/main/res/values-es/strings.xml
new file mode 100644
index 0000000..f7bf1e0
--- /dev/null
+++ b/common/src/main/res/values-es/strings.xml
@@ -0,0 +1,39 @@
+
+
+
+ - 10 fps
+ - 15 fps
+ - 24 fps
+ - 30 fps
+ - 60 fps
+
+ Hyperion Grabber
+ Configuraciones
+ Habilitado
+ Discapacitado
+
+ Salida
+
+ ¡Hola!
+ Iniciar escaneoe
+ Exploración…
+ No se encontraron resultados %s
+ reintento
+
+ Y el ganador es…
+ Me encanta!
+ Odio a púrpura
+
+ Conexión
+ Host de Hyperion
+ Host que está ejecutando la instancia de Hyperion
+ Hyperion Protobuf puerto
+ Prioridad del mensaje
+ Canal de prioridad de mensajes a utilizar
+ Tasa de captura
+
+ General
+ La configuración del host no debe estar vacía
+ El puerto no debe estar vacío
+ Permiso debe concederse a la pantalla de registro de datos
+
diff --git a/common/src/main/res/values-fr/strings.xml b/common/src/main/res/values-fr/strings.xml
new file mode 100644
index 0000000..d3d60c3
--- /dev/null
+++ b/common/src/main/res/values-fr/strings.xml
@@ -0,0 +1,68 @@
+
+
+
+ - 10 images/s
+ - 15 images/s
+ - 24 images/s
+ - 30 images/s
+ - 60 images/s
+
+ Grabber Hyperion
+ Paramètres
+ Activé
+ Désactivé
+
+ Fermer
+
+ Salut !
+ Le Grabber Hyperion peut analyser votre réseau à la recherche de serveurs en cours d\'exécution. Ainsi, vous n\'aurez pas à manipuler votre télécommande pour indiquer une adresse IP.
+ Lancer la recherche
+ Recherche de serveurs Hyperion sur votre réseau local %s
+ Recherche...
+ Aucun résultat trouvé %s
+ réessayer
+ Configuration manuelle
+
+ Et le gagnant est…
+ Pour célébrer ça, nous avons allumer toutes les LEDs en violet %s
+ J\'adore !
+ Je déteste le violet
+
+ Connexion
+ Serveur Hyperion
+ Adresse IP de votre serveur Hyperion
+ Port Hyperion
+ Port utilisée par votre instance Hyperion.
+ Nombre de LEDs verticales
+ Le nombre de LEDs verticales sur votre matériel
+ Nombre de LEDs horizontal
+ Nombre de LEDs horizontal sur votre matériel
+ Priorité du message
+ Priorité du canal à utiliser
+ Reconnecter
+ Reconnexion automatique à Hyperion en cas de perte de connexion
+ Délai de reconnexion
+ Nombre de secondes à attendre avant d\'essayer de se reconnecter
+
+ Capture
+ Fréquence de capture
+ Images par seconde envoyées au serveur Hyperion
+
+ Général
+ Lancer le grabber au démarrage de l\'appareil
+ Capturer au démarrage
+ %s ne doit pas être vide
+ %s n\'est pas valide pour %s
+ Le réglage de l\'hôte ne doit pas être vide.
+ Le réglage du port ne doit pas être vide.
+ Le nombre de LED horizontales et verticales doivent être réglées et supérieur à 0.
+ Impossible de se connecter au serveur hyperion. Vérifiez vos paramètres et assurez-vous qu\'Hyperion est en cours d´exécution
+ La connexion à votre serveur Hyperion a été perdue. Le grabber va s\'arrêter
+ Vous devez accepter l´autorisation pour permettre de capturer l´image à l´écran
+ Appuyez sur Retour pour fermer l\'application. Le contenu de votre écran continuera d\'être envoyé à Hyperion.
+ C\'est bizarre, il est attendu un nom d\'hôte ici
+ Notifications du Grabber Hyperion
+ Actuellement en train de capturer le contenu de l\'écran
+ Envoyer la couleur dominante de l\'écran
+ Envoie la couleur dominante de l\'écran de votre appareil plutôt qu\'une image de celui-ci
+
diff --git a/common/src/main/res/values-it/strings.xml b/common/src/main/res/values-it/strings.xml
new file mode 100644
index 0000000..8203b61
--- /dev/null
+++ b/common/src/main/res/values-it/strings.xml
@@ -0,0 +1,68 @@
+
+
+
+ - 10 fps
+ - 15 fps
+ - 24 fps
+ - 30 fps
+ - 60 fps
+
+ Hyperion Grabber
+ Impostazioni
+ Abilitato
+ Disabilitato
+
+ Uscita
+
+ Ciao!
+ Hyperion Grabber è in grado di scansionare la tua rete per individuare server in esecuzione, quindi non dovrai inserire un indirizzo IP con il telecomando.
+ Inizia scansione
+ Scansione rete locale per individuare server hyperion in esecuzione %s
+ Scansione ...
+ Nessun risultato trovato %s
+ Riprova
+ Configurazione manuale
+
+ E il vincitore è…
+ Per festeggiare, abbiamo acceso tutti i tuoi LED in viola %s
+ Lo adoro!
+ Odio il viola
+
+ Connessione
+ Hyperion Host
+ Host dove è in esecuzione l\'istanza di hyperion
+ Porta Protobuf Hyperion
+ La porta protobuf della tua istanza hyperion
+ Conteggio LED verticali
+ Il conteggio verticale dei LED sul tuo hardware
+ Conteggio LED orizzontali
+ Il conteggio orizzontale dei LED sul tuo hardware
+ Priorità del messaggio
+ Canale prioritario del messaggio da utilizzare
+ Riconnettere
+ Riconnettersi automaticamente a hyperion in caso di connessione persa
+ Ritardo riconnessione
+ Il numero di secondi da attendere prima di provare a riconnettersi
+
+ Acquisizione in corso
+ Velocità di acquisizione
+ Fotogrammi al secondo in cui inviare i dati a hyperion
+
+ Generale
+ Avvia lo screen grabber all\'avvio del dispositivo
+ Inizia acquisizione all\'avvio
+ %s non dovrebbe essere vuoto
+ %s non è valido per %s
+ Il valore dell\'host non dovrebbe essere vuoto
+ Il valore della porta non dovrebbe essere vuoto
+ I conteggi LED orizzontali e verticali devono essere impostati e maggiori di 0
+ Impossibile connettersi al server hyperion. Controlla le tue impostazioni e assicurati che hyperion sia in esecuzione
+ La connessione al tuo hyperion server è stata persa, l\'acquisizione verrà interrotta
+ Deve essere data l\'autorizzazione per registrare i dati dello schermo.
+ Premi Indietro per chiudere l\'app. Il contenuto dello schermo continuerà ad essere inviato a Hyperion
+ È strano, serve un nome host qui
+ Notifiche di Hyperion Grabber
+ Acquisizione schermo in corso
+ Invia il colore medio dello schermo
+ Invia il colore medio dello schermo del tuo dispositivo piuttosto che un\'immagine di esso
+
diff --git a/common/src/main/res/values-nl/strings.xml b/common/src/main/res/values-nl/strings.xml
new file mode 100644
index 0000000..5fdf1a8
--- /dev/null
+++ b/common/src/main/res/values-nl/strings.xml
@@ -0,0 +1,68 @@
+
+
+
+ - 10 fps
+ - 15 fps
+ - 24 fps
+ - 30 fps
+ - 60 fps
+
+ Hyperion Grabber
+ Instellingen
+ Ingeschakeld
+ Uitgeschakeld
+
+ Afsluiten
+
+ Hallo daar!
+ Hyperion Grabber kan uw netwerk scannen op draaiende servers, zodat u niet hoeft te knoeien met uw afstandsbediening om een ip-adres in te voeren.
+ Scan starten
+ Uw lokale netwerk scannen op Hyperion servers %s
+ Scannen...
+ Geen resultaten gevonden %s
+ opnieuw proberen
+ Handmatig instellen
+
+ En de winnaar is…
+ Om dit te vieren, hebben we al je LED\'s paars gemaakt %s
+ Mooi hoor!
+ Ik haat paars
+
+ Verbinding
+ Hyperion Hostnaam
+ Host waar uw Hyperion server op draait
+ Hyperion Protobuf-poort
+ De Protobuf-poort van uw hyperion-server
+ Verticale LED\'s
+ Het verticale aantal LED\'s van uw apparaat
+ Horizontale LED\'s
+ Het horizontale aantal LED\'s van uw apparaat
+ Hyperion-prioriteit
+ 1 is hoogste, 900 is laagste
+ Verloren verbinding herstellen
+ Automatisch opnieuw verbinding maken met Hyperion bij verloren verbinding
+ Vertraging voor opnieuw verbinden
+ Het aantal seconden voordat wordt geprobeerd opnieuw verbinding te maken
+
+ Opname
+ Opname-snelheid
+ Aantal keer per seconde dat het beeld naar Hyperion gestuurd wordt
+
+ Algemeen
+ Start schermopname wanneer uw apparaat start
+ Direct starten
+ %s mag niet leeg zijn
+ %s is niet geldig voor %s
+ Hostinstelling mag niet leeg zijn
+ Poortinstelling mag niet leeg zijn
+ Het aantal horizontale & verticale LEDs moet groter zijn dan 0
+ Kon geen verbinding maken met de Hyperion-server. Controleer uw instellingen en zorg ervoor dat Hyperion actief is
+ De verbinding met uw Hyperion-server is verbroken, schermopname wordt gestopt
+ Er moet toestemming worden verleend om scherminhoud door te sturen
+ Druk op Terug om de app te sluiten. Uw scherminhoud wordt nog steeds naar Hyperion verzonden
+ Dat is raar, ik verwachtte hier een hostnaam
+ Hyperion Grabber Notificaties
+ Scherminhoud wordt doorgestuurd
+ Stuur Gemiddelde Schermkleur
+ Stuurt de gemiddelde kleur van het scherm in plaats van een beeld van het
+
diff --git a/common/src/main/res/values-no/strings.xml b/common/src/main/res/values-no/strings.xml
new file mode 100644
index 0000000..af10d6a
--- /dev/null
+++ b/common/src/main/res/values-no/strings.xml
@@ -0,0 +1,68 @@
+
+
+
+ - 10 bilder per sekund (FPS)
+ - 15 bilder per sekund (FPS)
+ - 24 bilder per sekund (FPS)
+ - 30 bilder per sekund (FPS)
+ - 60 bilder per sekund (FPS)
+
+ Hyperion Grabber
+ Innstillinger
+ Aktivert
+ Deaktivert
+
+ Avslutt
+
+ Hei der!
+ Hyperion Grabber kan skanne nettverket etter aktive Hyperion servere, slik at du slipper å fikle med fjernkontrollen for å taste inn en ip-adresse.
+ Start søk
+ Skanner ditt lokale nettverk for aktive Hyperion servere %s
+ Skanner ...
+ Ingen resultater funnet %s
+ prøv på nytt
+ Manuelt oppsett
+
+ Og vinneren er...
+ For å feire, har vi gjort alle lysdiodene dine lilla %s
+ Digger det!
+ Jeg hater lilla
+
+ Tilkobling
+ Hyperion vert
+ Vertsnavn Hyperion kjører på
+ Hyperion Protobuf Port
+ Protobuf porten til Hyperion instansen
+ Antall vertikale LED
+ Antallet vertikale LED koblet til systemet
+ Antall horisontale LED
+ Antallet horisontale LED tilkoblet systemet
+ Meldings prioritet
+ Prioritert meldingskanal som skal benyttes
+ Koble til på nytt
+ Automatisk koble til Hyperion på nytt ved tapt tilkobling
+ Forsinkelse for påkoblingsforsøk
+ Antall sekunder å vente før nytt tilkoblingsforsøk
+
+ Fanger innhold
+ Capture rate
+ Bilder per sekund (FPS) som skal sendes til Hyperion
+
+ Generelt
+ Start screen grabber når enheten starter
+ Start grabbing ved restart av systemet
+ %s feltet må ikke være tomt
+ %s er ikke gyldig for %s
+ Vertsnavn feltet må fylles inn
+ Portnummer må fylles inn
+ Horisontale og vertikale LED tellerer må settes, og må være større enn 0
+ Kunne ikke koble til Hyperion serveren. Kontroller instillingene og sørg for at Hyperion kjører.
+ Tilkoblingen til Hyperion serveren has stoppet, grabber stoppes nå.
+ Tillatelser må være gitt for å hente skjermdata.
+ Trykk Tilbake for å lukke appen. Innholdet på skjermen din vil fortsatt bli sendt til Hyperion
+ Det var underlig, forventet et hostnavn her
+ Hyperion Grabber Varsler
+ Fanger innholdet på skjermen
+ Send gjennomsnittlig skjermfarge
+ Sender gjennomsnittsfargen i enhetens skjerm i stedet for et bilde av det
+
diff --git a/common/src/main/res/values-ru/strings.xml b/common/src/main/res/values-ru/strings.xml
new file mode 100644
index 0000000..ad61792
--- /dev/null
+++ b/common/src/main/res/values-ru/strings.xml
@@ -0,0 +1,34 @@
+
+
+
+ - 10 кадров в секунду
+ - 15 кадров в секунду
+ - 24 кадра в секунду
+ - 30 кадров в секунду
+ - 60 кадров в секунду
+
+ Настройки
+ Включено
+
+ Выход
+ сканирование...
+ Приоритет сообщений
+ Заново
+ Автоматическо заново соедините к hyperion припотеряли связи
+ Задержка повторного подключения
+ Количество секунд ожидания до попытки повторного подключения
+
+ Захват
+ Частота захвата
+
+ Общие
+ Запуск захвата экрана при запуске устройства
+ захват при загрузке
+ %s не должно быть пустым
+ %s недействительно для %s
+ Настройка хоста не должна быть пустой
+ Настройка порта не должна быть пустой
+ Соединение с вашим сервером hyperion было потеряно. Грабер останавливаться
+ Разрешение должно быть предоставлено для записи экрана данных.
+ Нажмите «Назад», чтобы закрыть приложение. Содержимое вашего экрана будет по-прежнему отправляться в Hyperion
+
diff --git a/common/src/main/res/values/colors.xml b/common/src/main/res/values/colors.xml
new file mode 100644
index 0000000..3ab3e9c
--- /dev/null
+++ b/common/src/main/res/values/colors.xml
@@ -0,0 +1,6 @@
+
+
+ #3F51B5
+ #303F9F
+ #FF4081
+
diff --git a/common/src/main/res/values/pref_values.xml b/common/src/main/res/values/pref_values.xml
new file mode 100644
index 0000000..0fdb318
--- /dev/null
+++ b/common/src/main/res/values/pref_values.xml
@@ -0,0 +1,37 @@
+
+ pref_key_host
+
+ pref_key_port
+ 19400
+
+ pref_key_y_led
+ 34
+
+ pref_key_x_led
+ 60
+
+ pref_key_priority
+ 100
+
+ pref_key_reconnect
+ true
+
+ pref_key_reconnect_delay
+ 5
+
+ pref_key_start_on_boot
+ false
+
+ pref_key_framerate
+ 30
+
+ - 10
+ - 15
+ - 24
+ - 30
+ - 60
+
+
+ pref_key_use_avg_color
+ false
+
diff --git a/common/src/main/res/values/strings.xml b/common/src/main/res/values/strings.xml
new file mode 100755
index 0000000..e325132
--- /dev/null
+++ b/common/src/main/res/values/strings.xml
@@ -0,0 +1,68 @@
+
+
+
+ - 10 fps
+ - 15 fps
+ - 24 fps
+ - 30 fps
+ - 60 fps
+
+ Hyperion Grabber
+ Settings
+ Enabled
+ Disabled
+
+ Exit
+
+ Hi there!
+ Hyperion Grabber can scan your network for running servers, so you won\'t have to fiddle with your remote to punch in an ip-address.
+ Start scan
+ Scanning your local network for running hyperion servers %s
+ Scanning…
+ No results found %s
+ retry
+ Manual setup
+
+ And the winner is…
+ To celebrate, we have turned all your LEDs purple %s
+ Love it!
+ I hate purple
+
+ Connection
+ Hyperion Host
+ Host your hyperion instance is running on
+ Hyperion FlatBuffers Port
+ The FlatBuffers port of your hyperion instance (usually 19400)
+ Vertical LED Count
+ The vertical count of LEDs on your hardware
+ Horizontal LED Count
+ The horizontal count of LEDs on your hardware
+ Message Priority
+ Message priority channel to use
+ Reconnect
+ Automatic reconnect to hyperion on lost connection
+ Reconnect Delay
+ The number of seconds to wait before trying to reconnect
+
+ Capturing
+ Capture Rate
+ Frames per second in which to send data to hyperion
+
+ General
+ Start screen grabber when device starts
+ Grab on Boot
+ %s should not be empty
+ %s is not valid for %s
+ Host setting should not be empty
+ Port setting should not be empty
+ Horizontal & vertical LED counts must be set and greater than 0
+ Could not connect to the hyperion server. Check your settings and make sure hyperion is running
+ The connection to your hyperion server has been lost, now stopping the grabber
+ Permission must be granted to record screen data.
+ Press Back to close the app. Your screen content will continue to be sent to Hyperion
+ That\'s weird, expected a hostname here
+ Hyperion Grabber Notifications
+ Currently grabbing screen content
+ Send Average Screen Color
+ Sends the average color of your device\'s screen rather than an image of it
+
diff --git a/common/src/main/res/values/styles.xml b/common/src/main/res/values/styles.xml
new file mode 100644
index 0000000..f59b40f
--- /dev/null
+++ b/common/src/main/res/values/styles.xml
@@ -0,0 +1,12 @@
+
+
+
+
\ No newline at end of file
diff --git a/common/src/main/res/xml/pref_general.xml b/common/src/main/res/xml/pref_general.xml
new file mode 100644
index 0000000..9d9726a
--- /dev/null
+++ b/common/src/main/res/xml/pref_general.xml
@@ -0,0 +1,118 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/common/variables.gradle b/common/variables.gradle
new file mode 100644
index 0000000..7aabaa9
--- /dev/null
+++ b/common/variables.gradle
@@ -0,0 +1 @@
+// AndroidX versions are managed in build.gradle files
\ No newline at end of file
diff --git a/gradle.properties b/gradle.properties
new file mode 100755
index 0000000..c2b58fe
--- /dev/null
+++ b/gradle.properties
@@ -0,0 +1,24 @@
+# Project-wide Gradle settings.
+
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
+
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
+
+# AndroidX package structure
+android.useAndroidX=true
+android.enableJetifier=true
+
+# Non-transitive R classes
+android.nonTransitiveRClass=true
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100755
index 0000000..13372ae
Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
new file mode 100755
index 0000000..28d50ee
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+#Updated for Android 12+ compatibility
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip
diff --git a/gradlew b/gradlew
new file mode 100755
index 0000000..9d82f78
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,160 @@
+#!/usr/bin/env bash
+
+##############################################################################
+##
+## Gradle start up script for UN*X
+##
+##############################################################################
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS=""
+
+APP_NAME="Gradle"
+APP_BASE_NAME=`basename "$0"`
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD="maximum"
+
+warn ( ) {
+ echo "$*"
+}
+
+die ( ) {
+ echo
+ echo "$*"
+ echo
+ exit 1
+}
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+case "`uname`" in
+ CYGWIN* )
+ cygwin=true
+ ;;
+ Darwin* )
+ darwin=true
+ ;;
+ MINGW* )
+ msys=true
+ ;;
+esac
+
+# Attempt to set APP_HOME
+# Resolve links: $0 may be a link
+PRG="$0"
+# Need this for relative symlinks.
+while [ -h "$PRG" ] ; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`"/$link"
+ fi
+done
+SAVED="`pwd`"
+cd "`dirname \"$PRG\"`/" >/dev/null
+APP_HOME="`pwd -P`"
+cd "$SAVED" >/dev/null
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD="$JAVA_HOME/jre/sh/java"
+ else
+ JAVACMD="$JAVA_HOME/bin/java"
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD="java"
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
+ MAX_FD_LIMIT=`ulimit -H -n`
+ if [ $? -eq 0 ] ; then
+ if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
+ MAX_FD="$MAX_FD_LIMIT"
+ fi
+ ulimit -n $MAX_FD
+ if [ $? -ne 0 ] ; then
+ warn "Could not set maximum file descriptor limit: $MAX_FD"
+ fi
+ else
+ warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
+ fi
+fi
+
+# For Darwin, add options to specify how the application appears in the dock
+if $darwin; then
+ GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
+fi
+
+# For Cygwin, switch paths to Windows format before running java
+if $cygwin ; then
+ APP_HOME=`cygpath --path --mixed "$APP_HOME"`
+ CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
+ JAVACMD=`cygpath --unix "$JAVACMD"`
+
+ # We build the pattern for arguments to be converted via cygpath
+ ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
+ SEP=""
+ for dir in $ROOTDIRSRAW ; do
+ ROOTDIRS="$ROOTDIRS$SEP$dir"
+ SEP="|"
+ done
+ OURCYGPATTERN="(^($ROOTDIRS))"
+ # Add a user-defined pattern to the cygpath arguments
+ if [ "$GRADLE_CYGPATTERN" != "" ] ; then
+ OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
+ fi
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ i=0
+ for arg in "$@" ; do
+ CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
+ CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
+
+ if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
+ eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
+ else
+ eval `echo args$i`="\"$arg\""
+ fi
+ i=$((i+1))
+ done
+ case $i in
+ (0) set -- ;;
+ (1) set -- "$args0" ;;
+ (2) set -- "$args0" "$args1" ;;
+ (3) set -- "$args0" "$args1" "$args2" ;;
+ (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
+ (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
+ (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
+ (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
+ (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
+ (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
+ esac
+fi
+
+# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
+function splitJvmOpts() {
+ JVM_OPTS=("$@")
+}
+eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
+JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
+
+exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100755
index 0000000..8a0b282
--- /dev/null
+++ b/gradlew.bat
@@ -0,0 +1,90 @@
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto init
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto init
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:init
+@rem Get command-line arguments, handling Windowz variants
+
+if not "%OS%" == "Windows_NT" goto win9xME_args
+if "%@eval[2+2]" == "4" goto 4NT_args
+
+:win9xME_args
+@rem Slurp the command line arguments.
+set CMD_LINE_ARGS=
+set _SKIP=2
+
+:win9xME_args_slurp
+if "x%~1" == "x" goto execute
+
+set CMD_LINE_ARGS=%*
+goto execute
+
+:4NT_args
+@rem Get arguments from the 4NT Shell from JP Software
+set CMD_LINE_ARGS=%$
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/privacy-policy.md b/privacy-policy.md
new file mode 100644
index 0000000..68f916b
--- /dev/null
+++ b/privacy-policy.md
@@ -0,0 +1,63 @@
+Privacy Policy
+--------------
+
+Dave Anderson built the Hyperion Android Grabber app as an Open Source app. This SERVICE is provided by Dave Anderson at no cost and is intended for use as is.
+
+This page is used to inform website visitors regarding my policies with the collection, use, and disclosure of Personal Information if anyone decided to use my Service.
+
+If you choose to use my Service, then you agree to the collection and use of information in relation to this policy. The Personal Information that I collect is used for providing and improving the Service. I will not use or share your information with anyone except as described in this Privacy Policy.
+
+The terms used in this Privacy Policy have the same meanings as in our Terms and Conditions, which is accessible at Hyperion Android Grabber unless otherwise defined in this Privacy Policy.
+
+**Information Collection and Use**
+
+For a better experience, while using our Service, I may require you to provide us with certain personally identifiable information, including but not limited to We do not collect any data other than the standard crash reporting already being performed by android.. The information that I request is retained on your device and is not collected by me in any way
+
+The app does use third party services that may collect information used to identify you.
+
+Link to privacy policy of third party service providers used by the app
+
+* [Google Play Services](https://www.google.com/policies/privacy/)
+
+**Log Data**
+
+I want to inform you that whenever you use my Service, in a case of an error in the app I collect data and information (through third party products) on your phone called Log Data. This Log Data may include information such as your device Internet Protocol (“IP”) address, device name, operating system version, the configuration of the app when utilizing my Service, the time and date of your use of the Service, and other statistics.
+
+**Cookies**
+
+Cookies are files with a small amount of data that are commonly used as anonymous unique identifiers. These are sent to your browser from the websites that you visit and are stored on your device's internal memory.
+
+This Service does not use these “cookies” explicitly. However, the app may use third party code and libraries that use “cookies” to collect information and improve their services. You have the option to either accept or refuse these cookies and know when a cookie is being sent to your device. If you choose to refuse our cookies, you may not be able to use some portions of this Service.
+
+**Service Providers**
+
+I may employ third-party companies and individuals due to the following reasons:
+
+* To facilitate our Service;
+* To provide the Service on our behalf;
+* To perform Service-related services; or
+* To assist us in analyzing how our Service is used.
+
+I want to inform users of this Service that these third parties have access to your Personal Information. The reason is to perform the tasks assigned to them on our behalf. However, they are obligated not to disclose or use the information for any other purpose.
+
+**Security**
+
+I value your trust in providing us your Personal Information, thus we are striving to use commercially acceptable means of protecting it. But remember that no method of transmission over the internet, or method of electronic storage is 100% secure and reliable, and I cannot guarantee its absolute security.
+
+**Links to Other Sites**
+
+This Service may contain links to other sites. If you click on a third-party link, you will be directed to that site. Note that these external sites are not operated by me. Therefore, I strongly advise you to review the Privacy Policy of these websites. I have no control over and assume no responsibility for the content, privacy policies, or practices of any third-party sites or services.
+
+**Children’s Privacy**
+
+These Services do not address anyone under the age of 13. I do not knowingly collect personally identifiable information from children under 13. In the case I discover that a child under 13 has provided me with personal information, I immediately delete this from our servers. If you are a parent or guardian and you are aware that your child has provided us with personal information, please contact me so that I will be able to do necessary actions.
+
+**Changes to This Privacy Policy**
+
+I may update our Privacy Policy from time to time. Thus, you are advised to review this page periodically for any changes. I will notify you of any changes by posting the new Privacy Policy on this page. These changes are effective immediately after they are posted on this page.
+
+**Contact Us**
+
+If you have any questions or suggestions about my Privacy Policy, do not hesitate to contact me.
+
+This privacy policy page was created at [privacypolicytemplate.net](https://privacypolicytemplate.net) and modified/generated by [App Privacy Policy Generator](https://app-privacy-policy-generator.firebaseapp.com/)
diff --git a/settings.gradle b/settings.gradle
new file mode 100755
index 0000000..db7e391
--- /dev/null
+++ b/settings.gradle
@@ -0,0 +1 @@
+include ':app', ':common'