diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 8c9379a..f02ee7f 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -38,3 +38,56 @@ jobs: with: name: meal-tracker path: meal-tracker.zip + + build-android: + runs-on: ubuntu-latest + needs: test-and-package + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Setup Java 17 + uses: actions/setup-java@v3 + with: + distribution: temurin + java-version: "17" + + - name: Build APK + run: | + export ANDROID_SDK_ROOT="$HOME/android-sdk" + mkdir -p "$ANDROID_SDK_ROOT" + + # Download Android command-line tools + wget -q https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip \ + -O /tmp/cmdline-tools.zip + unzip -qo /tmp/cmdline-tools.zip -d /tmp/cmdline-tools-tmp + mkdir -p "$ANDROID_SDK_ROOT/cmdline-tools" + mv /tmp/cmdline-tools-tmp/cmdline-tools "$ANDROID_SDK_ROOT/cmdline-tools/latest" + + # Accept licenses and install SDK packages + yes | "$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null 2>&1 + "$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager" \ + "platform-tools" \ + "build-tools;34.0.0" \ + "platforms;android-34" > /dev/null 2>&1 + + # Create local.properties + echo "sdk.dir=$ANDROID_SDK_ROOT" > android/local.properties + + # Download Gradle + wget -q https://services.gradle.org/distributions/gradle-8.7-bin.zip -O /tmp/gradle.zip + mkdir -p android/.gradle-home + unzip -qo /tmp/gradle.zip -d android/.gradle-home + + # Generate wrapper + cd android + .gradle-home/gradle-8.7/bin/gradle wrapper --gradle-version 8.7 --no-daemon + + # Build + ./gradlew assembleDebug --no-daemon + + - name: Upload APK artifact + uses: actions/upload-artifact@v3 + with: + name: meal-tracker-apk + path: android/app/build/outputs/apk/debug/*.apk diff --git a/.gitignore b/.gitignore index e4a2e85..048982c 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,10 @@ meals.db __pycache__/ .pytest_cache/ + +# Android +android/.gradle/ +android/.gradle-home/ +android/local.properties +android/app/build/ +*.apk diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 0000000..1cb0470 --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,38 @@ +plugins { + id 'com.android.application' +} + +android { + namespace 'com.mealtracker.app' + compileSdk 34 + + defaultConfig { + applicationId "com.mealtracker.app" + minSdk 24 + targetSdk 34 + versionCode 1 + versionName "1.0" + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + debug { + applicationIdSuffix ".debug" + versionNameSuffix "-debug" + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } +} + +dependencies { + implementation 'androidx.appcompat:appcompat:1.6.1' + implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0' + implementation 'com.google.android.material:material:1.11.0' +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000..8659771 --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,12 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in the SDK tools. + +# WebView - keep JavaScript interface methods +-keepclassmembers class * { + @android.webkit.JavascriptInterface ; +} + +# Keep material components +-dontwarn com.google.android.material.** +-keep class com.google.android.material.** { *; } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..2d53ced --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/com/mealtracker/app/MainActivity.java b/android/app/src/main/java/com/mealtracker/app/MainActivity.java new file mode 100644 index 0000000..c0409ed --- /dev/null +++ b/android/app/src/main/java/com/mealtracker/app/MainActivity.java @@ -0,0 +1,192 @@ +package com.mealtracker.app; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.SharedPreferences; +import android.graphics.Bitmap; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Bundle; +import android.view.KeyEvent; +import android.view.View; +import android.view.inputmethod.EditorInfo; +import android.webkit.WebChromeClient; +import android.webkit.WebResourceError; +import android.webkit.WebResourceRequest; +import android.webkit.WebSettings; +import android.webkit.WebView; +import android.webkit.WebViewClient; +import android.widget.EditText; +import android.widget.ImageButton; +import android.widget.ProgressBar; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.app.AppCompatActivity; +import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; + +public class MainActivity extends AppCompatActivity { + + private static final String PREFS_NAME = "mealtracker_prefs"; + private static final String KEY_PUBLIC_URL = "public_url"; + + private WebView webView; + private SwipeRefreshLayout swipeRefresh; + private ProgressBar progressBar; + private TextView errorView; + private String currentUrl; + + @SuppressLint("SetJavaScriptEnabled") + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + webView = findViewById(R.id.webview); + swipeRefresh = findViewById(R.id.swipe_refresh); + progressBar = findViewById(R.id.progress_bar); + errorView = findViewById(R.id.error_view); + ImageButton btnSettings = findViewById(R.id.btn_settings); + ImageButton btnRefresh = findViewById(R.id.btn_refresh); + + setupWebView(); + + swipeRefresh.setOnRefreshListener(() -> webView.reload()); + btnRefresh.setOnClickListener(v -> webView.reload()); + btnSettings.setOnClickListener(v -> showSettingsDialog()); + + // Load saved URL or show setup + SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); + String savedUrl = prefs.getString(KEY_PUBLIC_URL, ""); + if (!savedUrl.isEmpty()) { + loadUrl(savedUrl); + } else { + showSettingsDialog(); + } + } + + @SuppressLint("SetJavaScriptEnabled") + private void setupWebView() { + WebSettings settings = webView.getSettings(); + settings.setJavaScriptEnabled(true); + settings.setDomStorageEnabled(true); + settings.setUseWideViewPort(true); + settings.setLoadWithOverviewMode(true); + settings.setSupportZoom(true); + settings.setBuiltInZoomControls(true); + settings.setDisplayZoomControls(false); + settings.setCacheMode(WebSettings.LOAD_DEFAULT); + settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); + + webView.setWebViewClient(new WebViewClient() { + @Override + public void onPageStarted(WebView view, String url, Bitmap favicon) { + progressBar.setVisibility(View.VISIBLE); + errorView.setVisibility(View.GONE); + } + + @Override + public void onPageFinished(WebView view, String url) { + progressBar.setVisibility(View.GONE); + swipeRefresh.setRefreshing(false); + currentUrl = url; + } + + @Override + public void onReceivedError(WebView view, WebResourceRequest request, + WebResourceError error) { + if (request.isForMainFrame()) { + progressBar.setVisibility(View.GONE); + swipeRefresh.setRefreshing(false); + if (!isNetworkAvailable()) { + errorView.setText(R.string.error_no_network); + } else { + errorView.setText(R.string.error_load_failed); + } + errorView.setVisibility(View.VISIBLE); + webView.setVisibility(View.GONE); + } + } + + @Override + public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { + // Keep all navigation inside the WebView + view.loadUrl(request.getUrl().toString()); + return true; + } + }); + + webView.setWebChromeClient(new WebChromeClient() { + @Override + public void onProgressChanged(WebView view, int newProgress) { + if (newProgress == 100) { + progressBar.setVisibility(View.GONE); + swipeRefresh.setRefreshing(false); + } + } + }); + + // Retry on error tap + errorView.setOnClickListener(v -> { + if (currentUrl != null) { + loadUrl(currentUrl); + } + }); + } + + private void loadUrl(String url) { + currentUrl = url; + errorView.setVisibility(View.GONE); + webView.setVisibility(View.VISIBLE); + webView.loadUrl(url); + } + + private void showSettingsDialog() { + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(R.string.settings_title); + + View dialogView = getLayoutInflater().inflate(R.layout.dialog_settings, null); + EditText urlInput = dialogView.findViewById(R.id.url_input); + TextView hintView = dialogView.findViewById(R.id.url_hint); + + SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE); + String savedUrl = prefs.getString(KEY_PUBLIC_URL, ""); + urlInput.setText(savedUrl); + + hintView.setText(R.string.url_hint_text); + + builder.setView(dialogView); + builder.setPositiveButton(R.string.save, (dialog, which) -> { + String url = urlInput.getText().toString().trim(); + if (!url.isEmpty()) { + if (!url.startsWith("http://") && !url.startsWith("https://")) { + url = "https://" + url; + } + prefs.edit().putString(KEY_PUBLIC_URL, url).apply(); + loadUrl(url); + Toast.makeText(this, R.string.url_saved, Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(this, R.string.url_empty, Toast.LENGTH_SHORT).show(); + } + }); + builder.setNegativeButton(R.string.cancel, null); + builder.setCancelable(false); + builder.show(); + } + + private boolean isNetworkAvailable() { + ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo info = cm.getActiveNetworkInfo(); + return info != null && info.isConnected(); + } + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) { + webView.goBack(); + return true; + } + return super.onKeyDown(keyCode, event); + } +} diff --git a/android/app/src/main/res/drawable/ic_launcher_background.xml b/android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..34e537e --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,10 @@ + + + + diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/android/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..cc09403 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_refresh.xml b/android/app/src/main/res/drawable/ic_refresh.xml new file mode 100644 index 0000000..0aa774b --- /dev/null +++ b/android/app/src/main/res/drawable/ic_refresh.xml @@ -0,0 +1,11 @@ + + + + diff --git a/android/app/src/main/res/drawable/ic_settings.xml b/android/app/src/main/res/drawable/ic_settings.xml new file mode 100644 index 0000000..5c1a517 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_settings.xml @@ -0,0 +1,11 @@ + + + + diff --git a/android/app/src/main/res/layout/activity_main.xml b/android/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..e533eb0 --- /dev/null +++ b/android/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/res/layout/dialog_settings.xml b/android/app/src/main/res/layout/dialog_settings.xml new file mode 100644 index 0000000..ade161c --- /dev/null +++ b/android/app/src/main/res/layout/dialog_settings.xml @@ -0,0 +1,36 @@ + + + + + + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..d378acd --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..503cef1 --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + + #1565C0 + #0D47A1 + #1565C0 + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..8da9cfe --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,15 @@ + + + Meal Tracker + Refresh + Settings + Public URL + Enter the public sharing URL for your household: + Paste the link your household admin shared with you. It looks like:\nhttps://.../public/abc123... + Save + Cancel + URL saved + Please enter a URL + No network connection.\nTap to retry. + Could not load the page.\nTap to retry. + diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..ac3ab53 --- /dev/null +++ b/android/app/src/main/res/values/themes.xml @@ -0,0 +1,10 @@ + + + + diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 0000000..dbc1519 --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,3 @@ +plugins { + id 'com.android.application' version '8.5.0' apply false +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..2e11322 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +android.useAndroidX=true +android.nonTransitiveRClass=true diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..b82aa23 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 0000000..7101f8e --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@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 + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@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="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +: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 %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 0000000..39708ac --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,17 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "MealTracker" +include ':app' diff --git a/build-apk.sh b/build-apk.sh new file mode 100755 index 0000000..ce89661 --- /dev/null +++ b/build-apk.sh @@ -0,0 +1,171 @@ +#!/usr/bin/env bash +set -euo pipefail + +# ── build-apk.sh ────────────────────────────────────────────────────────────── +# Builds the Meal Tracker Android APK from the android/ directory. +# +# Usage: +# ./build-apk.sh # Build debug APK (default) +# ./build-apk.sh release # Build release APK (unsigned) +# +# Prerequisites (auto-installed if missing): +# - Java 17+ (OpenJDK) +# - Android SDK command-line tools +# - Gradle (via wrapper) +# ────────────────────────────────────────────────────────────────────────────── + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ANDROID_DIR="$SCRIPT_DIR/android" +OUTPUT_DIR="$ANDROID_DIR/app/build/outputs/apk" +SDK_ROOT="${ANDROID_SDK_ROOT:-$HOME/android-sdk}" +CMDLINE_URL="https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip" +BUILD_TOOLS_VER="34.0.0" +PLATFORM_VER="34" +GRADLE_VER="8.7" +GRADLE_URL="https://services.gradle.org/distributions/gradle-${GRADLE_VER}-bin.zip" + +BUILD_TYPE="${1:-debug}" + +# ── Colors ── +RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m' +info() { echo -e "${GREEN}[INFO]${NC} $*"; } +warn() { echo -e "${YELLOW}[WARN]${NC} $*"; } +err() { echo -e "${RED}[ERR]${NC} $*"; } + +# ── Detect package manager ── +if command -v apt-get &>/dev/null; then + PM="apt" +elif command -v yum &>/dev/null; then + PM="yum" +elif command -v dnf &>/dev/null; then + PM="dnf" +else + PM="" +fi + +# ── Install Java if needed ── +install_java() { + info "Installing Java 17..." + case "$PM" in + apt) + apt-get update -qq && apt-get install -y -qq openjdk-21-jdk-headless ;; + yum) + yum install -y java-17-openjdk-headless ;; + dnf) + dnf install -y java-17-openjdk-headless ;; + *) + err "Cannot install Java automatically. Please install Java 17+ manually." + exit 1 + ;; + esac +} + +if ! command -v java &>/dev/null; then + if [ "$PM" != "" ]; then + install_java + else + err "Java is required but not found. Install Java 17+ (OpenJDK)." + exit 1 + fi +fi + +JAVA_VER=$(java -version 2>&1 | head -1 | grep -oP '\d+' | head -1 || echo "0") +if [ "$JAVA_VER" -lt 17 ] 2>/dev/null; then + warn "Java $JAVA_VER detected. Java 17+ is recommended." +fi +info "Java: $(java -version 2>&1 | head -1)" + +# ── Install Android SDK if needed ── +install_sdk() { + info "Installing Android SDK command-line tools to $SDK_ROOT..." + mkdir -p "$SDK_ROOT" + tmp_zip="/tmp/cmdline-tools.zip" + tmp_dir="/tmp/cmdline-tools-tmp" + + if command -v wget &>/dev/null; then + wget -q --show-progress "$CMDLINE_URL" -O "$tmp_zip" + elif command -v curl &>/dev/null; then + curl -L --progress-bar "$CMDLINE_URL" -o "$tmp_zip" + else + err "Need wget or curl to download Android SDK." + exit 1 + fi + + rm -rf "$tmp_dir" + mkdir -p "$tmp_dir" + unzip -qo "$tmp_zip" -d "$tmp_dir" + mkdir -p "$SDK_ROOT/cmdline-tools" + rm -rf "$SDK_ROOT/cmdline-tools/latest" + mv "$tmp_dir/cmdline-tools" "$SDK_ROOT/cmdline-tools/latest" + rm -f "$tmp_zip" + rm -rf "$tmp_dir" + info "Android SDK command-line tools installed." +} + +if [ ! -f "$SDK_ROOT/cmdline-tools/latest/bin/sdkmanager" ]; then + install_sdk +fi + +export ANDROID_SDK_ROOT="$SDK_ROOT" + +# Accept SDK licenses +yes | "$SDK_ROOT/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null 2>&1 || true + +# ── Install required SDK packages ── +info "Checking Android SDK packages..." +"$SDK_ROOT/cmdline-tools/latest/bin/sdkmanager" \ + "platform-tools" \ + "build-tools;${BUILD_TOOLS_VER}" \ + "platforms;android-${PLATFORM_VER}" \ + > /dev/null 2>&1 || true + +# Create local.properties +cat > "$ANDROID_DIR/local.properties" </dev/null; then + wget -q --show-progress "$GRADLE_URL" -O "$gradle_zip" + else + curl -L --progress-bar "$GRADLE_URL" -o "$gradle_zip" + fi + rm -rf "$GRADLE_DIR" + mkdir -p "$GRADLE_DIR" + unzip -qo "$gradle_zip" -d "$GRADLE_DIR" + rm -f "$gradle_zip" + info "Gradle ${GRADLE_VER} ready." +fi + +# Generate wrapper in the android dir so gradlew works +if [ ! -f "$ANDROID_DIR/gradlew" ]; then + info "Generating Gradle wrapper..." + cd "$ANDROID_DIR" + "$GRADLE_BIN" wrapper --gradle-version "$GRADLE_VER" --no-daemon 2>&1 | tail -3 + cd "$SCRIPT_DIR" +fi + +# ── Build ── +info "Building $BUILD_TYPE APK..." +cd "$ANDROID_DIR" +./gradlew "assemble${BUILD_TYPE^}" --no-daemon --warning-mode=all + +# ── Report ── +APK_FILE=$(find "$OUTPUT_DIR" -name "*.apk" -type f | head -1) +if [ -f "$APK_FILE" ]; then + APK_SIZE=$(du -h "$APK_FILE" | cut -f1) + echo "" + echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" + echo -e " ${GREEN}✓ BUILD SUCCESSFUL${NC}" + echo " APK: $APK_FILE" + echo " Size: $APK_SIZE" + echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +else + err "APK not found in $OUTPUT_DIR" + exit 1 +fi