diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..64c6b47 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,3 @@ +.gradle +build +app/.cxx diff --git a/android/app/CMakeLists.txt b/android/app/CMakeLists.txt index e69de29..3c41c4d 100644 --- a/android/app/CMakeLists.txt +++ b/android/app/CMakeLists.txt @@ -0,0 +1,138 @@ +cmake_minimum_required(VERSION 3.22.1) +project(critterfolio_android LANGUAGES C CXX) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +include(ExternalProject) + +set(DEPS_INSTALL ${CMAKE_BINARY_DIR}/deps/install) + +# ExternalProject_Add spawns a completely separate CMake invocation for each +# dependency, so none of AGP's Android toolchain settings carry over +# automatically - we have to forward them explicitly to every sub-build. +set(ANDROID_TOOLCHAIN_ARGS + -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE} + -DANDROID_ABI=${ANDROID_ABI} + -DANDROID_PLATFORM=${ANDROID_PLATFORM} + -DANDROID_STL=c++_shared + -DCMAKE_BUILD_TYPE=Release + -DCMAKE_INSTALL_PREFIX=${DEPS_INSTALL} + -DCMAKE_PREFIX_PATH=${DEPS_INSTALL} + -DBUILD_SHARED_LIBS=OFF + -DCMAKE_CXX_STANDARD=17 + -DCMAKE_CXX_STANDARD_REQUIRED=ON + -DCMAKE_FIND_ROOT_PATH_MODE_PACKAGE=BOTH + -DCMAKE_FIND_ROOT_PATH_MODE_LIBRARY=BOTH + -DCMAKE_FIND_ROOT_PATH_MODE_INCLUDE=BOTH +) + +find_package(SDL3 REQUIRED CONFIG) +find_package(SDL3_image REQUIRED CONFIG) + +ExternalProject_Add(freetype_ext + GIT_REPOSITORY https://github.com/freetype/freetype.git + GIT_TAG VER-2-13-3 + CMAKE_ARGS ${ANDROID_TOOLCHAIN_ARGS} + -DFT_DISABLE_ZLIB=TRUE + -DFT_DISABLE_BZIP2=TRUE + -DFT_DISABLE_PNG=TRUE + -DFT_DISABLE_HARFBUZZ=TRUE + -DFT_DISABLE_BROTLI=TRUE +) + +ExternalProject_Add(lunasvg_ext + GIT_REPOSITORY https://github.com/sammycage/lunasvg.git + GIT_TAG v3.2.1 + CMAKE_ARGS ${ANDROID_TOOLCHAIN_ARGS} + DEPENDS freetype_ext +) + +# Lua ships no official CMakeLists, and we don't want its standalone lua/luac +# CLI targets (those need readline). We compile just the library sources. +ExternalProject_Add(lua_ext + GIT_REPOSITORY https://github.com/lua/lua.git + GIT_TAG v5.4.8 + CONFIGURE_COMMAND "" + BUILD_IN_SOURCE 1 + BUILD_COMMAND sh -c "${CMAKE_C_COMPILER} --target=${CMAKE_C_COMPILER_TARGET} --sysroot=${CMAKE_SYSROOT} -c -O2 -fPIC -DLUA_USE_POSIX $(ls *.c | grep -v -e '^lua.c$' -e '^luac.c$') && ${CMAKE_AR} rcs liblua.a *.o" + INSTALL_COMMAND ${CMAKE_COMMAND} -E make_directory ${DEPS_INSTALL}/lib ${DEPS_INSTALL}/include + COMMAND ${CMAKE_COMMAND} -E copy liblua.a ${DEPS_INSTALL}/lib/ + COMMAND ${CMAKE_COMMAND} -E copy lua.h lauxlib.h lualib.h luaconf.h ${DEPS_INSTALL}/include/ +) + +ExternalProject_Add(sqlitecpp_ext + GIT_REPOSITORY https://github.com/SRombauts/SQLiteCpp.git + GIT_TAG 3.3.3 + CMAKE_ARGS ${ANDROID_TOOLCHAIN_ARGS} + -DSQLITECPP_INTERNAL_SQLITE=ON + -DSQLITECPP_RUN_CPPLINT=OFF + -DSQLITECPP_RUN_CPPCHECK=OFF +) + +ExternalProject_Add(toml11_ext + GIT_REPOSITORY https://github.com/ToruNiina/toml11.git + GIT_TAG v3.8.1 + CMAKE_ARGS ${ANDROID_TOOLCHAIN_ARGS} +) + +ExternalProject_Add(rmlui_ext + GIT_REPOSITORY https://github.com/mikke89/RmlUi.git + GIT_TAG master + CMAKE_ARGS ${ANDROID_TOOLCHAIN_ARGS} + -DFreetype_ROOT=${DEPS_INSTALL} + -DRMLUI_LUA_BINDINGS=ON + -DRMLUI_LUA_BINDINGS_LIBRARY=lua + -DRMLUI_SVG_PLUGIN=ON + -DRMLUI_SAMPLES=OFF + -DBUILD_TESTING=OFF + DEPENDS freetype_ext lunasvg_ext lua_ext +) + +set(PROJECT_SRC_DIR ${CMAKE_SOURCE_DIR}/../../src) +set(RMLUI_BACKEND_DIR ${CMAKE_SOURCE_DIR}/../../vendor/rmlui_backend) + +add_library(critterfolio SHARED + ${PROJECT_SRC_DIR}/main.cpp + ${PROJECT_SRC_DIR}/database.cpp + ${PROJECT_SRC_DIR}/ui.cpp + ${PROJECT_SRC_DIR}/image_utils.cpp + ${RMLUI_BACKEND_DIR}/RmlUi_Backend_SDL_SDLrenderer.cpp + ${RMLUI_BACKEND_DIR}/RmlUi_Platform_SDL.cpp + ${RMLUI_BACKEND_DIR}/RmlUi_Renderer_SDL.cpp +) + +add_dependencies(critterfolio freetype_ext lunasvg_ext lua_ext sqlitecpp_ext toml11_ext rmlui_ext) + +target_include_directories(critterfolio PRIVATE + ${PROJECT_SRC_DIR} + ${RMLUI_BACKEND_DIR} + ${DEPS_INSTALL}/include +) + +target_compile_definitions(critterfolio PRIVATE + RMLUI_SDL_VERSION_MAJOR=3 + RMLUI_STATIC_LIB +) + +# Linked by explicit path rather than find_package(), since find_package() +# runs during THIS configure pass - before any ExternalProject_Add step +# above has actually built or installed anything (those only run later, +# during the actual build). This is what the superbuild pattern is for. +target_link_directories(critterfolio PRIVATE ${DEPS_INSTALL}/lib) + +target_link_libraries(critterfolio PRIVATE + SDL3::SDL3 + SDL3_image::SDL3_image + rmlui + rmlui_debugger + rmlui_lua + lua + freetype + lunasvg + plutovg + SQLiteCpp + sqlite3 +) + +target_link_options(critterfolio PRIVATE "-Wl,-u,SDL_main") diff --git a/android/buildlog.txt b/android/buildlog.txt new file mode 100644 index 0000000..0aa846a --- /dev/null +++ b/android/buildlog.txt @@ -0,0 +1,47 @@ +> Task :app:preBuild UP-TO-DATE +> Task :app:preDebugBuild UP-TO-DATE +> Task :app:mergeDebugNativeDebugMetadata NO-SOURCE +> Task :app:javaPreCompileDebug UP-TO-DATE +> Task :app:checkDebugAarMetadata UP-TO-DATE +> Task :app:generateDebugResValues UP-TO-DATE +> Task :app:mapDebugSourceSetPaths UP-TO-DATE +> Task :app:generateDebugResources UP-TO-DATE +> Task :app:mergeDebugResources UP-TO-DATE +> Task :app:packageDebugResources UP-TO-DATE +> Task :app:parseDebugLocalResources UP-TO-DATE +> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE +> Task :app:extractDeepLinksDebug UP-TO-DATE +> Task :app:processDebugMainManifest UP-TO-DATE +> Task :app:processDebugManifest UP-TO-DATE +> Task :app:processDebugManifestForPackage UP-TO-DATE +> Task :app:processDebugResources UP-TO-DATE +> Task :app:compileDebugJavaWithJavac UP-TO-DATE +> Task :app:mergeDebugShaders UP-TO-DATE +> Task :app:compileDebugShaders NO-SOURCE +> Task :app:generateDebugAssets UP-TO-DATE +> Task :app:mergeDebugAssets UP-TO-DATE +> Task :app:compressDebugAssets UP-TO-DATE +> Task :app:desugarDebugFileDependencies UP-TO-DATE +> Task :app:dexBuilderDebug UP-TO-DATE +> Task :app:mergeDebugGlobalSynthetics UP-TO-DATE +> Task :app:processDebugJavaRes NO-SOURCE +> Task :app:mergeDebugJavaResource UP-TO-DATE +> Task :app:checkDebugDuplicateClasses UP-TO-DATE +> Task :app:mergeDebugStartupProfile UP-TO-DATE +> Task :app:mergeExtDexDebug UP-TO-DATE +> Task :app:mergeLibDexDebug UP-TO-DATE +> Task :app:mergeProjectDexDebug UP-TO-DATE +> Task :app:configureCMakeDebug[arm64-v8a] +> Task :app:buildCMakeDebug[arm64-v8a] +> Task :app:mergeDebugJniLibFolders UP-TO-DATE +> Task :app:validateSigningDebug UP-TO-DATE +> Task :app:writeDebugAppMetadata UP-TO-DATE +> Task :app:writeDebugSigningConfigVersions UP-TO-DATE +> Task :app:mergeDebugNativeLibs +> Task :app:stripDebugDebugSymbols +> Task :app:packageDebug +> Task :app:createDebugApkListingFileRedirect UP-TO-DATE +> Task :app:assembleDebug + +BUILD SUCCESSFUL in 9s +37 actionable tasks: 5 executed, 32 up-to-date diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 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..23d15a9 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,251 @@ +#!/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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/platforms/jvm/plugins-application/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 -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || 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="\\\"\\\"" + + +# 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, 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" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# 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..db3a6ac --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,94 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +: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/flake.nix b/flake.nix index 3b915d0..0650c23 100644 --- a/flake.nix +++ b/flake.nix @@ -80,6 +80,7 @@ buildToolsVersions = [ "34.0.0" ]; includeNDK = true; ndkVersions = [ ndkVersion ]; + cmakeVersions = [ "3.22.1" ]; abiVersions = [ "arm64-v8a" ]; includeEmulator = false; }; diff --git a/src/asset_io.hpp b/src/asset_io.hpp new file mode 100644 index 0000000..0fd76fb --- /dev/null +++ b/src/asset_io.hpp @@ -0,0 +1,16 @@ +#pragma once + +#include +#include + +inline SDL_IOStream *OpenAssetFile(const std::string &virtual_path) { + std::string resolved = virtual_path; +#if defined(__ANDROID__) + if (resolved.rfind("./assets/", 0) == 0) { + resolved = resolved.substr(9); + } else if (resolved.rfind("assets/", 0) == 0) { + resolved = resolved.substr(7); + } +#endif + return SDL_IOFromFile(resolved.c_str(), "rb"); +} \ No newline at end of file diff --git a/src/database.cpp b/src/database.cpp index 751ecfd..7c4489f 100644 --- a/src/database.cpp +++ b/src/database.cpp @@ -1,10 +1,68 @@ #include "database.hpp" +#include "asset_io.hpp" #include +#include #include +#include + +std::string get_writable_db_path() { + char *pref = SDL_GetPrefPath("Critterfolio", "CritterFolio"); + std::string path = pref ? pref : "./"; + if (pref) { + SDL_free(pref); + } + path += "local.db"; + return path; +} + +bool ensure_db_copied() { + std::string dest_path = get_writable_db_path(); + + SDL_IOStream *check = SDL_IOFromFile(dest_path.c_str(), "rb"); + if (check) { + SDL_CloseIO(check); + return true; + } + + SDL_IOStream *src = OpenAssetFile("./assets/local.db"); + if (!src) { + std::cout << "[ERROR] Could not open seed database in assets: " << SDL_GetError() << "\n"; + return false; + } + + Sint64 size = SDL_GetIOSize(src); + if (size < 0) { + std::cout << "[ERROR] Could not determine seed database size.\n"; + SDL_CloseIO(src); + return false; + } + + std::vector buffer(static_cast(size)); + if (SDL_ReadIO(src, buffer.data(), buffer.size()) != buffer.size()) { + std::cout << "[ERROR] Failed reading seed database.\n"; + SDL_CloseIO(src); + return false; + } + SDL_CloseIO(src); + + SDL_IOStream *dst = SDL_IOFromFile(dest_path.c_str(), "wb"); + if (!dst) { + std::cout << "[ERROR] Could not open destination database for writing: " << SDL_GetError() << "\n"; + return false; + } + + bool ok = SDL_WriteIO(dst, buffer.data(), buffer.size()) == buffer.size(); + SDL_CloseIO(dst); + + if (!ok) { + std::cout << "[ERROR] Failed writing copied database.\n"; + } + return ok; +} bool db_get_all_critters(std::map &critters) { try { - SQLite::Database db("./assets/local.db", SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE); + SQLite::Database db(get_writable_db_path(), SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE); SQLite::Statement q(db, "SELECT * FROM critters"); critters.clear(); @@ -34,7 +92,7 @@ bool db_get_all_critters(std::map &critters) { bool db_add_critter(const Critter &c, int &out_id) { try { - SQLite::Database db("./assets/local.db", SQLite::OPEN_READWRITE); + SQLite::Database db(get_writable_db_path(), SQLite::OPEN_READWRITE); SQLite::Statement q(db, "INSERT INTO critters (name, gender, mother_id, father_id, notes, species) VALUES (?, ?, ?, ?, ?, ?)"); q.bind(1, c.name); @@ -56,7 +114,7 @@ bool db_add_critter(const Critter &c, int &out_id) { bool db_delete_critter(int id) { try { - SQLite::Database db("./assets/local.db", SQLite::OPEN_READWRITE); + SQLite::Database db(get_writable_db_path(), SQLite::OPEN_READWRITE); SQLite::Statement q(db, "DELETE FROM critters WHERE id = ?"); q.bind(1, id); q.exec(); diff --git a/src/database.hpp b/src/database.hpp index 34d0895..2004bfc 100644 --- a/src/database.hpp +++ b/src/database.hpp @@ -4,6 +4,8 @@ #include #include +std::string get_writable_db_path(); +bool ensure_db_copied(); bool db_get_all_critters(std::map &critters); bool db_add_critter(const Critter &c, int &out_id); bool db_delete_critter(int id); diff --git a/src/main.cpp b/src/main.cpp index 96c53d6..09ca9df 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,9 +1,11 @@ #include "critter.hpp" #include "database.hpp" #include "ui.hpp" +#include "sdl_file_interface.hpp" #include "../vendor/stb/stb_image.h" #include "../vendor/stb/stb_image_write.h" #include +#include #include #include #include @@ -19,6 +21,7 @@ static std::map critters; static std::vector critter_list; static Rml::ElementDocument *doc; static AppData app_data; +static SDLFileInterface file_interface; void shutdown() { Rml::Shutdown(); Backend::Shutdown(); @@ -36,8 +39,14 @@ bool initialize() { std::cout << "[INFO] RmlUI Backend initialized.\n"; Rml::SetSystemInterface(Backend::GetSystemInterface()); Rml::SetRenderInterface(Backend::GetRenderInterface()); + Rml::SetFileInterface(&file_interface); Rml::Initialise(); Rml::Lua::Initialise(); + std::cout << "[INFO] Preparing local DB...\n"; + if (!ensure_db_copied()) { + std::cout << "[ERROR] Could not prepare local DB.\n"; + return false; + } std::cout << "[INFO] Loading local DB...\n"; if (!db_get_all_critters(critters)) { std::cout << "[ERROR] Local DB failed to initialize.\n"; @@ -83,7 +92,6 @@ bool f8_was_pressed = false; void handle_input() { const bool *state = SDL_GetKeyboardState(NULL); if (state) { - // Reload ui bool f5_state = state[SDL_SCANCODE_F5]; if (f5_state && !f5_was_pressed) { f5_was_pressed = true; @@ -91,7 +99,6 @@ void handle_input() { } else if (!f5_state) { f5_was_pressed = false; } - // Toggle debugger window bool f8_state = state[SDL_SCANCODE_F8]; if (f8_state && !f8_was_pressed) { f8_was_pressed = true; @@ -102,7 +109,7 @@ void handle_input() { } } } -int main() { +int main(int arc, char *argv[]) { std::cout << "[INFO] Starting CritterFolio...\n"; is_initalized = initialize(); if (!is_initalized) { @@ -121,7 +128,7 @@ int main() { return 1; } std::cout << "[INFO] Main page loaded.\n"; - + while (is_running) { is_running = Backend::ProcessEvents(ctx); handle_input(); diff --git a/src/sdl_file_interface.hpp b/src/sdl_file_interface.hpp new file mode 100644 index 0000000..c8cb682 --- /dev/null +++ b/src/sdl_file_interface.hpp @@ -0,0 +1,37 @@ +#pragma once + +#include "asset_io.hpp" +#include +#include + +class SDLFileInterface : public Rml::FileInterface { +public: + Rml::FileHandle Open(const Rml::String &path) override { + SDL_IOStream *io = OpenAssetFile(path); + return reinterpret_cast(io); + } + + void Close(Rml::FileHandle file) override { + SDL_CloseIO(reinterpret_cast(file)); + } + + size_t Read(void *buffer, size_t size, Rml::FileHandle file) override { + return SDL_ReadIO(reinterpret_cast(file), buffer, size); + } + + bool Seek(Rml::FileHandle file, long offset, int origin) override { + SDL_IOWhence whence = SDL_IO_SEEK_SET; + if (origin == SEEK_CUR) whence = SDL_IO_SEEK_CUR; + else if (origin == SEEK_END) whence = SDL_IO_SEEK_END; + + return SDL_SeekIO(reinterpret_cast(file), offset, whence) >= 0; + } + + size_t Tell(Rml::FileHandle file) override { + return static_cast(SDL_TellIO(reinterpret_cast(file))); + } + + size_t Length(Rml::FileHandle file) override { + return static_cast(SDL_GetIOSize(reinterpret_cast(file))); + } +}; \ No newline at end of file