:zap: [Android Library] Play with sensor events & detect gestures in a breeze.
| Files | Last commit | Last update |
|---|---|---|
Update: 6 (#65) * updated readme * docs: sync usage docs with current API - overview.md: replace deprecated static API calls (Sensey.register, Sensey.unregister) with instance-based senseyRegister DSL - taponback.md: fix minJerk default from 5f to 2f - turnover.md: fix angleThreshold default from 130f to 150f - _index files: add links for new gestures (Clap, DeviceSpin, RaiseToEar, TurnOver) - movement.md: update event descriptions - clap.md, devicespin.md, raisetoear.md, turnover.md: add documentation for new gesture plugins * feat(internal): add core internal utilities and audio capture infra - EmaSmoother: single-pole exponential moving average filter for sensor data smoothing - GyroIntegrator: cumulative gyroscope integration for turnover and device-spin detection - Util: helper functions (magnitude3, angleBetweenDeg, linearAccelMag) - AudioCapture: generic coroutine-based AudioRecord wrapper shared by SoundLevelDetector and ClapDetector; uses getMinBufferSize for buffer allocation instead of hardcoded sizes * feat(gesture): add Clap, DeviceSpin, RaiseToEar, TurnOver detectors - ClapDetector/ClapTrigger: detects clap sounds via AudioRecord RMS energy rise detection (thresholdDb, riseDb params) - DeviceSpinDetector/DeviceSpinTrigger: detects rapid device rotation on any axis using gyro integration - RaiseToEarDetector/RaiseToEarTrigger: fuses proximity + gravity sensor to detect phone-at-ear position for calls - TurnOverEvent/TurnOverTrigger: gyroscope-based 180-degree flip detection (more precise than accel-based Flip plugin) - TapOnBackDetector/TapOnBackTrigger: double-tap detection using linear acceleration magnitude with EMA jerk filtering * feat(gesture): wire new gestures into plugin registry and DSL - Add turnOverPlugin, deviceSpinPlugin, raiseToEarPlugin, clapPlugin to top-level gesture DSL functions - Add corresponding builder methods to SenseyPluginRegistry - SoundLevelPlugin and ClapPlugin: add RECORD_AUDIO permission check on register with graceful disable if not granted - Refactor internal plugin classes (SensorGesturePlugin, SoundLevelPlugin, ClapPlugin) for consistency * refactor(trigger): improve detection algorithms across gestures - ChopTrigger: adjust threshold defaults, add EMA smoothing for impulse detection - MovementTrigger: refine stationary timeout logic, improve direction reporting accuracy - PinchScaleTrigger: add confirmation count for debounce against jittery touch input - WristTwistTrigger: tuning defaults for wrist-twist motion profile * refactor(soundlevel): delegate to shared AudioCapture - SoundLevelDetector now delegates audio recording to the shared AudioCapture<T> internal class instead of duplicating AudioRecord lifecycle, coroutine scope, and buffer management - Reduces SoundLevelDetector from ~130 lines to ~15 lines * test: add tests for new gestures and fix existing tests - Add ClapTriggerTest: RMS energy rise detection - Add DeviceSpinTriggerTest: gyro angle threshold detection - Add RaiseToEarTriggerTest and RaiseToEarDetectorTest: proximity + gravity fusion - Add TapOnBackDetectorTest: double-tap with EMA jerk - Add TurnOverTriggerTest: gyro-based flip detection - Add EmaSmootherTest and UtilTest for internal utilities - Fix ChopDetectorTest, WristTwistDetectorTest, PickupDeviceTriggerTest for updated trigger signatures * refactor(sample): extract permission logic into PermissionRequestUtil - PermissionRequestUtil: generic permission request utility with register() / isGranted() / requestIfNeeded() methods - Audio-specific extensions: registerAudioPermission(), isAudioPermissionGranted(), requestAudioIfNeeded() - MainActivity: use PermissionRequestUtil, register touch/pinch plugins via senseyRegister in onCreate, remove stale hasRecordAudioPermission caching * feat(sample): unify touch/pinch sensors, add pending permission flow - Add TOUCH_DETECTION and PINCH_SCALE to sensors list with createPlugin entries using touchTypePlugin/pinchScalePlugin - Add pendingSensor + startAfterPermissionGranted() with sensey==null guard for deferred permission handling - Add clearPendingPermission() for denial recovery - Add resultsMap with per-sensor result text and auto-clear after 2s (3s for touch/pinch) * refactor(sample): merge touch/pinch into main screen, remove TouchActivity * chore(sample): remove TouchActivity from manifest * docs: update architecture and setup for new gestures and AudioCapture - architecture.md: add AudioCapture, EmaSmoother, GyroIntegrator to internal/ listing; list all 22 gesture directories explicitly - setup.md: add eager-initialization pattern for Compose apps that need senseyGestures() to work during initial composition * feat(gesture): add EdgeSwipe — detect swipes from composable edges - EdgeSwipeEvent/EdgeSwipeTrigger: pure detection logic, reports which composable edge (LEFT/RIGHT/TOP/BOTTOM) the swipe originated from - EdgeSwipePlugin: Compose touch plugin using detectDragGestures; edgeThresholdDp is accepted as Dp (not raw pixels) and converted to px via Density for density-independent edge detection - Supports all four edges enabled by default; configure via edgeThresholdDp and enabledEdges parameters - Sample app: Edge Swipe sensor entry with SenseyRadioButtonWithTouchArea - Docs: edgeswipe.md with events, parameters, usage, and use cases * feat(gesture): add DiagonalSwipe — detect diagonal drags in composable - DiagonalSwipeEvent/DiagonalSwipeTrigger: pure logic using atan2 angle classification; reports UP_RIGHT, DOWN_RIGHT, DOWN_LEFT, UP_LEFT directions - Configurable minDragDistance and angleToleranceDeg (default 22.5°) - DiagonalSwipePlugin: Compose touch plugin using detectDragGestures - Sample app: Diagonal Swipe sensor entry with hit area - Docs: diagonalswipe.md with events, parameters, usage * ktlint format * refactor(sample): use SensorList composable, move touch handling inside it - SensorList now detects touch labels and renders SenseyRadioButtonWithTouchArea for touch/gesture sensors, SenseyRadioButton for all others - MainScreen simplified to just layout shell: Surface → Column(AppHeader, Box(SensorList)) * feat(sample): add SenseyTheme/PreviewTheme, remove hardcoded Colors.kt - Theme.kt: DarkColorScheme + LightColorScheme with orange/cyan/pink accents; SenseyTheme switches via isSystemInDarkTheme(); PreviewTheme wraps with Surface + background color + padding for previews - Colors.kt deleted — all color references replaced with MaterialTheme.colorScheme - MainActivity: wrap content in SenseyTheme * refactor(sample): simplify MainScreen, move touch logic into SensorList - MainScreen: reduced to layout shell (Surface → Column → AppHeader + Box → SensorList); all sensor rendering logic removed - SensorList: now handles both regular sensors (SenseyRadioButton) and touch-based sensors (SenseyRadioButtonWithTouchArea) with helper text mapping extracted into helperTextForLabel() - SenseyRadioButton/SenseyRadioButtonWithTouchArea: replace hardcoded colors with MaterialTheme.colorScheme references * fix(sample): Material3 TopAppBar header, ResultArea with fixed height - AppHeader: replace custom Surface/Text/Divider with CenterAlignedTopAppBar using topAppBarColors for proper insets, elevation, and typography - ResultArea: add .height(120.dp) for defined touch target and RoundedCornerShape(8.dp); all 4 previews use PreviewTheme * fix color * Add coroutines/flow support for gesture event collection - Add SenseyFlowScope with lifecycle-aware callbackFlow bridging - Add SenseyFlowEffect Compose wrapper using DisposableEffect - Add observe() default method to GestureTrigger interface - Add MockK and Turbine test dependencies - Add GestureTriggerFlowTest and SenseyFlowScopeTest - Update docs with flow API usage and architecture details * deps: remove unused catalog entries and switch to compileOnly Remove androidx-core-ktx and androidx-annotation (unused in source). Switch lifecycle-common, coroutines-core, coroutines-android, and all compose deps from implementation to compileOnly. Add lifecycle-runtime for test usage. * sample: add explicit deps for compileOnly libraries Lifecycle and coroutines are no longer transitively bundled by sensey. Add them explicitly in the sample app. * fix: resolve pre-existing test failures MovementTrigger: remove hasBaseline guard so first reading is not discarded. ScoopTrigger: reduce baselineSamples to 0 and minSustainedSamples to 1 for immediate response; set debounceMs to 0 and use >= for debounce check. Tests: align assertions with actual trigger behavior for direction ambiguity, partial magnitude conditions, infinite audio input, and mock proximity events. * docs: update for compileOnly dependencies Clarify that dependencies are not bundled transitively and consumers most likely already have them. Add dependency table mapping features to required libraries. * docs: add explicit dependency coordinates to setup guide Show the exact artifact coordinates under each bullet so users know what to include if they don't already have the dependency. * refactor: use Dispatchers.Default instead of Dispatchers.Main SenseyFlow scope and AudioCapture callback both used Dispatchers.Main. Switch to Default — sensor/audio processing and user callbacks are not UI-specific work. Drop kotlinx-coroutines-android entirely as no longer needed. * chore: remove unused kotlinx-coroutines-android catalog entry No longer referenced after switching to Dispatchers.Default. * feat: implement NodGesture gesture detection Add NodGestureTrigger and NodGestureEvent for detecting nod (yes) gestures using gyroscope pitch oscillation via GyroIntegrator. * feat: implement HeadShake gesture detection Add HeadShakeTrigger and HeadShakeEvent for detecting head shake (no) gestures using gyroscope yaw oscillation via GyroIntegrator. * test: add tests for NodGesture trigger Add NodGestureTriggerTest covering nod detection, debounce, cooldown, and noise suppression. * test: add tests for HeadShake trigger Add HeadShakeTriggerTest covering head shake detection, debounce, cooldown, and noise suppression. * feat: register NodGesture and HeadShake in plugin system Add nodGesturePlugin() and headShakePlugin() factory functions in GesturePlugins.kt, registration methods in SenseyPluginRegistry, and flow builder methods in SenseyFlowScope. Both use GyroIntegrator-based triggers. * feat: overhaul ClapTrigger with ZCR weighting, adaptive noise floor, and multi-clap counting Replaces old rise-dB threshold logic with a multi-stage pipeline:\n- ZCR-weighted RMS to reject narrow-band sounds (speech, music)\n- Adaptive noise floor with fast-attack/slow-release EMA\n- Multi-clap counting within configurable rolling time window\n- Configurable debounce to prevent re-trigger\n- Updated defaults: thresholdDb=-45f, requiredClaps=2, clapTimeframeMs=800L\n- Updated docs with new parameters and tuning tips * refactor: improve SoundLevelTrigger and AudioCapture error handling - SoundLevelTrigger: extract helper methods, add offset parameter with docs, fix constant naming\n- AudioCapture: handle CancellationException and SecurityException gracefully\n- AndroidManifest: remove maxSdkVersion=32 from RECORD_AUDIO so manifest targets all API levels\n- soundlevel.md: add parameters table, interpretation guide, and algorithm details * fix: add debounce to ChopTrigger, tune default threshold - Add cooldown check to prevent chop re-trigger within the gesture window\n- Raise default threshold from 25f to 35f to reduce false positives\n- Update chop.md with new default and 'How to perform' section * fix: use Modifier.pointerInput in sensey gesture modifier Fix dangling .pointerInput(Unit) call by chaining it as Modifier.pointerInput(Unit) within the compose modifier chain. * feat: update sample app with NodGesture, HeadShake, sensor availability check, and snackbar - Add NodGesture and HeadShake to sensor list with dispatchers\n- Add isSensorAvailable() check with snackbar notification for missing sensors\n- Refactor MainScreen to use Scaffold with SnackbarHost for feedback\n- Remove unused HapticUtil.confirmation()\n- Use SAMPLING_PERIOD_GAME for lower-latency sensor updates * chore: add git hooks install task to build Add installGitHooks Gradle task that sets core.hooksPath to .githooks, running ktlintFormat on each commit. * docs: update README with NodGesture and HeadShake Add NodGesture and HeadShake to the gesture list. Update coroutines/flow note to be more general. * docs: add NodGesture and HeadShake documentation pages Add new gesture documentation pages for NodGesture (nod 'yes') and HeadShake (shake 'no') with algorithm details, parameters, events, and usage examples. Update _index.md to list both. * docs: add 'How to perform' section to 7 gesture pages Add 'How to perform' section with user-facing descriptions to: DeviceSpin, DiagonalSwipe, EdgeSwipe, Flip, Light, Movement, Orientation. * docs: add 'How to perform' section to 7 gesture pages Add 'How to perform' section with user-facing descriptions to: PickupDevice, PinchScale, Proximity, RaiseToEar, RotationAngle, Scoop, Shake. * docs: add 'How to perform' section to 7 gesture pages Add 'How to perform' section with user-facing descriptions to: Step, TapOnBack, TiltDirection, TouchType, TurnOver, Wave, WristTwist. * chore: add pre-commit hook for ktlintFormat Add .githooks/pre-commit that runs ./gradlew ktlintFormat on every commit to enforce Kotlin formatting. * fix: detect head shake on combined Y+Z axes for tilted device When phone is held tilted (top higher), 'no' head shake projects onto both Y and Z axes. Previously only Z was tracked, missing half the signal. Fix: combine Y+Z into an effective horizontal angle. Works at any pitch angle. * docs: update HeadShake doc for combined Y+Z axis detection Update algorithm description from Z-only to combined Y+Z axes. Mention tilt-agnostic behavior in How to perform. Update parameter description to reflect horizontal rotation metric. * ci: add PR Check workflow with test, ktlint, and lint steps * update branch in pr-check workflow | 5 months ago | |
Update: 6 (#65) * updated readme * docs: sync usage docs with current API - overview.md: replace deprecated static API calls (Sensey.register, Sensey.unregister) with instance-based senseyRegister DSL - taponback.md: fix minJerk default from 5f to 2f - turnover.md: fix angleThreshold default from 130f to 150f - _index files: add links for new gestures (Clap, DeviceSpin, RaiseToEar, TurnOver) - movement.md: update event descriptions - clap.md, devicespin.md, raisetoear.md, turnover.md: add documentation for new gesture plugins * feat(internal): add core internal utilities and audio capture infra - EmaSmoother: single-pole exponential moving average filter for sensor data smoothing - GyroIntegrator: cumulative gyroscope integration for turnover and device-spin detection - Util: helper functions (magnitude3, angleBetweenDeg, linearAccelMag) - AudioCapture: generic coroutine-based AudioRecord wrapper shared by SoundLevelDetector and ClapDetector; uses getMinBufferSize for buffer allocation instead of hardcoded sizes * feat(gesture): add Clap, DeviceSpin, RaiseToEar, TurnOver detectors - ClapDetector/ClapTrigger: detects clap sounds via AudioRecord RMS energy rise detection (thresholdDb, riseDb params) - DeviceSpinDetector/DeviceSpinTrigger: detects rapid device rotation on any axis using gyro integration - RaiseToEarDetector/RaiseToEarTrigger: fuses proximity + gravity sensor to detect phone-at-ear position for calls - TurnOverEvent/TurnOverTrigger: gyroscope-based 180-degree flip detection (more precise than accel-based Flip plugin) - TapOnBackDetector/TapOnBackTrigger: double-tap detection using linear acceleration magnitude with EMA jerk filtering * feat(gesture): wire new gestures into plugin registry and DSL - Add turnOverPlugin, deviceSpinPlugin, raiseToEarPlugin, clapPlugin to top-level gesture DSL functions - Add corresponding builder methods to SenseyPluginRegistry - SoundLevelPlugin and ClapPlugin: add RECORD_AUDIO permission check on register with graceful disable if not granted - Refactor internal plugin classes (SensorGesturePlugin, SoundLevelPlugin, ClapPlugin) for consistency * refactor(trigger): improve detection algorithms across gestures - ChopTrigger: adjust threshold defaults, add EMA smoothing for impulse detection - MovementTrigger: refine stationary timeout logic, improve direction reporting accuracy - PinchScaleTrigger: add confirmation count for debounce against jittery touch input - WristTwistTrigger: tuning defaults for wrist-twist motion profile * refactor(soundlevel): delegate to shared AudioCapture - SoundLevelDetector now delegates audio recording to the shared AudioCapture<T> internal class instead of duplicating AudioRecord lifecycle, coroutine scope, and buffer management - Reduces SoundLevelDetector from ~130 lines to ~15 lines * test: add tests for new gestures and fix existing tests - Add ClapTriggerTest: RMS energy rise detection - Add DeviceSpinTriggerTest: gyro angle threshold detection - Add RaiseToEarTriggerTest and RaiseToEarDetectorTest: proximity + gravity fusion - Add TapOnBackDetectorTest: double-tap with EMA jerk - Add TurnOverTriggerTest: gyro-based flip detection - Add EmaSmootherTest and UtilTest for internal utilities - Fix ChopDetectorTest, WristTwistDetectorTest, PickupDeviceTriggerTest for updated trigger signatures * refactor(sample): extract permission logic into PermissionRequestUtil - PermissionRequestUtil: generic permission request utility with register() / isGranted() / requestIfNeeded() methods - Audio-specific extensions: registerAudioPermission(), isAudioPermissionGranted(), requestAudioIfNeeded() - MainActivity: use PermissionRequestUtil, register touch/pinch plugins via senseyRegister in onCreate, remove stale hasRecordAudioPermission caching * feat(sample): unify touch/pinch sensors, add pending permission flow - Add TOUCH_DETECTION and PINCH_SCALE to sensors list with createPlugin entries using touchTypePlugin/pinchScalePlugin - Add pendingSensor + startAfterPermissionGranted() with sensey==null guard for deferred permission handling - Add clearPendingPermission() for denial recovery - Add resultsMap with per-sensor result text and auto-clear after 2s (3s for touch/pinch) * refactor(sample): merge touch/pinch into main screen, remove TouchActivity * chore(sample): remove TouchActivity from manifest * docs: update architecture and setup for new gestures and AudioCapture - architecture.md: add AudioCapture, EmaSmoother, GyroIntegrator to internal/ listing; list all 22 gesture directories explicitly - setup.md: add eager-initialization pattern for Compose apps that need senseyGestures() to work during initial composition * feat(gesture): add EdgeSwipe — detect swipes from composable edges - EdgeSwipeEvent/EdgeSwipeTrigger: pure detection logic, reports which composable edge (LEFT/RIGHT/TOP/BOTTOM) the swipe originated from - EdgeSwipePlugin: Compose touch plugin using detectDragGestures; edgeThresholdDp is accepted as Dp (not raw pixels) and converted to px via Density for density-independent edge detection - Supports all four edges enabled by default; configure via edgeThresholdDp and enabledEdges parameters - Sample app: Edge Swipe sensor entry with SenseyRadioButtonWithTouchArea - Docs: edgeswipe.md with events, parameters, usage, and use cases * feat(gesture): add DiagonalSwipe — detect diagonal drags in composable - DiagonalSwipeEvent/DiagonalSwipeTrigger: pure logic using atan2 angle classification; reports UP_RIGHT, DOWN_RIGHT, DOWN_LEFT, UP_LEFT directions - Configurable minDragDistance and angleToleranceDeg (default 22.5°) - DiagonalSwipePlugin: Compose touch plugin using detectDragGestures - Sample app: Diagonal Swipe sensor entry with hit area - Docs: diagonalswipe.md with events, parameters, usage * ktlint format * refactor(sample): use SensorList composable, move touch handling inside it - SensorList now detects touch labels and renders SenseyRadioButtonWithTouchArea for touch/gesture sensors, SenseyRadioButton for all others - MainScreen simplified to just layout shell: Surface → Column(AppHeader, Box(SensorList)) * feat(sample): add SenseyTheme/PreviewTheme, remove hardcoded Colors.kt - Theme.kt: DarkColorScheme + LightColorScheme with orange/cyan/pink accents; SenseyTheme switches via isSystemInDarkTheme(); PreviewTheme wraps with Surface + background color + padding for previews - Colors.kt deleted — all color references replaced with MaterialTheme.colorScheme - MainActivity: wrap content in SenseyTheme * refactor(sample): simplify MainScreen, move touch logic into SensorList - MainScreen: reduced to layout shell (Surface → Column → AppHeader + Box → SensorList); all sensor rendering logic removed - SensorList: now handles both regular sensors (SenseyRadioButton) and touch-based sensors (SenseyRadioButtonWithTouchArea) with helper text mapping extracted into helperTextForLabel() - SenseyRadioButton/SenseyRadioButtonWithTouchArea: replace hardcoded colors with MaterialTheme.colorScheme references * fix(sample): Material3 TopAppBar header, ResultArea with fixed height - AppHeader: replace custom Surface/Text/Divider with CenterAlignedTopAppBar using topAppBarColors for proper insets, elevation, and typography - ResultArea: add .height(120.dp) for defined touch target and RoundedCornerShape(8.dp); all 4 previews use PreviewTheme * fix color * Add coroutines/flow support for gesture event collection - Add SenseyFlowScope with lifecycle-aware callbackFlow bridging - Add SenseyFlowEffect Compose wrapper using DisposableEffect - Add observe() default method to GestureTrigger interface - Add MockK and Turbine test dependencies - Add GestureTriggerFlowTest and SenseyFlowScopeTest - Update docs with flow API usage and architecture details * deps: remove unused catalog entries and switch to compileOnly Remove androidx-core-ktx and androidx-annotation (unused in source). Switch lifecycle-common, coroutines-core, coroutines-android, and all compose deps from implementation to compileOnly. Add lifecycle-runtime for test usage. * sample: add explicit deps for compileOnly libraries Lifecycle and coroutines are no longer transitively bundled by sensey. Add them explicitly in the sample app. * fix: resolve pre-existing test failures MovementTrigger: remove hasBaseline guard so first reading is not discarded. ScoopTrigger: reduce baselineSamples to 0 and minSustainedSamples to 1 for immediate response; set debounceMs to 0 and use >= for debounce check. Tests: align assertions with actual trigger behavior for direction ambiguity, partial magnitude conditions, infinite audio input, and mock proximity events. * docs: update for compileOnly dependencies Clarify that dependencies are not bundled transitively and consumers most likely already have them. Add dependency table mapping features to required libraries. * docs: add explicit dependency coordinates to setup guide Show the exact artifact coordinates under each bullet so users know what to include if they don't already have the dependency. * refactor: use Dispatchers.Default instead of Dispatchers.Main SenseyFlow scope and AudioCapture callback both used Dispatchers.Main. Switch to Default — sensor/audio processing and user callbacks are not UI-specific work. Drop kotlinx-coroutines-android entirely as no longer needed. * chore: remove unused kotlinx-coroutines-android catalog entry No longer referenced after switching to Dispatchers.Default. * feat: implement NodGesture gesture detection Add NodGestureTrigger and NodGestureEvent for detecting nod (yes) gestures using gyroscope pitch oscillation via GyroIntegrator. * feat: implement HeadShake gesture detection Add HeadShakeTrigger and HeadShakeEvent for detecting head shake (no) gestures using gyroscope yaw oscillation via GyroIntegrator. * test: add tests for NodGesture trigger Add NodGestureTriggerTest covering nod detection, debounce, cooldown, and noise suppression. * test: add tests for HeadShake trigger Add HeadShakeTriggerTest covering head shake detection, debounce, cooldown, and noise suppression. * feat: register NodGesture and HeadShake in plugin system Add nodGesturePlugin() and headShakePlugin() factory functions in GesturePlugins.kt, registration methods in SenseyPluginRegistry, and flow builder methods in SenseyFlowScope. Both use GyroIntegrator-based triggers. * feat: overhaul ClapTrigger with ZCR weighting, adaptive noise floor, and multi-clap counting Replaces old rise-dB threshold logic with a multi-stage pipeline:\n- ZCR-weighted RMS to reject narrow-band sounds (speech, music)\n- Adaptive noise floor with fast-attack/slow-release EMA\n- Multi-clap counting within configurable rolling time window\n- Configurable debounce to prevent re-trigger\n- Updated defaults: thresholdDb=-45f, requiredClaps=2, clapTimeframeMs=800L\n- Updated docs with new parameters and tuning tips * refactor: improve SoundLevelTrigger and AudioCapture error handling - SoundLevelTrigger: extract helper methods, add offset parameter with docs, fix constant naming\n- AudioCapture: handle CancellationException and SecurityException gracefully\n- AndroidManifest: remove maxSdkVersion=32 from RECORD_AUDIO so manifest targets all API levels\n- soundlevel.md: add parameters table, interpretation guide, and algorithm details * fix: add debounce to ChopTrigger, tune default threshold - Add cooldown check to prevent chop re-trigger within the gesture window\n- Raise default threshold from 25f to 35f to reduce false positives\n- Update chop.md with new default and 'How to perform' section * fix: use Modifier.pointerInput in sensey gesture modifier Fix dangling .pointerInput(Unit) call by chaining it as Modifier.pointerInput(Unit) within the compose modifier chain. * feat: update sample app with NodGesture, HeadShake, sensor availability check, and snackbar - Add NodGesture and HeadShake to sensor list with dispatchers\n- Add isSensorAvailable() check with snackbar notification for missing sensors\n- Refactor MainScreen to use Scaffold with SnackbarHost for feedback\n- Remove unused HapticUtil.confirmation()\n- Use SAMPLING_PERIOD_GAME for lower-latency sensor updates * chore: add git hooks install task to build Add installGitHooks Gradle task that sets core.hooksPath to .githooks, running ktlintFormat on each commit. * docs: update README with NodGesture and HeadShake Add NodGesture and HeadShake to the gesture list. Update coroutines/flow note to be more general. * docs: add NodGesture and HeadShake documentation pages Add new gesture documentation pages for NodGesture (nod 'yes') and HeadShake (shake 'no') with algorithm details, parameters, events, and usage examples. Update _index.md to list both. * docs: add 'How to perform' section to 7 gesture pages Add 'How to perform' section with user-facing descriptions to: DeviceSpin, DiagonalSwipe, EdgeSwipe, Flip, Light, Movement, Orientation. * docs: add 'How to perform' section to 7 gesture pages Add 'How to perform' section with user-facing descriptions to: PickupDevice, PinchScale, Proximity, RaiseToEar, RotationAngle, Scoop, Shake. * docs: add 'How to perform' section to 7 gesture pages Add 'How to perform' section with user-facing descriptions to: Step, TapOnBack, TiltDirection, TouchType, TurnOver, Wave, WristTwist. * chore: add pre-commit hook for ktlintFormat Add .githooks/pre-commit that runs ./gradlew ktlintFormat on every commit to enforce Kotlin formatting. * fix: detect head shake on combined Y+Z axes for tilted device When phone is held tilted (top higher), 'no' head shake projects onto both Y and Z axes. Previously only Z was tracked, missing half the signal. Fix: combine Y+Z into an effective horizontal angle. Works at any pitch angle. * docs: update HeadShake doc for combined Y+Z axis detection Update algorithm description from Z-only to combined Y+Z axes. Mention tilt-agnostic behavior in How to perform. Update parameter description to reflect horizontal rotation metric. * ci: add PR Check workflow with test, ktlint, and lint steps * update branch in pr-check workflow | 5 months ago | |
Update: 6 (#65) * updated readme * docs: sync usage docs with current API - overview.md: replace deprecated static API calls (Sensey.register, Sensey.unregister) with instance-based senseyRegister DSL - taponback.md: fix minJerk default from 5f to 2f - turnover.md: fix angleThreshold default from 130f to 150f - _index files: add links for new gestures (Clap, DeviceSpin, RaiseToEar, TurnOver) - movement.md: update event descriptions - clap.md, devicespin.md, raisetoear.md, turnover.md: add documentation for new gesture plugins * feat(internal): add core internal utilities and audio capture infra - EmaSmoother: single-pole exponential moving average filter for sensor data smoothing - GyroIntegrator: cumulative gyroscope integration for turnover and device-spin detection - Util: helper functions (magnitude3, angleBetweenDeg, linearAccelMag) - AudioCapture: generic coroutine-based AudioRecord wrapper shared by SoundLevelDetector and ClapDetector; uses getMinBufferSize for buffer allocation instead of hardcoded sizes * feat(gesture): add Clap, DeviceSpin, RaiseToEar, TurnOver detectors - ClapDetector/ClapTrigger: detects clap sounds via AudioRecord RMS energy rise detection (thresholdDb, riseDb params) - DeviceSpinDetector/DeviceSpinTrigger: detects rapid device rotation on any axis using gyro integration - RaiseToEarDetector/RaiseToEarTrigger: fuses proximity + gravity sensor to detect phone-at-ear position for calls - TurnOverEvent/TurnOverTrigger: gyroscope-based 180-degree flip detection (more precise than accel-based Flip plugin) - TapOnBackDetector/TapOnBackTrigger: double-tap detection using linear acceleration magnitude with EMA jerk filtering * feat(gesture): wire new gestures into plugin registry and DSL - Add turnOverPlugin, deviceSpinPlugin, raiseToEarPlugin, clapPlugin to top-level gesture DSL functions - Add corresponding builder methods to SenseyPluginRegistry - SoundLevelPlugin and ClapPlugin: add RECORD_AUDIO permission check on register with graceful disable if not granted - Refactor internal plugin classes (SensorGesturePlugin, SoundLevelPlugin, ClapPlugin) for consistency * refactor(trigger): improve detection algorithms across gestures - ChopTrigger: adjust threshold defaults, add EMA smoothing for impulse detection - MovementTrigger: refine stationary timeout logic, improve direction reporting accuracy - PinchScaleTrigger: add confirmation count for debounce against jittery touch input - WristTwistTrigger: tuning defaults for wrist-twist motion profile * refactor(soundlevel): delegate to shared AudioCapture - SoundLevelDetector now delegates audio recording to the shared AudioCapture<T> internal class instead of duplicating AudioRecord lifecycle, coroutine scope, and buffer management - Reduces SoundLevelDetector from ~130 lines to ~15 lines * test: add tests for new gestures and fix existing tests - Add ClapTriggerTest: RMS energy rise detection - Add DeviceSpinTriggerTest: gyro angle threshold detection - Add RaiseToEarTriggerTest and RaiseToEarDetectorTest: proximity + gravity fusion - Add TapOnBackDetectorTest: double-tap with EMA jerk - Add TurnOverTriggerTest: gyro-based flip detection - Add EmaSmootherTest and UtilTest for internal utilities - Fix ChopDetectorTest, WristTwistDetectorTest, PickupDeviceTriggerTest for updated trigger signatures * refactor(sample): extract permission logic into PermissionRequestUtil - PermissionRequestUtil: generic permission request utility with register() / isGranted() / requestIfNeeded() methods - Audio-specific extensions: registerAudioPermission(), isAudioPermissionGranted(), requestAudioIfNeeded() - MainActivity: use PermissionRequestUtil, register touch/pinch plugins via senseyRegister in onCreate, remove stale hasRecordAudioPermission caching * feat(sample): unify touch/pinch sensors, add pending permission flow - Add TOUCH_DETECTION and PINCH_SCALE to sensors list with createPlugin entries using touchTypePlugin/pinchScalePlugin - Add pendingSensor + startAfterPermissionGranted() with sensey==null guard for deferred permission handling - Add clearPendingPermission() for denial recovery - Add resultsMap with per-sensor result text and auto-clear after 2s (3s for touch/pinch) * refactor(sample): merge touch/pinch into main screen, remove TouchActivity * chore(sample): remove TouchActivity from manifest * docs: update architecture and setup for new gestures and AudioCapture - architecture.md: add AudioCapture, EmaSmoother, GyroIntegrator to internal/ listing; list all 22 gesture directories explicitly - setup.md: add eager-initialization pattern for Compose apps that need senseyGestures() to work during initial composition * feat(gesture): add EdgeSwipe — detect swipes from composable edges - EdgeSwipeEvent/EdgeSwipeTrigger: pure detection logic, reports which composable edge (LEFT/RIGHT/TOP/BOTTOM) the swipe originated from - EdgeSwipePlugin: Compose touch plugin using detectDragGestures; edgeThresholdDp is accepted as Dp (not raw pixels) and converted to px via Density for density-independent edge detection - Supports all four edges enabled by default; configure via edgeThresholdDp and enabledEdges parameters - Sample app: Edge Swipe sensor entry with SenseyRadioButtonWithTouchArea - Docs: edgeswipe.md with events, parameters, usage, and use cases * feat(gesture): add DiagonalSwipe — detect diagonal drags in composable - DiagonalSwipeEvent/DiagonalSwipeTrigger: pure logic using atan2 angle classification; reports UP_RIGHT, DOWN_RIGHT, DOWN_LEFT, UP_LEFT directions - Configurable minDragDistance and angleToleranceDeg (default 22.5°) - DiagonalSwipePlugin: Compose touch plugin using detectDragGestures - Sample app: Diagonal Swipe sensor entry with hit area - Docs: diagonalswipe.md with events, parameters, usage * ktlint format * refactor(sample): use SensorList composable, move touch handling inside it - SensorList now detects touch labels and renders SenseyRadioButtonWithTouchArea for touch/gesture sensors, SenseyRadioButton for all others - MainScreen simplified to just layout shell: Surface → Column(AppHeader, Box(SensorList)) * feat(sample): add SenseyTheme/PreviewTheme, remove hardcoded Colors.kt - Theme.kt: DarkColorScheme + LightColorScheme with orange/cyan/pink accents; SenseyTheme switches via isSystemInDarkTheme(); PreviewTheme wraps with Surface + background color + padding for previews - Colors.kt deleted — all color references replaced with MaterialTheme.colorScheme - MainActivity: wrap content in SenseyTheme * refactor(sample): simplify MainScreen, move touch logic into SensorList - MainScreen: reduced to layout shell (Surface → Column → AppHeader + Box → SensorList); all sensor rendering logic removed - SensorList: now handles both regular sensors (SenseyRadioButton) and touch-based sensors (SenseyRadioButtonWithTouchArea) with helper text mapping extracted into helperTextForLabel() - SenseyRadioButton/SenseyRadioButtonWithTouchArea: replace hardcoded colors with MaterialTheme.colorScheme references * fix(sample): Material3 TopAppBar header, ResultArea with fixed height - AppHeader: replace custom Surface/Text/Divider with CenterAlignedTopAppBar using topAppBarColors for proper insets, elevation, and typography - ResultArea: add .height(120.dp) for defined touch target and RoundedCornerShape(8.dp); all 4 previews use PreviewTheme * fix color * Add coroutines/flow support for gesture event collection - Add SenseyFlowScope with lifecycle-aware callbackFlow bridging - Add SenseyFlowEffect Compose wrapper using DisposableEffect - Add observe() default method to GestureTrigger interface - Add MockK and Turbine test dependencies - Add GestureTriggerFlowTest and SenseyFlowScopeTest - Update docs with flow API usage and architecture details * deps: remove unused catalog entries and switch to compileOnly Remove androidx-core-ktx and androidx-annotation (unused in source). Switch lifecycle-common, coroutines-core, coroutines-android, and all compose deps from implementation to compileOnly. Add lifecycle-runtime for test usage. * sample: add explicit deps for compileOnly libraries Lifecycle and coroutines are no longer transitively bundled by sensey. Add them explicitly in the sample app. * fix: resolve pre-existing test failures MovementTrigger: remove hasBaseline guard so first reading is not discarded. ScoopTrigger: reduce baselineSamples to 0 and minSustainedSamples to 1 for immediate response; set debounceMs to 0 and use >= for debounce check. Tests: align assertions with actual trigger behavior for direction ambiguity, partial magnitude conditions, infinite audio input, and mock proximity events. * docs: update for compileOnly dependencies Clarify that dependencies are not bundled transitively and consumers most likely already have them. Add dependency table mapping features to required libraries. * docs: add explicit dependency coordinates to setup guide Show the exact artifact coordinates under each bullet so users know what to include if they don't already have the dependency. * refactor: use Dispatchers.Default instead of Dispatchers.Main SenseyFlow scope and AudioCapture callback both used Dispatchers.Main. Switch to Default — sensor/audio processing and user callbacks are not UI-specific work. Drop kotlinx-coroutines-android entirely as no longer needed. * chore: remove unused kotlinx-coroutines-android catalog entry No longer referenced after switching to Dispatchers.Default. * feat: implement NodGesture gesture detection Add NodGestureTrigger and NodGestureEvent for detecting nod (yes) gestures using gyroscope pitch oscillation via GyroIntegrator. * feat: implement HeadShake gesture detection Add HeadShakeTrigger and HeadShakeEvent for detecting head shake (no) gestures using gyroscope yaw oscillation via GyroIntegrator. * test: add tests for NodGesture trigger Add NodGestureTriggerTest covering nod detection, debounce, cooldown, and noise suppression. * test: add tests for HeadShake trigger Add HeadShakeTriggerTest covering head shake detection, debounce, cooldown, and noise suppression. * feat: register NodGesture and HeadShake in plugin system Add nodGesturePlugin() and headShakePlugin() factory functions in GesturePlugins.kt, registration methods in SenseyPluginRegistry, and flow builder methods in SenseyFlowScope. Both use GyroIntegrator-based triggers. * feat: overhaul ClapTrigger with ZCR weighting, adaptive noise floor, and multi-clap counting Replaces old rise-dB threshold logic with a multi-stage pipeline:\n- ZCR-weighted RMS to reject narrow-band sounds (speech, music)\n- Adaptive noise floor with fast-attack/slow-release EMA\n- Multi-clap counting within configurable rolling time window\n- Configurable debounce to prevent re-trigger\n- Updated defaults: thresholdDb=-45f, requiredClaps=2, clapTimeframeMs=800L\n- Updated docs with new parameters and tuning tips * refactor: improve SoundLevelTrigger and AudioCapture error handling - SoundLevelTrigger: extract helper methods, add offset parameter with docs, fix constant naming\n- AudioCapture: handle CancellationException and SecurityException gracefully\n- AndroidManifest: remove maxSdkVersion=32 from RECORD_AUDIO so manifest targets all API levels\n- soundlevel.md: add parameters table, interpretation guide, and algorithm details * fix: add debounce to ChopTrigger, tune default threshold - Add cooldown check to prevent chop re-trigger within the gesture window\n- Raise default threshold from 25f to 35f to reduce false positives\n- Update chop.md with new default and 'How to perform' section * fix: use Modifier.pointerInput in sensey gesture modifier Fix dangling .pointerInput(Unit) call by chaining it as Modifier.pointerInput(Unit) within the compose modifier chain. * feat: update sample app with NodGesture, HeadShake, sensor availability check, and snackbar - Add NodGesture and HeadShake to sensor list with dispatchers\n- Add isSensorAvailable() check with snackbar notification for missing sensors\n- Refactor MainScreen to use Scaffold with SnackbarHost for feedback\n- Remove unused HapticUtil.confirmation()\n- Use SAMPLING_PERIOD_GAME for lower-latency sensor updates * chore: add git hooks install task to build Add installGitHooks Gradle task that sets core.hooksPath to .githooks, running ktlintFormat on each commit. * docs: update README with NodGesture and HeadShake Add NodGesture and HeadShake to the gesture list. Update coroutines/flow note to be more general. * docs: add NodGesture and HeadShake documentation pages Add new gesture documentation pages for NodGesture (nod 'yes') and HeadShake (shake 'no') with algorithm details, parameters, events, and usage examples. Update _index.md to list both. * docs: add 'How to perform' section to 7 gesture pages Add 'How to perform' section with user-facing descriptions to: DeviceSpin, DiagonalSwipe, EdgeSwipe, Flip, Light, Movement, Orientation. * docs: add 'How to perform' section to 7 gesture pages Add 'How to perform' section with user-facing descriptions to: PickupDevice, PinchScale, Proximity, RaiseToEar, RotationAngle, Scoop, Shake. * docs: add 'How to perform' section to 7 gesture pages Add 'How to perform' section with user-facing descriptions to: Step, TapOnBack, TiltDirection, TouchType, TurnOver, Wave, WristTwist. * chore: add pre-commit hook for ktlintFormat Add .githooks/pre-commit that runs ./gradlew ktlintFormat on every commit to enforce Kotlin formatting. * fix: detect head shake on combined Y+Z axes for tilted device When phone is held tilted (top higher), 'no' head shake projects onto both Y and Z axes. Previously only Z was tracked, missing half the signal. Fix: combine Y+Z into an effective horizontal angle. Works at any pitch angle. * docs: update HeadShake doc for combined Y+Z axis detection Update algorithm description from Z-only to combined Y+Z axes. Mention tilt-agnostic behavior in How to perform. Update parameter description to reflect horizontal rotation metric. * ci: add PR Check workflow with test, ktlint, and lint steps * update branch in pr-check workflow | 5 months ago | |
Update: 4 (#63) * Extract GesturePlugin contract and SenseyPluginRegistry - GesturePlugin interface with onRegister/onUnregister receiving Sensey instance - SenseyPluginRegistry DSL builder for registering multiple plugins - TouchHandler removed (replaced by Compose gesture system) * Refactor Sensey from singleton object to class with extension functions - Sensey is now a class accepting Context, optional Lifecycle, sampling period - internal registerSensorDetector/unregisterSensorDetector/composeGestureProvider methods - Removed setupDispatchTouchEvent, registerTouchHandler, unregisterTouchHandler - senseyRegister(context, lifecycle?) and senseyStop() top-level functions - defaultSensey internal property for compose modifier access * Decouple SensorDetector from Sensey singleton - sensorDataLoggingEnabled moved from static Sensey reference to internal var - Set by Sensey.registerSensorDetector() before registration - Allows SensorDetector to work without global singleton dependency * Create gesture plugin factory functions and private plugin classes - 17 factory functions: shakePlugin, flipPlugin, lightPlugin, proximityPlugin, etc. - SensorGesturePlugin: reusable base for sensor-based gesture registration - PinchScalePlugin + TouchTypePlugin: compose-based gesture detection - SoundLevelPlugin: AudioRecord-based detection - Private plugin classes prevent direct instantiation * Tighten public API: make all Detector and Trigger classes internal - 17 Detector and 17 Trigger classes changed from public to internal - Users interact only through factory functions (shakePlugin, flipPlugin, etc.) - GestureTrigger<T> interface remains public for custom trigger implementations - Event sealed classes remain public as callback data types * Migrate touch/scale gestures from View to Jetpack Compose - Add Compose dependencies (BOM, compose-ui, compose-foundation) to library - Enable compose build feature + compose compiler plugin - New compose/ package: ComposeGestureProvider interface + senseyGestures() Modifier + SenseyGestureEffect() - Delete View-based TouchTypeDetector and PinchScaleDetector - TouchTypeEvent/PinchScaleEvent now delivered via Compose pointer input - PinchScalePlugin uses detectTransformGestures, TouchTypePlugin uses detectTapGestures + detectDragGestures * Update sample app to use plugin-based API and Compose touch - SensorManager: register/unregister pattern via Sensey instance - TouchSensorManager: simplified to state holder, events received via lambdas - TouchActivity: uses SenseyGestureEffect instead of dispatchTouchEvent - TouchScreen: applies Modifier.senseyGestures() on touch area - MainActivity: uses senseyRegister/senseyStop extension functions * Fix test and remove stale gesture-details.md - ScoopTriggerTest: use correct parameter name (impulseThreshold instead of threshold) - gesture-details.md: removed (outdated View-based documentation) * Update documentation for plugin-based API and Compose integration - README: updated Quick start with both Activity and Compose patterns, simplified Architecture - USAGE.md: comprehensive rewrite with Setup, Common Examples (14 use cases), Context-specific usage, and all gesture docs with Compose patterns - dev-docs.md: updated custom plugin guide (removed TouchHandler, added ComposePlugin) - GitHub templates: simplified to minimal sections * Setup ktlint plugin and configuration * Fix ktlint code style violations across codebase * Enable Gradle configuration cache * Make log tags standout in logcat with ASCII art wrapping * Simplify SensorDetector hierarchy and Sensey core infrastructure - Replace isSensorEventBelongsToPluggedTypes with idiomatic '!in' - Extract resolveSensors helper using 'also' for logging side effects - Remove KDoc data table from GestureTrigger (now documented per trigger) - Use function references (::register, ::let) for conciseness * Refactor gesture triggers with private functions and simplified logic - Extract magnitude, baseline, and state detection into private functions - Replace Hungarian notation (mAccel, mAccelCurrent) with descriptive names - Use sealed enum for TouchTypeTrigger Quadrant classification - Simplify conditional chains with guard clauses - Add companion object constants for magic numbers * Simplify custom detectors and SoundLevelDetector coroutine code - Extract captureAudio, createAudioRecord, processAudioStream from SoundLevelDetector - Move audio release to dedicated private function - Extract computeOrientationAngles helper in RotationAngleDetector - Format OrientationTrigger toExpressionBody with proper when blocks * Setup Dokka 2.2.0 documentation generation with versioning plugins - Add dokka plugin to version catalog with versioning/kotlin-as-java/android-doc plugins - Configure Dokka HTML publication for sensey module with source links - Add publishDocs Gradle task for versioned documentation output - Add github-pages branch restore step for versioning continuity * Add GitHub Actions workflow for versioned docs deployment - Trigger on master/develop pushes and version tags - Restore previous docs from gh-pages branch for Dokka versioning - Organize output into versioned directories with index landing page - Deploy to GitHub Pages via upload-pages-artifact * Bump version to 2.0.0 * Update README and dev docs with Dokka, ktlint, and architecture details * Fix #47: clear sensor buffer on pickup so PutDown detection works * Fix #34: add minNearDurationMs to wave detection; bump #31: default timeWindowMillis to 2000ms * Fix #17: add debounce to proximity trigger to prevent false reads in multi-window * Fix broken tests: replace deleted Detector classes with TypedSensorDetector * Standardize gravity constant to 9.81f across all gesture triggers ScoopTrigger, ChopTrigger, TapOnBackTrigger used 9.8f while MovementTrigger used 9.81f. Consolidated all to the more accurate 9.81f to eliminate fractional threshold discrepancies between triggers. * Replace ArrayDeque with fixed FloatArray circular buffer in PickupDeviceTrigger ArrayDeque with addLast/removeFirst per sensor event creates unnecessary GC pressure. Pre-allocated FloatArray with rolling index + sum eliminates allocations in the sensor event hot path and improves cache locality. * Add baseline initialization to MovementTrigger to prevent spurious startup event Previous code used a hardcoded GRAVITY_EARTH (9.81f) as initial currentAccel. If the first real sensor reading differs (e.g. device on a table with slight tilt), a large delta would immediately fire a MovementEvent.Moved on startup. Now the first reading sets the baseline without producing an event. * Remove dead sensorTypes field from SensorGesturePlugin The sensorTypes constructor parameter was passed by all 14 factory functions but never read inside SensorGesturePlugin. The actual sensor type registration is handled internally by each SensorDetector subclass. Removing the dead code eliminates confusion and reduces constructor verbosity. * Add onDragCancel handler to TouchTypePlugin drag gesture Without onDragCancel, when the system cancels a drag gesture (e.g. incoming call, another gesture taking over), dragStart retains stale coordinates which corrupts the next drag's delta calculation. * Enable lint abortOnError in both modules Previously set to false, which suppressed security-relevant lint checks such as MissingPermission, UnsafeProtectedBroadcast, and ExportedContentProvider. Hardening to true ensures lint violations fail the build during CI. * Remove -assumenosideeffects Log.d from library proguard rules The assumenosideeffects rule stripped ALL Log.d calls from consumer apps' release builds, not just the library's own logging. This broke debugging/troubleshooting for host apps that rely on Log.d in production. Library proguard rules should only keep library internals, not alter consumer behavior. * Add RECORD_AUDIO permission declaration to library manifest The SoundLevelDetector uses AudioRecord with VOICE_RECOGNITION source. Without a manifest declaration, the Android package manager cannot enforce the permission at install time, leading to a runtime SecurityException on Android 12+ when permission is missing. maxSdkVersion=32 avoids redundant prompting on Android 13+ where the permission is granted at install time for legacy apps. * Fix PinchScalePlugin and TouchTypePlugin cleanup on unregister Previously onUnregister was a no-op for both plugins, meaning the ComposeGestureProvider instances added via registerComposeGestureProvider were never removed. This leaked pointer input handlers and caused stale callbacks if plugins were registered/unregistered dynamically. Now each plugin tracks its provider(s) and removes them on unregister. * Fix RuntimePermissionUtil multi-permission callback logic Previous code iterated over each grant result individually, firing onPermissionGranted for each granted and onPermissionDenied for each denied permission in the same request. For multi-permission requests, both callbacks would fire simultaneously. Now uses grantResults.all{} to emit a single success/failure decision per request. * Fix ShakeTrigger.initializeBaseline return type (Nothing? -> ShakeEvent?) Nothing? is Kotlin's bottom type, semantically meaning 'this function never returns normally'. initializeBaseline simply returns null to signal the baseline isn't ready yet. Using Nothing? disables compiler exhaustiveness checks and could mask future bugs. * Fix TapOnBackTrigger single-tap latency and silent drop Previous implementation deferred all tap events by tapSequenceTimeoutMs (500ms) and silently discarded single taps (only tapCount >= 2 fired). This made the gesture feel unresponsive and broke basic single-tap detection. Now fires TapOnBackEvent immediately on the first qualifying tap — the existing tapDebounceMs (250ms) prevents noise re-triggering. * Add RECORD_AUDIO permission guard to SoundLevelPlugin The SoundLevelDetector creates an AudioRecord without verifying that the host app holds RECORD_AUDIO permission, causing a SecurityException crash at runtime on Android 12+ or silent microphone access on older versions. Now SoundLevelPlugin.onRegister checks permission before starting the detector, and SoundLevelDetector.captureAudio catches SecurityException as defense-in-depth in case permission is revoked between check and use. * Revert "Fix TapOnBackTrigger single-tap latency and silent drop" This reverts commit 90b477baf33ad357f1735e7cb62c5b9ce39b58ce. * Add KDoc disclosure to soundLevelPlugin about microphone audio capture Documents that the plugin requires RECORD_AUDIO permission, captures raw audio via AudioRecord with VOICE_RECOGNITION source, and that no audio data is stored, transmitted, or persisted. * Enable minification in sample app release build Release build now uses R8 with proguard-android-optimize.txt and the sample's proguard-rules.pro which keeps Compose, Sensey public API, and Kotlin coroutines internals. * Expose FlipTrigger threshold parameters in flipPlugin() public API Previously flipPlugin() accepted only a dispatcher, hiding the FlipTrigger faceUp/faceDown bound parameters. Consumers can now calibrate detection sensitivity at plugin creation time. * Migrate sample permission flow to ActivityResultContracts and rename SensorManager - Replace deprecated onRequestPermissionsResult / ActivityCompat with registerForActivityResult(RequestPermission) - Rename sample SensorManager to SenseySensorManager to avoid shadowing android.hardware.SensorManager and prevent import collisions * Exclude develop branch from docs deployment Previously docs were published on pushes to both master and develop. Develop is an integration branch where intermediate snapshots should not overwrite the published documentation on GitHub Pages. | 5 months ago | |
Updates: 8 (#67) * feat(sample): add Modifier.touchIndicator() extension Reusable @Composable Modifier extension that draws a semi-transparent circle at each active touch point. Mimics Android "Show taps" behavior: - One circle per finger (keyed by pointer ID via mutableStateMapOf) - Follows finger during drag/move - Lingers 300ms after each pointer lifts, then fades out - Configurable color, defaults to semi-transparent black * feat(sample): integrate touch indicator into touch hit area - ResultArea gains showTouchIndicator param, applies touchIndicator modifier with MaterialTheme tertiary color at 55% alpha - SenseyRadioButtonWithTouchArea passes showHitArea as showTouchIndicator so the indicator only appears when a touch-like sensor is selected and the hit area is visible * refactor(taponback): sealed interface event type Convert TapOnBackEvent from plain object to sealed interface with Detected variant, matching ChopEvent pattern. * feat(taponback): rewrite with pre-settle gate, Z-axis check, direction coherence New 5-phase state machine: IDLE → SETTLING_FIRST → GUARD → LISTENING → SETTLING_SECOND → emit. Three noise rejection filters: - Pre-settle gate (200ms quiet required before first spike) - Z-axis dominance (back tap must be primarily along Z axis) - Direction coherence (both spikes must point same direction) * test(taponback): update tests for pre-settle gate and Z-axis check Test values now use Z-dominant acceleration. Each test adds a quiet period before the first spike to satisfy the pre-settle gate. * refactor(taponback): add preSettleMs parameter to plugin wiring All three plugin wiring entry points (GesturePlugins, SenseyPluginRegistry, SenseyFlow) now pass the preSettleMs parameter to TapOnBackTrigger. * feat(sample): add SensorLogger for independent data collection Registers for all 8 sensor types independently of Sensey. Wired into MainActivity lifecycle (start in onCreate/onResume, stop in onPause). * fix(sample): add bottom spacer for last gesture result visibility TapOnBack is the last item in the motion tab. Added 120dp Spacer at the bottom so result text is visible without scrolling. * docs(taponback): update algorithm description and parameter table Document the 5-phase state machine, preSettleMs and reboundGuardMs parameters, and noise rejection filters. | 4 months ago | |
Update: 7 (#66) * feat: add LongPressDrag, TwoFingerSwipe, CornerSwipe gesture plugins - GesturePlugins: factory functions + private plugin classes - LongPressDragPlugin (detectDragGesturesAfterLongPress) - TwoFingerSwipePlugin (awaitEachGesture + 2-pointer check) - CornerSwipePlugin (detectDragGestures + corner classification) - SenseyPluginRegistry: registration methods for all three - Event + Trigger + unit tests for each gesture * docs: add LongPressDrag, TwoFingerSwipe, CornerSwipe gesture docs - How to perform, algorithm description, events table - Configurable parameters with defaults - Usage code snippets and use-case tables * refactor(sample): clean up SenseySensorManager, wire new gestures - Remove unused parameter from setResultText - Merge handleStartDetector into startDetector/stopDetector - Add dispatchers and plugin creation for LongPressDrag, TwoFingerSwipe, CornerSwipe - Fix helperTextForLabel: return '' for non-touch sensors, add DiagonalSwipe entry * refactor(sample): create Paddings.kt, replace hardcoded dp values - Paddings: none(0), sm(4), md(8), lg(16), xl(20) - Wire helperText into SenseyRadioButton - Replace Color.LightGray with onSurfaceVariant for theme-aware gray * chore: fix banner path, add docs index banner, remove unused logo * fix(sample): add helper texts for all sensor gestures - Add descriptive helper text for all 29 sensor/gesture types - Each describes what event(s) the gesture detects - Update preview with more sensor variety * fix(sample): rewrite helper texts as user-facing action descriptions All helper texts now describe what gesture the user should perform instead of technical event names. e.g. 'Shake the device' instead of 'Shake / Shake Stopped' * sample: refactor with Nav3, gesture groups, ViewModel, adaptive nav - Add Navigation 3 with sealed GestureGroup routes (Touch, Motion, Orientation, Environment) - Group 30 gestures into 4 logical tabs with emoji-only nav items - Add SampleViewModel with StateFlow-driven UI state - Implement adaptive layout: NavigationBar on phones, NavigationRail on tablets+ - Wire ViewModel ↔ SenseySensorManager via result callback - Add gradle deps: nav3, kotlinx-serialization, lifecycle-viewmodel-compose - Split MainScreen into dedicated files: GestureNavBar, GestureNavRail, GestureNavRailLayout, GestureCompactLayout, SensorEntryProvider * sample: extract ScrollbarThumb as reusable component with KDoc - Move ScrollbarThumb from private function in SensorList to standalone file - Add configurable params: thumbColor, thumbWidth, hideDelayMs - Add KDoc with usage example and parameter documentation - Update SensorList to import from shared component * sample: reorganize ui package into sub-packages with internal visibility - ui/core/ — Theme, Paddings, AppHeader (shared primitives) - ui/sensors/ — SensorList, SensorEntryProvider, SenseyRadioButton, SenseyRadioButtonWithTouchArea, ResultArea, ScrollbarThumb - ui/nav/ — MainScreen, GestureNavBar, GestureNavRail, GestureNavRailLayout, GestureCompactLayout - ui/tabs/ — GestureGroupTab (unchanged) - Mark all composables internal except SensorItem, sensorEntryProvider, MainScreen, and core types needed cross-package * style: reformat SenseyRadioButtonWithTouchArea padding * sample: wire ViewModel snackbarEvent into UI, remove unused functions * refactor: add content slot and scroll behavior to navigation layouts * style: update navigation bar and rail styling * feat: update theme color palette * refactor: simplify radio button components with extracted RadioButtonRow * feat: animate scrollbar thumb auto-hide * chore: add edge-to-edge system bar styles * feat(touch): introduce consolidated touch gesture API Add unified touch/ package replacing the 7 separate touch detectors: - TouchEvent: sealed interface with Tap, Swipe, Scroll, LongPressDrag, PinchScale - TouchConfig: feature-based config (taps, swipe, edgeSwipe, cornerSwipe, ...) - TouchGesture: sealed contract for all touch triggers - TouchPlugin: single Compose plugin registering providers by config - 6 internal triggers: SwipeScrollTrigger, LongPressDragTrigger, PinchScaleTrigger, TwoFingerSwipeTrigger, EdgeSwipeTrigger, CornerSwipeTrigger - Internal utils: DirectionUtils, SwipeClassifier Pure addition. Old packages will be removed in a follow-up commit. * test(touch): add unit tests for all 6 touch triggers Cover SwipeScrollTrigger, LongPressDragTrigger, PinchScaleTrigger, TwoFingerSwipeTrigger, EdgeSwipeTrigger, and CornerSwipeTrigger. Each test file focuses on its trigger's evaluate() method with edge cases (threshold, filtering, direction classification). * refactor(touch): switch GesturePlugins, registry, flow to new touch/ API - Rewrite GesturePlugins.kt: all touch wrapper functions now create TouchPlugin with feature-based TouchConfig. Removed ~500 lines of private plugin classes (TouchTypePlugin, EdgeSwipePlugin, etc.). Removed touchTypePlugin (redundant with touchPlugin default config). - Update SenseyPluginRegistry.kt: touch methods use TouchEvent + new config types - Update SenseyFlow.kt: same, add missing longPressDrag/twoFingerSwipe/cornerSwipe - Delete 7 old source packages: cornerswipe/, edgeswipe/, diagonalswipe/, twofingerswipe/, longpressdrag/, pinchscale/, touchtype/ - Delete 5 old test files matching deleted packages * refactor(sample): update to use new TouchEvent types - Replace touchTypePlugin import with touchPlugin - Rename touchTypeDispatcher to touchDispatcher - Replace TouchTypeEvent references with TouchEvent sealed hierarchy - Use safe type checks (if is TouchEvent.Swipe) instead of hard casts - Remove ThreeFingerSingleTap handling - Update direction helpers to use TouchEvent.Direction * docs(touch): update documentation for consolidated touch API - Add touch.md as the generic touchPlugin entry point with feature-based config table and convenience wrapper reference - Update cornerswipe, edgeswipe, diagonalswipe, twofingerswipe, longpressdrag, pinchscale docs to describe them as wrappers around touchPlugin with pre-configured TouchConfig - Update context-specific-usage.md to use touchPlugin + TouchEvent instead of touchTypePlugin + TouchTypeEvent - Delete touchtype.md (replaced by touch.md) * fix(sample): handle both Swipe and Scroll in diagonal swipe dispatcher; fix pinch label mismatch - DiagonalSwipeDispatcher now handles TouchEvent.Scroll in addition to TouchEvent.Swipe (slow diagonal drags were being silently dropped) - Fix 'Pinch Scale Detection' label mismatch in SensorList.kt and GestureGroupTab.kt (constants were renamed to 'Pinch Scale' but the UI checks still referenced the old label) * fix(sample): add missing haptic feedback to tap and pinch scale dispatchers * fix(sample): show edge swipe origin and direction in dispatcher * docs(touch): add KDoc example for edge + direction differentiation * docs: add edge + direction differentiation examples in usage docs * feat(sample): replace Sensey text with logo vector drawable tinted primary * refactor(sample): update color palette with neon orange primary, amber secondary, bottle green tertiary * fix(sample): improve radio button label/helper typography * add the logo vector drawable * update readme banner and add logo svg | 5 months ago | |
added references of sensey to the repo | 6 years ago | |
Updates: 8 (#67) * feat(sample): add Modifier.touchIndicator() extension Reusable @Composable Modifier extension that draws a semi-transparent circle at each active touch point. Mimics Android "Show taps" behavior: - One circle per finger (keyed by pointer ID via mutableStateMapOf) - Follows finger during drag/move - Lingers 300ms after each pointer lifts, then fades out - Configurable color, defaults to semi-transparent black * feat(sample): integrate touch indicator into touch hit area - ResultArea gains showTouchIndicator param, applies touchIndicator modifier with MaterialTheme tertiary color at 55% alpha - SenseyRadioButtonWithTouchArea passes showHitArea as showTouchIndicator so the indicator only appears when a touch-like sensor is selected and the hit area is visible * refactor(taponback): sealed interface event type Convert TapOnBackEvent from plain object to sealed interface with Detected variant, matching ChopEvent pattern. * feat(taponback): rewrite with pre-settle gate, Z-axis check, direction coherence New 5-phase state machine: IDLE → SETTLING_FIRST → GUARD → LISTENING → SETTLING_SECOND → emit. Three noise rejection filters: - Pre-settle gate (200ms quiet required before first spike) - Z-axis dominance (back tap must be primarily along Z axis) - Direction coherence (both spikes must point same direction) * test(taponback): update tests for pre-settle gate and Z-axis check Test values now use Z-dominant acceleration. Each test adds a quiet period before the first spike to satisfy the pre-settle gate. * refactor(taponback): add preSettleMs parameter to plugin wiring All three plugin wiring entry points (GesturePlugins, SenseyPluginRegistry, SenseyFlow) now pass the preSettleMs parameter to TapOnBackTrigger. * feat(sample): add SensorLogger for independent data collection Registers for all 8 sensor types independently of Sensey. Wired into MainActivity lifecycle (start in onCreate/onResume, stop in onPause). * fix(sample): add bottom spacer for last gesture result visibility TapOnBack is the last item in the motion tab. Added 120dp Spacer at the bottom so result text is visible without scrolling. * docs(taponback): update algorithm description and parameter table Document the 5-phase state machine, preSettleMs and reboundGuardMs parameters, and noise rejection filters. | 4 months ago | |
Update: 5 (#64) * Remove Apache license headers from source files * updated gitgnore * Remove Dokka setup and restructure documentation - Remove Dokka plugin, config, and dependencies from build system - Delete Dokka CI workflow and publishDocs task - Move usage guide and dev docs into docs/ directory - Update README and dev docs to remove Dokka references * Add Hugo site configuration and CI * Update .gitignore and README for Hugo docs migration * Restructure usage docs into Hugo content directory * Restructure development docs into Hugo content directory * Extract GRAVITY_EARTH constant to shared internal/Constants.kt * Make SensorDetector, TypedSensorDetector, ComposeGestureProvider and registration methods public * Rewrite architecture and custom plugin docs with practical examples and inline comments * Tighten language and add inline comments across usage docs and dev guides * Clean up trailing whitespace in README * Version docs by git tag — pushes to /vX.Y.Z/ on gh-pages branch * Split Components.kt into individual files and add @Preview to MainScreen and TouchScreen * updated ui * Fix ProximityTrigger stalling and LightTrigger baseline inconsistency ProximityTrigger: Remove 2-event debounce state machine that stalled with on-change proximity sensors (most Android hardware). Near never dispatched, Far dispatched once then trigger was permanently stuck. LightTrigger: initializeBaseline() used lightThreshold for wasDark but darkThreshold for the return event. When ambient light was in the hysteresis band, the state machine desynced and silently ate Dark transitions. * Replace isDetected boolean with eventCount counter in SenseySensorManager mutableStateOf<Boolean> doesn't trigger recomposition when set to the same value (true → true on rapid events). Use mutableIntStateOf counter that guarantees a unique value on every event. Removed unused resetJob and coroutine delay imports. * Use eventCount with LaunchedEffect for DetectionIndicator timing MainScreen accepts eventCount: Int instead of detected: Boolean. LaunchedEffect watches the counter, sets detected = true on each event, resets after 3s. MainActivity passes sensorManager.eventCount. * Fix StepTrigger flood and PinchScaleTrigger counter accumulation StepTrigger: Gate buildStepEvent behind actual step detection. - evaluateStepCounter now returns null for the baseline-reading call and filters repeated sensor values via lastDispatchedSteps - evaluateAccelerometer no longer calls buildStepEvent unconditionally; only emits when magnitude delta exceeds threshold - Starting previousMagnitude=0 no longer triggers a phantom first step (abs(9.8 - 0) > 3 was always true) PinchScaleTrigger: Reset opposite counter after dispatching. - scaleInCount and scaleOutCount only incremented, never reset → after the first SCALE_IN, scaleInCount was permanently > 2, so all subsequent SCALE_IN events fired on the first reading * Fix ScoopTrigger baseline race, WaveTrigger time window, PickupDeviceTrigger buffer clearing ScoopTrigger: Add baselineReadings counter to skip impulse detection during the first 10 readings, letting the EMA baseline converge before evaluating impulses. Prevents false triggers from stale GRAVITY_EARTH. WaveTrigger: Change timeWindowMillis from Float to Long. Only update lastProximityEventTime on the Near transition, so the time window correctly measures the full gesture duration (Near→Far) instead of resetting on every continuous-sensor reading. PickupDeviceTrigger: Remove buffer clearing on PickedUp — the rolling window self-heals naturally. Eliminates the 3-reading blind spot. * Add class-level KDoc and inline comments to all 18 gesture triggers * Update all gesture doc pages with algorithm descriptions and corrected defaults * Move algorithm descriptions into dedicated ## Algorithm section on each gesture page * Remove internal-only parameters from gesture docs that users cannot configure * Change PickupDeviceTrigger settle from reading-count to time-based * Expose settleTimeMs parameter in pickupDevicePlugin API * Update pickup device docs with settleTimeMs parameter * Wire resultText into MainScreen status row from sensor manager * Update sample app theme to black background | 5 months ago | |
Updates: 8 (#67) * feat(sample): add Modifier.touchIndicator() extension Reusable @Composable Modifier extension that draws a semi-transparent circle at each active touch point. Mimics Android "Show taps" behavior: - One circle per finger (keyed by pointer ID via mutableStateMapOf) - Follows finger during drag/move - Lingers 300ms after each pointer lifts, then fades out - Configurable color, defaults to semi-transparent black * feat(sample): integrate touch indicator into touch hit area - ResultArea gains showTouchIndicator param, applies touchIndicator modifier with MaterialTheme tertiary color at 55% alpha - SenseyRadioButtonWithTouchArea passes showHitArea as showTouchIndicator so the indicator only appears when a touch-like sensor is selected and the hit area is visible * refactor(taponback): sealed interface event type Convert TapOnBackEvent from plain object to sealed interface with Detected variant, matching ChopEvent pattern. * feat(taponback): rewrite with pre-settle gate, Z-axis check, direction coherence New 5-phase state machine: IDLE → SETTLING_FIRST → GUARD → LISTENING → SETTLING_SECOND → emit. Three noise rejection filters: - Pre-settle gate (200ms quiet required before first spike) - Z-axis dominance (back tap must be primarily along Z axis) - Direction coherence (both spikes must point same direction) * test(taponback): update tests for pre-settle gate and Z-axis check Test values now use Z-dominant acceleration. Each test adds a quiet period before the first spike to satisfy the pre-settle gate. * refactor(taponback): add preSettleMs parameter to plugin wiring All three plugin wiring entry points (GesturePlugins, SenseyPluginRegistry, SenseyFlow) now pass the preSettleMs parameter to TapOnBackTrigger. * feat(sample): add SensorLogger for independent data collection Registers for all 8 sensor types independently of Sensey. Wired into MainActivity lifecycle (start in onCreate/onResume, stop in onPause). * fix(sample): add bottom spacer for last gesture result visibility TapOnBack is the last item in the motion tab. Added 120dp Spacer at the bottom so result text is visible without scrolling. * docs(taponback): update algorithm description and parameter table Document the 5-phase state machine, preSettleMs and reboundGuardMs parameters, and noise rejection filters. | 4 months ago | |
Update: 7 (#66) * feat: add LongPressDrag, TwoFingerSwipe, CornerSwipe gesture plugins - GesturePlugins: factory functions + private plugin classes - LongPressDragPlugin (detectDragGesturesAfterLongPress) - TwoFingerSwipePlugin (awaitEachGesture + 2-pointer check) - CornerSwipePlugin (detectDragGestures + corner classification) - SenseyPluginRegistry: registration methods for all three - Event + Trigger + unit tests for each gesture * docs: add LongPressDrag, TwoFingerSwipe, CornerSwipe gesture docs - How to perform, algorithm description, events table - Configurable parameters with defaults - Usage code snippets and use-case tables * refactor(sample): clean up SenseySensorManager, wire new gestures - Remove unused parameter from setResultText - Merge handleStartDetector into startDetector/stopDetector - Add dispatchers and plugin creation for LongPressDrag, TwoFingerSwipe, CornerSwipe - Fix helperTextForLabel: return '' for non-touch sensors, add DiagonalSwipe entry * refactor(sample): create Paddings.kt, replace hardcoded dp values - Paddings: none(0), sm(4), md(8), lg(16), xl(20) - Wire helperText into SenseyRadioButton - Replace Color.LightGray with onSurfaceVariant for theme-aware gray * chore: fix banner path, add docs index banner, remove unused logo * fix(sample): add helper texts for all sensor gestures - Add descriptive helper text for all 29 sensor/gesture types - Each describes what event(s) the gesture detects - Update preview with more sensor variety * fix(sample): rewrite helper texts as user-facing action descriptions All helper texts now describe what gesture the user should perform instead of technical event names. e.g. 'Shake the device' instead of 'Shake / Shake Stopped' * sample: refactor with Nav3, gesture groups, ViewModel, adaptive nav - Add Navigation 3 with sealed GestureGroup routes (Touch, Motion, Orientation, Environment) - Group 30 gestures into 4 logical tabs with emoji-only nav items - Add SampleViewModel with StateFlow-driven UI state - Implement adaptive layout: NavigationBar on phones, NavigationRail on tablets+ - Wire ViewModel ↔ SenseySensorManager via result callback - Add gradle deps: nav3, kotlinx-serialization, lifecycle-viewmodel-compose - Split MainScreen into dedicated files: GestureNavBar, GestureNavRail, GestureNavRailLayout, GestureCompactLayout, SensorEntryProvider * sample: extract ScrollbarThumb as reusable component with KDoc - Move ScrollbarThumb from private function in SensorList to standalone file - Add configurable params: thumbColor, thumbWidth, hideDelayMs - Add KDoc with usage example and parameter documentation - Update SensorList to import from shared component * sample: reorganize ui package into sub-packages with internal visibility - ui/core/ — Theme, Paddings, AppHeader (shared primitives) - ui/sensors/ — SensorList, SensorEntryProvider, SenseyRadioButton, SenseyRadioButtonWithTouchArea, ResultArea, ScrollbarThumb - ui/nav/ — MainScreen, GestureNavBar, GestureNavRail, GestureNavRailLayout, GestureCompactLayout - ui/tabs/ — GestureGroupTab (unchanged) - Mark all composables internal except SensorItem, sensorEntryProvider, MainScreen, and core types needed cross-package * style: reformat SenseyRadioButtonWithTouchArea padding * sample: wire ViewModel snackbarEvent into UI, remove unused functions * refactor: add content slot and scroll behavior to navigation layouts * style: update navigation bar and rail styling * feat: update theme color palette * refactor: simplify radio button components with extracted RadioButtonRow * feat: animate scrollbar thumb auto-hide * chore: add edge-to-edge system bar styles * feat(touch): introduce consolidated touch gesture API Add unified touch/ package replacing the 7 separate touch detectors: - TouchEvent: sealed interface with Tap, Swipe, Scroll, LongPressDrag, PinchScale - TouchConfig: feature-based config (taps, swipe, edgeSwipe, cornerSwipe, ...) - TouchGesture: sealed contract for all touch triggers - TouchPlugin: single Compose plugin registering providers by config - 6 internal triggers: SwipeScrollTrigger, LongPressDragTrigger, PinchScaleTrigger, TwoFingerSwipeTrigger, EdgeSwipeTrigger, CornerSwipeTrigger - Internal utils: DirectionUtils, SwipeClassifier Pure addition. Old packages will be removed in a follow-up commit. * test(touch): add unit tests for all 6 touch triggers Cover SwipeScrollTrigger, LongPressDragTrigger, PinchScaleTrigger, TwoFingerSwipeTrigger, EdgeSwipeTrigger, and CornerSwipeTrigger. Each test file focuses on its trigger's evaluate() method with edge cases (threshold, filtering, direction classification). * refactor(touch): switch GesturePlugins, registry, flow to new touch/ API - Rewrite GesturePlugins.kt: all touch wrapper functions now create TouchPlugin with feature-based TouchConfig. Removed ~500 lines of private plugin classes (TouchTypePlugin, EdgeSwipePlugin, etc.). Removed touchTypePlugin (redundant with touchPlugin default config). - Update SenseyPluginRegistry.kt: touch methods use TouchEvent + new config types - Update SenseyFlow.kt: same, add missing longPressDrag/twoFingerSwipe/cornerSwipe - Delete 7 old source packages: cornerswipe/, edgeswipe/, diagonalswipe/, twofingerswipe/, longpressdrag/, pinchscale/, touchtype/ - Delete 5 old test files matching deleted packages * refactor(sample): update to use new TouchEvent types - Replace touchTypePlugin import with touchPlugin - Rename touchTypeDispatcher to touchDispatcher - Replace TouchTypeEvent references with TouchEvent sealed hierarchy - Use safe type checks (if is TouchEvent.Swipe) instead of hard casts - Remove ThreeFingerSingleTap handling - Update direction helpers to use TouchEvent.Direction * docs(touch): update documentation for consolidated touch API - Add touch.md as the generic touchPlugin entry point with feature-based config table and convenience wrapper reference - Update cornerswipe, edgeswipe, diagonalswipe, twofingerswipe, longpressdrag, pinchscale docs to describe them as wrappers around touchPlugin with pre-configured TouchConfig - Update context-specific-usage.md to use touchPlugin + TouchEvent instead of touchTypePlugin + TouchTypeEvent - Delete touchtype.md (replaced by touch.md) * fix(sample): handle both Swipe and Scroll in diagonal swipe dispatcher; fix pinch label mismatch - DiagonalSwipeDispatcher now handles TouchEvent.Scroll in addition to TouchEvent.Swipe (slow diagonal drags were being silently dropped) - Fix 'Pinch Scale Detection' label mismatch in SensorList.kt and GestureGroupTab.kt (constants were renamed to 'Pinch Scale' but the UI checks still referenced the old label) * fix(sample): add missing haptic feedback to tap and pinch scale dispatchers * fix(sample): show edge swipe origin and direction in dispatcher * docs(touch): add KDoc example for edge + direction differentiation * docs: add edge + direction differentiation examples in usage docs * feat(sample): replace Sensey text with logo vector drawable tinted primary * refactor(sample): update color palette with neon orange primary, amber secondary, bottle green tertiary * fix(sample): improve radio button label/helper typography * add the logo vector drawable * update readme banner and add logo svg | 5 months ago | |
Update: 4 (#63) * Extract GesturePlugin contract and SenseyPluginRegistry - GesturePlugin interface with onRegister/onUnregister receiving Sensey instance - SenseyPluginRegistry DSL builder for registering multiple plugins - TouchHandler removed (replaced by Compose gesture system) * Refactor Sensey from singleton object to class with extension functions - Sensey is now a class accepting Context, optional Lifecycle, sampling period - internal registerSensorDetector/unregisterSensorDetector/composeGestureProvider methods - Removed setupDispatchTouchEvent, registerTouchHandler, unregisterTouchHandler - senseyRegister(context, lifecycle?) and senseyStop() top-level functions - defaultSensey internal property for compose modifier access * Decouple SensorDetector from Sensey singleton - sensorDataLoggingEnabled moved from static Sensey reference to internal var - Set by Sensey.registerSensorDetector() before registration - Allows SensorDetector to work without global singleton dependency * Create gesture plugin factory functions and private plugin classes - 17 factory functions: shakePlugin, flipPlugin, lightPlugin, proximityPlugin, etc. - SensorGesturePlugin: reusable base for sensor-based gesture registration - PinchScalePlugin + TouchTypePlugin: compose-based gesture detection - SoundLevelPlugin: AudioRecord-based detection - Private plugin classes prevent direct instantiation * Tighten public API: make all Detector and Trigger classes internal - 17 Detector and 17 Trigger classes changed from public to internal - Users interact only through factory functions (shakePlugin, flipPlugin, etc.) - GestureTrigger<T> interface remains public for custom trigger implementations - Event sealed classes remain public as callback data types * Migrate touch/scale gestures from View to Jetpack Compose - Add Compose dependencies (BOM, compose-ui, compose-foundation) to library - Enable compose build feature + compose compiler plugin - New compose/ package: ComposeGestureProvider interface + senseyGestures() Modifier + SenseyGestureEffect() - Delete View-based TouchTypeDetector and PinchScaleDetector - TouchTypeEvent/PinchScaleEvent now delivered via Compose pointer input - PinchScalePlugin uses detectTransformGestures, TouchTypePlugin uses detectTapGestures + detectDragGestures * Update sample app to use plugin-based API and Compose touch - SensorManager: register/unregister pattern via Sensey instance - TouchSensorManager: simplified to state holder, events received via lambdas - TouchActivity: uses SenseyGestureEffect instead of dispatchTouchEvent - TouchScreen: applies Modifier.senseyGestures() on touch area - MainActivity: uses senseyRegister/senseyStop extension functions * Fix test and remove stale gesture-details.md - ScoopTriggerTest: use correct parameter name (impulseThreshold instead of threshold) - gesture-details.md: removed (outdated View-based documentation) * Update documentation for plugin-based API and Compose integration - README: updated Quick start with both Activity and Compose patterns, simplified Architecture - USAGE.md: comprehensive rewrite with Setup, Common Examples (14 use cases), Context-specific usage, and all gesture docs with Compose patterns - dev-docs.md: updated custom plugin guide (removed TouchHandler, added ComposePlugin) - GitHub templates: simplified to minimal sections * Setup ktlint plugin and configuration * Fix ktlint code style violations across codebase * Enable Gradle configuration cache * Make log tags standout in logcat with ASCII art wrapping * Simplify SensorDetector hierarchy and Sensey core infrastructure - Replace isSensorEventBelongsToPluggedTypes with idiomatic '!in' - Extract resolveSensors helper using 'also' for logging side effects - Remove KDoc data table from GestureTrigger (now documented per trigger) - Use function references (::register, ::let) for conciseness * Refactor gesture triggers with private functions and simplified logic - Extract magnitude, baseline, and state detection into private functions - Replace Hungarian notation (mAccel, mAccelCurrent) with descriptive names - Use sealed enum for TouchTypeTrigger Quadrant classification - Simplify conditional chains with guard clauses - Add companion object constants for magic numbers * Simplify custom detectors and SoundLevelDetector coroutine code - Extract captureAudio, createAudioRecord, processAudioStream from SoundLevelDetector - Move audio release to dedicated private function - Extract computeOrientationAngles helper in RotationAngleDetector - Format OrientationTrigger toExpressionBody with proper when blocks * Setup Dokka 2.2.0 documentation generation with versioning plugins - Add dokka plugin to version catalog with versioning/kotlin-as-java/android-doc plugins - Configure Dokka HTML publication for sensey module with source links - Add publishDocs Gradle task for versioned documentation output - Add github-pages branch restore step for versioning continuity * Add GitHub Actions workflow for versioned docs deployment - Trigger on master/develop pushes and version tags - Restore previous docs from gh-pages branch for Dokka versioning - Organize output into versioned directories with index landing page - Deploy to GitHub Pages via upload-pages-artifact * Bump version to 2.0.0 * Update README and dev docs with Dokka, ktlint, and architecture details * Fix #47: clear sensor buffer on pickup so PutDown detection works * Fix #34: add minNearDurationMs to wave detection; bump #31: default timeWindowMillis to 2000ms * Fix #17: add debounce to proximity trigger to prevent false reads in multi-window * Fix broken tests: replace deleted Detector classes with TypedSensorDetector * Standardize gravity constant to 9.81f across all gesture triggers ScoopTrigger, ChopTrigger, TapOnBackTrigger used 9.8f while MovementTrigger used 9.81f. Consolidated all to the more accurate 9.81f to eliminate fractional threshold discrepancies between triggers. * Replace ArrayDeque with fixed FloatArray circular buffer in PickupDeviceTrigger ArrayDeque with addLast/removeFirst per sensor event creates unnecessary GC pressure. Pre-allocated FloatArray with rolling index + sum eliminates allocations in the sensor event hot path and improves cache locality. * Add baseline initialization to MovementTrigger to prevent spurious startup event Previous code used a hardcoded GRAVITY_EARTH (9.81f) as initial currentAccel. If the first real sensor reading differs (e.g. device on a table with slight tilt), a large delta would immediately fire a MovementEvent.Moved on startup. Now the first reading sets the baseline without producing an event. * Remove dead sensorTypes field from SensorGesturePlugin The sensorTypes constructor parameter was passed by all 14 factory functions but never read inside SensorGesturePlugin. The actual sensor type registration is handled internally by each SensorDetector subclass. Removing the dead code eliminates confusion and reduces constructor verbosity. * Add onDragCancel handler to TouchTypePlugin drag gesture Without onDragCancel, when the system cancels a drag gesture (e.g. incoming call, another gesture taking over), dragStart retains stale coordinates which corrupts the next drag's delta calculation. * Enable lint abortOnError in both modules Previously set to false, which suppressed security-relevant lint checks such as MissingPermission, UnsafeProtectedBroadcast, and ExportedContentProvider. Hardening to true ensures lint violations fail the build during CI. * Remove -assumenosideeffects Log.d from library proguard rules The assumenosideeffects rule stripped ALL Log.d calls from consumer apps' release builds, not just the library's own logging. This broke debugging/troubleshooting for host apps that rely on Log.d in production. Library proguard rules should only keep library internals, not alter consumer behavior. * Add RECORD_AUDIO permission declaration to library manifest The SoundLevelDetector uses AudioRecord with VOICE_RECOGNITION source. Without a manifest declaration, the Android package manager cannot enforce the permission at install time, leading to a runtime SecurityException on Android 12+ when permission is missing. maxSdkVersion=32 avoids redundant prompting on Android 13+ where the permission is granted at install time for legacy apps. * Fix PinchScalePlugin and TouchTypePlugin cleanup on unregister Previously onUnregister was a no-op for both plugins, meaning the ComposeGestureProvider instances added via registerComposeGestureProvider were never removed. This leaked pointer input handlers and caused stale callbacks if plugins were registered/unregistered dynamically. Now each plugin tracks its provider(s) and removes them on unregister. * Fix RuntimePermissionUtil multi-permission callback logic Previous code iterated over each grant result individually, firing onPermissionGranted for each granted and onPermissionDenied for each denied permission in the same request. For multi-permission requests, both callbacks would fire simultaneously. Now uses grantResults.all{} to emit a single success/failure decision per request. * Fix ShakeTrigger.initializeBaseline return type (Nothing? -> ShakeEvent?) Nothing? is Kotlin's bottom type, semantically meaning 'this function never returns normally'. initializeBaseline simply returns null to signal the baseline isn't ready yet. Using Nothing? disables compiler exhaustiveness checks and could mask future bugs. * Fix TapOnBackTrigger single-tap latency and silent drop Previous implementation deferred all tap events by tapSequenceTimeoutMs (500ms) and silently discarded single taps (only tapCount >= 2 fired). This made the gesture feel unresponsive and broke basic single-tap detection. Now fires TapOnBackEvent immediately on the first qualifying tap — the existing tapDebounceMs (250ms) prevents noise re-triggering. * Add RECORD_AUDIO permission guard to SoundLevelPlugin The SoundLevelDetector creates an AudioRecord without verifying that the host app holds RECORD_AUDIO permission, causing a SecurityException crash at runtime on Android 12+ or silent microphone access on older versions. Now SoundLevelPlugin.onRegister checks permission before starting the detector, and SoundLevelDetector.captureAudio catches SecurityException as defense-in-depth in case permission is revoked between check and use. * Revert "Fix TapOnBackTrigger single-tap latency and silent drop" This reverts commit 90b477baf33ad357f1735e7cb62c5b9ce39b58ce. * Add KDoc disclosure to soundLevelPlugin about microphone audio capture Documents that the plugin requires RECORD_AUDIO permission, captures raw audio via AudioRecord with VOICE_RECOGNITION source, and that no audio data is stored, transmitted, or persisted. * Enable minification in sample app release build Release build now uses R8 with proguard-android-optimize.txt and the sample's proguard-rules.pro which keeps Compose, Sensey public API, and Kotlin coroutines internals. * Expose FlipTrigger threshold parameters in flipPlugin() public API Previously flipPlugin() accepted only a dispatcher, hiding the FlipTrigger faceUp/faceDown bound parameters. Consumers can now calibrate detection sensitivity at plugin creation time. * Migrate sample permission flow to ActivityResultContracts and rename SensorManager - Replace deprecated onRequestPermissionsResult / ActivityCompat with registerForActivityResult(RequestPermission) - Rename sample SensorManager to SenseySensorManager to avoid shadowing android.hardware.SensorManager and prevent import collisions * Exclude develop branch from docs deployment Previously docs were published on pushes to both master and develop. Develop is an integration branch where intermediate snapshots should not overwrite the published documentation on GitHub Pages. | 5 months ago | |
Update: 6 (#65) * updated readme * docs: sync usage docs with current API - overview.md: replace deprecated static API calls (Sensey.register, Sensey.unregister) with instance-based senseyRegister DSL - taponback.md: fix minJerk default from 5f to 2f - turnover.md: fix angleThreshold default from 130f to 150f - _index files: add links for new gestures (Clap, DeviceSpin, RaiseToEar, TurnOver) - movement.md: update event descriptions - clap.md, devicespin.md, raisetoear.md, turnover.md: add documentation for new gesture plugins * feat(internal): add core internal utilities and audio capture infra - EmaSmoother: single-pole exponential moving average filter for sensor data smoothing - GyroIntegrator: cumulative gyroscope integration for turnover and device-spin detection - Util: helper functions (magnitude3, angleBetweenDeg, linearAccelMag) - AudioCapture: generic coroutine-based AudioRecord wrapper shared by SoundLevelDetector and ClapDetector; uses getMinBufferSize for buffer allocation instead of hardcoded sizes * feat(gesture): add Clap, DeviceSpin, RaiseToEar, TurnOver detectors - ClapDetector/ClapTrigger: detects clap sounds via AudioRecord RMS energy rise detection (thresholdDb, riseDb params) - DeviceSpinDetector/DeviceSpinTrigger: detects rapid device rotation on any axis using gyro integration - RaiseToEarDetector/RaiseToEarTrigger: fuses proximity + gravity sensor to detect phone-at-ear position for calls - TurnOverEvent/TurnOverTrigger: gyroscope-based 180-degree flip detection (more precise than accel-based Flip plugin) - TapOnBackDetector/TapOnBackTrigger: double-tap detection using linear acceleration magnitude with EMA jerk filtering * feat(gesture): wire new gestures into plugin registry and DSL - Add turnOverPlugin, deviceSpinPlugin, raiseToEarPlugin, clapPlugin to top-level gesture DSL functions - Add corresponding builder methods to SenseyPluginRegistry - SoundLevelPlugin and ClapPlugin: add RECORD_AUDIO permission check on register with graceful disable if not granted - Refactor internal plugin classes (SensorGesturePlugin, SoundLevelPlugin, ClapPlugin) for consistency * refactor(trigger): improve detection algorithms across gestures - ChopTrigger: adjust threshold defaults, add EMA smoothing for impulse detection - MovementTrigger: refine stationary timeout logic, improve direction reporting accuracy - PinchScaleTrigger: add confirmation count for debounce against jittery touch input - WristTwistTrigger: tuning defaults for wrist-twist motion profile * refactor(soundlevel): delegate to shared AudioCapture - SoundLevelDetector now delegates audio recording to the shared AudioCapture<T> internal class instead of duplicating AudioRecord lifecycle, coroutine scope, and buffer management - Reduces SoundLevelDetector from ~130 lines to ~15 lines * test: add tests for new gestures and fix existing tests - Add ClapTriggerTest: RMS energy rise detection - Add DeviceSpinTriggerTest: gyro angle threshold detection - Add RaiseToEarTriggerTest and RaiseToEarDetectorTest: proximity + gravity fusion - Add TapOnBackDetectorTest: double-tap with EMA jerk - Add TurnOverTriggerTest: gyro-based flip detection - Add EmaSmootherTest and UtilTest for internal utilities - Fix ChopDetectorTest, WristTwistDetectorTest, PickupDeviceTriggerTest for updated trigger signatures * refactor(sample): extract permission logic into PermissionRequestUtil - PermissionRequestUtil: generic permission request utility with register() / isGranted() / requestIfNeeded() methods - Audio-specific extensions: registerAudioPermission(), isAudioPermissionGranted(), requestAudioIfNeeded() - MainActivity: use PermissionRequestUtil, register touch/pinch plugins via senseyRegister in onCreate, remove stale hasRecordAudioPermission caching * feat(sample): unify touch/pinch sensors, add pending permission flow - Add TOUCH_DETECTION and PINCH_SCALE to sensors list with createPlugin entries using touchTypePlugin/pinchScalePlugin - Add pendingSensor + startAfterPermissionGranted() with sensey==null guard for deferred permission handling - Add clearPendingPermission() for denial recovery - Add resultsMap with per-sensor result text and auto-clear after 2s (3s for touch/pinch) * refactor(sample): merge touch/pinch into main screen, remove TouchActivity * chore(sample): remove TouchActivity from manifest * docs: update architecture and setup for new gestures and AudioCapture - architecture.md: add AudioCapture, EmaSmoother, GyroIntegrator to internal/ listing; list all 22 gesture directories explicitly - setup.md: add eager-initialization pattern for Compose apps that need senseyGestures() to work during initial composition * feat(gesture): add EdgeSwipe — detect swipes from composable edges - EdgeSwipeEvent/EdgeSwipeTrigger: pure detection logic, reports which composable edge (LEFT/RIGHT/TOP/BOTTOM) the swipe originated from - EdgeSwipePlugin: Compose touch plugin using detectDragGestures; edgeThresholdDp is accepted as Dp (not raw pixels) and converted to px via Density for density-independent edge detection - Supports all four edges enabled by default; configure via edgeThresholdDp and enabledEdges parameters - Sample app: Edge Swipe sensor entry with SenseyRadioButtonWithTouchArea - Docs: edgeswipe.md with events, parameters, usage, and use cases * feat(gesture): add DiagonalSwipe — detect diagonal drags in composable - DiagonalSwipeEvent/DiagonalSwipeTrigger: pure logic using atan2 angle classification; reports UP_RIGHT, DOWN_RIGHT, DOWN_LEFT, UP_LEFT directions - Configurable minDragDistance and angleToleranceDeg (default 22.5°) - DiagonalSwipePlugin: Compose touch plugin using detectDragGestures - Sample app: Diagonal Swipe sensor entry with hit area - Docs: diagonalswipe.md with events, parameters, usage * ktlint format * refactor(sample): use SensorList composable, move touch handling inside it - SensorList now detects touch labels and renders SenseyRadioButtonWithTouchArea for touch/gesture sensors, SenseyRadioButton for all others - MainScreen simplified to just layout shell: Surface → Column(AppHeader, Box(SensorList)) * feat(sample): add SenseyTheme/PreviewTheme, remove hardcoded Colors.kt - Theme.kt: DarkColorScheme + LightColorScheme with orange/cyan/pink accents; SenseyTheme switches via isSystemInDarkTheme(); PreviewTheme wraps with Surface + background color + padding for previews - Colors.kt deleted — all color references replaced with MaterialTheme.colorScheme - MainActivity: wrap content in SenseyTheme * refactor(sample): simplify MainScreen, move touch logic into SensorList - MainScreen: reduced to layout shell (Surface → Column → AppHeader + Box → SensorList); all sensor rendering logic removed - SensorList: now handles both regular sensors (SenseyRadioButton) and touch-based sensors (SenseyRadioButtonWithTouchArea) with helper text mapping extracted into helperTextForLabel() - SenseyRadioButton/SenseyRadioButtonWithTouchArea: replace hardcoded colors with MaterialTheme.colorScheme references * fix(sample): Material3 TopAppBar header, ResultArea with fixed height - AppHeader: replace custom Surface/Text/Divider with CenterAlignedTopAppBar using topAppBarColors for proper insets, elevation, and typography - ResultArea: add .height(120.dp) for defined touch target and RoundedCornerShape(8.dp); all 4 previews use PreviewTheme * fix color * Add coroutines/flow support for gesture event collection - Add SenseyFlowScope with lifecycle-aware callbackFlow bridging - Add SenseyFlowEffect Compose wrapper using DisposableEffect - Add observe() default method to GestureTrigger interface - Add MockK and Turbine test dependencies - Add GestureTriggerFlowTest and SenseyFlowScopeTest - Update docs with flow API usage and architecture details * deps: remove unused catalog entries and switch to compileOnly Remove androidx-core-ktx and androidx-annotation (unused in source). Switch lifecycle-common, coroutines-core, coroutines-android, and all compose deps from implementation to compileOnly. Add lifecycle-runtime for test usage. * sample: add explicit deps for compileOnly libraries Lifecycle and coroutines are no longer transitively bundled by sensey. Add them explicitly in the sample app. * fix: resolve pre-existing test failures MovementTrigger: remove hasBaseline guard so first reading is not discarded. ScoopTrigger: reduce baselineSamples to 0 and minSustainedSamples to 1 for immediate response; set debounceMs to 0 and use >= for debounce check. Tests: align assertions with actual trigger behavior for direction ambiguity, partial magnitude conditions, infinite audio input, and mock proximity events. * docs: update for compileOnly dependencies Clarify that dependencies are not bundled transitively and consumers most likely already have them. Add dependency table mapping features to required libraries. * docs: add explicit dependency coordinates to setup guide Show the exact artifact coordinates under each bullet so users know what to include if they don't already have the dependency. * refactor: use Dispatchers.Default instead of Dispatchers.Main SenseyFlow scope and AudioCapture callback both used Dispatchers.Main. Switch to Default — sensor/audio processing and user callbacks are not UI-specific work. Drop kotlinx-coroutines-android entirely as no longer needed. * chore: remove unused kotlinx-coroutines-android catalog entry No longer referenced after switching to Dispatchers.Default. * feat: implement NodGesture gesture detection Add NodGestureTrigger and NodGestureEvent for detecting nod (yes) gestures using gyroscope pitch oscillation via GyroIntegrator. * feat: implement HeadShake gesture detection Add HeadShakeTrigger and HeadShakeEvent for detecting head shake (no) gestures using gyroscope yaw oscillation via GyroIntegrator. * test: add tests for NodGesture trigger Add NodGestureTriggerTest covering nod detection, debounce, cooldown, and noise suppression. * test: add tests for HeadShake trigger Add HeadShakeTriggerTest covering head shake detection, debounce, cooldown, and noise suppression. * feat: register NodGesture and HeadShake in plugin system Add nodGesturePlugin() and headShakePlugin() factory functions in GesturePlugins.kt, registration methods in SenseyPluginRegistry, and flow builder methods in SenseyFlowScope. Both use GyroIntegrator-based triggers. * feat: overhaul ClapTrigger with ZCR weighting, adaptive noise floor, and multi-clap counting Replaces old rise-dB threshold logic with a multi-stage pipeline:\n- ZCR-weighted RMS to reject narrow-band sounds (speech, music)\n- Adaptive noise floor with fast-attack/slow-release EMA\n- Multi-clap counting within configurable rolling time window\n- Configurable debounce to prevent re-trigger\n- Updated defaults: thresholdDb=-45f, requiredClaps=2, clapTimeframeMs=800L\n- Updated docs with new parameters and tuning tips * refactor: improve SoundLevelTrigger and AudioCapture error handling - SoundLevelTrigger: extract helper methods, add offset parameter with docs, fix constant naming\n- AudioCapture: handle CancellationException and SecurityException gracefully\n- AndroidManifest: remove maxSdkVersion=32 from RECORD_AUDIO so manifest targets all API levels\n- soundlevel.md: add parameters table, interpretation guide, and algorithm details * fix: add debounce to ChopTrigger, tune default threshold - Add cooldown check to prevent chop re-trigger within the gesture window\n- Raise default threshold from 25f to 35f to reduce false positives\n- Update chop.md with new default and 'How to perform' section * fix: use Modifier.pointerInput in sensey gesture modifier Fix dangling .pointerInput(Unit) call by chaining it as Modifier.pointerInput(Unit) within the compose modifier chain. * feat: update sample app with NodGesture, HeadShake, sensor availability check, and snackbar - Add NodGesture and HeadShake to sensor list with dispatchers\n- Add isSensorAvailable() check with snackbar notification for missing sensors\n- Refactor MainScreen to use Scaffold with SnackbarHost for feedback\n- Remove unused HapticUtil.confirmation()\n- Use SAMPLING_PERIOD_GAME for lower-latency sensor updates * chore: add git hooks install task to build Add installGitHooks Gradle task that sets core.hooksPath to .githooks, running ktlintFormat on each commit. * docs: update README with NodGesture and HeadShake Add NodGesture and HeadShake to the gesture list. Update coroutines/flow note to be more general. * docs: add NodGesture and HeadShake documentation pages Add new gesture documentation pages for NodGesture (nod 'yes') and HeadShake (shake 'no') with algorithm details, parameters, events, and usage examples. Update _index.md to list both. * docs: add 'How to perform' section to 7 gesture pages Add 'How to perform' section with user-facing descriptions to: DeviceSpin, DiagonalSwipe, EdgeSwipe, Flip, Light, Movement, Orientation. * docs: add 'How to perform' section to 7 gesture pages Add 'How to perform' section with user-facing descriptions to: PickupDevice, PinchScale, Proximity, RaiseToEar, RotationAngle, Scoop, Shake. * docs: add 'How to perform' section to 7 gesture pages Add 'How to perform' section with user-facing descriptions to: Step, TapOnBack, TiltDirection, TouchType, TurnOver, Wave, WristTwist. * chore: add pre-commit hook for ktlintFormat Add .githooks/pre-commit that runs ./gradlew ktlintFormat on every commit to enforce Kotlin formatting. * fix: detect head shake on combined Y+Z axes for tilted device When phone is held tilted (top higher), 'no' head shake projects onto both Y and Z axes. Previously only Z was tracked, missing half the signal. Fix: combine Y+Z into an effective horizontal angle. Works at any pitch angle. * docs: update HeadShake doc for combined Y+Z axis detection Update algorithm description from Z-only to combined Y+Z axes. Mention tilt-agnostic behavior in How to perform. Update parameter description to reflect horizontal rotation metric. * ci: add PR Check workflow with test, ktlint, and lint steps * update branch in pr-check workflow | 5 months ago | |
[+] added License.txt | 10 years ago | |
Update: 7 (#66) * feat: add LongPressDrag, TwoFingerSwipe, CornerSwipe gesture plugins - GesturePlugins: factory functions + private plugin classes - LongPressDragPlugin (detectDragGesturesAfterLongPress) - TwoFingerSwipePlugin (awaitEachGesture + 2-pointer check) - CornerSwipePlugin (detectDragGestures + corner classification) - SenseyPluginRegistry: registration methods for all three - Event + Trigger + unit tests for each gesture * docs: add LongPressDrag, TwoFingerSwipe, CornerSwipe gesture docs - How to perform, algorithm description, events table - Configurable parameters with defaults - Usage code snippets and use-case tables * refactor(sample): clean up SenseySensorManager, wire new gestures - Remove unused parameter from setResultText - Merge handleStartDetector into startDetector/stopDetector - Add dispatchers and plugin creation for LongPressDrag, TwoFingerSwipe, CornerSwipe - Fix helperTextForLabel: return '' for non-touch sensors, add DiagonalSwipe entry * refactor(sample): create Paddings.kt, replace hardcoded dp values - Paddings: none(0), sm(4), md(8), lg(16), xl(20) - Wire helperText into SenseyRadioButton - Replace Color.LightGray with onSurfaceVariant for theme-aware gray * chore: fix banner path, add docs index banner, remove unused logo * fix(sample): add helper texts for all sensor gestures - Add descriptive helper text for all 29 sensor/gesture types - Each describes what event(s) the gesture detects - Update preview with more sensor variety * fix(sample): rewrite helper texts as user-facing action descriptions All helper texts now describe what gesture the user should perform instead of technical event names. e.g. 'Shake the device' instead of 'Shake / Shake Stopped' * sample: refactor with Nav3, gesture groups, ViewModel, adaptive nav - Add Navigation 3 with sealed GestureGroup routes (Touch, Motion, Orientation, Environment) - Group 30 gestures into 4 logical tabs with emoji-only nav items - Add SampleViewModel with StateFlow-driven UI state - Implement adaptive layout: NavigationBar on phones, NavigationRail on tablets+ - Wire ViewModel ↔ SenseySensorManager via result callback - Add gradle deps: nav3, kotlinx-serialization, lifecycle-viewmodel-compose - Split MainScreen into dedicated files: GestureNavBar, GestureNavRail, GestureNavRailLayout, GestureCompactLayout, SensorEntryProvider * sample: extract ScrollbarThumb as reusable component with KDoc - Move ScrollbarThumb from private function in SensorList to standalone file - Add configurable params: thumbColor, thumbWidth, hideDelayMs - Add KDoc with usage example and parameter documentation - Update SensorList to import from shared component * sample: reorganize ui package into sub-packages with internal visibility - ui/core/ — Theme, Paddings, AppHeader (shared primitives) - ui/sensors/ — SensorList, SensorEntryProvider, SenseyRadioButton, SenseyRadioButtonWithTouchArea, ResultArea, ScrollbarThumb - ui/nav/ — MainScreen, GestureNavBar, GestureNavRail, GestureNavRailLayout, GestureCompactLayout - ui/tabs/ — GestureGroupTab (unchanged) - Mark all composables internal except SensorItem, sensorEntryProvider, MainScreen, and core types needed cross-package * style: reformat SenseyRadioButtonWithTouchArea padding * sample: wire ViewModel snackbarEvent into UI, remove unused functions * refactor: add content slot and scroll behavior to navigation layouts * style: update navigation bar and rail styling * feat: update theme color palette * refactor: simplify radio button components with extracted RadioButtonRow * feat: animate scrollbar thumb auto-hide * chore: add edge-to-edge system bar styles * feat(touch): introduce consolidated touch gesture API Add unified touch/ package replacing the 7 separate touch detectors: - TouchEvent: sealed interface with Tap, Swipe, Scroll, LongPressDrag, PinchScale - TouchConfig: feature-based config (taps, swipe, edgeSwipe, cornerSwipe, ...) - TouchGesture: sealed contract for all touch triggers - TouchPlugin: single Compose plugin registering providers by config - 6 internal triggers: SwipeScrollTrigger, LongPressDragTrigger, PinchScaleTrigger, TwoFingerSwipeTrigger, EdgeSwipeTrigger, CornerSwipeTrigger - Internal utils: DirectionUtils, SwipeClassifier Pure addition. Old packages will be removed in a follow-up commit. * test(touch): add unit tests for all 6 touch triggers Cover SwipeScrollTrigger, LongPressDragTrigger, PinchScaleTrigger, TwoFingerSwipeTrigger, EdgeSwipeTrigger, and CornerSwipeTrigger. Each test file focuses on its trigger's evaluate() method with edge cases (threshold, filtering, direction classification). * refactor(touch): switch GesturePlugins, registry, flow to new touch/ API - Rewrite GesturePlugins.kt: all touch wrapper functions now create TouchPlugin with feature-based TouchConfig. Removed ~500 lines of private plugin classes (TouchTypePlugin, EdgeSwipePlugin, etc.). Removed touchTypePlugin (redundant with touchPlugin default config). - Update SenseyPluginRegistry.kt: touch methods use TouchEvent + new config types - Update SenseyFlow.kt: same, add missing longPressDrag/twoFingerSwipe/cornerSwipe - Delete 7 old source packages: cornerswipe/, edgeswipe/, diagonalswipe/, twofingerswipe/, longpressdrag/, pinchscale/, touchtype/ - Delete 5 old test files matching deleted packages * refactor(sample): update to use new TouchEvent types - Replace touchTypePlugin import with touchPlugin - Rename touchTypeDispatcher to touchDispatcher - Replace TouchTypeEvent references with TouchEvent sealed hierarchy - Use safe type checks (if is TouchEvent.Swipe) instead of hard casts - Remove ThreeFingerSingleTap handling - Update direction helpers to use TouchEvent.Direction * docs(touch): update documentation for consolidated touch API - Add touch.md as the generic touchPlugin entry point with feature-based config table and convenience wrapper reference - Update cornerswipe, edgeswipe, diagonalswipe, twofingerswipe, longpressdrag, pinchscale docs to describe them as wrappers around touchPlugin with pre-configured TouchConfig - Update context-specific-usage.md to use touchPlugin + TouchEvent instead of touchTypePlugin + TouchTypeEvent - Delete touchtype.md (replaced by touch.md) * fix(sample): handle both Swipe and Scroll in diagonal swipe dispatcher; fix pinch label mismatch - DiagonalSwipeDispatcher now handles TouchEvent.Scroll in addition to TouchEvent.Swipe (slow diagonal drags were being silently dropped) - Fix 'Pinch Scale Detection' label mismatch in SensorList.kt and GestureGroupTab.kt (constants were renamed to 'Pinch Scale' but the UI checks still referenced the old label) * fix(sample): add missing haptic feedback to tap and pinch scale dispatchers * fix(sample): show edge swipe origin and direction in dispatcher * docs(touch): add KDoc example for edge + direction differentiation * docs: add edge + direction differentiation examples in usage docs * feat(sample): replace Sensey text with logo vector drawable tinted primary * refactor(sample): update color palette with neon orange primary, amber secondary, bottle green tertiary * fix(sample): improve radio button label/helper typography * add the logo vector drawable * update readme banner and add logo svg | 5 months ago | |
Update: 6 (#65) * updated readme * docs: sync usage docs with current API - overview.md: replace deprecated static API calls (Sensey.register, Sensey.unregister) with instance-based senseyRegister DSL - taponback.md: fix minJerk default from 5f to 2f - turnover.md: fix angleThreshold default from 130f to 150f - _index files: add links for new gestures (Clap, DeviceSpin, RaiseToEar, TurnOver) - movement.md: update event descriptions - clap.md, devicespin.md, raisetoear.md, turnover.md: add documentation for new gesture plugins * feat(internal): add core internal utilities and audio capture infra - EmaSmoother: single-pole exponential moving average filter for sensor data smoothing - GyroIntegrator: cumulative gyroscope integration for turnover and device-spin detection - Util: helper functions (magnitude3, angleBetweenDeg, linearAccelMag) - AudioCapture: generic coroutine-based AudioRecord wrapper shared by SoundLevelDetector and ClapDetector; uses getMinBufferSize for buffer allocation instead of hardcoded sizes * feat(gesture): add Clap, DeviceSpin, RaiseToEar, TurnOver detectors - ClapDetector/ClapTrigger: detects clap sounds via AudioRecord RMS energy rise detection (thresholdDb, riseDb params) - DeviceSpinDetector/DeviceSpinTrigger: detects rapid device rotation on any axis using gyro integration - RaiseToEarDetector/RaiseToEarTrigger: fuses proximity + gravity sensor to detect phone-at-ear position for calls - TurnOverEvent/TurnOverTrigger: gyroscope-based 180-degree flip detection (more precise than accel-based Flip plugin) - TapOnBackDetector/TapOnBackTrigger: double-tap detection using linear acceleration magnitude with EMA jerk filtering * feat(gesture): wire new gestures into plugin registry and DSL - Add turnOverPlugin, deviceSpinPlugin, raiseToEarPlugin, clapPlugin to top-level gesture DSL functions - Add corresponding builder methods to SenseyPluginRegistry - SoundLevelPlugin and ClapPlugin: add RECORD_AUDIO permission check on register with graceful disable if not granted - Refactor internal plugin classes (SensorGesturePlugin, SoundLevelPlugin, ClapPlugin) for consistency * refactor(trigger): improve detection algorithms across gestures - ChopTrigger: adjust threshold defaults, add EMA smoothing for impulse detection - MovementTrigger: refine stationary timeout logic, improve direction reporting accuracy - PinchScaleTrigger: add confirmation count for debounce against jittery touch input - WristTwistTrigger: tuning defaults for wrist-twist motion profile * refactor(soundlevel): delegate to shared AudioCapture - SoundLevelDetector now delegates audio recording to the shared AudioCapture<T> internal class instead of duplicating AudioRecord lifecycle, coroutine scope, and buffer management - Reduces SoundLevelDetector from ~130 lines to ~15 lines * test: add tests for new gestures and fix existing tests - Add ClapTriggerTest: RMS energy rise detection - Add DeviceSpinTriggerTest: gyro angle threshold detection - Add RaiseToEarTriggerTest and RaiseToEarDetectorTest: proximity + gravity fusion - Add TapOnBackDetectorTest: double-tap with EMA jerk - Add TurnOverTriggerTest: gyro-based flip detection - Add EmaSmootherTest and UtilTest for internal utilities - Fix ChopDetectorTest, WristTwistDetectorTest, PickupDeviceTriggerTest for updated trigger signatures * refactor(sample): extract permission logic into PermissionRequestUtil - PermissionRequestUtil: generic permission request utility with register() / isGranted() / requestIfNeeded() methods - Audio-specific extensions: registerAudioPermission(), isAudioPermissionGranted(), requestAudioIfNeeded() - MainActivity: use PermissionRequestUtil, register touch/pinch plugins via senseyRegister in onCreate, remove stale hasRecordAudioPermission caching * feat(sample): unify touch/pinch sensors, add pending permission flow - Add TOUCH_DETECTION and PINCH_SCALE to sensors list with createPlugin entries using touchTypePlugin/pinchScalePlugin - Add pendingSensor + startAfterPermissionGranted() with sensey==null guard for deferred permission handling - Add clearPendingPermission() for denial recovery - Add resultsMap with per-sensor result text and auto-clear after 2s (3s for touch/pinch) * refactor(sample): merge touch/pinch into main screen, remove TouchActivity * chore(sample): remove TouchActivity from manifest * docs: update architecture and setup for new gestures and AudioCapture - architecture.md: add AudioCapture, EmaSmoother, GyroIntegrator to internal/ listing; list all 22 gesture directories explicitly - setup.md: add eager-initialization pattern for Compose apps that need senseyGestures() to work during initial composition * feat(gesture): add EdgeSwipe — detect swipes from composable edges - EdgeSwipeEvent/EdgeSwipeTrigger: pure detection logic, reports which composable edge (LEFT/RIGHT/TOP/BOTTOM) the swipe originated from - EdgeSwipePlugin: Compose touch plugin using detectDragGestures; edgeThresholdDp is accepted as Dp (not raw pixels) and converted to px via Density for density-independent edge detection - Supports all four edges enabled by default; configure via edgeThresholdDp and enabledEdges parameters - Sample app: Edge Swipe sensor entry with SenseyRadioButtonWithTouchArea - Docs: edgeswipe.md with events, parameters, usage, and use cases * feat(gesture): add DiagonalSwipe — detect diagonal drags in composable - DiagonalSwipeEvent/DiagonalSwipeTrigger: pure logic using atan2 angle classification; reports UP_RIGHT, DOWN_RIGHT, DOWN_LEFT, UP_LEFT directions - Configurable minDragDistance and angleToleranceDeg (default 22.5°) - DiagonalSwipePlugin: Compose touch plugin using detectDragGestures - Sample app: Diagonal Swipe sensor entry with hit area - Docs: diagonalswipe.md with events, parameters, usage * ktlint format * refactor(sample): use SensorList composable, move touch handling inside it - SensorList now detects touch labels and renders SenseyRadioButtonWithTouchArea for touch/gesture sensors, SenseyRadioButton for all others - MainScreen simplified to just layout shell: Surface → Column(AppHeader, Box(SensorList)) * feat(sample): add SenseyTheme/PreviewTheme, remove hardcoded Colors.kt - Theme.kt: DarkColorScheme + LightColorScheme with orange/cyan/pink accents; SenseyTheme switches via isSystemInDarkTheme(); PreviewTheme wraps with Surface + background color + padding for previews - Colors.kt deleted — all color references replaced with MaterialTheme.colorScheme - MainActivity: wrap content in SenseyTheme * refactor(sample): simplify MainScreen, move touch logic into SensorList - MainScreen: reduced to layout shell (Surface → Column → AppHeader + Box → SensorList); all sensor rendering logic removed - SensorList: now handles both regular sensors (SenseyRadioButton) and touch-based sensors (SenseyRadioButtonWithTouchArea) with helper text mapping extracted into helperTextForLabel() - SenseyRadioButton/SenseyRadioButtonWithTouchArea: replace hardcoded colors with MaterialTheme.colorScheme references * fix(sample): Material3 TopAppBar header, ResultArea with fixed height - AppHeader: replace custom Surface/Text/Divider with CenterAlignedTopAppBar using topAppBarColors for proper insets, elevation, and typography - ResultArea: add .height(120.dp) for defined touch target and RoundedCornerShape(8.dp); all 4 previews use PreviewTheme * fix color * Add coroutines/flow support for gesture event collection - Add SenseyFlowScope with lifecycle-aware callbackFlow bridging - Add SenseyFlowEffect Compose wrapper using DisposableEffect - Add observe() default method to GestureTrigger interface - Add MockK and Turbine test dependencies - Add GestureTriggerFlowTest and SenseyFlowScopeTest - Update docs with flow API usage and architecture details * deps: remove unused catalog entries and switch to compileOnly Remove androidx-core-ktx and androidx-annotation (unused in source). Switch lifecycle-common, coroutines-core, coroutines-android, and all compose deps from implementation to compileOnly. Add lifecycle-runtime for test usage. * sample: add explicit deps for compileOnly libraries Lifecycle and coroutines are no longer transitively bundled by sensey. Add them explicitly in the sample app. * fix: resolve pre-existing test failures MovementTrigger: remove hasBaseline guard so first reading is not discarded. ScoopTrigger: reduce baselineSamples to 0 and minSustainedSamples to 1 for immediate response; set debounceMs to 0 and use >= for debounce check. Tests: align assertions with actual trigger behavior for direction ambiguity, partial magnitude conditions, infinite audio input, and mock proximity events. * docs: update for compileOnly dependencies Clarify that dependencies are not bundled transitively and consumers most likely already have them. Add dependency table mapping features to required libraries. * docs: add explicit dependency coordinates to setup guide Show the exact artifact coordinates under each bullet so users know what to include if they don't already have the dependency. * refactor: use Dispatchers.Default instead of Dispatchers.Main SenseyFlow scope and AudioCapture callback both used Dispatchers.Main. Switch to Default — sensor/audio processing and user callbacks are not UI-specific work. Drop kotlinx-coroutines-android entirely as no longer needed. * chore: remove unused kotlinx-coroutines-android catalog entry No longer referenced after switching to Dispatchers.Default. * feat: implement NodGesture gesture detection Add NodGestureTrigger and NodGestureEvent for detecting nod (yes) gestures using gyroscope pitch oscillation via GyroIntegrator. * feat: implement HeadShake gesture detection Add HeadShakeTrigger and HeadShakeEvent for detecting head shake (no) gestures using gyroscope yaw oscillation via GyroIntegrator. * test: add tests for NodGesture trigger Add NodGestureTriggerTest covering nod detection, debounce, cooldown, and noise suppression. * test: add tests for HeadShake trigger Add HeadShakeTriggerTest covering head shake detection, debounce, cooldown, and noise suppression. * feat: register NodGesture and HeadShake in plugin system Add nodGesturePlugin() and headShakePlugin() factory functions in GesturePlugins.kt, registration methods in SenseyPluginRegistry, and flow builder methods in SenseyFlowScope. Both use GyroIntegrator-based triggers. * feat: overhaul ClapTrigger with ZCR weighting, adaptive noise floor, and multi-clap counting Replaces old rise-dB threshold logic with a multi-stage pipeline:\n- ZCR-weighted RMS to reject narrow-band sounds (speech, music)\n- Adaptive noise floor with fast-attack/slow-release EMA\n- Multi-clap counting within configurable rolling time window\n- Configurable debounce to prevent re-trigger\n- Updated defaults: thresholdDb=-45f, requiredClaps=2, clapTimeframeMs=800L\n- Updated docs with new parameters and tuning tips * refactor: improve SoundLevelTrigger and AudioCapture error handling - SoundLevelTrigger: extract helper methods, add offset parameter with docs, fix constant naming\n- AudioCapture: handle CancellationException and SecurityException gracefully\n- AndroidManifest: remove maxSdkVersion=32 from RECORD_AUDIO so manifest targets all API levels\n- soundlevel.md: add parameters table, interpretation guide, and algorithm details * fix: add debounce to ChopTrigger, tune default threshold - Add cooldown check to prevent chop re-trigger within the gesture window\n- Raise default threshold from 25f to 35f to reduce false positives\n- Update chop.md with new default and 'How to perform' section * fix: use Modifier.pointerInput in sensey gesture modifier Fix dangling .pointerInput(Unit) call by chaining it as Modifier.pointerInput(Unit) within the compose modifier chain. * feat: update sample app with NodGesture, HeadShake, sensor availability check, and snackbar - Add NodGesture and HeadShake to sensor list with dispatchers\n- Add isSensorAvailable() check with snackbar notification for missing sensors\n- Refactor MainScreen to use Scaffold with SnackbarHost for feedback\n- Remove unused HapticUtil.confirmation()\n- Use SAMPLING_PERIOD_GAME for lower-latency sensor updates * chore: add git hooks install task to build Add installGitHooks Gradle task that sets core.hooksPath to .githooks, running ktlintFormat on each commit. * docs: update README with NodGesture and HeadShake Add NodGesture and HeadShake to the gesture list. Update coroutines/flow note to be more general. * docs: add NodGesture and HeadShake documentation pages Add new gesture documentation pages for NodGesture (nod 'yes') and HeadShake (shake 'no') with algorithm details, parameters, events, and usage examples. Update _index.md to list both. * docs: add 'How to perform' section to 7 gesture pages Add 'How to perform' section with user-facing descriptions to: DeviceSpin, DiagonalSwipe, EdgeSwipe, Flip, Light, Movement, Orientation. * docs: add 'How to perform' section to 7 gesture pages Add 'How to perform' section with user-facing descriptions to: PickupDevice, PinchScale, Proximity, RaiseToEar, RotationAngle, Scoop, Shake. * docs: add 'How to perform' section to 7 gesture pages Add 'How to perform' section with user-facing descriptions to: Step, TapOnBack, TiltDirection, TouchType, TurnOver, Wave, WristTwist. * chore: add pre-commit hook for ktlintFormat Add .githooks/pre-commit that runs ./gradlew ktlintFormat on every commit to enforce Kotlin formatting. * fix: detect head shake on combined Y+Z axes for tilted device When phone is held tilted (top higher), 'no' head shake projects onto both Y and Z axes. Previously only Z was tracked, missing half the signal. Fix: combine Y+Z into an effective horizontal angle. Works at any pitch angle. * docs: update HeadShake doc for combined Y+Z axis detection Update algorithm description from Z-only to combined Y+Z axes. Mention tilt-agnostic behavior in How to perform. Update parameter description to reflect horizontal rotation metric. * ci: add PR Check workflow with test, ktlint, and lint steps * update branch in pr-check workflow | 5 months ago | |
Update: 5 (#64) * Remove Apache license headers from source files * updated gitgnore * Remove Dokka setup and restructure documentation - Remove Dokka plugin, config, and dependencies from build system - Delete Dokka CI workflow and publishDocs task - Move usage guide and dev docs into docs/ directory - Update README and dev docs to remove Dokka references * Add Hugo site configuration and CI * Update .gitignore and README for Hugo docs migration * Restructure usage docs into Hugo content directory * Restructure development docs into Hugo content directory * Extract GRAVITY_EARTH constant to shared internal/Constants.kt * Make SensorDetector, TypedSensorDetector, ComposeGestureProvider and registration methods public * Rewrite architecture and custom plugin docs with practical examples and inline comments * Tighten language and add inline comments across usage docs and dev guides * Clean up trailing whitespace in README * Version docs by git tag — pushes to /vX.Y.Z/ on gh-pages branch * Split Components.kt into individual files and add @Preview to MainScreen and TouchScreen * updated ui * Fix ProximityTrigger stalling and LightTrigger baseline inconsistency ProximityTrigger: Remove 2-event debounce state machine that stalled with on-change proximity sensors (most Android hardware). Near never dispatched, Far dispatched once then trigger was permanently stuck. LightTrigger: initializeBaseline() used lightThreshold for wasDark but darkThreshold for the return event. When ambient light was in the hysteresis band, the state machine desynced and silently ate Dark transitions. * Replace isDetected boolean with eventCount counter in SenseySensorManager mutableStateOf<Boolean> doesn't trigger recomposition when set to the same value (true → true on rapid events). Use mutableIntStateOf counter that guarantees a unique value on every event. Removed unused resetJob and coroutine delay imports. * Use eventCount with LaunchedEffect for DetectionIndicator timing MainScreen accepts eventCount: Int instead of detected: Boolean. LaunchedEffect watches the counter, sets detected = true on each event, resets after 3s. MainActivity passes sensorManager.eventCount. * Fix StepTrigger flood and PinchScaleTrigger counter accumulation StepTrigger: Gate buildStepEvent behind actual step detection. - evaluateStepCounter now returns null for the baseline-reading call and filters repeated sensor values via lastDispatchedSteps - evaluateAccelerometer no longer calls buildStepEvent unconditionally; only emits when magnitude delta exceeds threshold - Starting previousMagnitude=0 no longer triggers a phantom first step (abs(9.8 - 0) > 3 was always true) PinchScaleTrigger: Reset opposite counter after dispatching. - scaleInCount and scaleOutCount only incremented, never reset → after the first SCALE_IN, scaleInCount was permanently > 2, so all subsequent SCALE_IN events fired on the first reading * Fix ScoopTrigger baseline race, WaveTrigger time window, PickupDeviceTrigger buffer clearing ScoopTrigger: Add baselineReadings counter to skip impulse detection during the first 10 readings, letting the EMA baseline converge before evaluating impulses. Prevents false triggers from stale GRAVITY_EARTH. WaveTrigger: Change timeWindowMillis from Float to Long. Only update lastProximityEventTime on the Near transition, so the time window correctly measures the full gesture duration (Near→Far) instead of resetting on every continuous-sensor reading. PickupDeviceTrigger: Remove buffer clearing on PickedUp — the rolling window self-heals naturally. Eliminates the 3-reading blind spot. * Add class-level KDoc and inline comments to all 18 gesture triggers * Update all gesture doc pages with algorithm descriptions and corrected defaults * Move algorithm descriptions into dedicated ## Algorithm section on each gesture page * Remove internal-only parameters from gesture docs that users cannot configure * Change PickupDeviceTrigger settle from reading-count to time-based * Expose settleTimeMs parameter in pickupDevicePlugin API * Update pickup device docs with settleTimeMs parameter * Wire resultText into MainScreen status row from sensor manager * Update sample app theme to black background | 5 months ago | |
Update: 5 (#64) * Remove Apache license headers from source files * updated gitgnore * Remove Dokka setup and restructure documentation - Remove Dokka plugin, config, and dependencies from build system - Delete Dokka CI workflow and publishDocs task - Move usage guide and dev docs into docs/ directory - Update README and dev docs to remove Dokka references * Add Hugo site configuration and CI * Update .gitignore and README for Hugo docs migration * Restructure usage docs into Hugo content directory * Restructure development docs into Hugo content directory * Extract GRAVITY_EARTH constant to shared internal/Constants.kt * Make SensorDetector, TypedSensorDetector, ComposeGestureProvider and registration methods public * Rewrite architecture and custom plugin docs with practical examples and inline comments * Tighten language and add inline comments across usage docs and dev guides * Clean up trailing whitespace in README * Version docs by git tag — pushes to /vX.Y.Z/ on gh-pages branch * Split Components.kt into individual files and add @Preview to MainScreen and TouchScreen * updated ui * Fix ProximityTrigger stalling and LightTrigger baseline inconsistency ProximityTrigger: Remove 2-event debounce state machine that stalled with on-change proximity sensors (most Android hardware). Near never dispatched, Far dispatched once then trigger was permanently stuck. LightTrigger: initializeBaseline() used lightThreshold for wasDark but darkThreshold for the return event. When ambient light was in the hysteresis band, the state machine desynced and silently ate Dark transitions. * Replace isDetected boolean with eventCount counter in SenseySensorManager mutableStateOf<Boolean> doesn't trigger recomposition when set to the same value (true → true on rapid events). Use mutableIntStateOf counter that guarantees a unique value on every event. Removed unused resetJob and coroutine delay imports. * Use eventCount with LaunchedEffect for DetectionIndicator timing MainScreen accepts eventCount: Int instead of detected: Boolean. LaunchedEffect watches the counter, sets detected = true on each event, resets after 3s. MainActivity passes sensorManager.eventCount. * Fix StepTrigger flood and PinchScaleTrigger counter accumulation StepTrigger: Gate buildStepEvent behind actual step detection. - evaluateStepCounter now returns null for the baseline-reading call and filters repeated sensor values via lastDispatchedSteps - evaluateAccelerometer no longer calls buildStepEvent unconditionally; only emits when magnitude delta exceeds threshold - Starting previousMagnitude=0 no longer triggers a phantom first step (abs(9.8 - 0) > 3 was always true) PinchScaleTrigger: Reset opposite counter after dispatching. - scaleInCount and scaleOutCount only incremented, never reset → after the first SCALE_IN, scaleInCount was permanently > 2, so all subsequent SCALE_IN events fired on the first reading * Fix ScoopTrigger baseline race, WaveTrigger time window, PickupDeviceTrigger buffer clearing ScoopTrigger: Add baselineReadings counter to skip impulse detection during the first 10 readings, letting the EMA baseline converge before evaluating impulses. Prevents false triggers from stale GRAVITY_EARTH. WaveTrigger: Change timeWindowMillis from Float to Long. Only update lastProximityEventTime on the Near transition, so the time window correctly measures the full gesture duration (Near→Far) instead of resetting on every continuous-sensor reading. PickupDeviceTrigger: Remove buffer clearing on PickedUp — the rolling window self-heals naturally. Eliminates the 3-reading blind spot. * Add class-level KDoc and inline comments to all 18 gesture triggers * Update all gesture doc pages with algorithm descriptions and corrected defaults * Move algorithm descriptions into dedicated ## Algorithm section on each gesture page * Remove internal-only parameters from gesture docs that users cannot configure * Change PickupDeviceTrigger settle from reading-count to time-based * Expose settleTimeMs parameter in pickupDevicePlugin API * Update pickup device docs with settleTimeMs parameter * Wire resultText into MainScreen status row from sensor manager * Update sample app theme to black background | 5 months ago | |
Update: 4 (#63) * Extract GesturePlugin contract and SenseyPluginRegistry - GesturePlugin interface with onRegister/onUnregister receiving Sensey instance - SenseyPluginRegistry DSL builder for registering multiple plugins - TouchHandler removed (replaced by Compose gesture system) * Refactor Sensey from singleton object to class with extension functions - Sensey is now a class accepting Context, optional Lifecycle, sampling period - internal registerSensorDetector/unregisterSensorDetector/composeGestureProvider methods - Removed setupDispatchTouchEvent, registerTouchHandler, unregisterTouchHandler - senseyRegister(context, lifecycle?) and senseyStop() top-level functions - defaultSensey internal property for compose modifier access * Decouple SensorDetector from Sensey singleton - sensorDataLoggingEnabled moved from static Sensey reference to internal var - Set by Sensey.registerSensorDetector() before registration - Allows SensorDetector to work without global singleton dependency * Create gesture plugin factory functions and private plugin classes - 17 factory functions: shakePlugin, flipPlugin, lightPlugin, proximityPlugin, etc. - SensorGesturePlugin: reusable base for sensor-based gesture registration - PinchScalePlugin + TouchTypePlugin: compose-based gesture detection - SoundLevelPlugin: AudioRecord-based detection - Private plugin classes prevent direct instantiation * Tighten public API: make all Detector and Trigger classes internal - 17 Detector and 17 Trigger classes changed from public to internal - Users interact only through factory functions (shakePlugin, flipPlugin, etc.) - GestureTrigger<T> interface remains public for custom trigger implementations - Event sealed classes remain public as callback data types * Migrate touch/scale gestures from View to Jetpack Compose - Add Compose dependencies (BOM, compose-ui, compose-foundation) to library - Enable compose build feature + compose compiler plugin - New compose/ package: ComposeGestureProvider interface + senseyGestures() Modifier + SenseyGestureEffect() - Delete View-based TouchTypeDetector and PinchScaleDetector - TouchTypeEvent/PinchScaleEvent now delivered via Compose pointer input - PinchScalePlugin uses detectTransformGestures, TouchTypePlugin uses detectTapGestures + detectDragGestures * Update sample app to use plugin-based API and Compose touch - SensorManager: register/unregister pattern via Sensey instance - TouchSensorManager: simplified to state holder, events received via lambdas - TouchActivity: uses SenseyGestureEffect instead of dispatchTouchEvent - TouchScreen: applies Modifier.senseyGestures() on touch area - MainActivity: uses senseyRegister/senseyStop extension functions * Fix test and remove stale gesture-details.md - ScoopTriggerTest: use correct parameter name (impulseThreshold instead of threshold) - gesture-details.md: removed (outdated View-based documentation) * Update documentation for plugin-based API and Compose integration - README: updated Quick start with both Activity and Compose patterns, simplified Architecture - USAGE.md: comprehensive rewrite with Setup, Common Examples (14 use cases), Context-specific usage, and all gesture docs with Compose patterns - dev-docs.md: updated custom plugin guide (removed TouchHandler, added ComposePlugin) - GitHub templates: simplified to minimal sections * Setup ktlint plugin and configuration * Fix ktlint code style violations across codebase * Enable Gradle configuration cache * Make log tags standout in logcat with ASCII art wrapping * Simplify SensorDetector hierarchy and Sensey core infrastructure - Replace isSensorEventBelongsToPluggedTypes with idiomatic '!in' - Extract resolveSensors helper using 'also' for logging side effects - Remove KDoc data table from GestureTrigger (now documented per trigger) - Use function references (::register, ::let) for conciseness * Refactor gesture triggers with private functions and simplified logic - Extract magnitude, baseline, and state detection into private functions - Replace Hungarian notation (mAccel, mAccelCurrent) with descriptive names - Use sealed enum for TouchTypeTrigger Quadrant classification - Simplify conditional chains with guard clauses - Add companion object constants for magic numbers * Simplify custom detectors and SoundLevelDetector coroutine code - Extract captureAudio, createAudioRecord, processAudioStream from SoundLevelDetector - Move audio release to dedicated private function - Extract computeOrientationAngles helper in RotationAngleDetector - Format OrientationTrigger toExpressionBody with proper when blocks * Setup Dokka 2.2.0 documentation generation with versioning plugins - Add dokka plugin to version catalog with versioning/kotlin-as-java/android-doc plugins - Configure Dokka HTML publication for sensey module with source links - Add publishDocs Gradle task for versioned documentation output - Add github-pages branch restore step for versioning continuity * Add GitHub Actions workflow for versioned docs deployment - Trigger on master/develop pushes and version tags - Restore previous docs from gh-pages branch for Dokka versioning - Organize output into versioned directories with index landing page - Deploy to GitHub Pages via upload-pages-artifact * Bump version to 2.0.0 * Update README and dev docs with Dokka, ktlint, and architecture details * Fix #47: clear sensor buffer on pickup so PutDown detection works * Fix #34: add minNearDurationMs to wave detection; bump #31: default timeWindowMillis to 2000ms * Fix #17: add debounce to proximity trigger to prevent false reads in multi-window * Fix broken tests: replace deleted Detector classes with TypedSensorDetector * Standardize gravity constant to 9.81f across all gesture triggers ScoopTrigger, ChopTrigger, TapOnBackTrigger used 9.8f while MovementTrigger used 9.81f. Consolidated all to the more accurate 9.81f to eliminate fractional threshold discrepancies between triggers. * Replace ArrayDeque with fixed FloatArray circular buffer in PickupDeviceTrigger ArrayDeque with addLast/removeFirst per sensor event creates unnecessary GC pressure. Pre-allocated FloatArray with rolling index + sum eliminates allocations in the sensor event hot path and improves cache locality. * Add baseline initialization to MovementTrigger to prevent spurious startup event Previous code used a hardcoded GRAVITY_EARTH (9.81f) as initial currentAccel. If the first real sensor reading differs (e.g. device on a table with slight tilt), a large delta would immediately fire a MovementEvent.Moved on startup. Now the first reading sets the baseline without producing an event. * Remove dead sensorTypes field from SensorGesturePlugin The sensorTypes constructor parameter was passed by all 14 factory functions but never read inside SensorGesturePlugin. The actual sensor type registration is handled internally by each SensorDetector subclass. Removing the dead code eliminates confusion and reduces constructor verbosity. * Add onDragCancel handler to TouchTypePlugin drag gesture Without onDragCancel, when the system cancels a drag gesture (e.g. incoming call, another gesture taking over), dragStart retains stale coordinates which corrupts the next drag's delta calculation. * Enable lint abortOnError in both modules Previously set to false, which suppressed security-relevant lint checks such as MissingPermission, UnsafeProtectedBroadcast, and ExportedContentProvider. Hardening to true ensures lint violations fail the build during CI. * Remove -assumenosideeffects Log.d from library proguard rules The assumenosideeffects rule stripped ALL Log.d calls from consumer apps' release builds, not just the library's own logging. This broke debugging/troubleshooting for host apps that rely on Log.d in production. Library proguard rules should only keep library internals, not alter consumer behavior. * Add RECORD_AUDIO permission declaration to library manifest The SoundLevelDetector uses AudioRecord with VOICE_RECOGNITION source. Without a manifest declaration, the Android package manager cannot enforce the permission at install time, leading to a runtime SecurityException on Android 12+ when permission is missing. maxSdkVersion=32 avoids redundant prompting on Android 13+ where the permission is granted at install time for legacy apps. * Fix PinchScalePlugin and TouchTypePlugin cleanup on unregister Previously onUnregister was a no-op for both plugins, meaning the ComposeGestureProvider instances added via registerComposeGestureProvider were never removed. This leaked pointer input handlers and caused stale callbacks if plugins were registered/unregistered dynamically. Now each plugin tracks its provider(s) and removes them on unregister. * Fix RuntimePermissionUtil multi-permission callback logic Previous code iterated over each grant result individually, firing onPermissionGranted for each granted and onPermissionDenied for each denied permission in the same request. For multi-permission requests, both callbacks would fire simultaneously. Now uses grantResults.all{} to emit a single success/failure decision per request. * Fix ShakeTrigger.initializeBaseline return type (Nothing? -> ShakeEvent?) Nothing? is Kotlin's bottom type, semantically meaning 'this function never returns normally'. initializeBaseline simply returns null to signal the baseline isn't ready yet. Using Nothing? disables compiler exhaustiveness checks and could mask future bugs. * Fix TapOnBackTrigger single-tap latency and silent drop Previous implementation deferred all tap events by tapSequenceTimeoutMs (500ms) and silently discarded single taps (only tapCount >= 2 fired). This made the gesture feel unresponsive and broke basic single-tap detection. Now fires TapOnBackEvent immediately on the first qualifying tap — the existing tapDebounceMs (250ms) prevents noise re-triggering. * Add RECORD_AUDIO permission guard to SoundLevelPlugin The SoundLevelDetector creates an AudioRecord without verifying that the host app holds RECORD_AUDIO permission, causing a SecurityException crash at runtime on Android 12+ or silent microphone access on older versions. Now SoundLevelPlugin.onRegister checks permission before starting the detector, and SoundLevelDetector.captureAudio catches SecurityException as defense-in-depth in case permission is revoked between check and use. * Revert "Fix TapOnBackTrigger single-tap latency and silent drop" This reverts commit 90b477baf33ad357f1735e7cb62c5b9ce39b58ce. * Add KDoc disclosure to soundLevelPlugin about microphone audio capture Documents that the plugin requires RECORD_AUDIO permission, captures raw audio via AudioRecord with VOICE_RECOGNITION source, and that no audio data is stored, transmitted, or persisted. * Enable minification in sample app release build Release build now uses R8 with proguard-android-optimize.txt and the sample's proguard-rules.pro which keeps Compose, Sensey public API, and Kotlin coroutines internals. * Expose FlipTrigger threshold parameters in flipPlugin() public API Previously flipPlugin() accepted only a dispatcher, hiding the FlipTrigger faceUp/faceDown bound parameters. Consumers can now calibrate detection sensitivity at plugin creation time. * Migrate sample permission flow to ActivityResultContracts and rename SensorManager - Replace deprecated onRequestPermissionsResult / ActivityCompat with registerForActivityResult(RequestPermission) - Rename sample SensorManager to SenseySensorManager to avoid shadowing android.hardware.SensorManager and prevent import collisions * Exclude develop branch from docs deployment Previously docs were published on pushes to both master and develop. Develop is an integration branch where intermediate snapshots should not overwrite the published documentation on GitHub Pages. | 5 months ago | |
Update 1 (#60) * update gitignore file * migrate to agp 9.2.1 + gradle 9.5.1 + kotlin 2.3.21 * update readme and dev docs * add edge-to-edge support in sample app * convert sample ui to jetpack compose * use systembarspadding in compose screens, use version catalog for compose plugin * cleanup version catalog, use bundles | 5 months ago | |
Update 1 (#60) * update gitignore file * migrate to agp 9.2.1 + gradle 9.5.1 + kotlin 2.3.21 * update readme and dev docs * add edge-to-edge support in sample app * convert sample ui to jetpack compose * use systembarspadding in compose screens, use version catalog for compose plugin * cleanup version catalog, use bundles | 5 months ago | |
Update: 5 (#64) * Remove Apache license headers from source files * updated gitgnore * Remove Dokka setup and restructure documentation - Remove Dokka plugin, config, and dependencies from build system - Delete Dokka CI workflow and publishDocs task - Move usage guide and dev docs into docs/ directory - Update README and dev docs to remove Dokka references * Add Hugo site configuration and CI * Update .gitignore and README for Hugo docs migration * Restructure usage docs into Hugo content directory * Restructure development docs into Hugo content directory * Extract GRAVITY_EARTH constant to shared internal/Constants.kt * Make SensorDetector, TypedSensorDetector, ComposeGestureProvider and registration methods public * Rewrite architecture and custom plugin docs with practical examples and inline comments * Tighten language and add inline comments across usage docs and dev guides * Clean up trailing whitespace in README * Version docs by git tag — pushes to /vX.Y.Z/ on gh-pages branch * Split Components.kt into individual files and add @Preview to MainScreen and TouchScreen * updated ui * Fix ProximityTrigger stalling and LightTrigger baseline inconsistency ProximityTrigger: Remove 2-event debounce state machine that stalled with on-change proximity sensors (most Android hardware). Near never dispatched, Far dispatched once then trigger was permanently stuck. LightTrigger: initializeBaseline() used lightThreshold for wasDark but darkThreshold for the return event. When ambient light was in the hysteresis band, the state machine desynced and silently ate Dark transitions. * Replace isDetected boolean with eventCount counter in SenseySensorManager mutableStateOf<Boolean> doesn't trigger recomposition when set to the same value (true → true on rapid events). Use mutableIntStateOf counter that guarantees a unique value on every event. Removed unused resetJob and coroutine delay imports. * Use eventCount with LaunchedEffect for DetectionIndicator timing MainScreen accepts eventCount: Int instead of detected: Boolean. LaunchedEffect watches the counter, sets detected = true on each event, resets after 3s. MainActivity passes sensorManager.eventCount. * Fix StepTrigger flood and PinchScaleTrigger counter accumulation StepTrigger: Gate buildStepEvent behind actual step detection. - evaluateStepCounter now returns null for the baseline-reading call and filters repeated sensor values via lastDispatchedSteps - evaluateAccelerometer no longer calls buildStepEvent unconditionally; only emits when magnitude delta exceeds threshold - Starting previousMagnitude=0 no longer triggers a phantom first step (abs(9.8 - 0) > 3 was always true) PinchScaleTrigger: Reset opposite counter after dispatching. - scaleInCount and scaleOutCount only incremented, never reset → after the first SCALE_IN, scaleInCount was permanently > 2, so all subsequent SCALE_IN events fired on the first reading * Fix ScoopTrigger baseline race, WaveTrigger time window, PickupDeviceTrigger buffer clearing ScoopTrigger: Add baselineReadings counter to skip impulse detection during the first 10 readings, letting the EMA baseline converge before evaluating impulses. Prevents false triggers from stale GRAVITY_EARTH. WaveTrigger: Change timeWindowMillis from Float to Long. Only update lastProximityEventTime on the Near transition, so the time window correctly measures the full gesture duration (Near→Far) instead of resetting on every continuous-sensor reading. PickupDeviceTrigger: Remove buffer clearing on PickedUp — the rolling window self-heals naturally. Eliminates the 3-reading blind spot. * Add class-level KDoc and inline comments to all 18 gesture triggers * Update all gesture doc pages with algorithm descriptions and corrected defaults * Move algorithm descriptions into dedicated ## Algorithm section on each gesture page * Remove internal-only parameters from gesture docs that users cannot configure * Change PickupDeviceTrigger settle from reading-count to time-based * Expose settleTimeMs parameter in pickupDevicePlugin API * Update pickup device docs with settleTimeMs parameter * Wire resultText into MainScreen status row from sensor manager * Update sample app theme to black background | 5 months ago | |
cleanup and upgrade project files | 2 years ago |

Android library that makes sensor event and gesture detection a breeze. Eliminates boilerplate for setting up sensor-based gesture detection.
Quick Start
import com.github.nisrulz.sensey.senseyRegister
import com.github.nisrulz.sensey.gesture.shake.ShakeEvent
import com.github.nisrulz.sensey.gesture.flip.FlipEvent
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
senseyRegister(lifecycle) {
shakePlugin { event ->
when (event) {
ShakeEvent.Detected -> println("Shake detected!")
ShakeEvent.Stopped -> println("Shake stopped")
}
}
flipPlugin { event ->
when (event) {
FlipEvent.FaceUp -> println("Face up")
FlipEvent.FaceDown -> println("Face down")
}
}
}
}
}
Coroutines / Flow
Events as Flow<T> with lifecycle-aware collection:
import com.github.nisrulz.sensey.flow.senseyFlow
context.senseyFlow(lifecycle) {
shakePlugin { event ->
when (event) {
ShakeEvent.Detected -> println("Shake detected!")
ShakeEvent.Stopped -> println("Shake stopped")
}
}
}
Auto-collects on STARTED, pauses on STOP, cleans up on DESTROY. All gestures support it.
// Compose
SenseyFlowEffect(lifecycle) {
shakePlugin { /* events */ }
}
See the coroutines/flow guide for details.
Gestures
Shake, Flip, Light, Proximity, Movement, Orientation, Chop, TapOnBack, WristTwist, Wave, Scoop, PickupDevice, TiltDirection, RotationAngle, PinchScale, TouchType, EdgeSwipe, DiagonalSwipe, SoundLevel, Step, TurnOver, DeviceSpin, RaiseToEar, Clap, NodGesture, HeadShake.
See the usage guide for events, parameters, and examples.
Checkout
- 📖 Full usage guide
- 💡 Overview
- 🌊 Coroutines / Flow
- 🔧 Context-specific usage (Compose, Service, WorkManager)
- 📐 Architecture
- 🛠 Development guide
- 📜 Changelog
Including in your project
implementation 'com.github.nisrulz:sensey:{latest version}'
Latest version on Maven Central.
Sensey declares its dependencies as compileOnly. Depending on which features you use,
add the required deps:
| Feature | Required dependency |
|---|---|
| Lifecycle-aware registration | androidx.lifecycle:lifecycle-common |
| Flow-based API (SenseyFlow) | kotlinx-coroutines-core |
| Touch gesture plugins | androidx.compose.ui, androidx.compose.foundation |
Sensor-only plugins (shake, flip, light, proximity, etc.) work with just sensey alone.
License
Licensed under the Apache License, Version 2.0.
Copyright 2016 Nishant Srivastava
Introduction
:zap: [Android Library] Play with sensor events & detect gestures in a breeze.