also looking at this
Zig-native mobile: iOS compiles, serves a bridge call on a simulator, and is gated against drift
#83
28 files
+2460
-6557
Review threads live on the whole diff, not on one commit, so none are shown here - a thread's line means something in the branch's final form, and painting it into an intermediate step would put it on code it is not about.
| @@ -1,1099 +0,0 @@ | ||
| 1 | /** | |
| 2 | * Craft Android Bridge | |
| 3 | * Complete Android native bridge with WebView, permissions, and platform APIs | |
| 4 | */ | |
| 5 | ||
| 6 | import { secureId } from './ids.js' | |
| 7 | ||
| 8 | // Types | |
| 9 | export interface AndroidWebViewConfig { | |
| 10 | url?: string | |
| 11 | html?: string | |
| 12 | javaScriptEnabled?: boolean | |
| 13 | domStorageEnabled?: boolean | |
| 14 | allowFileAccess?: boolean | |
| 15 | allowContentAccess?: boolean | |
| 16 | mediaPlaybackRequiresUserGesture?: boolean | |
| 17 | supportZoom?: boolean | |
| 18 | builtInZoomControls?: boolean | |
| 19 | displayZoomControls?: boolean | |
| 20 | cacheMode?: 'default' | 'noCache' | 'cacheOnly' | 'cacheElseNetwork' | |
| 21 | mixedContentMode?: 'never' | 'always' | 'compatibility' | |
| 22 | safeBrowsingEnabled?: boolean | |
| 23 | } | |
| 24 | ||
| 25 | export interface AndroidPermission { | |
| 26 | type: | |
| 27 | | 'camera' | |
| 28 | | 'microphone' | |
| 29 | | 'readStorage' | |
| 30 | | 'writeStorage' | |
| 31 | | 'location' | |
| 32 | | 'fineLocation' | |
| 33 | | 'backgroundLocation' | |
| 34 | | 'contacts' | |
| 35 | | 'calendar' | |
| 36 | | 'phone' | |
| 37 | | 'sms' | |
| 38 | | 'bluetooth' | |
| 39 | | 'bluetoothConnect' | |
| 40 | | 'bluetoothScan' | |
| 41 | | 'bluetoothAdvertise' | |
| 42 | | 'notifications' | |
| 43 | | 'bodySensors' | |
| 44 | | 'activityRecognition' | |
| 45 | | 'nearbyWifiDevices' | |
| 46 | | 'readMediaImages' | |
| 47 | | 'readMediaVideo' | |
| 48 | | 'readMediaAudio' | |
| 49 | status: 'granted' | 'denied' | 'shouldShowRationale' | |
| 50 | } | |
| 51 | ||
| 52 | export interface AndroidBiometricConfig { | |
| 53 | title: string | |
| 54 | subtitle?: string | |
| 55 | description?: string | |
| 56 | negativeButtonText: string | |
| 57 | allowedAuthenticators?: ('biometricStrong' | 'biometricWeak' | 'deviceCredential')[] | |
| 58 | } | |
| 59 | ||
| 60 | export interface AndroidNotificationChannel { | |
| 61 | id: string | |
| 62 | name: string | |
| 63 | description?: string | |
| 64 | importance: 'none' | 'min' | 'low' | 'default' | 'high' | 'max' | |
| 65 | enableLights?: boolean | |
| 66 | lightColor?: string | |
| 67 | enableVibration?: boolean | |
| 68 | vibrationPattern?: number[] | |
| 69 | showBadge?: boolean | |
| 70 | sound?: string | |
| 71 | bypassDnd?: boolean | |
| 72 | } | |
| 73 | ||
| 74 | export interface AndroidNotification { | |
| 75 | channelId: string | |
| 76 | id: number | |
| 77 | title: string | |
| 78 | body: string | |
| 79 | smallIcon: string | |
| 80 | largeIcon?: string | |
| 81 | color?: string | |
| 82 | autoCancel?: boolean | |
| 83 | ongoing?: boolean | |
| 84 | priority?: 'min' | 'low' | 'default' | 'high' | 'max' | |
| 85 | category?: 'alarm' | 'call' | 'email' | 'error' | 'event' | 'message' | 'progress' | 'promo' | 'recommendation' | 'reminder' | 'service' | 'social' | 'status' | 'system' | 'transport' | |
| 86 | visibility?: 'public' | 'private' | 'secret' | |
| 87 | actions?: Array<{ action: string; title: string; icon?: string }> | |
| 88 | bigTextStyle?: { bigText: string; contentTitle?: string; summaryText?: string } | |
| 89 | bigPictureStyle?: { picture: string; contentTitle?: string; summaryText?: string; largeIcon?: string } | |
| 90 | inboxStyle?: { lines: string[]; contentTitle?: string; summaryText?: string } | |
| 91 | } | |
| 92 | ||
| 93 | export interface AndroidMaterialYouColors { | |
| 94 | primary: string | |
| 95 | onPrimary: string | |
| 96 | primaryContainer: string | |
| 97 | onPrimaryContainer: string | |
| 98 | secondary: string | |
| 99 | onSecondary: string | |
| 100 | secondaryContainer: string | |
| 101 | onSecondaryContainer: string | |
| 102 | tertiary: string | |
| 103 | onTertiary: string | |
| 104 | tertiaryContainer: string | |
| 105 | onTertiaryContainer: string | |
| 106 | error: string | |
| 107 | onError: string | |
| 108 | errorContainer: string | |
| 109 | onErrorContainer: string | |
| 110 | background: string | |
| 111 | onBackground: string | |
| 112 | surface: string | |
| 113 | onSurface: string | |
| 114 | surfaceVariant: string | |
| 115 | onSurfaceVariant: string | |
| 116 | outline: string | |
| 117 | outlineVariant: string | |
| 118 | } | |
| 119 | ||
| 120 | export interface AndroidWidget { | |
| 121 | widgetId: string | |
| 122 | className: string | |
| 123 | updatePeriodMillis?: number | |
| 124 | initialLayout: string | |
| 125 | } | |
| 126 | ||
| 127 | export interface AndroidWorkRequest { | |
| 128 | id: string | |
| 129 | workerClass: string | |
| 130 | inputData?: Record<string, unknown> | |
| 131 | constraints?: { | |
| 132 | networkType?: 'connected' | 'unmetered' | 'notRoaming' | 'metered' | |
| 133 | requiresCharging?: boolean | |
| 134 | requiresDeviceIdle?: boolean | |
| 135 | requiresBatteryNotLow?: boolean | |
| 136 | requiresStorageNotLow?: boolean | |
| 137 | } | |
| 138 | backoffPolicy?: { policy: 'linear' | 'exponential'; delay: number } | |
| 139 | tags?: string[] | |
| 140 | } | |
| 141 | ||
| 142 | // Android WebView Bridge | |
| 143 | export class AndroidWebView { | |
| 144 | private id: string | |
| 145 | private config: AndroidWebViewConfig | |
| 146 | ||
| 147 | constructor(config: AndroidWebViewConfig = {}) { | |
| 148 | this.id = secureId('webview') | |
| 149 | this.config = config | |
| 150 | } | |
| 151 | ||
| 152 | /** | |
| 153 | * Create the WebView | |
| 154 | */ | |
| 155 | async create(): Promise<void> { | |
| 156 | await this.callNative('createWebView', { | |
| 157 | id: this.id, | |
| 158 | config: this.config, | |
| 159 | }) | |
| 160 | } | |
| 161 | ||
| 162 | /** | |
| 163 | * Load a URL | |
| 164 | */ | |
| 165 | async loadURL(url: string, headers?: Record<string, string>): Promise<void> { | |
| 166 | await this.callNative('loadURL', { id: this.id, url, headers }) | |
| 167 | } | |
| 168 | ||
| 169 | /** | |
| 170 | * Load HTML content | |
| 171 | */ | |
| 172 | async loadHTML(html: string, baseUrl?: string, mimeType?: string): Promise<void> { | |
| 173 | await this.callNative('loadHTML', { id: this.id, html, baseUrl, mimeType }) | |
| 174 | } | |
| 175 | ||
| 176 | /** | |
| 177 | * Evaluate JavaScript | |
| 178 | */ | |
| 179 | async evaluateJavaScript<T = unknown>(script: string): Promise<T> { | |
| 180 | return this.callNative('evaluateJavaScript', { id: this.id, script }) | |
| 181 | } | |
| 182 | ||
| 183 | /** | |
| 184 | * Go back in history | |
| 185 | */ | |
| 186 | async goBack(): Promise<void> { | |
| 187 | await this.callNative('goBack', { id: this.id }) | |
| 188 | } | |
| 189 | ||
| 190 | /** | |
| 191 | * Go forward in history | |
| 192 | */ | |
| 193 | async goForward(): Promise<void> { | |
| 194 | await this.callNative('goForward', { id: this.id }) | |
| 195 | } | |
| 196 | ||
| 197 | /** | |
| 198 | * Reload the page | |
| 199 | */ | |
| 200 | async reload(): Promise<void> { | |
| 201 | await this.callNative('reload', { id: this.id }) | |
| 202 | } | |
| 203 | ||
| 204 | /** | |
| 205 | * Stop loading | |
| 206 | */ | |
| 207 | async stopLoading(): Promise<void> { | |
| 208 | await this.callNative('stopLoading', { id: this.id }) | |
| 209 | } | |
| 210 | ||
| 211 | /** | |
| 212 | * Clear cache | |
| 213 | */ | |
| 214 | async clearCache(includeDiskFiles = true): Promise<void> { | |
| 215 | await this.callNative('clearCache', { id: this.id, includeDiskFiles }) | |
| 216 | } | |
| 217 | ||
| 218 | /** | |
| 219 | * Destroy the WebView | |
| 220 | */ | |
| 221 | async destroy(): Promise<void> { | |
| 222 | await this.callNative('destroyWebView', { id: this.id }) | |
| 223 | } | |
| 224 | ||
| 225 | private async callNative<T>(method: string, params: Record<string, unknown> | object): Promise<T> { | |
| 226 | if (typeof window !== 'undefined' && (window as any).CraftBridge) { | |
| 227 | return new Promise((resolve, reject) => { | |
| 228 | const callbackId = secureId('cb') | |
| 229 | ;(window as any)[callbackId] = (result: string) => { | |
| 230 | delete (window as any)[callbackId] | |
| 231 | try { | |
| 232 | const parsed = JSON.parse(result) | |
| 233 | if (parsed.error) reject(new Error(parsed.error)) | |
| 234 | else resolve(parsed.result) | |
| 235 | } | |
| 236 | catch { | |
| 237 | resolve(result as T) | |
| 238 | } | |
| 239 | } | |
| 240 | ;(window as any).CraftBridge.postMessage(JSON.stringify({ method, params, callbackId })) | |
| 241 | }) | |
| 242 | } | |
| 243 | console.warn(`[AndroidBridge] ${method} called but not in Android WebView context`) | |
| 244 | return undefined as T | |
| 245 | } | |
| 246 | } | |
| 247 | ||
| 248 | // Android Permissions | |
| 249 | export class AndroidPermissions { | |
| 250 | /** | |
| 251 | * Check permission status | |
| 252 | */ | |
| 253 | async check(type: AndroidPermission['type']): Promise<AndroidPermission['status']> { | |
| 254 | return this.callNative('checkPermission', { type }) | |
| 255 | } | |
| 256 | ||
| 257 | /** | |
| 258 | * Request single permission | |
| 259 | */ | |
| 260 | async request(type: AndroidPermission['type']): Promise<AndroidPermission['status']> { | |
| 261 | return this.callNative('requestPermission', { type }) | |
| 262 | } | |
| 263 | ||
| 264 | /** | |
| 265 | * Request multiple permissions | |
| 266 | */ | |
| 267 | async requestMultiple(types: AndroidPermission['type'][]): Promise<Record<AndroidPermission['type'], AndroidPermission['status']>> { | |
| 268 | return this.callNative('requestMultiplePermissions', { types }) | |
| 269 | } | |
| 270 | ||
| 271 | /** | |
| 272 | * Should show request rationale | |
| 273 | */ | |
| 274 | async shouldShowRationale(type: AndroidPermission['type']): Promise<boolean> { | |
| 275 | return this.callNative('shouldShowRequestRationale', { type }) | |
| 276 | } | |
| 277 | ||
| 278 | /** | |
| 279 | * Open app settings | |
| 280 | */ | |
| 281 | async openSettings(): Promise<void> { | |
| 282 | await this.callNative('openAppSettings', {}) | |
| 283 | } | |
| 284 | ||
| 285 | private async callNative<T>(method: string, params: Record<string, unknown> | object): Promise<T> { | |
| 286 | if (typeof window !== 'undefined' && (window as any).CraftBridge) { | |
| 287 | return new Promise((resolve, reject) => { | |
| 288 | const callbackId = `cb_${Date.now()}` | |
| 289 | ;(window as any)[callbackId] = (result: string) => { | |
| 290 | delete (window as any)[callbackId] | |
| 291 | try { | |
| 292 | const parsed = JSON.parse(result) | |
| 293 | if (parsed.error) reject(new Error(parsed.error)) | |
| 294 | else resolve(parsed.result) | |
| 295 | } | |
| 296 | catch { | |
| 297 | resolve(result as T) | |
| 298 | } | |
| 299 | } | |
| 300 | ;(window as any).CraftBridge.postMessage(JSON.stringify({ method, params, callbackId })) | |
| 301 | }) | |
| 302 | } | |
| 303 | return 'granted' as T | |
| 304 | } | |
| 305 | } | |
| 306 | ||
| 307 | // Android Biometrics | |
| 308 | export class AndroidBiometrics { | |
| 309 | /** | |
| 310 | * Check biometric availability | |
| 311 | */ | |
| 312 | async isAvailable(): Promise<{ available: boolean; biometricType: 'fingerprint' | 'face' | 'iris' | 'none' }> { | |
| 313 | return this.callNative('checkBiometricAvailability', {}) | |
| 314 | } | |
| 315 | ||
| 316 | /** | |
| 317 | * Authenticate with biometrics | |
| 318 | */ | |
| 319 | async authenticate(config: AndroidBiometricConfig): Promise<{ success: boolean; error?: string }> { | |
| 320 | return this.callNative('authenticateBiometric', config) | |
| 321 | } | |
| 322 | ||
| 323 | /** | |
| 324 | * Check if device has enrolled biometrics | |
| 325 | */ | |
| 326 | async hasEnrolledBiometrics(): Promise<boolean> { | |
| 327 | return this.callNative('hasEnrolledBiometrics', {}) | |
| 328 | } | |
| 329 | ||
| 330 | private async callNative<T>(method: string, params: Record<string, unknown> | object): Promise<T> { | |
| 331 | if (typeof window !== 'undefined' && (window as any).CraftBridge) { | |
| 332 | return new Promise((resolve, reject) => { | |
| 333 | const callbackId = `cb_${Date.now()}` | |
| 334 | ;(window as any)[callbackId] = (result: string) => { | |
| 335 | delete (window as any)[callbackId] | |
| 336 | try { | |
| 337 | const parsed = JSON.parse(result) | |
| 338 | if (parsed.error) reject(new Error(parsed.error)) | |
| 339 | else resolve(parsed.result) | |
| 340 | } | |
| 341 | catch { | |
| 342 | resolve(result as T) | |
| 343 | } | |
| 344 | } | |
| 345 | ;(window as any).CraftBridge.postMessage(JSON.stringify({ method, params, callbackId })) | |
| 346 | }) | |
| 347 | } | |
| 348 | return { available: false, biometricType: 'none' } as T | |
| 349 | } | |
| 350 | } | |
| 351 | ||
| 352 | // Android Notifications | |
| 353 | export class AndroidNotifications { | |
| 354 | /** | |
| 355 | * Create notification channel (required for Android 8+) | |
| 356 | */ | |
| 357 | async createChannel(channel: AndroidNotificationChannel): Promise<void> { | |
| 358 | await this.callNative('createNotificationChannel', channel) | |
| 359 | } | |
| 360 | ||
| 361 | /** | |
| 362 | * Delete notification channel | |
| 363 | */ | |
| 364 | async deleteChannel(channelId: string): Promise<void> { | |
| 365 | await this.callNative('deleteNotificationChannel', { channelId }) | |
| 366 | } | |
| 367 | ||
| 368 | /** | |
| 369 | * Show notification | |
| 370 | */ | |
| 371 | async show(notification: AndroidNotification): Promise<void> { | |
| 372 | await this.callNative('showNotification', notification) | |
| 373 | } | |
| 374 | ||
| 375 | /** | |
| 376 | * Cancel notification | |
| 377 | */ | |
| 378 | async cancel(notificationId: number): Promise<void> { | |
| 379 | await this.callNative('cancelNotification', { notificationId }) | |
| 380 | } | |
| 381 | ||
| 382 | /** | |
| 383 | * Cancel all notifications | |
| 384 | */ | |
| 385 | async cancelAll(): Promise<void> { | |
| 386 | await this.callNative('cancelAllNotifications', {}) | |
| 387 | } | |
| 388 | ||
| 389 | /** | |
| 390 | * Request notification permission (Android 13+) | |
| 391 | */ | |
| 392 | async requestPermission(): Promise<boolean> { | |
| 393 | return this.callNative('requestNotificationPermission', {}) | |
| 394 | } | |
| 395 | ||
| 396 | /** | |
| 397 | * Check if notifications are enabled | |
| 398 | */ | |
| 399 | async areNotificationsEnabled(): Promise<boolean> { | |
| 400 | return this.callNative('areNotificationsEnabled', {}) | |
| 401 | } | |
| 402 | ||
| 403 | private async callNative<T>(method: string, params: Record<string, unknown> | object): Promise<T> { | |
| 404 | if (typeof window !== 'undefined' && (window as any).CraftBridge) { | |
| 405 | return new Promise((resolve, reject) => { | |
| 406 | const callbackId = `cb_${Date.now()}` | |
| 407 | ;(window as any)[callbackId] = (result: string) => { | |
| 408 | delete (window as any)[callbackId] | |
| 409 | try { | |
| 410 | const parsed = JSON.parse(result) | |
| 411 | if (parsed.error) reject(new Error(parsed.error)) | |
| 412 | else resolve(parsed.result) | |
| 413 | } | |
| 414 | catch { | |
| 415 | resolve(result as T) | |
| 416 | } | |
| 417 | } | |
| 418 | ;(window as any).CraftBridge.postMessage(JSON.stringify({ method, params, callbackId })) | |
| 419 | }) | |
| 420 | } | |
| 421 | return true as T | |
| 422 | } | |
| 423 | } | |
| 424 | ||
| 425 | // Android Material You / Dynamic Colors | |
| 426 | export class AndroidMaterialYou { | |
| 427 | /** | |
| 428 | * Check if dynamic colors are available | |
| 429 | */ | |
| 430 | async isAvailable(): Promise<boolean> { | |
| 431 | return this.callNative('isDynamicColorAvailable', {}) | |
| 432 | } | |
| 433 | ||
| 434 | /** | |
| 435 | * Get dynamic colors | |
| 436 | */ | |
| 437 | async getColors(): Promise<AndroidMaterialYouColors | null> { | |
| 438 | return this.callNative('getDynamicColors', {}) | |
| 439 | } | |
| 440 | ||
| 441 | /** | |
| 442 | * Listen for color changes (wallpaper change) | |
| 443 | */ | |
| 444 | onColorChange(callback: (colors: AndroidMaterialYouColors) => void): () => void { | |
| 445 | const handler = (event: CustomEvent) => callback(event.detail) | |
| 446 | window.addEventListener('material-you-colors' as any, handler) | |
| 447 | return () => window.removeEventListener('material-you-colors' as any, handler) | |
| 448 | } | |
| 449 | ||
| 450 | private async callNative<T>(method: string, params: Record<string, unknown> | object): Promise<T> { | |
| 451 | if (typeof window !== 'undefined' && (window as any).CraftBridge) { | |
| 452 | return new Promise((resolve, reject) => { | |
| 453 | const callbackId = `cb_${Date.now()}` | |
| 454 | ;(window as any)[callbackId] = (result: string) => { | |
| 455 | delete (window as any)[callbackId] | |
| 456 | try { | |
| 457 | const parsed = JSON.parse(result) | |
| 458 | if (parsed.error) reject(new Error(parsed.error)) | |
| 459 | else resolve(parsed.result) | |
| 460 | } | |
| 461 | catch { | |
| 462 | resolve(result as T) | |
| 463 | } | |
| 464 | } | |
| 465 | ;(window as any).CraftBridge.postMessage(JSON.stringify({ method, params, callbackId })) | |
| 466 | }) | |
| 467 | } | |
| 468 | return false as T | |
| 469 | } | |
| 470 | } | |
| 471 | ||
| 472 | // Android Photo Picker | |
| 473 | export class AndroidPhotoPicker { | |
| 474 | /** | |
| 475 | * Pick single image | |
| 476 | */ | |
| 477 | async pickImage(): Promise<{ uri: string; mimeType: string } | null> { | |
| 478 | return this.callNative('pickImage', {}) | |
| 479 | } | |
| 480 | ||
| 481 | /** | |
| 482 | * Pick multiple images | |
| 483 | */ | |
| 484 | async pickImages(maxItems = 10): Promise<Array<{ uri: string; mimeType: string }>> { | |
| 485 | return this.callNative('pickImages', { maxItems }) | |
| 486 | } | |
| 487 | ||
| 488 | /** | |
| 489 | * Pick single video | |
| 490 | */ | |
| 491 | async pickVideo(): Promise<{ uri: string; mimeType: string; duration: number } | null> { | |
| 492 | return this.callNative('pickVideo', {}) | |
| 493 | } | |
| 494 | ||
| 495 | /** | |
| 496 | * Pick visual media (images and videos) | |
| 497 | */ | |
| 498 | async pickVisualMedia(maxItems = 10): Promise<Array<{ uri: string; mimeType: string; type: 'image' | 'video' }>> { | |
| 499 | return this.callNative('pickVisualMedia', { maxItems }) | |
| 500 | } | |
| 501 | ||
| 502 | private async callNative<T>(method: string, params: Record<string, unknown> | object): Promise<T> { | |
| 503 | if (typeof window !== 'undefined' && (window as any).CraftBridge) { | |
| 504 | return new Promise((resolve, reject) => { | |
| 505 | const callbackId = `cb_${Date.now()}` | |
| 506 | ;(window as any)[callbackId] = (result: string) => { | |
| 507 | delete (window as any)[callbackId] | |
| 508 | try { | |
| 509 | const parsed = JSON.parse(result) | |
| 510 | if (parsed.error) reject(new Error(parsed.error)) | |
| 511 | else resolve(parsed.result) | |
| 512 | } | |
| 513 | catch { | |
| 514 | resolve(result as T) | |
| 515 | } | |
| 516 | } | |
| 517 | ;(window as any).CraftBridge.postMessage(JSON.stringify({ method, params, callbackId })) | |
| 518 | }) | |
| 519 | } | |
| 520 | return null as T | |
| 521 | } | |
| 522 | } | |
| 523 | ||
| 524 | // Android Work Manager | |
| 525 | export class AndroidWorkManager { | |
| 526 | /** | |
| 527 | * Enqueue one-time work | |
| 528 | */ | |
| 529 | async enqueueOneTime(request: AndroidWorkRequest): Promise<void> { | |
| 530 | await this.callNative('enqueueOneTimeWork', request) | |
| 531 | } | |
| 532 | ||
| 533 | /** | |
| 534 | * Enqueue periodic work | |
| 535 | */ | |
| 536 | async enqueuePeriodic(request: AndroidWorkRequest & { repeatInterval: number; repeatIntervalUnit: 'minutes' | 'hours' | 'days' }): Promise<void> { | |
| 537 | await this.callNative('enqueuePeriodicWork', request) | |
| 538 | } | |
| 539 | ||
| 540 | /** | |
| 541 | * Cancel work by ID | |
| 542 | */ | |
| 543 | async cancelById(id: string): Promise<void> { | |
| 544 | await this.callNative('cancelWorkById', { id }) | |
| 545 | } | |
| 546 | ||
| 547 | /** | |
| 548 | * Cancel work by tag | |
| 549 | */ | |
| 550 | async cancelByTag(tag: string): Promise<void> { | |
| 551 | await this.callNative('cancelWorkByTag', { tag }) | |
| 552 | } | |
| 553 | ||
| 554 | /** | |
| 555 | * Cancel all work | |
| 556 | */ | |
| 557 | async cancelAll(): Promise<void> { | |
| 558 | await this.callNative('cancelAllWork', {}) | |
| 559 | } | |
| 560 | ||
| 561 | /** | |
| 562 | * Get work info by ID | |
| 563 | */ | |
| 564 | async getWorkInfoById(id: string): Promise<{ state: 'enqueued' | 'running' | 'succeeded' | 'failed' | 'blocked' | 'cancelled'; outputData?: Record<string, unknown> } | null> { | |
| 565 | return this.callNative('getWorkInfoById', { id }) | |
| 566 | } | |
| 567 | ||
| 568 | private async callNative<T>(method: string, params: Record<string, unknown> | object): Promise<T> { | |
| 569 | if (typeof window !== 'undefined' && (window as any).CraftBridge) { | |
| 570 | return new Promise((resolve, reject) => { | |
| 571 | const callbackId = `cb_${Date.now()}` | |
| 572 | ;(window as any)[callbackId] = (result: string) => { | |
| 573 | delete (window as any)[callbackId] | |
| 574 | try { | |
| 575 | const parsed = JSON.parse(result) | |
| 576 | if (parsed.error) reject(new Error(parsed.error)) | |
| 577 | else resolve(parsed.result) | |
| 578 | } | |
| 579 | catch { | |
| 580 | resolve(result as T) | |
| 581 | } | |
| 582 | } | |
| 583 | ;(window as any).CraftBridge.postMessage(JSON.stringify({ method, params, callbackId })) | |
| 584 | }) | |
| 585 | } | |
| 586 | return undefined as T | |
| 587 | } | |
| 588 | } | |
| 589 | ||
| 590 | // Android Foreground Service | |
| 591 | export class AndroidForegroundService { | |
| 592 | /** | |
| 593 | * Start foreground service | |
| 594 | */ | |
| 595 | async start(config: { | |
| 596 | notificationId: number | |
| 597 | notification: AndroidNotification | |
| 598 | serviceType?: 'camera' | 'connectedDevice' | 'dataSync' | 'location' | 'mediaPlayback' | 'mediaProjection' | 'microphone' | 'phoneCall' | 'remoteMessaging' | 'shortService' | |
| 599 | }): Promise<void> { | |
| 600 | await this.callNative('startForegroundService', config) | |
| 601 | } | |
| 602 | ||
| 603 | /** | |
| 604 | * Stop foreground service | |
| 605 | */ | |
| 606 | async stop(): Promise<void> { | |
| 607 | await this.callNative('stopForegroundService', {}) | |
| 608 | } | |
| 609 | ||
| 610 | /** | |
| 611 | * Update notification | |
| 612 | */ | |
| 613 | async updateNotification(notification: Partial<AndroidNotification>): Promise<void> { | |
| 614 | await this.callNative('updateForegroundNotification', notification) | |
| 615 | } | |
| 616 | ||
| 617 | private async callNative<T>(method: string, params: Record<string, unknown> | object): Promise<T> { | |
| 618 | if (typeof window !== 'undefined' && (window as any).CraftBridge) { | |
| 619 | return new Promise((resolve, reject) => { | |
| 620 | const callbackId = `cb_${Date.now()}` | |
| 621 | ;(window as any)[callbackId] = (result: string) => { | |
| 622 | delete (window as any)[callbackId] | |
| 623 | try { | |
| 624 | const parsed = JSON.parse(result) | |
| 625 | if (parsed.error) reject(new Error(parsed.error)) | |
| 626 | else resolve(parsed.result) | |
| 627 | } | |
| 628 | catch { | |
| 629 | resolve(result as T) | |
| 630 | } | |
| 631 | } | |
| 632 | ;(window as any).CraftBridge.postMessage(JSON.stringify({ method, params, callbackId })) | |
| 633 | }) | |
| 634 | } | |
| 635 | return undefined as T | |
| 636 | } | |
| 637 | } | |
| 638 | ||
| 639 | // Android Predictive Back Gesture | |
| 640 | export class AndroidPredictiveBack { | |
| 641 | /** | |
| 642 | * Enable predictive back gesture | |
| 643 | */ | |
| 644 | async enable(): Promise<void> { | |
| 645 | await this.callNative('enablePredictiveBack', {}) | |
| 646 | } | |
| 647 | ||
| 648 | /** | |
| 649 | * Disable predictive back gesture | |
| 650 | */ | |
| 651 | async disable(): Promise<void> { | |
| 652 | await this.callNative('disablePredictiveBack', {}) | |
| 653 | } | |
| 654 | ||
| 655 | /** | |
| 656 | * Register back callback | |
| 657 | */ | |
| 658 | onBackPressed(callback: () => boolean): () => void { | |
| 659 | const handler = (_event: CustomEvent) => { | |
| 660 | const handled = callback() | |
| 661 | if ((window as any).CraftBridge) { | |
| 662 | ;(window as any).CraftBridge.postMessage( | |
| 663 | JSON.stringify({ | |
| 664 | method: 'backPressedResult', | |
| 665 | params: { handled }, | |
| 666 | }) | |
| 667 | ) | |
| 668 | } | |
| 669 | } | |
| 670 | window.addEventListener('back-pressed' as any, handler) | |
| 671 | return () => window.removeEventListener('back-pressed' as any, handler) | |
| 672 | } | |
| 673 | ||
| 674 | /** | |
| 675 | * Listen for back progress (for animations) | |
| 676 | */ | |
| 677 | onBackProgress(callback: (progress: { touchX: number; touchY: number; progress: number }) => void): () => void { | |
| 678 | const handler = (event: CustomEvent) => callback(event.detail) | |
| 679 | window.addEventListener('back-progress' as any, handler) | |
| 680 | return () => window.removeEventListener('back-progress' as any, handler) | |
| 681 | } | |
| 682 | ||
| 683 | private async callNative<T>(method: string, params: Record<string, unknown> | object): Promise<T> { | |
| 684 | if (typeof window !== 'undefined' && (window as any).CraftBridge) { | |
| 685 | return new Promise((resolve, reject) => { | |
| 686 | const callbackId = `cb_${Date.now()}` | |
| 687 | ;(window as any)[callbackId] = (result: string) => { | |
| 688 | delete (window as any)[callbackId] | |
| 689 | try { | |
| 690 | const parsed = JSON.parse(result) | |
| 691 | if (parsed.error) reject(new Error(parsed.error)) | |
| 692 | else resolve(parsed.result) | |
| 693 | } | |
| 694 | catch { | |
| 695 | resolve(result as T) | |
| 696 | } | |
| 697 | } | |
| 698 | ;(window as any).CraftBridge.postMessage(JSON.stringify({ method, params, callbackId })) | |
| 699 | }) | |
| 700 | } | |
| 701 | return undefined as T | |
| 702 | } | |
| 703 | } | |
| 704 | ||
| 705 | // Android Per-App Language | |
| 706 | export class AndroidPerAppLanguage { | |
| 707 | /** | |
| 708 | * Get current app locale | |
| 709 | */ | |
| 710 | async getCurrentLocale(): Promise<string> { | |
| 711 | return this.callNative('getCurrentAppLocale', {}) | |
| 712 | } | |
| 713 | ||
| 714 | /** | |
| 715 | * Set app locale | |
| 716 | */ | |
| 717 | async setLocale(localeTag: string): Promise<void> { | |
| 718 | await this.callNative('setAppLocale', { localeTag }) | |
| 719 | } | |
| 720 | ||
| 721 | /** | |
| 722 | * Reset to system locale | |
| 723 | */ | |
| 724 | async resetToSystemLocale(): Promise<void> { | |
| 725 | await this.callNative('resetToSystemLocale', {}) | |
| 726 | } | |
| 727 | ||
| 728 | private async callNative<T>(method: string, params: Record<string, unknown> | object): Promise<T> { | |
| 729 | if (typeof window !== 'undefined' && (window as any).CraftBridge) { | |
| 730 | return new Promise((resolve, reject) => { | |
| 731 | const callbackId = `cb_${Date.now()}` | |
| 732 | ;(window as any)[callbackId] = (result: string) => { | |
| 733 | delete (window as any)[callbackId] | |
| 734 | try { | |
| 735 | const parsed = JSON.parse(result) | |
| 736 | if (parsed.error) reject(new Error(parsed.error)) | |
| 737 | else resolve(parsed.result) | |
| 738 | } | |
| 739 | catch { | |
| 740 | resolve(result as T) | |
| 741 | } | |
| 742 | } | |
| 743 | ;(window as any).CraftBridge.postMessage(JSON.stringify({ method, params, callbackId })) | |
| 744 | }) | |
| 745 | } | |
| 746 | return 'en' as T | |
| 747 | } | |
| 748 | } | |
| 749 | ||
| 750 | // Android Widgets | |
| 751 | export class AndroidWidgets { | |
| 752 | /** | |
| 753 | * Register widget | |
| 754 | */ | |
| 755 | async register(widget: AndroidWidget): Promise<void> { | |
| 756 | await this.callNative('registerWidget', widget) | |
| 757 | } | |
| 758 | ||
| 759 | /** | |
| 760 | * Update widget | |
| 761 | */ | |
| 762 | async update(widgetId: string, views: Record<string, unknown>): Promise<void> { | |
| 763 | await this.callNative('updateWidget', { widgetId, views }) | |
| 764 | } | |
| 765 | ||
| 766 | /** | |
| 767 | * Get widget IDs | |
| 768 | */ | |
| 769 | async getWidgetIds(className: string): Promise<number[]> { | |
| 770 | return this.callNative('getWidgetIds', { className }) | |
| 771 | } | |
| 772 | ||
| 773 | private async callNative<T>(method: string, params: Record<string, unknown> | object): Promise<T> { | |
| 774 | if (typeof window !== 'undefined' && (window as any).CraftBridge) { | |
| 775 | return new Promise((resolve, reject) => { | |
| 776 | const callbackId = `cb_${Date.now()}` | |
| 777 | ;(window as any)[callbackId] = (result: string) => { | |
| 778 | delete (window as any)[callbackId] | |
| 779 | try { | |
| 780 | const parsed = JSON.parse(result) | |
| 781 | if (parsed.error) reject(new Error(parsed.error)) | |
| 782 | else resolve(parsed.result) | |
| 783 | } | |
| 784 | catch { | |
| 785 | resolve(result as T) | |
| 786 | } | |
| 787 | } | |
| 788 | ;(window as any).CraftBridge.postMessage(JSON.stringify({ method, params, callbackId })) | |
| 789 | }) | |
| 790 | } | |
| 791 | return [] as T | |
| 792 | } | |
| 793 | } | |
| 794 | ||
| 795 | // Android Play Billing | |
| 796 | export class AndroidPlayBilling { | |
| 797 | /** | |
| 798 | * Check if billing is ready | |
| 799 | */ | |
| 800 | async isReady(): Promise<boolean> { | |
| 801 | return this.callNative('isBillingReady', {}) | |
| 802 | } | |
| 803 | ||
| 804 | /** | |
| 805 | * Query product details | |
| 806 | */ | |
| 807 | async queryProducts(productIds: string[], productType: 'inapp' | 'subs'): Promise< | |
| 808 | Array<{ | |
| 809 | productId: string | |
| 810 | name: string | |
| 811 | description: string | |
| 812 | formattedPrice: string | |
| 813 | priceAmountMicros: number | |
| 814 | priceCurrencyCode: string | |
| 815 | }> | |
| 816 | > { | |
| 817 | return this.callNative('queryProductDetails', { productIds, productType }) | |
| 818 | } | |
| 819 | ||
| 820 | /** | |
| 821 | * Launch purchase flow | |
| 822 | */ | |
| 823 | async purchase(productId: string, productType: 'inapp' | 'subs'): Promise<{ purchaseToken: string; orderId: string } | null> { | |
| 824 | return this.callNative('launchBillingFlow', { productId, productType }) | |
| 825 | } | |
| 826 | ||
| 827 | /** | |
| 828 | * Consume purchase | |
| 829 | */ | |
| 830 | async consumePurchase(purchaseToken: string): Promise<void> { | |
| 831 | await this.callNative('consumePurchase', { purchaseToken }) | |
| 832 | } | |
| 833 | ||
| 834 | /** | |
| 835 | * Acknowledge purchase | |
| 836 | */ | |
| 837 | async acknowledgePurchase(purchaseToken: string): Promise<void> { | |
| 838 | await this.callNative('acknowledgePurchase', { purchaseToken }) | |
| 839 | } | |
| 840 | ||
| 841 | /** | |
| 842 | * Query purchases | |
| 843 | */ | |
| 844 | async queryPurchases(productType: 'inapp' | 'subs'): Promise< | |
| 845 | Array<{ | |
| 846 | productId: string | |
| 847 | purchaseToken: string | |
| 848 | orderId: string | |
| 849 | purchaseTime: number | |
| 850 | isAcknowledged: boolean | |
| 851 | purchaseState: 'pending' | 'purchased' | 'unspecified' | |
| 852 | }> | |
| 853 | > { | |
| 854 | return this.callNative('queryPurchases', { productType }) | |
| 855 | } | |
| 856 | ||
| 857 | private async callNative<T>(method: string, params: Record<string, unknown> | object): Promise<T> { | |
| 858 | if (typeof window !== 'undefined' && (window as any).CraftBridge) { | |
| 859 | return new Promise((resolve, reject) => { | |
| 860 | const callbackId = `cb_${Date.now()}` | |
| 861 | ;(window as any)[callbackId] = (result: string) => { | |
| 862 | delete (window as any)[callbackId] | |
| 863 | try { | |
| 864 | const parsed = JSON.parse(result) | |
| 865 | if (parsed.error) reject(new Error(parsed.error)) | |
| 866 | else resolve(parsed.result) | |
| 867 | } | |
| 868 | catch { | |
| 869 | resolve(result as T) | |
| 870 | } | |
| 871 | } | |
| 872 | ;(window as any).CraftBridge.postMessage(JSON.stringify({ method, params, callbackId })) | |
| 873 | }) | |
| 874 | } | |
| 875 | return [] as T | |
| 876 | } | |
| 877 | } | |
| 878 | ||
| 879 | // Android Firebase | |
| 880 | export class AndroidFirebase { | |
| 881 | /** | |
| 882 | * Get FCM token | |
| 883 | */ | |
| 884 | async getFCMToken(): Promise<string | null> { | |
| 885 | return this.callNative('getFCMToken', {}) | |
| 886 | } | |
| 887 | ||
| 888 | /** | |
| 889 | * Subscribe to topic | |
| 890 | */ | |
| 891 | async subscribeToTopic(topic: string): Promise<void> { | |
| 892 | await this.callNative('subscribeToTopic', { topic }) | |
| 893 | } | |
| 894 | ||
| 895 | /** | |
| 896 | * Unsubscribe from topic | |
| 897 | */ | |
| 898 | async unsubscribeFromTopic(topic: string): Promise<void> { | |
| 899 | await this.callNative('unsubscribeFromTopic', { topic }) | |
| 900 | } | |
| 901 | ||
| 902 | /** | |
| 903 | * Log analytics event | |
| 904 | */ | |
| 905 | async logEvent(name: string, params?: Record<string, unknown>): Promise<void> { | |
| 906 | await this.callNative('logAnalyticsEvent', { name, params }) | |
| 907 | } | |
| 908 | ||
| 909 | /** | |
| 910 | * Set user property | |
| 911 | */ | |
| 912 | async setUserProperty(name: string, value: string): Promise<void> { | |
| 913 | await this.callNative('setUserProperty', { name, value }) | |
| 914 | } | |
| 915 | ||
| 916 | /** | |
| 917 | * Set user ID | |
| 918 | */ | |
| 919 | async setUserId(userId: string | null): Promise<void> { | |
| 920 | await this.callNative('setUserId', { userId }) | |
| 921 | } | |
| 922 | ||
| 923 | /** | |
| 924 | * Record exception | |
| 925 | */ | |
| 926 | async recordException(error: Error): Promise<void> { | |
| 927 | await this.callNative('recordException', { | |
| 928 | message: error.message, | |
| 929 | stack: error.stack, | |
| 930 | }) | |
| 931 | } | |
| 932 | ||
| 933 | /** | |
| 934 | * Set Crashlytics key | |
| 935 | */ | |
| 936 | async setCrashlyticsKey(key: string, value: string | number | boolean): Promise<void> { | |
| 937 | await this.callNative('setCrashlyticsKey', { key, value }) | |
| 938 | } | |
| 939 | ||
| 940 | /** | |
| 941 | * Get Remote Config value | |
| 942 | */ | |
| 943 | async getRemoteConfigValue(key: string): Promise<string | number | boolean | null> { | |
| 944 | return this.callNative('getRemoteConfigValue', { key }) | |
| 945 | } | |
| 946 | ||
| 947 | /** | |
| 948 | * Fetch Remote Config | |
| 949 | */ | |
| 950 | async fetchRemoteConfig(minimumFetchInterval?: number): Promise<void> { | |
| 951 | await this.callNative('fetchRemoteConfig', { minimumFetchInterval }) | |
| 952 | } | |
| 953 | ||
| 954 | private async callNative<T>(method: string, params: Record<string, unknown> | object): Promise<T> { | |
| 955 | if (typeof window !== 'undefined' && (window as any).CraftBridge) { | |
| 956 | return new Promise((resolve, reject) => { | |
| 957 | const callbackId = `cb_${Date.now()}` | |
| 958 | ;(window as any)[callbackId] = (result: string) => { | |
| 959 | delete (window as any)[callbackId] | |
| 960 | try { | |
| 961 | const parsed = JSON.parse(result) | |
| 962 | if (parsed.error) reject(new Error(parsed.error)) | |
| 963 | else resolve(parsed.result) | |
| 964 | } | |
| 965 | catch { | |
| 966 | resolve(result as T) | |
| 967 | } | |
| 968 | } | |
| 969 | ;(window as any).CraftBridge.postMessage(JSON.stringify({ method, params, callbackId })) | |
| 970 | }) | |
| 971 | } | |
| 972 | return null as T | |
| 973 | } | |
| 974 | } | |
| 975 | ||
| 976 | // Android Native Components | |
| 977 | export class AndroidNativeComponents { | |
| 978 | /** | |
| 979 | * Show bottom sheet | |
| 980 | */ | |
| 981 | async showBottomSheet(config: { | |
| 982 | title?: string | |
| 983 | items?: Array<{ id: string; title: string; icon?: string; subtitle?: string }> | |
| 984 | dismissible?: boolean | |
| 985 | halfExpanded?: boolean | |
| 986 | }): Promise<string | null> { | |
| 987 | return this.callNative('showBottomSheet', config) | |
| 988 | } | |
| 989 | ||
| 990 | /** | |
| 991 | * Show navigation drawer | |
| 992 | */ | |
| 993 | async showNavigationDrawer(config: { | |
| 994 | items: Array<{ id: string; title: string; icon?: string; selected?: boolean; group?: string }> | |
| 995 | headerTitle?: string | |
| 996 | headerSubtitle?: string | |
| 997 | headerImage?: string | |
| 998 | }): Promise<string | null> { | |
| 999 | return this.callNative('showNavigationDrawer', config) | |
| 1000 | } | |
| 1001 | ||
| 1002 | /** | |
| 1003 | * Show date picker | |
| 1004 | */ | |
| 1005 | async showDatePicker(config?: { | |
| 1006 | initialDate?: string | |
| 1007 | minDate?: string | |
| 1008 | maxDate?: string | |
| 1009 | title?: string | |
| 1010 | }): Promise<string | null> { | |
| 1011 | return this.callNative('showDatePicker', config || {}) | |
| 1012 | } | |
| 1013 | ||
| 1014 | /** | |
| 1015 | * Show time picker | |
| 1016 | */ | |
| 1017 | async showTimePicker(config?: { | |
| 1018 | initialHour?: number | |
| 1019 | initialMinute?: number | |
| 1020 | is24Hour?: boolean | |
| 1021 | title?: string | |
| 1022 | }): Promise<{ hour: number; minute: number } | null> { | |
| 1023 | return this.callNative('showTimePicker', config || {}) | |
| 1024 | } | |
| 1025 | ||
| 1026 | /** | |
| 1027 | * Show toast | |
| 1028 | */ | |
| 1029 | async showToast(message: string, duration: 'short' | 'long' = 'short'): Promise<void> { | |
| 1030 | await this.callNative('showToast', { message, duration }) | |
| 1031 | } | |
| 1032 | ||
| 1033 | /** | |
| 1034 | * Show snackbar | |
| 1035 | */ | |
| 1036 | async showSnackbar(config: { | |
| 1037 | message: string | |
| 1038 | action?: { text: string; color?: string } | |
| 1039 | duration?: 'short' | 'long' | 'indefinite' | |
| 1040 | }): Promise<boolean> { | |
| 1041 | return this.callNative('showSnackbar', config) | |
| 1042 | } | |
| 1043 | ||
| 1044 | private async callNative<T>(method: string, params: Record<string, unknown> | object): Promise<T> { | |
| 1045 | if (typeof window !== 'undefined' && (window as any).CraftBridge) { | |
| 1046 | return new Promise((resolve, reject) => { | |
| 1047 | const callbackId = `cb_${Date.now()}` | |
| 1048 | ;(window as any)[callbackId] = (result: string) => { | |
| 1049 | delete (window as any)[callbackId] | |
| 1050 | try { | |
| 1051 | const parsed = JSON.parse(result) | |
| 1052 | if (parsed.error) reject(new Error(parsed.error)) | |
| 1053 | else resolve(parsed.result) | |
| 1054 | } | |
| 1055 | catch { | |
| 1056 | resolve(result as T) | |
| 1057 | } | |
| 1058 | } | |
| 1059 | ;(window as any).CraftBridge.postMessage(JSON.stringify({ method, params, callbackId })) | |
| 1060 | }) | |
| 1061 | } | |
| 1062 | return null as T | |
| 1063 | } | |
| 1064 | } | |
| 1065 | ||
| 1066 | // Export all Android modules | |
| 1067 | export const android: { | |
| 1068 | WebView: typeof AndroidWebView | |
| 1069 | Permissions: AndroidPermissions | |
| 1070 | Biometrics: AndroidBiometrics | |
| 1071 | Notifications: AndroidNotifications | |
| 1072 | MaterialYou: AndroidMaterialYou | |
| 1073 | PhotoPicker: AndroidPhotoPicker | |
| 1074 | WorkManager: AndroidWorkManager | |
| 1075 | ForegroundService: AndroidForegroundService | |
| 1076 | PredictiveBack: AndroidPredictiveBack | |
| 1077 | PerAppLanguage: AndroidPerAppLanguage | |
| 1078 | Widgets: AndroidWidgets | |
| 1079 | PlayBilling: AndroidPlayBilling | |
| 1080 | Firebase: AndroidFirebase | |
| 1081 | NativeComponents: AndroidNativeComponents | |
| 1082 | } = { | |
| 1083 | WebView: AndroidWebView, | |
| 1084 | Permissions: new AndroidPermissions(), | |
| 1085 | Biometrics: new AndroidBiometrics(), | |
| 1086 | Notifications: new AndroidNotifications(), | |
| 1087 | MaterialYou: new AndroidMaterialYou(), | |
| 1088 | PhotoPicker: new AndroidPhotoPicker(), | |
| 1089 | WorkManager: new AndroidWorkManager(), | |
| 1090 | ForegroundService: new AndroidForegroundService(), | |
| 1091 | PredictiveBack: new AndroidPredictiveBack(), | |
| 1092 | PerAppLanguage: new AndroidPerAppLanguage(), | |
| 1093 | Widgets: new AndroidWidgets(), | |
| 1094 | PlayBilling: new AndroidPlayBilling(), | |
| 1095 | Firebase: new AndroidFirebase(), | |
| 1096 | NativeComponents: new AndroidNativeComponents(), | |
| 1097 | } | |
| 1098 | ||
| 1099 | export default android | |
| @@ -1834,11 +1834,6 @@ pub fn build(b: *std.Build) void { | ||
| 1834 | 1834 | const build_android_x86 = b.step("build-android-x86", "Build for Android (x86_64)"); |
| 1835 | 1835 | const build_android_all = b.step("build-android-all", "Build for Android (all architectures)"); |
| 1836 | 1836 | |
| 1837 | // Android module | |
| 1838 | const android_module = b.createModule(.{ | |
| 1839 | .root_source_file = b.path("src/android.zig"), | |
| 1840 | }); | |
| 1841 | ||
| 1842 | 1837 | // Android Device (arm64) |
| 1843 | 1838 | const android_arm64_target = b.resolveTargetQuery(.{ |
| 1844 | 1839 | .cpu_arch = .aarch64, |
| @@ -1889,46 +1884,13 @@ pub fn build(b: *std.Build) void { | ||
| 1889 | 1884 | build_android_x86.dependOn(&android_x86_install.step); |
| 1890 | 1885 | build_android_all.dependOn(&android_x86_install.step); |
| 1891 | 1886 | |
| 1892 | // ======================================================================== | |
| 1893 | // Android Example (demo mode - runs on host for testing) | |
| 1894 | // ======================================================================== | |
| 1895 | ||
| 1896 | const run_android = b.step("run-android", "Run the Android example (demo mode)"); | |
| 1897 | ||
| 1898 | const android_demo_exe = b.addExecutable(.{ | |
| 1899 | .name = "android-example", | |
| 1900 | .root_module = b.createModule(.{ | |
| 1901 | .root_source_file = b.path("examples/android/main.zig"), | |
| 1902 | .target = target, | |
| 1903 | .optimize = optimize, | |
| 1904 | .imports = &.{ | |
| 1905 | .{ .name = "craft", .module = craft_module }, | |
| 1906 | .{ .name = "android", .module = android_module }, | |
| 1907 | }, | |
| 1908 | }), | |
| 1909 | }); | |
| 1910 | ||
| 1911 | switch (target_os) { | |
| 1912 | .macos => { | |
| 1913 | android_demo_exe.root_module.linkFramework("Cocoa", .{}); | |
| 1914 | android_demo_exe.root_module.linkFramework("WebKit", .{}); | |
| 1915 | }, | |
| 1916 | .linux => { | |
| 1917 | android_demo_exe.root_module.linkSystemLibrary("gtk+-3.0", .{}); | |
| 1918 | android_demo_exe.root_module.linkSystemLibrary("webkit2gtk-4.1", .{}); | |
| 1919 | }, | |
| 1920 | .windows => { | |
| 1921 | android_demo_exe.root_module.linkSystemLibrary("ole32", .{}); | |
| 1922 | android_demo_exe.root_module.linkSystemLibrary("user32", .{}); | |
| 1923 | android_demo_exe.root_module.linkSystemLibrary("gdi32", .{}); | |
| 1924 | android_demo_exe.root_module.linkSystemLibrary("shell32", .{}); | |
| 1925 | }, | |
| 1926 | else => {}, | |
| 1927 | } | |
| 1928 | android_demo_exe.root_module.link_libc = true; | |
| 1929 | ||
| 1930 | const run_android_cmd = b.addRunArtifact(android_demo_exe); | |
| 1931 | run_android.dependOn(&run_android_cmd.step); | |
| 1887 | // The `run-android` step and its `android-example` executable used to sit | |
| 1888 | // here. It was not an Android artifact: it built for the *host* and linked | |
| 1889 | // Cocoa/WebKit on macOS and GTK on Linux, so "running the Android example" | |
| 1890 | // meant running a desktop printf demo. Its source called | |
| 1891 | // `AndroidFeatures.getDeviceInfo()`, which returned a hardcoded | |
| 1892 | // "Android Device" / SDK 34 no matter what, and printed the result as if | |
| 1893 | // it had queried something. | |
| 1932 | 1894 | |
| 1933 | 1895 | // ======================================================================== |
| 1934 | 1896 | // Android Tests |
| @@ -1,281 +0,0 @@ | ||
| 1 | const std = @import("std"); | |
| 2 | const craft = @import("craft"); | |
| 3 | ||
| 4 | /// Android Example | |
| 5 | /// | |
| 6 | /// Demonstrates how to build Android apps with Craft: | |
| 7 | /// - CraftActivity for Android lifecycle | |
| 8 | /// - JavaScript bridge for web-native communication | |
| 9 | /// - Native Android features (toast, vibration, etc.) | |
| 10 | ||
| 11 | pub fn main() !void { | |
| 12 | var gpa = std.heap.GeneralPurposeAllocator(.{}){}; | |
| 13 | defer _ = gpa.deinit(); | |
| 14 | const allocator = gpa.allocator(); | |
| 15 | ||
| 16 | std.debug.print("\n=== Craft Android Demo ===\n\n", .{}); | |
| 17 | ||
| 18 | // Demo 1: Create CraftActivity | |
| 19 | std.debug.print("1. Creating CraftActivity...\n", .{}); | |
| 20 | ||
| 21 | var app = craft.CraftActivity.init(allocator, .{ | |
| 22 | .name = "My Craft App", | |
| 23 | .package_name = "com.example.craftapp", | |
| 24 | .initial_content = .{ .html = app_html }, | |
| 25 | .theme = .system, | |
| 26 | .orientation = .portrait, | |
| 27 | .enable_javascript = true, | |
| 28 | .enable_dom_storage = true, | |
| 29 | .enable_inspector = true, // Enable WebView inspector in debug | |
| 30 | }); | |
| 31 | defer app.deinit(); | |
| 32 | ||
| 33 | std.debug.print(" Activity created: {s}\n", .{app.config.name}); | |
| 34 | std.debug.print(" Package: {s}\n", .{app.config.package_name}); | |
| 35 | ||
| 36 | // Demo 2: Set lifecycle callbacks | |
| 37 | std.debug.print("\n2. Setting lifecycle callbacks...\n", .{}); | |
| 38 | ||
| 39 | app.onCreate(onAppCreate); | |
| 40 | app.onResume(onAppResume); | |
| 41 | app.onPause(onAppPause); | |
| 42 | app.onDestroy(onAppDestroy); | |
| 43 | app.onBackPressed(onBackPressed); | |
| 44 | ||
| 45 | std.debug.print(" Callbacks registered!\n", .{}); | |
| 46 | ||
| 47 | // Demo 3: Register custom JavaScript handlers | |
| 48 | std.debug.print("\n3. Registering custom JS handlers...\n", .{}); | |
| 49 | ||
| 50 | try app.run(); | |
| 51 | ||
| 52 | if (app.getBridge()) |bridge| { | |
| 53 | try bridge.registerHandler("customAction", handleCustomAction); | |
| 54 | try bridge.registerHandler("getUserData", handleGetUserData); | |
| 55 | std.debug.print(" Custom handlers registered!\n", .{}); | |
| 56 | } | |
| 57 | ||
| 58 | // Demo 4: Show available native features | |
| 59 | std.debug.print("\n4. Available Android features:\n", .{}); | |
| 60 | std.debug.print(" - showToast: Show toast messages\n", .{}); | |
| 61 | std.debug.print(" - vibrate: Device vibration\n", .{}); | |
| 62 | std.debug.print(" - setClipboard/getClipboard: Clipboard access\n", .{}); | |
| 63 | std.debug.print(" - share: Native share dialog\n", .{}); | |
| 64 | std.debug.print(" - openURL: Open URLs in browser\n", .{}); | |
| 65 | std.debug.print(" - showAlert: Native alert dialogs\n", .{}); | |
| 66 | ||
| 67 | // Demo 5: Device info | |
| 68 | std.debug.print("\n5. Device info:\n", .{}); | |
| 69 | const device = craft.AndroidFeatures.getDeviceInfo(); | |
| 70 | std.debug.print(" Manufacturer: {s}\n", .{device.manufacturer}); | |
| 71 | std.debug.print(" Model: {s}\n", .{device.model}); | |
| 72 | std.debug.print(" OS Version: {s}\n", .{device.os_version}); | |
| 73 | std.debug.print(" SDK Version: {d}\n", .{device.sdk_version}); | |
| 74 | ||
| 75 | std.debug.print("\n=== Demo Complete ===\n", .{}); | |
| 76 | std.debug.print("Build APK with: zig build android-apk\n\n", .{}); | |
| 77 | } | |
| 78 | ||
| 79 | // Lifecycle callbacks | |
| 80 | fn onAppCreate() void { | |
| 81 | std.debug.print(" [LIFECYCLE] onCreate called\n", .{}); | |
| 82 | } | |
| 83 | ||
| 84 | fn onAppResume() void { | |
| 85 | std.debug.print(" [LIFECYCLE] onResume called\n", .{}); | |
| 86 | } | |
| 87 | ||
| 88 | fn onAppPause() void { | |
| 89 | std.debug.print(" [LIFECYCLE] onPause called\n", .{}); | |
| 90 | } | |
| 91 | ||
| 92 | fn onAppDestroy() void { | |
| 93 | std.debug.print(" [LIFECYCLE] onDestroy called\n", .{}); | |
| 94 | } | |
| 95 | ||
| 96 | fn onBackPressed() bool { | |
| 97 | std.debug.print(" [LIFECYCLE] onBackPressed - consuming event\n", .{}); | |
| 98 | return true; // Consume the back button event | |
| 99 | } | |
| 100 | ||
| 101 | // Custom JavaScript handlers | |
| 102 | fn handleCustomAction(params: []const u8, bridge: *craft.AndroidJSBridge, callback_id: []const u8) void { | |
| 103 | std.debug.print(" [JS] customAction called with: {s}\n", .{params}); | |
| 104 | bridge.sendResponse(callback_id, "{ \"status\": \"ok\" }") catch {}; | |
| 105 | } | |
| 106 | ||
| 107 | fn handleGetUserData(_: []const u8, bridge: *craft.AndroidJSBridge, callback_id: []const u8) void { | |
| 108 | std.debug.print(" [JS] getUserData called\n", .{}); | |
| 109 | const response = | |
| 110 | \\{ "user": { "name": "John Doe", "email": "john@example.com" } } | |
| 111 | ; | |
| 112 | bridge.sendResponse(callback_id, response) catch {}; | |
| 113 | } | |
| 114 | ||
| 115 | // Example HTML for the app | |
| 116 | const app_html = | |
| 117 | \\<!DOCTYPE html> | |
| 118 | \\<html> | |
| 119 | \\<head> | |
| 120 | \\ <meta charset="UTF-8"> | |
| 121 | \\ <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> | |
| 122 | \\ <title>Craft Android App</title> | |
| 123 | \\ <style> | |
| 124 | \\ * { box-sizing: border-box; margin: 0; padding: 0; } | |
| 125 | \\ body { | |
| 126 | \\ font-family: 'Roboto', sans-serif; | |
| 127 | \\ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); | |
| 128 | \\ min-height: 100vh; | |
| 129 | \\ padding: 20px; | |
| 130 | \\ color: white; | |
| 131 | \\ } | |
| 132 | \\ .container { | |
| 133 | \\ max-width: 400px; | |
| 134 | \\ margin: 0 auto; | |
| 135 | \\ } | |
| 136 | \\ h1 { | |
| 137 | \\ font-size: 1.8rem; | |
| 138 | \\ margin-bottom: 20px; | |
| 139 | \\ text-align: center; | |
| 140 | \\ } | |
| 141 | \\ .card { | |
| 142 | \\ background: rgba(255, 255, 255, 0.15); | |
| 143 | \\ border-radius: 16px; | |
| 144 | \\ padding: 20px; | |
| 145 | \\ margin-bottom: 16px; | |
| 146 | \\ backdrop-filter: blur(10px); | |
| 147 | \\ } | |
| 148 | \\ .card h2 { | |
| 149 | \\ font-size: 1.1rem; | |
| 150 | \\ margin-bottom: 12px; | |
| 151 | \\ opacity: 0.9; | |
| 152 | \\ } | |
| 153 | \\ button { | |
| 154 | \\ width: 100%; | |
| 155 | \\ padding: 14px; | |
| 156 | \\ border: none; | |
| 157 | \\ border-radius: 8px; | |
| 158 | \\ font-size: 1rem; | |
| 159 | \\ cursor: pointer; | |
| 160 | \\ margin-bottom: 10px; | |
| 161 | \\ background: rgba(255, 255, 255, 0.9); | |
| 162 | \\ color: #333; | |
| 163 | \\ font-weight: 500; | |
| 164 | \\ transition: transform 0.1s; | |
| 165 | \\ } | |
| 166 | \\ button:active { | |
| 167 | \\ transform: scale(0.98); | |
| 168 | \\ } | |
| 169 | \\ #output { | |
| 170 | \\ background: rgba(0, 0, 0, 0.2); | |
| 171 | \\ padding: 12px; | |
| 172 | \\ border-radius: 8px; | |
| 173 | \\ font-family: monospace; | |
| 174 | \\ font-size: 0.85rem; | |
| 175 | \\ min-height: 60px; | |
| 176 | \\ word-wrap: break-word; | |
| 177 | \\ } | |
| 178 | \\ </style> | |
| 179 | \\</head> | |
| 180 | \\<body> | |
| 181 | \\ <div class="container"> | |
| 182 | \\ <h1>Craft Android</h1> | |
| 183 | \\ | |
| 184 | \\ <div class="card"> | |
| 185 | \\ <h2>Native Features</h2> | |
| 186 | \\ <button onclick="showToast()">Show Toast</button> | |
| 187 | \\ <button onclick="vibrate()">Vibrate</button> | |
| 188 | \\ <button onclick="shareContent()">Share</button> | |
| 189 | \\ <button onclick="getPlatform()">Get Platform Info</button> | |
| 190 | \\ </div> | |
| 191 | \\ | |
| 192 | \\ <div class="card"> | |
| 193 | \\ <h2>Custom Actions</h2> | |
| 194 | \\ <button onclick="customAction()">Custom Action</button> | |
| 195 | \\ <button onclick="getUserData()">Get User Data</button> | |
| 196 | \\ </div> | |
| 197 | \\ | |
| 198 | \\ <div class="card"> | |
| 199 | \\ <h2>Output</h2> | |
| 200 | \\ <div id="output">Ready...</div> | |
| 201 | \\ </div> | |
| 202 | \\ </div> | |
| 203 | \\ | |
| 204 | \\ <script> | |
| 205 | \\ function log(msg) { | |
| 206 | \\ document.getElementById('output').textContent = msg; | |
| 207 | \\ } | |
| 208 | \\ | |
| 209 | \\ async function invoke(method, params = {}) { | |
| 210 | \\ return new Promise((resolve) => { | |
| 211 | \\ const callbackId = 'cb_' + Date.now(); | |
| 212 | \\ window['__craftCallback_' + callbackId] = (result) => { | |
| 213 | \\ delete window['__craftCallback_' + callbackId]; | |
| 214 | \\ resolve(result); | |
| 215 | \\ }; | |
| 216 | \\ if (window.CraftBridge) { | |
| 217 | \\ CraftBridge.postMessage(JSON.stringify({ | |
| 218 | \\ method: method, | |
| 219 | \\ params: params, | |
| 220 | \\ callbackId: callbackId | |
| 221 | \\ })); | |
| 222 | \\ } else { | |
| 223 | \\ log('CraftBridge not available (demo mode)'); | |
| 224 | \\ resolve({ demo: true }); | |
| 225 | \\ } | |
| 226 | \\ }); | |
| 227 | \\ } | |
| 228 | \\ | |
| 229 | \\ async function showToast() { | |
| 230 | \\ const result = await invoke('showToast', { message: 'Hello from Craft!' }); | |
| 231 | \\ log('Toast: ' + JSON.stringify(result)); | |
| 232 | \\ } | |
| 233 | \\ | |
| 234 | \\ async function vibrate() { | |
| 235 | \\ const result = await invoke('vibrate', { duration: 100 }); | |
| 236 | \\ log('Vibrate: ' + JSON.stringify(result)); | |
| 237 | \\ } | |
| 238 | \\ | |
| 239 | \\ async function shareContent() { | |
| 240 | \\ const result = await invoke('share', { text: 'Check out Craft!' }); | |
| 241 | \\ log('Share: ' + JSON.stringify(result)); | |
| 242 | \\ } | |
| 243 | \\ | |
| 244 | \\ async function getPlatform() { | |
| 245 | \\ const result = await invoke('getPlatform'); | |
| 246 | \\ log('Platform: ' + JSON.stringify(result)); | |
| 247 | \\ } | |
| 248 | \\ | |
| 249 | \\ async function customAction() { | |
| 250 | \\ const result = await invoke('customAction', { action: 'test' }); | |
| 251 | \\ log('Custom: ' + JSON.stringify(result)); | |
| 252 | \\ } | |
| 253 | \\ | |
| 254 | \\ async function getUserData() { | |
| 255 | \\ const result = await invoke('getUserData'); | |
| 256 | \\ log('User: ' + JSON.stringify(result)); | |
| 257 | \\ } | |
| 258 | \\ | |
| 259 | \\ // Listen for native events | |
| 260 | \\ window.addEventListener('craft:ready', () => { | |
| 261 | \\ log('Craft native bridge ready!'); | |
| 262 | \\ }); | |
| 263 | \\ </script> | |
| 264 | \\</body> | |
| 265 | \\</html> | |
| 266 | ; | |
| 267 | ||
| 268 | // Example: Using quick start | |
| 269 | pub fn simpleApp() !void { | |
| 270 | var gpa = std.heap.GeneralPurposeAllocator(.{}){}; | |
| 271 | defer _ = gpa.deinit(); | |
| 272 | const allocator = gpa.allocator(); | |
| 273 | ||
| 274 | // One-liner to start an Android app | |
| 275 | try craft.android.quickStart(allocator, | |
| 276 | \\<!DOCTYPE html> | |
| 277 | \\<html> | |
| 278 | \\<body><h1>Hello, Android!</h1></body> | |
| 279 | \\</html> | |
| 280 | ); | |
| 281 | } | |
| @@ -13,22 +13,6 @@ const mobile = @import("mobile.zig"); | ||
| 13 | 13 | /// }); |
| 14 | 14 | /// try app.run(); |
| 15 | 15 | |
| 16 | // ============================================================================ | |
| 17 | // JNI Types (for cross-compilation) | |
| 18 | // ============================================================================ | |
| 19 | ||
| 20 | pub const jni = struct { | |
| 21 | pub const JNIEnv = *anyopaque; | |
| 22 | pub const jobject = *anyopaque; | |
| 23 | pub const jclass = *anyopaque; | |
| 24 | pub const jstring = *anyopaque; | |
| 25 | pub const jint = i32; | |
| 26 | pub const jlong = i64; | |
| 27 | pub const jboolean = u8; | |
| 28 | pub const jfloat = f32; | |
| 29 | pub const jdouble = f64; | |
| 30 | }; | |
| 31 | ||
| 32 | 16 | // ============================================================================ |
| 33 | 17 | // CraftActivity - Main Android Activity |
| 34 | 18 | // ============================================================================ |
| @@ -42,8 +26,13 @@ pub const CraftActivity = struct { | ||
| 42 | 26 | webview: ?*mobile.Android.WebView = null, |
| 43 | 27 | |
| 44 | 28 | // JNI references |
| 45 | jni_env: ?jni.JNIEnv = null, | |
| 46 | activity: ?jni.jobject = null, | |
| 29 | // These were `?jni.JNIEnv` and `?jni.jobject` against a local `jni` | |
| 30 | // namespace that aliased everything to `*anyopaque` — no vtable, no | |
| 31 | // JavaVM, nothing that could actually reach Java. Untyped pointers say the | |
| 32 | // same thing without implying a binding exists. The real types arrive with | |
| 33 | // `android_jni.zig`, from the NDK's own `jni.h`. | |
| 34 | jni_env: ?*anyopaque = null, | |
| 35 | activity: ?*anyopaque = null, | |
| 47 | 36 | |
| 48 | 37 | // Callbacks |
| 49 | 38 | on_create: ?*const fn () void = null, |
| @@ -209,91 +198,27 @@ pub const JSBridge = struct { | ||
| 209 | 198 | const Self = @This(); |
| 210 | 199 | |
| 211 | 200 | pub fn init(allocator: std.mem.Allocator) JSBridge { |
| 212 | var bridge = JSBridge{ | |
| 201 | // No built-in handlers are registered any more. The nine that used to | |
| 202 | // be here — `getPlatform`, `showToast`, `vibrate`, `setClipboard`, | |
| 203 | // `getClipboard`, `share`, `openURL`, `getNetworkStatus`, `showAlert` | |
| 204 | // — each extracted their arguments, discarded them, and replied | |
| 205 | // `{"success": true}`. `getPlatform` answered with a hardcoded | |
| 206 | // `"version": "14"`. A handler that fabricates success is worse than a | |
| 207 | // missing one: the missing one is reported to the caller. | |
| 208 | return .{ | |
| 213 | 209 | .handlers = std.StringHashMap(Handler).init(allocator), |
| 214 | 210 | .allocator = allocator, |
| 215 | 211 | }; |
| 216 | ||
| 217 | // Register built-in handlers | |
| 218 | bridge.registerBuiltinHandlers() catch |err| { | |
| 219 | std.log.warn("failed to register Android built-in JS handlers: {}", .{err}); | |
| 220 | }; | |
| 221 | ||
| 222 | return bridge; | |
| 223 | 212 | } |
| 224 | 213 | |
| 225 | 214 | pub fn deinit(self: *Self) void { |
| 226 | 215 | self.handlers.deinit(); |
| 227 | 216 | } |
| 228 | 217 | |
| 229 | fn registerBuiltinHandlers(self: *Self) !void { | |
| 230 | try self.handlers.put("getPlatform", handleGetPlatform); | |
| 231 | try self.handlers.put("showToast", handleShowToast); | |
| 232 | try self.handlers.put("vibrate", handleVibrate); | |
| 233 | try self.handlers.put("setClipboard", handleSetClipboard); | |
| 234 | try self.handlers.put("getClipboard", handleGetClipboard); | |
| 235 | try self.handlers.put("share", handleShare); | |
| 236 | try self.handlers.put("openURL", handleOpenURL); | |
| 237 | try self.handlers.put("getNetworkStatus", handleGetNetworkStatus); | |
| 238 | try self.handlers.put("showAlert", handleShowAlert); | |
| 239 | } | |
| 240 | ||
| 241 | 218 | pub fn registerHandler(self: *Self, name: []const u8, handler: Handler) !void { |
| 242 | 219 | try self.handlers.put(name, handler); |
| 243 | 220 | } |
| 244 | 221 | |
| 245 | /// Handle message from JavaScript (called via JNI) | |
| 246 | pub fn handleMessage(self: *Self, message: []const u8) void { | |
| 247 | const method = self.extractJsonString(message, "method") orelse return; | |
| 248 | const callback_id = self.extractJsonString(message, "callbackId") orelse ""; | |
| 249 | const params = self.extractJsonObject(message, "params") orelse "{}"; | |
| 250 | ||
| 251 | if (self.handlers.get(method)) |handler| { | |
| 252 | handler(params, self, callback_id); | |
| 253 | } else { | |
| 254 | self.sendError(callback_id, "Unknown method") catch |err| { | |
| 255 | std.log.warn("failed to send unknown method error to Android JS: {}", .{err}); | |
| 256 | }; | |
| 257 | } | |
| 258 | } | |
| 259 | ||
| 260 | fn extractJsonString(self: *Self, json: []const u8, key: []const u8) ?[]const u8 { | |
| 261 | _ = self; | |
| 262 | var pattern_buf: [64]u8 = undefined; | |
| 263 | const pattern = std.fmt.bufPrint(&pattern_buf, "\"{s}\":\"", .{key}) catch return null; | |
| 264 | ||
| 265 | if (std.mem.indexOf(u8, json, pattern)) |start| { | |
| 266 | const value_start = start + pattern.len; | |
| 267 | if (value_start < json.len) { | |
| 268 | if (std.mem.indexOf(u8, json[value_start..], "\"")) |end| { | |
| 269 | return json[value_start..][0..end]; | |
| 270 | } | |
| 271 | } | |
| 272 | } | |
| 273 | return null; | |
| 274 | } | |
| 275 | ||
| 276 | fn extractJsonObject(self: *Self, json: []const u8, key: []const u8) ?[]const u8 { | |
| 277 | _ = self; | |
| 278 | var pattern_buf: [64]u8 = undefined; | |
| 279 | const pattern = std.fmt.bufPrint(&pattern_buf, "\"{s}\":{{", .{key}) catch return null; | |
| 280 | ||
| 281 | if (std.mem.indexOf(u8, json, pattern)) |start| { | |
| 282 | const value_start = start + pattern.len - 1; | |
| 283 | if (value_start < json.len) { | |
| 284 | var depth: usize = 0; | |
| 285 | var i: usize = value_start; | |
| 286 | while (i < json.len) : (i += 1) { | |
| 287 | if (json[i] == '{') depth += 1 else if (json[i] == '}') { | |
| 288 | depth -= 1; | |
| 289 | if (depth == 0) return json[value_start .. i + 1]; | |
| 290 | } | |
| 291 | } | |
| 292 | } | |
| 293 | } | |
| 294 | return null; | |
| 295 | } | |
| 296 | ||
| 297 | 222 | pub fn sendResponse(self: *Self, callback_id: []const u8, result: []const u8) !void { |
| 298 | 223 | if (self.activity == null) return error.NoActivity; |
| 299 | 224 | if (callback_id.len == 0) return; |
| @@ -329,167 +254,6 @@ pub const JSBridge = struct { | ||
| 329 | 254 | try self.activity.?.evaluateJavaScript(script, null); |
| 330 | 255 | } |
| 331 | 256 | |
| 332 | // Built-in handlers | |
| 333 | fn handleGetPlatform(params: []const u8, bridge: *JSBridge, callback_id: []const u8) void { | |
| 334 | _ = params; | |
| 335 | const response = | |
| 336 | \\{"os": "android", "version": "14", "device": "Android", "native": true} | |
| 337 | ; | |
| 338 | bridge.sendResponse(callback_id, response) catch |err| { | |
| 339 | std.log.debug("failed to send getPlatform response: {}", .{err}); | |
| 340 | }; | |
| 341 | } | |
| 342 | ||
| 343 | fn handleShowToast(params: []const u8, bridge: *JSBridge, callback_id: []const u8) void { | |
| 344 | const message = bridge.extractJsonString(params, "message") orelse "Toast"; | |
| 345 | _ = message; | |
| 346 | // Would call Toast.makeText via JNI | |
| 347 | bridge.sendResponse(callback_id, "{ \"success\": true }") catch |err| { | |
| 348 | std.log.debug("failed to send showToast response: {}", .{err}); | |
| 349 | }; | |
| 350 | } | |
| 351 | ||
| 352 | fn handleVibrate(params: []const u8, bridge: *JSBridge, callback_id: []const u8) void { | |
| 353 | _ = params; | |
| 354 | // Would call Vibrator.vibrate via JNI | |
| 355 | bridge.sendResponse(callback_id, "{ \"success\": true }") catch |err| { | |
| 356 | std.log.debug("failed to send vibrate response: {}", .{err}); | |
| 357 | }; | |
| 358 | } | |
| 359 | ||
| 360 | fn handleSetClipboard(params: []const u8, bridge: *JSBridge, callback_id: []const u8) void { | |
| 361 | const text = bridge.extractJsonString(params, "text") orelse ""; | |
| 362 | _ = text; | |
| 363 | // Would call ClipboardManager.setPrimaryClip via JNI | |
| 364 | bridge.sendResponse(callback_id, "{ \"success\": true }") catch |err| { | |
| 365 | std.log.debug("failed to send setClipboard response: {}", .{err}); | |
| 366 | }; | |
| 367 | } | |
| 368 | ||
| 369 | fn handleGetClipboard(params: []const u8, bridge: *JSBridge, callback_id: []const u8) void { | |
| 370 | _ = params; | |
| 371 | // Would call ClipboardManager.getPrimaryClip via JNI | |
| 372 | bridge.sendResponse(callback_id, "{ \"text\": \"\" }") catch |err| { | |
| 373 | std.log.debug("failed to send getClipboard response: {}", .{err}); | |
| 374 | }; | |
| 375 | } | |
| 376 | ||
| 377 | fn handleShare(params: []const u8, bridge: *JSBridge, callback_id: []const u8) void { | |
| 378 | const text = bridge.extractJsonString(params, "text") orelse ""; | |
| 379 | _ = text; | |
| 380 | // Would start Intent.ACTION_SEND via JNI | |
| 381 | bridge.sendResponse(callback_id, "{ \"success\": true }") catch |err| { | |
| 382 | std.log.debug("failed to send share response: {}", .{err}); | |
| 383 | }; | |
| 384 | } | |
| 385 | ||
| 386 | fn handleOpenURL(params: []const u8, bridge: *JSBridge, callback_id: []const u8) void { | |
| 387 | const url = bridge.extractJsonString(params, "url") orelse ""; | |
| 388 | _ = url; | |
| 389 | // Would start Intent.ACTION_VIEW via JNI | |
| 390 | bridge.sendResponse(callback_id, "{ \"success\": true }") catch |err| { | |
| 391 | std.log.debug("failed to send openURL response: {}", .{err}); | |
| 392 | }; | |
| 393 | } | |
| 394 | ||
| 395 | fn handleGetNetworkStatus(params: []const u8, bridge: *JSBridge, callback_id: []const u8) void { | |
| 396 | _ = params; | |
| 397 | // Would check ConnectivityManager via JNI | |
| 398 | bridge.sendResponse(callback_id, "{ \"connected\": true, \"type\": \"wifi\" }") catch |err| { | |
| 399 | std.log.debug("failed to send getNetworkStatus response: {}", .{err}); | |
| 400 | }; | |
| 401 | } | |
| 402 | ||
| 403 | fn handleShowAlert(params: []const u8, bridge: *JSBridge, callback_id: []const u8) void { | |
| 404 | const title = bridge.extractJsonString(params, "title") orelse "Alert"; | |
| 405 | const message = bridge.extractJsonString(params, "message") orelse ""; | |
| 406 | _ = title; | |
| 407 | _ = message; | |
| 408 | // Would show AlertDialog via JNI | |
| 409 | bridge.sendResponse(callback_id, "{ \"success\": true }") catch |err| { | |
| 410 | std.log.debug("failed to send showAlert response: {}", .{err}); | |
| 411 | }; | |
| 412 | } | |
| 413 | }; | |
| 414 | ||
| 415 | // ============================================================================ | |
| 416 | // Android Native Features | |
| 417 | // ============================================================================ | |
| 418 | ||
| 419 | pub const AndroidFeatures = struct { | |
| 420 | /// Show a Toast message | |
| 421 | pub fn showToast(message: []const u8, long_duration: bool) void { | |
| 422 | _ = message; | |
| 423 | _ = long_duration; | |
| 424 | // JNI call to Toast.makeText().show() | |
| 425 | } | |
| 426 | ||
| 427 | /// Vibrate the device | |
| 428 | pub fn vibrate(duration_ms: i64) void { | |
| 429 | _ = duration_ms; | |
| 430 | // JNI call to Vibrator.vibrate() | |
| 431 | } | |
| 432 | ||
| 433 | /// Request a permission | |
| 434 | pub fn requestPermission(permission: []const u8) void { | |
| 435 | _ = permission; | |
| 436 | // JNI call to ActivityCompat.requestPermissions() | |
| 437 | } | |
| 438 | ||
| 439 | /// Check if permission is granted | |
| 440 | pub fn hasPermission(permission: []const u8) bool { | |
| 441 | _ = permission; | |
| 442 | // JNI call to ContextCompat.checkSelfPermission() | |
| 443 | return false; | |
| 444 | } | |
| 445 | ||
| 446 | /// Open URL in browser | |
| 447 | pub fn openURL(url: []const u8) void { | |
| 448 | _ = url; | |
| 449 | // JNI call to startActivity with ACTION_VIEW intent | |
| 450 | } | |
| 451 | ||
| 452 | /// Share text/content | |
| 453 | pub fn share(text: []const u8) void { | |
| 454 | _ = text; | |
| 455 | // JNI call to startActivity with ACTION_SEND intent | |
| 456 | } | |
| 457 | ||
| 458 | /// Copy text to clipboard | |
| 459 | pub fn setClipboard(text: []const u8) void { | |
| 460 | _ = text; | |
| 461 | // JNI call to ClipboardManager.setPrimaryClip() | |
| 462 | } | |
| 463 | ||
| 464 | /// Get text from clipboard | |
| 465 | pub fn getClipboard(allocator: std.mem.Allocator) ![]const u8 { | |
| 466 | _ = allocator; | |
| 467 | // JNI call to ClipboardManager.getPrimaryClip() | |
| 468 | return ""; | |
| 469 | } | |
| 470 | ||
| 471 | /// Check network connectivity | |
| 472 | pub fn isNetworkConnected() bool { | |
| 473 | // JNI call to ConnectivityManager.getActiveNetworkInfo() | |
| 474 | return true; | |
| 475 | } | |
| 476 | ||
| 477 | /// Get device info | |
| 478 | pub fn getDeviceInfo() DeviceInfo { | |
| 479 | return .{ | |
| 480 | .manufacturer = "Unknown", | |
| 481 | .model = "Android Device", | |
| 482 | .os_version = "14", | |
| 483 | .sdk_version = 34, | |
| 484 | }; | |
| 485 | } | |
| 486 | ||
| 487 | pub const DeviceInfo = struct { | |
| 488 | manufacturer: []const u8, | |
| 489 | model: []const u8, | |
| 490 | os_version: []const u8, | |
| 491 | sdk_version: i32, | |
| 492 | }; | |
| 493 | 257 | }; |
| 494 | 258 | |
| 495 | 259 | // ============================================================================ |
| @@ -1,553 +0,0 @@ | ||
| 1 | const std = @import("std"); | |
| 2 | const io_context = @import("io_context.zig"); | |
| 3 | ||
| 4 | /// Android Kotlin Template Generator | |
| 5 | /// Generates complete Android app templates with Craft integration | |
| 6 | pub const AndroidTemplate = struct { | |
| 7 | allocator: std.mem.Allocator, | |
| 8 | app_name: []const u8, | |
| 9 | package_name: []const u8, | |
| 10 | output_dir: []const u8, | |
| 11 | ||
| 12 | pub fn init(allocator: std.mem.Allocator, app_name: []const u8, package_name: []const u8, output_dir: []const u8) AndroidTemplate { | |
| 13 | return .{ | |
| 14 | .allocator = allocator, | |
| 15 | .app_name = app_name, | |
| 16 | .package_name = package_name, | |
| 17 | .output_dir = output_dir, | |
| 18 | }; | |
| 19 | } | |
| 20 | ||
| 21 | pub fn generate(self: *AndroidTemplate) !void { | |
| 22 | // Create directory structure | |
| 23 | try self.createDirectoryStructure(); | |
| 24 | ||
| 25 | // Generate Kotlin files | |
| 26 | try self.generateMainActivity(); | |
| 27 | try self.generateCraftBridge(); | |
| 28 | try self.generateCameraXBridge(); | |
| 29 | try self.generateBiometricsBridge(); | |
| 30 | ||
| 31 | // Generate configuration files | |
| 32 | try self.generateAndroidManifest(); | |
| 33 | try self.generateBuildGradle(); | |
| 34 | try self.generateAppBuildGradle(); | |
| 35 | try self.generateStringsXml(); | |
| 36 | ||
| 37 | std.debug.print("Android template generated successfully at: {s}\n", .{self.output_dir}); | |
| 38 | } | |
| 39 | ||
| 40 | fn createDirectoryStructure(self: *AndroidTemplate) !void { | |
| 41 | const io = io_context.get(); | |
| 42 | const cwd = io_context.cwd(); | |
| 43 | ||
| 44 | const package_path = try std.mem.replaceOwned(u8, self.allocator, self.package_name, ".", "/"); | |
| 45 | defer self.allocator.free(package_path); | |
| 46 | ||
| 47 | const dirs = [_][]const u8{ | |
| 48 | self.output_dir, | |
| 49 | try std.fmt.allocPrint(self.allocator, "{s}/app", .{self.output_dir}), | |
| 50 | try std.fmt.allocPrint(self.allocator, "{s}/app/src", .{self.output_dir}), | |
| 51 | try std.fmt.allocPrint(self.allocator, "{s}/app/src/main", .{self.output_dir}), | |
| 52 | try std.fmt.allocPrint(self.allocator, "{s}/app/src/main/java/{s}", .{ self.output_dir, package_path }), | |
| 53 | try std.fmt.allocPrint(self.allocator, "{s}/app/src/main/java/{s}/bridge", .{ self.output_dir, package_path }), | |
| 54 | try std.fmt.allocPrint(self.allocator, "{s}/app/src/main/java/{s}/features", .{ self.output_dir, package_path }), | |
| 55 | try std.fmt.allocPrint(self.allocator, "{s}/app/src/main/res", .{self.output_dir}), | |
| 56 | try std.fmt.allocPrint(self.allocator, "{s}/app/src/main/res/values", .{self.output_dir}), | |
| 57 | try std.fmt.allocPrint(self.allocator, "{s}/app/src/main/res/layout", .{self.output_dir}), | |
| 58 | }; | |
| 59 | ||
| 60 | for (dirs) |dir| { | |
| 61 | cwd.createDir(io, dir, .default_dir) catch |err| { | |
| 62 | if (err != error.PathAlreadyExists) return err; | |
| 63 | }; | |
| 64 | } | |
| 65 | } | |
| 66 | ||
| 67 | fn generateMainActivity(self: *AndroidTemplate) !void { | |
| 68 | const content = try std.fmt.allocPrint( | |
| 69 | self.allocator, | |
| 70 | \\package {s} | |
| 71 | \\ | |
| 72 | \\import android.os.Bundle | |
| 73 | \\import android.webkit.WebView | |
| 74 | \\import android.webkit.WebSettings | |
| 75 | \\import androidx.appcompat.app.AppCompatActivity | |
| 76 | \\import {s}.bridge.CraftBridge | |
| 77 | \\ | |
| 78 | \\class MainActivity : AppCompatActivity() {{ | |
| 79 | \\ private lateinit var webView: WebView | |
| 80 | \\ private lateinit var craftBridge: CraftBridge | |
| 81 | \\ | |
| 82 | \\ override fun onCreate(savedInstanceState: Bundle?) {{ | |
| 83 | \\ super.onCreate(savedInstanceState) | |
| 84 | \\ setContentView(R.layout.activity_main) | |
| 85 | \\ | |
| 86 | \\ // Initialize WebView | |
| 87 | \\ webView = findViewById(R.id.webview) | |
| 88 | \\ configureWebView() | |
| 89 | \\ | |
| 90 | \\ // Initialize Craft Bridge | |
| 91 | \\ craftBridge = CraftBridge(this, webView) | |
| 92 | \\ craftBridge.inject() | |
| 93 | \\ | |
| 94 | \\ // Load initial URL | |
| 95 | \\ webView.loadUrl("http://10.0.2.2:3000") // Android emulator localhost | |
| 96 | \\ }} | |
| 97 | \\ | |
| 98 | \\ private fun configureWebView() {{ | |
| 99 | \\ webView.settings.apply {{ | |
| 100 | \\ javaScriptEnabled = true | |
| 101 | \\ domStorageEnabled = true | |
| 102 | \\ databaseEnabled = true | |
| 103 | \\ mediaPlaybackRequiresUserGesture = false | |
| 104 | \\ allowFileAccess = false | |
| 105 | \\ allowContentAccess = false | |
| 106 | \\ mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW | |
| 107 | \\ // Required by WebGL2 / interactive map rendering. | |
| 108 | \\ loadWithOverviewMode = true | |
| 109 | \\ useWideViewPort = true | |
| 110 | \\ setSupportZoom(false) | |
| 111 | \\ builtInZoomControls = false | |
| 112 | \\ displayZoomControls = false | |
| 113 | \\ }} | |
| 114 | \\ | |
| 115 | \\ // Hardware layer keeps canvas + WebGL2 on the GPU path. | |
| 116 | \\ webView.setLayerType(android.view.View.LAYER_TYPE_HARDWARE, null) | |
| 117 | \\ | |
| 118 | \\ webView.webViewClient = android.webkit.WebViewClient() | |
| 119 | \\ webView.webChromeClient = android.webkit.WebChromeClient() | |
| 120 | \\ }} | |
| 121 | \\ | |
| 122 | \\ override fun onBackPressed() {{ | |
| 123 | \\ if (webView.canGoBack()) {{ | |
| 124 | \\ webView.goBack() | |
| 125 | \\ }} else {{ | |
| 126 | \\ super.onBackPressed() | |
| 127 | \\ }} | |
| 128 | \\ }} | |
| 129 | \\}} | |
| 130 | \\ | |
| 131 | , | |
| 132 | .{ self.package_name, self.package_name }, | |
| 133 | ); | |
| 134 | defer self.allocator.free(content); | |
| 135 | ||
| 136 | const package_path = try std.mem.replaceOwned(u8, self.allocator, self.package_name, ".", "/"); | |
| 137 | defer self.allocator.free(package_path); | |
| 138 | ||
| 139 | const path = try std.fmt.allocPrint(self.allocator, "app/src/main/java/{s}/MainActivity.kt", .{package_path}); | |
| 140 | defer self.allocator.free(path); | |
| 141 | ||
| 142 | try self.writeFile(path, content); | |
| 143 | } | |
| 144 | ||
| 145 | fn generateCraftBridge(self: *AndroidTemplate) !void { | |
| 146 | const content = try std.fmt.allocPrint( | |
| 147 | self.allocator, | |
| 148 | \\package {s}.bridge | |
| 149 | \\ | |
| 150 | \\import android.content.Context | |
| 151 | \\import android.os.Vibrator | |
| 152 | \\import android.webkit.JavascriptInterface | |
| 153 | \\import android.webkit.WebView | |
| 154 | \\import android.widget.Toast | |
| 155 | \\import org.json.JSONObject | |
| 156 | \\ | |
| 157 | \\class CraftBridge(private val context: Context, private val webView: WebView) {{ | |
| 158 | \\ private val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator | |
| 159 | \\ | |
| 160 | \\ fun inject() {{ | |
| 161 | \\ webView.addJavascriptInterface(this, "Android") | |
| 162 | \\ | |
| 163 | \\ // Inject bridge script | |
| 164 | \\ val bridgeScript = """ | |
| 165 | \\ window.craft = window.craft || {{}}; | |
| 166 | \\ window.craft.invoke = function(method, params) {{ | |
| 167 | \\ return new Promise((resolve, reject) => {{ | |
| 168 | \\ const messageId = Date.now() + '_' + Math.random(); | |
| 169 | \\ window.Android.postMessage(JSON.stringify({{ | |
| 170 | \\ id: messageId, | |
| 171 | \\ method: method, | |
| 172 | \\ params: params | |
| 173 | \\ }})); | |
| 174 | \\ }}); | |
| 175 | \\ }}; | |
| 176 | \\ """.trimIndent() | |
| 177 | \\ | |
| 178 | \\ webView.evaluateJavascript(bridgeScript, null) | |
| 179 | \\ }} | |
| 180 | \\ | |
| 181 | \\ @JavascriptInterface | |
| 182 | \\ fun postMessage(message: String) {{ | |
| 183 | \\ try {{ | |
| 184 | \\ val json = JSONObject(message) | |
| 185 | \\ val method = json.getString("method") | |
| 186 | \\ val messageId = json.getString("id") | |
| 187 | \\ val params = if (json.has("params")) json.getJSONObject("params") else JSONObject() | |
| 188 | \\ | |
| 189 | \\ handleMessage(method, params) {{ result -> | |
| 190 | \\ sendResponse(messageId, result) | |
| 191 | \\ }} | |
| 192 | \\ }} catch (e: Exception) {{ | |
| 193 | \\ e.printStackTrace() | |
| 194 | \\ }} | |
| 195 | \\ }} | |
| 196 | \\ | |
| 197 | \\ private fun handleMessage(method: String, params: JSONObject, callback: (JSONObject) -> Unit) {{ | |
| 198 | \\ val result = JSONObject() | |
| 199 | \\ | |
| 200 | \\ when (method) {{ | |
| 201 | \\ "getPlatform" -> {{ | |
| 202 | \\ result.put("platform", "android") | |
| 203 | \\ result.put("version", android.os.Build.VERSION.RELEASE) | |
| 204 | \\ callback(result) | |
| 205 | \\ }} | |
| 206 | \\ | |
| 207 | \\ "showToast" -> {{ | |
| 208 | \\ val message = params.getString("message") | |
| 209 | \\ val duration = if (params.optString("duration") == "long") Toast.LENGTH_LONG else Toast.LENGTH_SHORT | |
| 210 | \\ Toast.makeText(context, message, duration).show() | |
| 211 | \\ result.put("success", true) | |
| 212 | \\ callback(result) | |
| 213 | \\ }} | |
| 214 | \\ | |
| 215 | \\ "vibrate" -> {{ | |
| 216 | \\ val duration = params.optLong("duration", 50) | |
| 217 | \\ vibrator.vibrate(duration) | |
| 218 | \\ result.put("success", true) | |
| 219 | \\ callback(result) | |
| 220 | \\ }} | |
| 221 | \\ | |
| 222 | \\ "requestPermission" -> {{ | |
| 223 | \\ val permission = params.getString("permission") | |
| 224 | \\ // Permission handling will be implemented | |
| 225 | \\ result.put("granted", false) | |
| 226 | \\ result.put("message", "Not implemented") | |
| 227 | \\ callback(result) | |
| 228 | \\ }} | |
| 229 | \\ | |
| 230 | \\ else -> {{ | |
| 231 | \\ result.put("error", "Unknown method: $method") | |
| 232 | \\ callback(result) | |
| 233 | \\ }} | |
| 234 | \\ }} | |
| 235 | \\ }} | |
| 236 | \\ | |
| 237 | \\ private fun sendResponse(messageId: String, result: JSONObject) {{ | |
| 238 | \\ val response = JSONObject() | |
| 239 | \\ response.put("id", messageId) | |
| 240 | \\ response.put("success", !result.has("error")) | |
| 241 | \\ response.put("result", result) | |
| 242 | \\ | |
| 243 | \\ val script = "window.craftHandleResponse('${{response.toString()}}')" | |
| 244 | \\ webView.post {{ | |
| 245 | \\ webView.evaluateJavascript(script, null) | |
| 246 | \\ }} | |
| 247 | \\ }} | |
| 248 | \\}} | |
| 249 | \\ | |
| 250 | , | |
| 251 | .{self.package_name}, | |
| 252 | ); | |
| 253 | defer self.allocator.free(content); | |
| 254 | ||
| 255 | const package_path = try std.mem.replaceOwned(u8, self.allocator, self.package_name, ".", "/"); | |
| 256 | defer self.allocator.free(package_path); | |
| 257 | ||
| 258 | const path = try std.fmt.allocPrint(self.allocator, "app/src/main/java/{s}/bridge/CraftBridge.kt", .{package_path}); | |
| 259 | defer self.allocator.free(path); | |
| 260 | ||
| 261 | try self.writeFile(path, content); | |
| 262 | } | |
| 263 | ||
| 264 | fn generateCameraXBridge(self: *AndroidTemplate) !void { | |
| 265 | const content = try std.fmt.allocPrint( | |
| 266 | self.allocator, | |
| 267 | \\package {s}.features | |
| 268 | \\ | |
| 269 | \\import android.content.Context | |
| 270 | \\import androidx.camera.core.CameraSelector | |
| 271 | \\import androidx.camera.core.Preview | |
| 272 | \\import androidx.camera.lifecycle.ProcessCameraProvider | |
| 273 | \\import androidx.camera.view.PreviewView | |
| 274 | \\import androidx.core.content.ContextCompat | |
| 275 | \\import androidx.lifecycle.LifecycleOwner | |
| 276 | \\import com.google.common.util.concurrent.ListenableFuture | |
| 277 | \\ | |
| 278 | \\class CameraXBridge(private val context: Context) {{ | |
| 279 | \\ private lateinit var cameraProviderFuture: ListenableFuture<ProcessCameraProvider> | |
| 280 | \\ | |
| 281 | \\ fun startCamera(lifecycleOwner: LifecycleOwner, previewView: PreviewView) {{ | |
| 282 | \\ cameraProviderFuture = ProcessCameraProvider.getInstance(context) | |
| 283 | \\ | |
| 284 | \\ cameraProviderFuture.addListener({{ | |
| 285 | \\ val cameraProvider = cameraProviderFuture.get() | |
| 286 | \\ bindPreview(cameraProvider, lifecycleOwner, previewView) | |
| 287 | \\ }}, ContextCompat.getMainExecutor(context)) | |
| 288 | \\ }} | |
| 289 | \\ | |
| 290 | \\ private fun bindPreview( | |
| 291 | \\ cameraProvider: ProcessCameraProvider, | |
| 292 | \\ lifecycleOwner: LifecycleOwner, | |
| 293 | \\ previewView: PreviewView | |
| 294 | \\ ) {{ | |
| 295 | \\ val preview = Preview.Builder().build() | |
| 296 | \\ val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA | |
| 297 | \\ | |
| 298 | \\ preview.setSurfaceProvider(previewView.surfaceProvider) | |
| 299 | \\ | |
| 300 | \\ try {{ | |
| 301 | \\ cameraProvider.unbindAll() | |
| 302 | \\ cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, preview) | |
| 303 | \\ }} catch (e: Exception) {{ | |
| 304 | \\ e.printStackTrace() | |
| 305 | \\ }} | |
| 306 | \\ }} | |
| 307 | \\}} | |
| 308 | \\ | |
| 309 | , | |
| 310 | .{self.package_name}, | |
| 311 | ); | |
| 312 | defer self.allocator.free(content); | |
| 313 | ||
| 314 | const package_path = try std.mem.replaceOwned(u8, self.allocator, self.package_name, ".", "/"); | |
| 315 | defer self.allocator.free(package_path); | |
| 316 | ||
| 317 | const path = try std.fmt.allocPrint(self.allocator, "app/src/main/java/{s}/features/CameraXBridge.kt", .{package_path}); | |
| 318 | defer self.allocator.free(path); | |
| 319 | ||
| 320 | try self.writeFile(path, content); | |
| 321 | } | |
| 322 | ||
| 323 | fn generateBiometricsBridge(self: *AndroidTemplate) !void { | |
| 324 | const content = try std.fmt.allocPrint( | |
| 325 | self.allocator, | |
| 326 | \\package {s}.features | |
| 327 | \\ | |
| 328 | \\import android.content.Context | |
| 329 | \\import androidx.biometric.BiometricManager | |
| 330 | \\import androidx.biometric.BiometricPrompt | |
| 331 | \\import androidx.core.content.ContextCompat | |
| 332 | \\import androidx.fragment.app.FragmentActivity | |
| 333 | \\ | |
| 334 | \\class BiometricsBridge(private val context: Context) {{ | |
| 335 | \\ fun canAuthenticate(): Boolean {{ | |
| 336 | \\ val biometricManager = BiometricManager.from(context) | |
| 337 | \\ return biometricManager.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS | |
| 338 | \\ }} | |
| 339 | \\ | |
| 340 | \\ fun authenticate(activity: FragmentActivity, callback: (Boolean, String?) -> Unit) {{ | |
| 341 | \\ val executor = ContextCompat.getMainExecutor(context) | |
| 342 | \\ | |
| 343 | \\ val biometricPrompt = BiometricPrompt(activity, executor, | |
| 344 | \\ object : BiometricPrompt.AuthenticationCallback() {{ | |
| 345 | \\ override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {{ | |
| 346 | \\ super.onAuthenticationSucceeded(result) | |
| 347 | \\ callback(true, null) | |
| 348 | \\ }} | |
| 349 | \\ | |
| 350 | \\ override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {{ | |
| 351 | \\ super.onAuthenticationError(errorCode, errString) | |
| 352 | \\ callback(false, errString.toString()) | |
| 353 | \\ }} | |
| 354 | \\ | |
| 355 | \\ override fun onAuthenticationFailed() {{ | |
| 356 | \\ super.onAuthenticationFailed() | |
| 357 | \\ callback(false, "Authentication failed") | |
| 358 | \\ }} | |
| 359 | \\ }}) | |
| 360 | \\ | |
| 361 | \\ val promptInfo = BiometricPrompt.PromptInfo.Builder() | |
| 362 | \\ .setTitle("Biometric Authentication") | |
| 363 | \\ .setSubtitle("Log in using your biometric credential") | |
| 364 | \\ .setNegativeButtonText("Cancel") | |
| 365 | \\ .build() | |
| 366 | \\ | |
| 367 | \\ biometricPrompt.authenticate(promptInfo) | |
| 368 | \\ }} | |
| 369 | \\}} | |
| 370 | \\ | |
| 371 | , | |
| 372 | .{self.package_name}, | |
| 373 | ); | |
| 374 | defer self.allocator.free(content); | |
| 375 | ||
| 376 | const package_path = try std.mem.replaceOwned(u8, self.allocator, self.package_name, ".", "/"); | |
| 377 | defer self.allocator.free(package_path); | |
| 378 | ||
| 379 | const path = try std.fmt.allocPrint(self.allocator, "app/src/main/java/{s}/features/BiometricsBridge.kt", .{package_path}); | |
| 380 | defer self.allocator.free(path); | |
| 381 | ||
| 382 | try self.writeFile(path, content); | |
| 383 | } | |
| 384 | ||
| 385 | fn generateAndroidManifest(self: *AndroidTemplate) !void { | |
| 386 | const content = try std.fmt.allocPrint( | |
| 387 | self.allocator, | |
| 388 | \\<?xml version="1.0" encoding="utf-8"?> | |
| 389 | \\<manifest xmlns:android="http://schemas.android.com/apk/res/android" | |
| 390 | \\ package="{s}"> | |
| 391 | \\ | |
| 392 | \\ <uses-permission android:name="android.permission.INTERNET" /> | |
| 393 | \\ <uses-permission android:name="android.permission.CAMERA" /> | |
| 394 | \\ <uses-permission android:name="android.permission.VIBRATE" /> | |
| 395 | \\ <uses-permission android:name="android.permission.USE_BIOMETRIC" /> | |
| 396 | \\ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> | |
| 397 | \\ | |
| 398 | \\ <application | |
| 399 | \\ android:allowBackup="true" | |
| 400 | \\ android:hardwareAccelerated="true" | |
| 401 | \\ android:largeHeap="true" | |
| 402 | \\ android:icon="@mipmap/ic_launcher" | |
| 403 | \\ android:label="@string/app_name" | |
| 404 | \\ android:roundIcon="@mipmap/ic_launcher_round" | |
| 405 | \\ android:supportsRtl="true" | |
| 406 | \\ android:theme="@style/Theme.AppCompat.Light.DarkActionBar" | |
| 407 | \\ android:usesCleartextTraffic="true"> | |
| 408 | \\ <activity | |
| 409 | \\ android:name=".MainActivity" | |
| 410 | \\ android:exported="true"> | |
| 411 | \\ <intent-filter> | |
| 412 | \\ <action android:name="android.intent.action.MAIN" /> | |
| 413 | \\ <category android:name="android.intent.category.LAUNCHER" /> | |
| 414 | \\ </intent-filter> | |
| 415 | \\ </activity> | |
| 416 | \\ </application> | |
| 417 | \\</manifest> | |
| 418 | \\ | |
| 419 | , | |
| 420 | .{self.package_name}, | |
| 421 | ); | |
| 422 | defer self.allocator.free(content); | |
| 423 | ||
| 424 | try self.writeFile("app/src/main/AndroidManifest.xml", content); | |
| 425 | } | |
| 426 | ||
| 427 | fn generateBuildGradle(self: *AndroidTemplate) !void { | |
| 428 | const content = | |
| 429 | \\// Top-level build file | |
| 430 | \\buildscript { | |
| 431 | \\ ext.kotlin_version = "1.9.0" | |
| 432 | \\ repositories { | |
| 433 | \\ google() | |
| 434 | \\ mavenCentral() | |
| 435 | \\ } | |
| 436 | \\ dependencies { | |
| 437 | \\ classpath "com.android.tools.build:gradle:8.1.0" | |
| 438 | \\ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" | |
| 439 | \\ } | |
| 440 | \\} | |
| 441 | \\ | |
| 442 | \\allprojects { | |
| 443 | \\ repositories { | |
| 444 | \\ google() | |
| 445 | \\ mavenCentral() | |
| 446 | \\ } | |
| 447 | \\} | |
| 448 | \\ | |
| 449 | \\task clean(type: Delete) { | |
| 450 | \\ delete rootProject.buildDir | |
| 451 | \\} | |
| 452 | \\ | |
| 453 | ; | |
| 454 | ||
| 455 | try self.writeFile("build.gradle", content); | |
| 456 | } | |
| 457 | ||
| 458 | fn generateAppBuildGradle(self: *AndroidTemplate) !void { | |
| 459 | const content = try std.fmt.allocPrint( | |
| 460 | self.allocator, | |
| 461 | \\plugins {{ | |
| 462 | \\ id 'com.android.application' | |
| 463 | \\ id 'kotlin-android' | |
| 464 | \\}} | |
| 465 | \\ | |
| 466 | \\android {{ | |
| 467 | \\ compileSdk 34 | |
| 468 | \\ | |
| 469 | \\ defaultConfig {{ | |
| 470 | \\ applicationId "{s}" | |
| 471 | \\ minSdk 21 | |
| 472 | \\ targetSdk 34 | |
| 473 | \\ versionCode 1 | |
| 474 | \\ versionName "1.0" | |
| 475 | \\ }} | |
| 476 | \\ | |
| 477 | \\ buildTypes {{ | |
| 478 | \\ release {{ | |
| 479 | \\ minifyEnabled false | |
| 480 | \\ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' | |
| 481 | \\ }} | |
| 482 | \\ }} | |
| 483 | \\ | |
| 484 | \\ compileOptions {{ | |
| 485 | \\ sourceCompatibility JavaVersion.VERSION_1_8 | |
| 486 | \\ targetCompatibility JavaVersion.VERSION_1_8 | |
| 487 | \\ }} | |
| 488 | \\ | |
| 489 | \\ kotlinOptions {{ | |
| 490 | \\ jvmTarget = '1.8' | |
| 491 | \\ }} | |
| 492 | \\}} | |
| 493 | \\ | |
| 494 | \\dependencies {{ | |
| 495 | \\ implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" | |
| 496 | \\ implementation 'androidx.core:core-ktx:1.12.0' | |
| 497 | \\ implementation 'androidx.appcompat:appcompat:1.6.1' | |
| 498 | \\ implementation 'com.google.android.material:material:1.10.0' | |
| 499 | \\ | |
| 500 | \\ // CameraX | |
| 501 | \\ implementation "androidx.camera:camera-core:1.3.0" | |
| 502 | \\ implementation "androidx.camera:camera-camera2:1.3.0" | |
| 503 | \\ implementation "androidx.camera:camera-lifecycle:1.3.0" | |
| 504 | \\ implementation "androidx.camera:camera-view:1.3.0" | |
| 505 | \\ | |
| 506 | \\ // Biometrics | |
| 507 | \\ implementation "androidx.biometric:biometric:1.1.0" | |
| 508 | \\}} | |
| 509 | \\ | |
| 510 | , | |
| 511 | .{self.package_name}, | |
| 512 | ); | |
| 513 | defer self.allocator.free(content); | |
| 514 | ||
| 515 | try self.writeFile("app/build.gradle", content); | |
| 516 | } | |
| 517 | ||
| 518 | fn generateStringsXml(self: *AndroidTemplate) !void { | |
| 519 | const content = try std.fmt.allocPrint( | |
| 520 | self.allocator, | |
| 521 | \\<resources> | |
| 522 | \\ <string name="app_name">{s}</string> | |
| 523 | \\</resources> | |
| 524 | \\ | |
| 525 | , | |
| 526 | .{self.app_name}, | |
| 527 | ); | |
| 528 | defer self.allocator.free(content); | |
| 529 | ||
| 530 | try self.writeFile("app/src/main/res/values/strings.xml", content); | |
| 531 | } | |
| 532 | ||
| 533 | fn writeFile(self: *AndroidTemplate, relative_path: []const u8, content: []const u8) !void { | |
| 534 | const full_path = try std.fmt.allocPrint(self.allocator, "{s}/{s}", .{ self.output_dir, relative_path }); | |
| 535 | defer self.allocator.free(full_path); | |
| 536 | ||
| 537 | const io = io_context.get(); | |
| 538 | const cwd = io_context.cwd(); | |
| 539 | const file = try cwd.createFile(io, full_path, .{}); | |
| 540 | defer file.close(io); | |
| 541 | ||
| 542 | try file.writeStreamingAll(io, content); | |
| 543 | } | |
| 544 | }; | |
| 545 | ||
| 546 | // Test | |
| 547 | test "Android template generation" { | |
| 548 | const allocator = std.testing.allocator; | |
| 549 | const template = AndroidTemplate.init(allocator, "TestApp", "com.test.app", "test_android_output"); | |
| 550 | ||
| 551 | // Would generate files - skipping in test | |
| 552 | _ = template; | |
| 553 | } | |
| @@ -29,7 +29,13 @@ pub const mobile = @import("mobile.zig"); | ||
| 29 | 29 | pub const android = @import("android.zig"); |
| 30 | 30 | pub const CraftActivity = android.CraftActivity; |
| 31 | 31 | pub const AndroidJSBridge = android.JSBridge; |
| 32 | pub const AndroidFeatures = android.AndroidFeatures; | |
| 32 | // `AndroidFeatures` was re-exported here. It was ten functions — `showToast`, | |
| 33 | // `vibrate`, `requestPermission`, `openURL`, `share`, `setClipboard`, | |
| 34 | // `getClipboard`, `hasPermission`, `isNetworkConnected`, `getDeviceInfo` — and | |
| 35 | // every one had a body of `_ = param;` and a comment naming the JNI call it | |
| 36 | // would have made. `isNetworkConnected` returned true unconditionally and | |
| 37 | // `getDeviceInfo` returned a hardcoded "Android Device" on SDK 34, so a caller | |
| 38 | // asking about the device got a plausible answer that was never true. | |
| 33 | 39 | |
| 34 | 40 | // Re-export API module |
| 35 | 41 | pub const api = @import("api.zig"); |
| @@ -8,204 +8,6 @@ const compat = @import("compat.zig"); | ||
| 8 | 8 | // Use the proper Objective-C runtime wrapper |
| 9 | 9 | const objc = objc_runtime.objc; |
| 10 | 10 | |
| 11 | // JNI for Android | |
| 12 | const jni = if (@import("builtin").target.os.tag == .linux) struct { | |
| 13 | // JNI types | |
| 14 | pub const JNIEnv = opaque {}; | |
| 15 | pub const jobject = ?*anyopaque; | |
| 16 | pub const jclass = ?*anyopaque; | |
| 17 | pub const jmethodID = ?*anyopaque; | |
| 18 | pub const jfieldID = ?*anyopaque; | |
| 19 | pub const jstring = ?*anyopaque; | |
| 20 | pub const jboolean = u8; | |
| 21 | pub const jint = i32; | |
| 22 | pub const jlong = i64; | |
| 23 | ||
| 24 | // JNI function pointers (these will be looked up from JNIEnv vtable) | |
| 25 | // The JNIEnv is actually a pointer to a vtable of function pointers | |
| 26 | const JNINativeInterface = extern struct { | |
| 27 | reserved0: ?*anyopaque, | |
| 28 | reserved1: ?*anyopaque, | |
| 29 | reserved2: ?*anyopaque, | |
| 30 | reserved3: ?*anyopaque, | |
| 31 | GetVersion: ?*const fn (*JNIEnv) callconv(.c) jint, | |
| 32 | // ... many more function pointers ... | |
| 33 | FindClass: ?*const fn (*JNIEnv, [*:0]const u8) callconv(.c) jclass, | |
| 34 | GetMethodID: ?*const fn (*JNIEnv, jclass, [*:0]const u8, [*:0]const u8) callconv(.c) jmethodID, | |
| 35 | GetObjectClass: ?*const fn (*JNIEnv, jobject) callconv(.c) jclass, | |
| 36 | CallObjectMethodV: ?*const fn (*JNIEnv, jobject, jmethodID, ...) callconv(.c) jobject, | |
| 37 | CallVoidMethodV: ?*const fn (*JNIEnv, jobject, jmethodID, ...) callconv(.c) void, | |
| 38 | NewStringUTF: ?*const fn (*JNIEnv, [*:0]const u8) callconv(.c) jstring, | |
| 39 | GetStringUTFChars: ?*const fn (*JNIEnv, jstring, ?*jboolean) callconv(.c) [*:0]const u8, | |
| 40 | ReleaseStringUTFChars: ?*const fn (*JNIEnv, jstring, [*:0]const u8) callconv(.c) void, | |
| 41 | }; | |
| 42 | ||
| 43 | // Helper to get the function table from JNIEnv | |
| 44 | fn getTable(env: *JNIEnv) *JNINativeInterface { | |
| 45 | const env_ptr: **JNINativeInterface = @ptrCast(@alignCast(env)); | |
| 46 | return env_ptr.*; | |
| 47 | } | |
| 48 | ||
| 49 | // Wrapper functions | |
| 50 | pub fn FindClass(env: *JNIEnv, name: [*:0]const u8) jclass { | |
| 51 | const table = getTable(env); | |
| 52 | if (table.FindClass) |func| { | |
| 53 | return func(env, name); | |
| 54 | } | |
| 55 | return null; | |
| 56 | } | |
| 57 | ||
| 58 | pub fn GetObjectClass(env: *JNIEnv, obj: jobject) jclass { | |
| 59 | const table = getTable(env); | |
| 60 | if (table.GetObjectClass) |func| { | |
| 61 | return func(env, obj); | |
| 62 | } | |
| 63 | return null; | |
| 64 | } | |
| 65 | ||
| 66 | pub fn GetMethodID(env: *JNIEnv, cls: jclass, name: [*:0]const u8, sig: [*:0]const u8) jmethodID { | |
| 67 | const table = getTable(env); | |
| 68 | if (table.GetMethodID) |func| { | |
| 69 | return func(env, cls, name, sig); | |
| 70 | } | |
| 71 | return null; | |
| 72 | } | |
| 73 | ||
| 74 | pub fn CallVoidMethod(env: *JNIEnv, obj: jobject, methodID: jmethodID, args: anytype) void { | |
| 75 | const table = getTable(env); | |
| 76 | if (table.CallVoidMethodV) |func| { | |
| 77 | _ = @call(.auto, func, .{ env, obj, methodID } ++ args); | |
| 78 | } | |
| 79 | } | |
| 80 | ||
| 81 | pub fn CallObjectMethod(env: *JNIEnv, obj: jobject, methodID: jmethodID, args: anytype) jobject { | |
| 82 | const table = getTable(env); | |
| 83 | if (table.CallObjectMethodV) |func| { | |
| 84 | return @call(.auto, func, .{ env, obj, methodID } ++ args); | |
| 85 | } | |
| 86 | return null; | |
| 87 | } | |
| 88 | ||
| 89 | pub fn NewStringUTF(env: *JNIEnv, bytes: [*:0]const u8) jstring { | |
| 90 | const table = getTable(env); | |
| 91 | if (table.NewStringUTF) |func| { | |
| 92 | return func(env, bytes); | |
| 93 | } | |
| 94 | return null; | |
| 95 | } | |
| 96 | ||
| 97 | pub fn GetStringUTFChars(env: *JNIEnv, string: jstring, isCopy: ?*jboolean) [*:0]const u8 { | |
| 98 | const table = getTable(env); | |
| 99 | if (table.GetStringUTFChars) |func| { | |
| 100 | return func(env, string, isCopy); | |
| 101 | } | |
| 102 | return @ptrCast(&[_]u8{0}); | |
| 103 | } | |
| 104 | ||
| 105 | pub fn ReleaseStringUTFChars(env: *JNIEnv, string: jstring, utf: [*:0]const u8) void { | |
| 106 | const table = getTable(env); | |
| 107 | if (table.ReleaseStringUTFChars) |func| { | |
| 108 | func(env, string, utf); | |
| 109 | } | |
| 110 | } | |
| 111 | } else struct {}; | |
| 112 | ||
| 113 | // ============================================================================ | |
| 114 | // Android Callback Storage | |
| 115 | // ============================================================================ | |
| 116 | ||
| 117 | /// Stored callbacks for Android ValueCallback (JS evaluation) and permissions | |
| 118 | pub const AndroidCallbackStorage = struct { | |
| 119 | // JavaScript evaluation callbacks - indexed by request ID | |
| 120 | js_callbacks: [16]?*const fn ([]const u8) void = @splat(null), | |
| 121 | js_callback_next_id: u32 = 0, | |
| 122 | ||
| 123 | // Permission callbacks - indexed by request code | |
| 124 | permission_callbacks: [16]?*const fn (bool) void = @splat(null), | |
| 125 | ||
| 126 | const Self = @This(); | |
| 127 | ||
| 128 | /// Store a JS callback and return its ID | |
| 129 | pub fn storeJsCallback(self: *Self, callback: *const fn ([]const u8) void) u32 { | |
| 130 | const id = self.js_callback_next_id % 16; | |
| 131 | self.js_callbacks[id] = callback; | |
| 132 | self.js_callback_next_id +%= 1; | |
| 133 | return id; | |
| 134 | } | |
| 135 | ||
| 136 | /// Invoke and clear a JS callback | |
| 137 | pub fn invokeJsCallback(self: *Self, id: u32, result: []const u8) void { | |
| 138 | const idx = id % 16; | |
| 139 | if (self.js_callbacks[idx]) |callback| { | |
| 140 | callback(result); | |
| 141 | self.js_callbacks[idx] = null; | |
| 142 | } | |
| 143 | } | |
| 144 | ||
| 145 | /// Store a permission callback with request code | |
| 146 | pub fn storePermissionCallback(self: *Self, request_code: u32, callback: *const fn (bool) void) void { | |
| 147 | const idx = request_code % 16; | |
| 148 | self.permission_callbacks[idx] = callback; | |
| 149 | } | |
| 150 | ||
| 151 | /// Invoke and clear a permission callback | |
| 152 | pub fn invokePermissionCallback(self: *Self, request_code: u32, granted: bool) void { | |
| 153 | const idx = request_code % 16; | |
| 154 | if (self.permission_callbacks[idx]) |callback| { | |
| 155 | callback(granted); | |
| 156 | self.permission_callbacks[idx] = null; | |
| 157 | } | |
| 158 | } | |
| 159 | }; | |
| 160 | ||
| 161 | /// Global callback storage for Android | |
| 162 | var android_callbacks: AndroidCallbackStorage = .{}; | |
| 163 | ||
| 164 | // JNI export functions are only compiled on Android (Linux target) | |
| 165 | // On other platforms, these are no-ops | |
| 166 | comptime { | |
| 167 | if (@import("builtin").target.os.tag == .linux) { | |
| 168 | @export(&Java_app_craft_CraftValueCallback_nativeOnReceiveValue_impl, .{ .name = "Java_app_craft_CraftValueCallback_nativeOnReceiveValue" }); | |
| 169 | @export(&Java_app_craft_CraftActivity_nativeOnPermissionResult_impl, .{ .name = "Java_app_craft_CraftActivity_nativeOnPermissionResult" }); | |
| 170 | } | |
| 171 | } | |
| 172 | ||
| 173 | /// JNI callback function exported for ValueCallback.onReceiveValue | |
| 174 | /// Called from Java when evaluateJavascript completes | |
| 175 | fn Java_app_craft_CraftValueCallback_nativeOnReceiveValue_impl( | |
| 176 | env: *jni.JNIEnv, | |
| 177 | this: jni.jobject, | |
| 178 | callback_id: jni.jint, | |
| 179 | result: jni.jstring, | |
| 180 | ) callconv(.c) void { | |
| 181 | _ = this; | |
| 182 | ||
| 183 | // Convert Java string result to Zig slice | |
| 184 | const result_chars = jni.GetStringUTFChars(env, result, null); | |
| 185 | const result_slice = std.mem.span(result_chars); | |
| 186 | ||
| 187 | // Invoke the stored callback | |
| 188 | android_callbacks.invokeJsCallback(@intCast(callback_id), result_slice); | |
| 189 | ||
| 190 | // Release the string | |
| 191 | jni.ReleaseStringUTFChars(env, result, result_chars); | |
| 192 | } | |
| 193 | ||
| 194 | /// JNI callback function exported for permission results | |
| 195 | /// Called from Activity.onRequestPermissionsResult | |
| 196 | fn Java_app_craft_CraftActivity_nativeOnPermissionResult_impl( | |
| 197 | env: *jni.JNIEnv, | |
| 198 | this: jni.jobject, | |
| 199 | request_code: jni.jint, | |
| 200 | granted: jni.jboolean, | |
| 201 | ) callconv(.c) void { | |
| 202 | _ = env; | |
| 203 | _ = this; | |
| 204 | ||
| 205 | // Invoke the stored callback | |
| 206 | android_callbacks.invokePermissionCallback(@intCast(request_code), granted != 0); | |
| 207 | } | |
| 208 | ||
| 209 | 11 | pub const Platform = enum { |
| 210 | 12 | ios, |
| 211 | 13 | android, |
| @@ -798,161 +600,6 @@ pub const Android = struct { | ||
| 798 | 600 | }; |
| 799 | 601 | }; |
| 800 | 602 | |
| 801 | /// JNI Environment (global reference, must be set by Java/Kotlin code) | |
| 802 | var jni_env: ?*jni.JNIEnv = null; | |
| 803 | ||
| 804 | pub fn setJNIEnv(env: *jni.JNIEnv) void { | |
| 805 | jni_env = env; | |
| 806 | } | |
| 807 | ||
| 808 | /// Create Android WebView | |
| 809 | pub fn createWebView(allocator: std.mem.Allocator, context: *Context, config: WebViewConfig) !*WebView { | |
| 810 | const builtin = @import("builtin"); | |
| 811 | if (builtin.target.os.tag != .linux) { | |
| 812 | return error.UnsupportedPlatform; | |
| 813 | } | |
| 814 | ||
| 815 | const env = jni_env orelse return error.JNINotInitialized; | |
| 816 | ||
| 817 | // Get WebView class | |
| 818 | const webview_class_name = "android/webkit/WebView"; | |
| 819 | const webview_class = try getJNIClass(env, webview_class_name); | |
| 820 | ||
| 821 | // Get WebView constructor | |
| 822 | const constructor_id = try getJNIMethod(env, webview_class, "<init>", "(Landroid/content/Context;)V"); | |
| 823 | ||
| 824 | // Create WebView instance | |
| 825 | const webview_obj = jni.CallObjectMethod(env, context, constructor_id, .{}); | |
| 826 | if (webview_obj == null) { | |
| 827 | return error.WebViewCreationFailed; | |
| 828 | } | |
| 829 | ||
| 830 | // Configure WebView settings | |
| 831 | const settings_method = try getJNIMethod(env, webview_class, "getSettings", "()Landroid/webkit/WebSettings;"); | |
| 832 | const settings = jni.CallObjectMethod(env, webview_obj, settings_method, .{}); | |
| 833 | ||
| 834 | if (settings != null) { | |
| 835 | const settings_class_name = "android/webkit/WebSettings"; | |
| 836 | const settings_class = try getJNIClass(env, settings_class_name); | |
| 837 | ||
| 838 | // Enable JavaScript | |
| 839 | if (config.javascript_enabled) { | |
| 840 | const set_js_enabled = try getJNIMethod(env, settings_class, "setJavaScriptEnabled", "(Z)V"); | |
| 841 | jni.CallVoidMethod(env, settings, set_js_enabled, .{@as(jni.jboolean, 1)}); | |
| 842 | } | |
| 843 | ||
| 844 | // Enable DOM storage | |
| 845 | if (config.dom_storage_enabled) { | |
| 846 | const set_dom_storage = try getJNIMethod(env, settings_class, "setDomStorageEnabled", "(Z)V"); | |
| 847 | jni.CallVoidMethod(env, settings, set_dom_storage, .{@as(jni.jboolean, 1)}); | |
| 848 | } | |
| 849 | ||
| 850 | // Enable database | |
| 851 | if (config.database_enabled) { | |
| 852 | const set_database = try getJNIMethod(env, settings_class, "setDatabaseEnabled", "(Z)V"); | |
| 853 | jni.CallVoidMethod(env, settings, set_database, .{@as(jni.jboolean, 1)}); | |
| 854 | } | |
| 855 | } | |
| 856 | ||
| 857 | _ = allocator; // Will be used for cleanup tracking | |
| 858 | return @ptrCast(@alignCast(webview_obj)); | |
| 859 | } | |
| 860 | ||
| 861 | /// Load URL in WebView | |
| 862 | pub fn loadURL(webview: *WebView, url: []const u8) !void { | |
| 863 | const builtin = @import("builtin"); | |
| 864 | if (builtin.target.os.tag != .linux) { | |
| 865 | return error.UnsupportedPlatform; | |
| 866 | } | |
| 867 | ||
| 868 | const env = jni_env orelse return error.JNINotInitialized; | |
| 869 | ||
| 870 | // Get WebView class | |
| 871 | const webview_obj: jni.jobject = @ptrCast(@alignCast(webview)); | |
| 872 | const webview_class = jni.GetObjectClass(env, webview_obj); | |
| 873 | ||
| 874 | // Get loadUrl method | |
| 875 | const load_url_method = try getJNIMethod(env, webview_class, "loadUrl", "(Ljava/lang/String;)V"); | |
| 876 | ||
| 877 | // Convert URL to Java string (need null-terminated string) | |
| 878 | const allocator = std.heap.page_allocator; | |
| 879 | const url_z = try @import("memory.zig").dupeZ(allocator, u8, url); | |
| 880 | defer allocator.free(url_z); | |
| 881 | const url_jstring = jni.NewStringUTF(env, url_z.ptr); | |
| 882 | ||
| 883 | // Call loadUrl | |
| 884 | jni.CallVoidMethod(env, webview_obj, load_url_method, .{url_jstring}); | |
| 885 | } | |
| 886 | ||
| 887 | /// Execute JavaScript | |
| 888 | pub fn evaluateJavaScript(webview: *WebView, script: []const u8, callback: ?*const fn ([]const u8) void) !void { | |
| 889 | const builtin = @import("builtin"); | |
| 890 | if (builtin.target.os.tag != .linux) { | |
| 891 | return error.UnsupportedPlatform; | |
| 892 | } | |
| 893 | ||
| 894 | const env = jni_env orelse return error.JNINotInitialized; | |
| 895 | ||
| 896 | // Get WebView class | |
| 897 | const webview_obj: jni.jobject = @ptrCast(@alignCast(webview)); | |
| 898 | const webview_class = jni.GetObjectClass(env, webview_obj); | |
| 899 | ||
| 900 | // Get evaluateJavascript method | |
| 901 | const eval_js_method = try getJNIMethod(env, webview_class, "evaluateJavascript", "(Ljava/lang/String;Landroid/webkit/ValueCallback;)V"); | |
| 902 | ||
| 903 | // Convert script to Java string (need null-terminated string) | |
| 904 | const allocator = std.heap.page_allocator; | |
| 905 | const script_z = try @import("memory.zig").dupeZ(allocator, u8, script); | |
| 906 | defer allocator.free(script_z); | |
| 907 | const script_jstring = jni.NewStringUTF(env, script_z.ptr); | |
| 908 | ||
| 909 | // Create ValueCallback wrapper if callback is provided | |
| 910 | var value_callback: jni.jobject = null; | |
| 911 | if (callback) |cb| { | |
| 912 | // Store callback and get ID | |
| 913 | const callback_id = android_callbacks.storeJsCallback(cb); | |
| 914 | ||
| 915 | // Create CraftValueCallback instance (Java class that implements ValueCallback) | |
| 916 | // Java code: new CraftValueCallback(callbackId) | |
| 917 | const craft_callback_class = try getJNIClass(env, "app/craft/CraftValueCallback"); | |
| 918 | const callback_init = try getJNIMethod(env, craft_callback_class, "<init>", "(I)V"); | |
| 919 | ||
| 920 | // Allocate new object | |
| 921 | const alloc_method = try getJNIMethod(env, craft_callback_class, "<init>", "(I)V"); | |
| 922 | _ = alloc_method; | |
| 923 | ||
| 924 | // Create instance with callback ID | |
| 925 | value_callback = jni.CallObjectMethod(env, craft_callback_class, callback_init, .{@as(jni.jint, @intCast(callback_id))}); | |
| 926 | } | |
| 927 | ||
| 928 | // Call evaluateJavascript with the ValueCallback wrapper | |
| 929 | jni.CallVoidMethod(env, webview_obj, eval_js_method, .{ script_jstring, value_callback }); | |
| 930 | } | |
| 931 | ||
| 932 | /// Helper function to get JNI class | |
| 933 | fn getJNIClass(env: *jni.JNIEnv, class_name: [:0]const u8) !jni.jclass { | |
| 934 | const cls = jni.FindClass(env, class_name.ptr); | |
| 935 | if (cls == null) { | |
| 936 | return error.ClassNotFound; | |
| 937 | } | |
| 938 | return cls; | |
| 939 | } | |
| 940 | ||
| 941 | /// Helper function to get JNI method | |
| 942 | fn getJNIMethod(env: *jni.JNIEnv, cls: jni.jclass, method_name: [:0]const u8, signature: [:0]const u8) !jni.jmethodID { | |
| 943 | const method_id = jni.GetMethodID(env, cls, method_name.ptr, signature.ptr); | |
| 944 | if (method_id == null) { | |
| 945 | return error.MethodNotFound; | |
| 946 | } | |
| 947 | return method_id; | |
| 948 | } | |
| 949 | ||
| 950 | /// Handle Deep Links | |
| 951 | pub fn handleDeepLink(intent_data: []const u8) !void { | |
| 952 | _ = intent_data; | |
| 953 | // Parse and handle Android Intent data | |
| 954 | } | |
| 955 | ||
| 956 | 603 | /// Request Permissions |
| 957 | 604 | pub const Permission = enum { |
| 958 | 605 | camera, |
| @@ -966,133 +613,36 @@ pub const Android = struct { | ||
| 966 | 613 | record_audio, |
| 967 | 614 | }; |
| 968 | 615 | |
| 969 | pub fn requestPermission(activity: *Activity, permission: Permission, callback: *const fn (bool) void) !void { | |
| 970 | const builtin = @import("builtin"); | |
| 971 | if (builtin.target.os.tag != .linux) { | |
| 972 | return error.UnsupportedPlatform; | |
| 973 | } | |
| 974 | ||
| 975 | const env = jni_env orelse return error.JNINotInitialized; | |
| 976 | ||
| 977 | // Get ActivityCompat class | |
| 978 | const activity_compat_class = try getJNIClass(env, "androidx/core/app/ActivityCompat"); | |
| 979 | ||
| 980 | // Convert permission to Android permission string | |
| 981 | const permission_str = switch (permission) { | |
| 982 | .camera => "android.permission.CAMERA", | |
| 983 | .microphone => "android.permission.RECORD_AUDIO", | |
| 984 | .location_fine => "android.permission.ACCESS_FINE_LOCATION", | |
| 985 | .location_coarse => "android.permission.ACCESS_COARSE_LOCATION", | |
| 986 | .read_external_storage => "android.permission.READ_EXTERNAL_STORAGE", | |
| 987 | .write_external_storage => "android.permission.WRITE_EXTERNAL_STORAGE", | |
| 988 | .read_contacts => "android.permission.READ_CONTACTS", | |
| 989 | .write_contacts => "android.permission.WRITE_CONTACTS", | |
| 990 | .record_audio => "android.permission.RECORD_AUDIO", | |
| 991 | }; | |
| 992 | ||
| 993 | // Get requestPermissions method | |
| 994 | const request_permissions_method = try getJNIMethod( | |
| 995 | env, | |
| 996 | activity_compat_class, | |
| 997 | "requestPermissions", | |
| 998 | "(Landroid/app/Activity;[Ljava/lang/String;I)V", | |
| 999 | ); | |
| 1000 | ||
| 1001 | // Create string array with single permission | |
| 1002 | const allocator = std.heap.page_allocator; | |
| 1003 | const permission_z = try @import("memory.zig").dupeZ(allocator, u8, permission_str); | |
| 1004 | defer allocator.free(permission_z); | |
| 1005 | const permission_jstring = jni.NewStringUTF(env, permission_z.ptr); | |
| 1006 | ||
| 1007 | // Use a unique request code based on permission type | |
| 1008 | const request_code: u32 = 1001 + @backingInt(permission); | |
| 1009 | ||
| 1010 | // Store callback to be invoked in onRequestPermissionsResult | |
| 1011 | if (callback) |cb| { | |
| 1012 | android_callbacks.storePermissionCallback(request_code, cb); | |
| 1013 | } | |
| 1014 | ||
| 1015 | // Call requestPermissions with unique request code | |
| 1016 | const activity_obj: jni.jobject = @ptrCast(@alignCast(activity)); | |
| 1017 | jni.CallVoidMethod(env, activity_obj, request_permissions_method, .{ permission_jstring, @as(jni.jint, @intCast(request_code)) }); | |
| 1018 | } | |
| 1019 | ||
| 1020 | /// Vibration | |
| 1021 | pub fn vibrate(context: *Context, duration_ms: u64) void { | |
| 1022 | const builtin = @import("builtin"); | |
| 1023 | if (builtin.target.os.tag != .linux) { | |
| 1024 | return; | |
| 1025 | } | |
| 1026 | ||
| 1027 | const env = jni_env orelse return; | |
| 1028 | ||
| 1029 | // Get Vibrator service | |
| 1030 | const context_obj: jni.jobject = @ptrCast(@alignCast(context)); | |
| 1031 | const context_class = jni.GetObjectClass(env, context_obj); | |
| 1032 | ||
| 1033 | const get_system_service_method = getJNIMethod(env, context_class, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;") catch return; | |
| 1034 | ||
| 1035 | // Get VIBRATOR_SERVICE constant | |
| 1036 | const vibrator_service_str = jni.NewStringUTF(env, "vibrator"); | |
| 1037 | const vibrator_obj = jni.CallObjectMethod(env, context_obj, get_system_service_method, .{vibrator_service_str}); | |
| 1038 | ||
| 1039 | if (vibrator_obj != null) { | |
| 1040 | const vibrator_class = jni.GetObjectClass(env, vibrator_obj); | |
| 1041 | ||
| 1042 | // For Android 26+, use VibrationEffect | |
| 1043 | const vibrate_method = getJNIMethod(env, vibrator_class, "vibrate", "(J)V") catch return; | |
| 1044 | jni.CallVoidMethod(env, vibrator_obj, vibrate_method, .{@as(jni.jlong, @intCast(duration_ms))}); | |
| 1045 | } | |
| 1046 | } | |
| 1047 | ||
| 1048 | /// Toast Notification | |
| 1049 | pub fn showToast(context: *Context, message: []const u8, duration: ToastDuration) void { | |
| 1050 | const builtin = @import("builtin"); | |
| 1051 | if (builtin.target.os.tag != .linux) { | |
| 1052 | return; | |
| 1053 | } | |
| 1054 | ||
| 1055 | const env = jni_env orelse return; | |
| 1056 | ||
| 1057 | // Get Toast class | |
| 1058 | const toast_class = getJNIClass(env, "android/widget/Toast") catch return; | |
| 1059 | ||
| 1060 | // Get makeText method | |
| 1061 | const make_text_method = getJNIMethod( | |
| 1062 | env, | |
| 1063 | toast_class, | |
| 1064 | "makeText", | |
| 1065 | "(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;", | |
| 1066 | ) catch return; | |
| 1067 | ||
| 1068 | // Convert message to Java string (need null-terminated string) | |
| 1069 | const allocator = std.heap.page_allocator; | |
| 1070 | const message_z = @import("memory.zig").dupeZ(allocator, u8, message) catch return; | |
| 1071 | defer allocator.free(message_z); | |
| 1072 | const message_jstring = jni.NewStringUTF(env, message_z.ptr); | |
| 1073 | ||
| 1074 | // Convert duration | |
| 1075 | const duration_int: jni.jint = switch (duration) { | |
| 1076 | .short => 0, // Toast.LENGTH_SHORT | |
| 1077 | .long => 1, // Toast.LENGTH_LONG | |
| 1078 | }; | |
| 1079 | ||
| 1080 | // Create toast | |
| 1081 | const context_obj: jni.jobject = @ptrCast(@alignCast(context)); | |
| 1082 | const toast_obj = jni.CallObjectMethod(env, toast_class, make_text_method, .{ context_obj, message_jstring, duration_int }); | |
| 1083 | ||
| 1084 | if (toast_obj != null) { | |
| 1085 | // Show toast | |
| 1086 | const toast_obj_class = jni.GetObjectClass(env, toast_obj); | |
| 1087 | const show_method = getJNIMethod(env, toast_obj_class, "show", "()V") catch return; | |
| 1088 | jni.CallVoidMethod(env, toast_obj, show_method, .{}); | |
| 1089 | } | |
| 1090 | } | |
| 1091 | ||
| 1092 | 616 | pub const ToastDuration = enum { |
| 1093 | 617 | short, |
| 1094 | 618 | long, |
| 1095 | 619 | }; |
| 620 | ||
| 621 | // Every function that used to live in this struct — `setJNIEnv`, | |
| 622 | // `createWebView`, `loadURL`, `evaluateJavaScript`, `getJNIClass`, | |
| 623 | // `getJNIMethod`, `handleDeepLink`, `requestPermission`, `vibrate`, | |
| 624 | // `showToast` — has been deleted. The types stay because they are the | |
| 625 | // vocabulary the rest of the codebase and the test suite use; the | |
| 626 | // functions went because none of them could ever have worked. | |
| 627 | // | |
| 628 | // They all read through a hand-written `JNINativeInterface` that declared | |
| 629 | // four reserved slots, then `GetVersion`, then jumped straight to | |
| 630 | // `FindClass` under a comment reading "... many more function pointers | |
| 631 | // ...". The real JNI vtable has roughly 230 entries in a fixed ABI order — | |
| 632 | // `FindClass` is index 6, `GetObjectClass` 31, `NewStringUTF` 167 — so | |
| 633 | // every call read the wrong slot and would have jumped to a garbage | |
| 634 | // address. That is not a bug you fix in place; the replacement `@cImport`s | |
| 635 | // the NDK's own `jni.h`, where the layout cannot be got wrong. | |
| 636 | // | |
| 637 | // Individually they were also wrong in ways that prove none was ever | |
| 638 | // compiled, let alone run: `requestPermission` resolved the *static* | |
| 639 | // `ActivityCompat.requestPermissions` with `GetMethodID` and passed two | |
| 640 | // varargs where the signature demands three with a `jobjectArray`; | |
| 641 | // `createWebView` and `evaluateJavaScript` invoked constructors through | |
| 642 | // `CallObjectMethod`, which cannot construct anything — `NewObject` is the | |
| 643 | // one that can; and `requestPermission` contained `if (callback) |cb|` on | |
| 644 | // a non-optional parameter, an unconditional compile error that never | |
| 645 | // fired because nothing referenced the function. | |
| 1096 | 646 | }; |
| 1097 | 647 | |
| 1098 | 648 | /// Cross-Platform Mobile Window |
| @@ -1139,10 +689,11 @@ pub const MobileWindow = struct { | ||
| 1139 | 689 | const webview: *iOS.WKWebView = @ptrCast(@alignCast(self.handle)); |
| 1140 | 690 | try iOS.loadURL(webview, url); |
| 1141 | 691 | }, |
| 1142 | .android => { | |
| 1143 | const webview: *Android.WebView = @ptrCast(@alignCast(self.handle)); | |
| 1144 | try Android.loadURL(webview, url); | |
| 1145 | }, | |
| 692 | // Android has no JNI layer yet. Returning an error is the honest | |
| 693 | // answer; the deleted `Android.loadURL` would have jumped through | |
| 694 | // a mis-ordered vtable instead, which is a crash wearing the | |
| 695 | // costume of an implementation. | |
| 696 | .android => return error.AndroidBridgeNotImplemented, | |
| 1146 | 697 | .unknown => return error.UnsupportedPlatform, |
| 1147 | 698 | } |
| 1148 | 699 | } |
| @@ -1153,10 +704,7 @@ pub const MobileWindow = struct { | ||
| 1153 | 704 | const webview: *iOS.WKWebView = @ptrCast(@alignCast(self.handle)); |
| 1154 | 705 | try iOS.evaluateJavaScript(webview, script, null); |
| 1155 | 706 | }, |
| 1156 | .android => { | |
| 1157 | const webview: *Android.WebView = @ptrCast(@alignCast(self.handle)); | |
| 1158 | try Android.evaluateJavaScript(webview, script, null); | |
| 1159 | }, | |
| 707 | .android => return error.AndroidBridgeNotImplemented, | |
| 1160 | 708 | .unknown => return error.UnsupportedPlatform, |
| 1161 | 709 | } |
| 1162 | 710 | } |
| @@ -1,373 +0,0 @@ | ||
| 1 | const std = @import("std"); | |
| 2 | const testing = std.testing; | |
| 3 | const android = @import("../src/android.zig"); | |
| 4 | ||
| 5 | // ============================================================================ | |
| 6 | // JNI Types Tests | |
| 7 | // ============================================================================ | |
| 8 | ||
| 9 | test "JNI - type definitions" { | |
| 10 | // Verify JNI type sizes match expected values | |
| 11 | try testing.expectEqual(@as(usize, @sizeOf(i32)), @sizeOf(android.jni.jint)); | |
| 12 | try testing.expectEqual(@as(usize, @sizeOf(i64)), @sizeOf(android.jni.jlong)); | |
| 13 | try testing.expectEqual(@as(usize, @sizeOf(u8)), @sizeOf(android.jni.jboolean)); | |
| 14 | try testing.expectEqual(@as(usize, @sizeOf(f32)), @sizeOf(android.jni.jfloat)); | |
| 15 | try testing.expectEqual(@as(usize, @sizeOf(f64)), @sizeOf(android.jni.jdouble)); | |
| 16 | } | |
| 17 | ||
| 18 | // ============================================================================ | |
| 19 | // CraftActivity Tests | |
| 20 | // ============================================================================ | |
| 21 | ||
| 22 | test "CraftActivity - Theme enum" { | |
| 23 | try testing.expectEqual(android.CraftActivity.Theme.light, .light); | |
| 24 | try testing.expectEqual(android.CraftActivity.Theme.dark, .dark); | |
| 25 | try testing.expectEqual(android.CraftActivity.Theme.system, .system); | |
| 26 | } | |
| 27 | ||
| 28 | test "CraftActivity - Orientation enum" { | |
| 29 | try testing.expectEqual(android.CraftActivity.Orientation.portrait, .portrait); | |
| 30 | try testing.expectEqual(android.CraftActivity.Orientation.landscape, .landscape); | |
| 31 | try testing.expectEqual(android.CraftActivity.Orientation.sensor, .sensor); | |
| 32 | try testing.expectEqual(android.CraftActivity.Orientation.unspecified, .unspecified); | |
| 33 | } | |
| 34 | ||
| 35 | test "CraftActivity - Content union" { | |
| 36 | const html_content = android.CraftActivity.Content{ .html = "<h1>Hello</h1>" }; | |
| 37 | const url_content = android.CraftActivity.Content{ .url = "https://example.com" }; | |
| 38 | const asset_content = android.CraftActivity.Content{ .asset = "index.html" }; | |
| 39 | ||
| 40 | switch (html_content) { | |
| 41 | .html => |h| try testing.expectEqualStrings("<h1>Hello</h1>", h), | |
| 42 | else => return error.UnexpectedContent, | |
| 43 | } | |
| 44 | ||
| 45 | switch (url_content) { | |
| 46 | .url => |u| try testing.expectEqualStrings("https://example.com", u), | |
| 47 | else => return error.UnexpectedContent, | |
| 48 | } | |
| 49 | ||
| 50 | switch (asset_content) { | |
| 51 | .asset => |a| try testing.expectEqualStrings("index.html", a), | |
| 52 | else => return error.UnexpectedContent, | |
| 53 | } | |
| 54 | } | |
| 55 | ||
| 56 | test "CraftActivity - ActivityConfig defaults" { | |
| 57 | const config = android.CraftActivity.ActivityConfig{}; | |
| 58 | ||
| 59 | try testing.expectEqualStrings("Craft App", config.name); | |
| 60 | try testing.expectEqualStrings("com.craft.app", config.package_name); | |
| 61 | try testing.expectEqual(android.CraftActivity.Theme.light, config.theme); | |
| 62 | try testing.expectEqual(android.CraftActivity.Orientation.portrait, config.orientation); | |
| 63 | try testing.expect(!config.fullscreen); | |
| 64 | try testing.expect(config.hardware_accelerated); | |
| 65 | try testing.expect(config.enable_javascript); | |
| 66 | try testing.expect(config.enable_dom_storage); | |
| 67 | try testing.expect(!config.allow_file_access); | |
| 68 | try testing.expect(!config.enable_inspector); | |
| 69 | } | |
| 70 | ||
| 71 | test "CraftActivity - ActivityConfig custom" { | |
| 72 | const config = android.CraftActivity.ActivityConfig{ | |
| 73 | .name = "My App", | |
| 74 | .package_name = "com.example.myapp", | |
| 75 | .theme = .dark, | |
| 76 | .orientation = .landscape, | |
| 77 | .fullscreen = true, | |
| 78 | .enable_inspector = true, | |
| 79 | .allow_file_access = true, | |
| 80 | }; | |
| 81 | ||
| 82 | try testing.expectEqualStrings("My App", config.name); | |
| 83 | try testing.expectEqualStrings("com.example.myapp", config.package_name); | |
| 84 | try testing.expectEqual(android.CraftActivity.Theme.dark, config.theme); | |
| 85 | try testing.expectEqual(android.CraftActivity.Orientation.landscape, config.orientation); | |
| 86 | try testing.expect(config.fullscreen); | |
| 87 | try testing.expect(config.enable_inspector); | |
| 88 | try testing.expect(config.allow_file_access); | |
| 89 | } | |
| 90 | ||
| 91 | test "CraftActivity - init" { | |
| 92 | const config = android.CraftActivity.ActivityConfig{ | |
| 93 | .name = "Test App", | |
| 94 | .package_name = "com.test.app", | |
| 95 | .initial_content = .{ .html = "<h1>Test</h1>" }, | |
| 96 | }; | |
| 97 | ||
| 98 | const activity = android.CraftActivity.init(testing.allocator, config); | |
| 99 | ||
| 100 | try testing.expectEqualStrings("Test App", activity.config.name); | |
| 101 | try testing.expectEqualStrings("com.test.app", activity.config.package_name); | |
| 102 | try testing.expect(activity.js_bridge == null); | |
| 103 | try testing.expect(activity.webview == null); | |
| 104 | try testing.expect(activity.on_create == null); | |
| 105 | try testing.expect(activity.on_resume == null); | |
| 106 | try testing.expect(activity.on_pause == null); | |
| 107 | try testing.expect(activity.on_destroy == null); | |
| 108 | try testing.expect(activity.on_back_pressed == null); | |
| 109 | } | |
| 110 | ||
| 111 | test "CraftActivity - lifecycle callbacks" { | |
| 112 | var activity = android.CraftActivity.init(testing.allocator, .{}); | |
| 113 | ||
| 114 | var create_called = false; | |
| 115 | var resume_called = false; | |
| 116 | var pause_called = false; | |
| 117 | var destroy_called = false; | |
| 118 | ||
| 119 | const Callbacks = struct { | |
| 120 | var create_flag: *bool = undefined; | |
| 121 | var resume_flag: *bool = undefined; | |
| 122 | var pause_flag: *bool = undefined; | |
| 123 | var destroy_flag: *bool = undefined; | |
| 124 | ||
| 125 | fn onCreate() void { | |
| 126 | create_flag.* = true; | |
| 127 | } | |
| 128 | fn onResume() void { | |
| 129 | resume_flag.* = true; | |
| 130 | } | |
| 131 | fn onPause() void { | |
| 132 | pause_flag.* = true; | |
| 133 | } | |
| 134 | fn onDestroy() void { | |
| 135 | destroy_flag.* = true; | |
| 136 | } | |
| 137 | }; | |
| 138 | ||
| 139 | Callbacks.create_flag = &create_called; | |
| 140 | Callbacks.resume_flag = &resume_called; | |
| 141 | Callbacks.pause_flag = &pause_called; | |
| 142 | Callbacks.destroy_flag = &destroy_called; | |
| 143 | ||
| 144 | activity.onCreate(Callbacks.onCreate); | |
| 145 | activity.onResume(Callbacks.onResume); | |
| 146 | activity.onPause(Callbacks.onPause); | |
| 147 | activity.onDestroy(Callbacks.onDestroy); | |
| 148 | ||
| 149 | try testing.expect(activity.on_create != null); | |
| 150 | try testing.expect(activity.on_resume != null); | |
| 151 | try testing.expect(activity.on_pause != null); | |
| 152 | try testing.expect(activity.on_destroy != null); | |
| 153 | ||
| 154 | // Invoke callbacks | |
| 155 | if (activity.on_create) |cb| cb(); | |
| 156 | if (activity.on_resume) |cb| cb(); | |
| 157 | if (activity.on_pause) |cb| cb(); | |
| 158 | if (activity.on_destroy) |cb| cb(); | |
| 159 | ||
| 160 | try testing.expect(create_called); | |
| 161 | try testing.expect(resume_called); | |
| 162 | try testing.expect(pause_called); | |
| 163 | try testing.expect(destroy_called); | |
| 164 | } | |
| 165 | ||
| 166 | test "CraftActivity - onBackPressed callback" { | |
| 167 | var activity = android.CraftActivity.init(testing.allocator, .{}); | |
| 168 | ||
| 169 | const Callback = struct { | |
| 170 | fn onBackPressed() bool { | |
| 171 | return true; // Consume event | |
| 172 | } | |
| 173 | }; | |
| 174 | ||
| 175 | activity.onBackPressed(Callback.onBackPressed); | |
| 176 | try testing.expect(activity.on_back_pressed != null); | |
| 177 | ||
| 178 | if (activity.on_back_pressed) |cb| { | |
| 179 | const consumed = cb(); | |
| 180 | try testing.expect(consumed); | |
| 181 | } | |
| 182 | } | |
| 183 | ||
| 184 | // ============================================================================ | |
| 185 | // JSBridge Tests | |
| 186 | // ============================================================================ | |
| 187 | ||
| 188 | test "JSBridge - init and deinit" { | |
| 189 | var bridge = android.JSBridge.init(testing.allocator); | |
| 190 | defer bridge.deinit(); | |
| 191 | ||
| 192 | try testing.expect(bridge.activity == null); | |
| 193 | // Built-in handlers should be registered | |
| 194 | try testing.expect(bridge.handlers.get("getPlatform") != null); | |
| 195 | try testing.expect(bridge.handlers.get("showToast") != null); | |
| 196 | try testing.expect(bridge.handlers.get("vibrate") != null); | |
| 197 | try testing.expect(bridge.handlers.get("setClipboard") != null); | |
| 198 | try testing.expect(bridge.handlers.get("getClipboard") != null); | |
| 199 | try testing.expect(bridge.handlers.get("share") != null); | |
| 200 | try testing.expect(bridge.handlers.get("openURL") != null); | |
| 201 | try testing.expect(bridge.handlers.get("getNetworkStatus") != null); | |
| 202 | try testing.expect(bridge.handlers.get("showAlert") != null); | |
| 203 | } | |
| 204 | ||
| 205 | test "JSBridge - registerHandler" { | |
| 206 | var bridge = android.JSBridge.init(testing.allocator); | |
| 207 | defer bridge.deinit(); | |
| 208 | ||
| 209 | const handler = struct { | |
| 210 | fn handle(_: []const u8, _: *android.JSBridge, _: []const u8) void {} | |
| 211 | }.handle; | |
| 212 | ||
| 213 | try bridge.registerHandler("customHandler", handler); | |
| 214 | try testing.expect(bridge.handlers.get("customHandler") != null); | |
| 215 | } | |
| 216 | ||
| 217 | test "JSBridge - registerHandler overwrites" { | |
| 218 | var bridge = android.JSBridge.init(testing.allocator); | |
| 219 | defer bridge.deinit(); | |
| 220 | ||
| 221 | const handler1 = struct { | |
| 222 | fn handle(_: []const u8, _: *android.JSBridge, _: []const u8) void {} | |
| 223 | }.handle; | |
| 224 | ||
| 225 | const handler2 = struct { | |
| 226 | fn handle(_: []const u8, _: *android.JSBridge, _: []const u8) void {} | |
| 227 | }.handle; | |
| 228 | ||
| 229 | try bridge.registerHandler("test", handler1); | |
| 230 | try bridge.registerHandler("test", handler2); | |
| 231 | ||
| 232 | // Should not error, just overwrite | |
| 233 | try testing.expect(bridge.handlers.get("test") != null); | |
| 234 | } | |
| 235 | ||
| 236 | test "JSBridge - handleMessage with unknown method" { | |
| 237 | var bridge = android.JSBridge.init(testing.allocator); | |
| 238 | defer bridge.deinit(); | |
| 239 | ||
| 240 | // This should not crash, just silently fail (no activity to send error) | |
| 241 | bridge.handleMessage("{\"method\":\"unknownMethod\",\"callbackId\":\"123\",\"params\":{}}"); | |
| 242 | } | |
| 243 | ||
| 244 | test "JSBridge - handleMessage with getPlatform" { | |
| 245 | var bridge = android.JSBridge.init(testing.allocator); | |
| 246 | defer bridge.deinit(); | |
| 247 | ||
| 248 | // This should not crash (no activity to send response, but handler runs) | |
| 249 | bridge.handleMessage("{\"method\":\"getPlatform\",\"callbackId\":\"456\",\"params\":{}}"); | |
| 250 | } | |
| 251 | ||
| 252 | // ============================================================================ | |
| 253 | // AndroidFeatures Tests | |
| 254 | // ============================================================================ | |
| 255 | ||
| 256 | test "AndroidFeatures - DeviceInfo struct" { | |
| 257 | const info = android.AndroidFeatures.DeviceInfo{ | |
| 258 | .manufacturer = "Samsung", | |
| 259 | .model = "Galaxy S21", | |
| 260 | .os_version = "13", | |
| 261 | .sdk_version = 33, | |
| 262 | }; | |
| 263 | ||
| 264 | try testing.expectEqualStrings("Samsung", info.manufacturer); | |
| 265 | try testing.expectEqualStrings("Galaxy S21", info.model); | |
| 266 | try testing.expectEqualStrings("13", info.os_version); | |
| 267 | try testing.expectEqual(@as(i32, 33), info.sdk_version); | |
| 268 | } | |
| 269 | ||
| 270 | test "AndroidFeatures - getDeviceInfo" { | |
| 271 | const info = android.AndroidFeatures.getDeviceInfo(); | |
| 272 | ||
| 273 | // Returns default values in non-Android environment | |
| 274 | try testing.expectEqualStrings("Unknown", info.manufacturer); | |
| 275 | try testing.expectEqualStrings("Android Device", info.model); | |
| 276 | try testing.expectEqualStrings("14", info.os_version); | |
| 277 | try testing.expectEqual(@as(i32, 34), info.sdk_version); | |
| 278 | } | |
| 279 | ||
| 280 | test "AndroidFeatures - isNetworkConnected" { | |
| 281 | // Returns true by default in non-Android environment | |
| 282 | const connected = android.AndroidFeatures.isNetworkConnected(); | |
| 283 | try testing.expect(connected); | |
| 284 | } | |
| 285 | ||
| 286 | test "AndroidFeatures - hasPermission" { | |
| 287 | // Returns false by default in non-Android environment | |
| 288 | const has_camera = android.AndroidFeatures.hasPermission("android.permission.CAMERA"); | |
| 289 | try testing.expect(!has_camera); | |
| 290 | } | |
| 291 | ||
| 292 | test "AndroidFeatures - getClipboard" { | |
| 293 | // Returns empty string in non-Android environment | |
| 294 | const text = try android.AndroidFeatures.getClipboard(testing.allocator); | |
| 295 | try testing.expectEqualStrings("", text); | |
| 296 | } | |
| 297 | ||
| 298 | // ============================================================================ | |
| 299 | // Quick Start Helper Tests | |
| 300 | // ============================================================================ | |
| 301 | ||
| 302 | test "quickStart function exists" { | |
| 303 | // Just verify the function signature compiles | |
| 304 | const func = android.quickStart; | |
| 305 | try testing.expect(@TypeOf(func) == fn (std.mem.Allocator, []const u8) anyerror!void); | |
| 306 | } | |
| 307 | ||
| 308 | // ============================================================================ | |
| 309 | // Integration Tests | |
| 310 | // ============================================================================ | |
| 311 | ||
| 312 | test "CraftActivity - full lifecycle simulation" { | |
| 313 | var activity = android.CraftActivity.init(testing.allocator, .{ | |
| 314 | .name = "Integration Test App", | |
| 315 | .package_name = "com.test.integration", | |
| 316 | .initial_content = .{ .html = "<h1>Test</h1>" }, | |
| 317 | .theme = .system, | |
| 318 | .orientation = .sensor, | |
| 319 | }); | |
| 320 | defer activity.deinit(); | |
| 321 | ||
| 322 | // Set up all lifecycle callbacks | |
| 323 | var lifecycle_order = std.ArrayList([]const u8).init(testing.allocator); | |
| 324 | defer lifecycle_order.deinit(); | |
| 325 | ||
| 326 | // Note: We can't easily test the actual callback invocation order | |
| 327 | // without modifying the activity internals, so we just verify setup | |
| 328 | try testing.expectEqualStrings("Integration Test App", activity.config.name); | |
| 329 | try testing.expectEqual(android.CraftActivity.Theme.system, activity.config.theme); | |
| 330 | try testing.expectEqual(android.CraftActivity.Orientation.sensor, activity.config.orientation); | |
| 331 | } | |
| 332 | ||
| 333 | test "JSBridge - message parsing" { | |
| 334 | var bridge = android.JSBridge.init(testing.allocator); | |
| 335 | defer bridge.deinit(); | |
| 336 | ||
| 337 | // Test with various JSON formats | |
| 338 | const messages = [_][]const u8{ | |
| 339 | "{\"method\":\"getPlatform\",\"callbackId\":\"1\",\"params\":{}}", | |
| 340 | "{\"method\":\"showToast\",\"callbackId\":\"2\",\"params\":{\"message\":\"Hello\"}}", | |
| 341 | "{\"method\":\"vibrate\",\"callbackId\":\"3\",\"params\":{\"duration\":100}}", | |
| 342 | }; | |
| 343 | ||
| 344 | for (messages) |msg| { | |
| 345 | // Should not crash | |
| 346 | bridge.handleMessage(msg); | |
| 347 | } | |
| 348 | } | |
| 349 | ||
| 350 | test "Activity with JSBridge integration" { | |
| 351 | var activity = android.CraftActivity.init(testing.allocator, .{ | |
| 352 | .name = "Bridge Test", | |
| 353 | }); | |
| 354 | defer activity.deinit(); | |
| 355 | ||
| 356 | // Run initializes the bridge | |
| 357 | try activity.run(); | |
| 358 | ||
| 359 | // Bridge should now be available | |
| 360 | try testing.expect(activity.js_bridge != null); | |
| 361 | ||
| 362 | if (activity.getBridge()) |bridge| { | |
| 363 | // Register custom handler | |
| 364 | const handler = struct { | |
| 365 | fn handle(_: []const u8, b: *android.JSBridge, callback_id: []const u8) void { | |
| 366 | b.sendResponse(callback_id, "{}") catch {}; | |
| 367 | } | |
| 368 | }.handle; | |
| 369 | ||
| 370 | try bridge.registerHandler("customTest", handler); | |
| 371 | try testing.expect(bridge.handlers.get("customTest") != null); | |
| 372 | } | |
| 373 | } | |