@poolse/native 3.6.2 → 3.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,31 @@
2
2
 
3
3
  Formerly `@poolse/react-native-calls` (0.x).
4
4
 
5
+ ## 3.7.1 — 2026-11-21
6
+
7
+ - No changes; released with the other `@poolse/*` packages at 3.7.1.
8
+
9
+ ## 3.7.0 — 2026-11-21
10
+
11
+ - Custom incoming ringtone. Plugin option `ringtone` (a file path, or
12
+ `{ ios, android }`) ships the sound in both apps; `configure({ ringtone })`
13
+ overrides it at runtime and is persisted for closed-app rings. iOS: CallKit's
14
+ `ringtoneSound` (caf/aiff/wav, 30 s or shorter, read from Info.plist
15
+ `PoolseRingtone` at a PushKit cold wake). Android: the module plays
16
+ `res/raw/<name>` looping on the ringtone stream; the incoming-call channel
17
+ stays silent, so the sound can change without a new channel. Default is
18
+ still the system ringtone.
19
+ - Android: the full-screen incoming call takes the app's look. Plugin option
20
+ `incomingCall` / `configure({ incomingCall })` with `accentColor`,
21
+ `backgroundColor` (a light one switches the text to dark) and `avatarUrl`, a
22
+ template with `{externalId}` / `{userId}` (a push's `caller_avatar_url` wins).
23
+ The picture loads off the main thread over the initials, which are now up to
24
+ two letters. The ring notification is tinted with an app-set accent.
25
+ - Android: `incomingCall.activity` launches the app's own Activity instead of
26
+ the built-in screen, with `PoolseIncomingCall.EXTRA_*` extras; it answers
27
+ and declines through `dev.poolse.callcore.android.PoolseIncomingCall`
28
+ (`isLive`, `answer`, `decline`, `ACTION_RING_CLOSED`).
29
+
5
30
  ## 3.6.2 — 2026-11-21
6
31
 
7
32
  - Android: `takeNotificationActions` compiles (3.6.1's
package/README.md CHANGED
@@ -37,13 +37,15 @@ In `app.json`, after `expo-notifications`:
37
37
  ]
38
38
  ```
39
39
 
40
- | Option | Default | What it does |
41
- | ---------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
42
- | `ringback` | none | Ships this sound in both apps; pass its base name to `configure({ ringback })`. Lowercase letters, digits and underscores only. |
43
- | `pictureInPicture` | `true` | Android: the activity may float as a picture-in-picture window. |
44
- | `lockscreen` | `true` | Android: the app shows over the lock screen when opened for a call. |
45
- | `messageReplyRequiresUnlock` | `false` | Both: a chat notification's Reply asks for the passcode / Face ID / fingerprint before it sends. Off, Reply works straight from the lock screen (as in WhatsApp). Mark as read never asks. |
46
- | `screenShare` | `false` | iOS: adds the broadcast upload extension that sharing the screen needs, and the app group `group.<bundle id>` it shares with the app (`{ "appGroup": "…" }` for your own). Register that group in the Apple Developer portal and assign it to the app's and `<bundle id>.broadcast`'s App IDs. |
40
+ | Option | Default | What it does |
41
+ | ---------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
42
+ | `ringback` | none | Ships this sound in both apps; pass its base name to `configure({ ringback })`. Lowercase letters, digits and underscores only. |
43
+ | `ringtone` | system | The incoming-call ring: a file path, or `{ "ios": "…", "android": "…" }`. iOS: caf, aiff or wav, 30 s or shorter (CallKit rings with the system tone otherwise). Android: ogg, mp3 or wav. Lowercase letters, digits and underscores in the name, not the same name as `ringback`. See [Ringtone](#ringtone). |
44
+ | `incomingCall` | none | Android: the full-screen incoming call's `accentColor`, `backgroundColor` and `avatarUrl` template, or `activity` — your own Activity to launch instead. See [Incoming call screen (Android)](#incoming-call-screen-android). |
45
+ | `pictureInPicture` | `true` | Android: the activity may float as a picture-in-picture window. |
46
+ | `lockscreen` | `true` | Android: the app shows over the lock screen when opened for a call. |
47
+ | `messageReplyRequiresUnlock` | `false` | Both: a chat notification's Reply asks for the passcode / Face ID / fingerprint before it sends. Off, Reply works straight from the lock screen (as in WhatsApp). Mark as read never asks. |
48
+ | `screenShare` | `false` | iOS: adds the broadcast upload extension that sharing the screen needs, and the app group `group.<bundle id>` it shares with the app (`{ "appGroup": "…" }` for your own). Register that group in the Apple Developer portal and assign it to the app's and `<bundle id>.broadcast`'s App IDs. |
47
49
 
48
50
  Always applied on Android: the LiveKit media adapter, and `expo-notifications`
49
51
  as the receiver for pushes that aren't calls. On iOS, add `UIBackgroundModes`
@@ -113,6 +115,116 @@ The full API:
113
115
  userChannel.onCallFinished((e) => calls.onCallFinished(e.call_id, e.reason));
114
116
  ```
115
117
 
118
+ ## Ringtone
119
+
120
+ ```json
121
+ ["@poolse/native", { "ringtone": "./assets/sounds/ring.wav" }]
122
+ ["@poolse/native", { "ringtone": { "ios": "./assets/sounds/ring.caf", "android": "./assets/sounds/ring.ogg" } }]
123
+ ```
124
+
125
+ `expo prebuild` copies the file into the iOS app bundle and Android's
126
+ `res/raw`, and records its name (Info.plist `PoolseRingtone`, application
127
+ meta-data `dev.poolse.calls.ringtone`) so a ring that wakes a closed app uses
128
+ it before any JS runs. Convert an mp3 for iOS with
129
+ `afconvert -f caff -d LEI16 ring.mp3 ring.caf`.
130
+
131
+ To switch at runtime (a ringtone picker), ship each sound with the app (for
132
+ example as extra `res/raw` files and bundle resources) and pass its name:
133
+
134
+ ```ts
135
+ await calls.configure(apiOrigin, { ringtone: 'ring_classic' }); // Android: res/raw name; iOS: 'ring_classic.caf' or the base name
136
+ ```
137
+
138
+ Leaving `ringtone` out of `configure` falls back to the plugin's sound, and
139
+ without that to the system ringtone. A name the app doesn't contain also rings
140
+ with the system ringtone.
141
+
142
+ Android plays the sound itself, looping on the ringtone stream (so it follows
143
+ the ringer volume), and stops it the moment the ring resolves. The
144
+ `poolse_incoming_calls` notification channel has no sound of its own on
145
+ purpose: Android fixes a channel's sound once the channel exists, and a
146
+ channel sound would ring twice and could not be stopped. Changing the
147
+ ringtone therefore never needs a new channel id, and an existing install picks
148
+ up a new sound on its next ring. Silent and vibrate modes silence it like the
149
+ system ringtone.
150
+
151
+ ## Incoming call screen (Android)
152
+
153
+ When a call rings on a locked or idle Android phone, the module shows its own
154
+ full-screen call screen. Give it your app's look:
155
+
156
+ ```json
157
+ [
158
+ "@poolse/native",
159
+ {
160
+ "incomingCall": {
161
+ "accentColor": "#FF5A1F",
162
+ "backgroundColor": "#101014",
163
+ "avatarUrl": "https://cdn.example.com/avatars/{externalId}.jpg"
164
+ }
165
+ }
166
+ ]
167
+ ```
168
+
169
+ | Field | Default | What it does |
170
+ | ----------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
171
+ | `accentColor` | `#5B54E8` | `#RRGGBB` or `#AARRGGBB`: the glow, the pulsing ring and the initials disc. Also tints the ring notification. |
172
+ | `backgroundColor` | `#0B0B14` | The screen's ground. A light colour switches the text to dark. |
173
+ | `avatarUrl` | none | The caller's picture: `{externalId}` (your id for the caller) and `{userId}` (the poolse user id) are filled in, URL-encoded. A ring push's own `caller_avatar_url` takes precedence. |
174
+ | `activity` | none | Your own Activity to launch instead (below). |
175
+
176
+ The picture is downloaded off the main thread (6 s timeout, 4 MB cap) and
177
+ covers the caller's initials once it has loaded; if there is no URL, or the
178
+ download fails, the initials stay. The URL must be reachable without
179
+ authentication. `configure({ incomingCall: { … } })` overrides any field at
180
+ runtime (for example a theme the user picked) and is persisted, so a ring that
181
+ wakes a closed app uses it too; a field left out keeps the plugin's value. iOS
182
+ ignores all of this: CallKit draws the call screen.
183
+
184
+ ### Your own incoming-call Activity
185
+
186
+ Set `activity` to a fully qualified class name (or `.RingActivity`, relative
187
+ to the application id). Declare the Activity in your manifest (for example
188
+ with your own config plugin) with `android:showWhenLocked="true"`,
189
+ `android:turnScreenOn="true"`, `android:exported="false"` and
190
+ `android:launchMode="singleInstance"`. If the class isn't in the manifest the
191
+ built-in screen is used and a warning is logged.
192
+
193
+ The ring notification's full-screen intent and heads-up tap start it with
194
+ `FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TOP` and these extras (constants
195
+ on `dev.poolse.callcore.android.PoolseIncomingCall`):
196
+
197
+ | Extra | Key | Type |
198
+ | ------------------------- | -------------------------- | ---------------------- |
199
+ | `EXTRA_CALL_ID` | `poolse_call_id` | String |
200
+ | `EXTRA_CONVERSATION_ID` | `poolse_conversation_id` | String |
201
+ | `EXTRA_CONVERSATION_NAME` | `poolse_conversation_name` | String, may be null |
202
+ | `EXTRA_CALLER_NAME` | `poolse_caller_name` | String, may be null |
203
+ | `EXTRA_CALLER_AVATAR_URL` | `poolse_caller_avatar_url` | String, may be null |
204
+ | `EXTRA_MEDIA` | `poolse_media` | `"audio"` or `"video"` |
205
+ | `EXTRA_RING_DEADLINE` | `poolse_ring_deadline` | Long, epoch ms |
206
+
207
+ plus an opaque `poolse_ring` bundle that the functions below read; pass them
208
+ the Intent you were started with (and the new one in `onNewIntent`):
209
+
210
+ - `PoolseIncomingCall.isLive(context, intent): Boolean`: whether the ring can
211
+ still be answered. Finish at once when it can't (a stale tap).
212
+ - `PoolseIncomingCall.answer(activity, intent): Boolean`: answers and brings
213
+ the app forward from your Activity (only a foreground Activity may). On
214
+ `true`, finish in `onStop`, once the app covers you; finishing immediately
215
+ dropped the launch on some devices. On `false`, finish.
216
+ - `PoolseIncomingCall.decline(context, intent)`: declines; then finish.
217
+ - `PoolseIncomingCall.ACTION_RING_CLOSED`: a package-local broadcast with
218
+ `EXTRA_CALL_ID` when the ring ends anywhere else (caller hung up, answered
219
+ on another device, timed out). Register for it with
220
+ `ContextCompat.RECEIVER_NOT_EXPORTED` and finish, except after you
221
+ answered: it is sent then too.
222
+
223
+ The ring tone, the notification and its Answer / Decline buttons stay the
224
+ module's. Answer on the notification still goes through the built-in
225
+ trampoline, which answers and opens the app without showing your Activity.
226
+ See the KDoc on `PoolseIncomingCall` for a complete example.
227
+
116
228
  ## Reply and Mark as read from a notification
117
229
 
118
230
  poolse's chat pushes carry a reply grant (24 h, bound to the device and
@@ -110,6 +110,8 @@ data class RingContext(
110
110
  val media: String,
111
111
  val grant: String,
112
112
  val ringDeadlineEpochMs: Long,
113
+ /** The caller's picture for the ring screen, if the push or the app's template gives one. */
114
+ val callerAvatarUrl: String? = null,
113
115
  )
114
116
 
115
117
  /** Android: the phoneCall foreground service. iOS: the CallKit session. */
@@ -3,6 +3,7 @@ package dev.poolse.callcore.android
3
3
  import android.app.NotificationChannel
4
4
  import android.app.NotificationManager
5
5
  import android.app.PendingIntent
6
+ import android.content.ContentResolver
6
7
  import android.content.Context
7
8
  import android.content.Intent
8
9
  import android.media.AudioAttributes
@@ -13,6 +14,7 @@ import android.os.Handler
13
14
  import android.os.Looper
14
15
  import android.media.Ringtone
15
16
  import android.media.RingtoneManager
17
+ import android.net.Uri
16
18
  import android.os.Build
17
19
  import android.util.Log
18
20
  import androidx.core.app.NotificationCompat
@@ -104,7 +106,20 @@ internal class AndroidRingSurface(
104
106
  )
105
107
  }
106
108
 
107
- val fullScreen = incomingActivity(autoAnswer = false, requestOffset = 0)
109
+ // The app's own ring activity, when it names one (incomingCall.activity),
110
+ // gets the full-screen intent and the heads-up tap; it answers and
111
+ // declines through [PoolseIncomingCall]. The notification's Answer
112
+ // button keeps the built-in trampoline either way.
113
+ val look = config.incomingCall
114
+ val fullScreen = look.customActivityIntent(context)?.let { custom ->
115
+ PendingIntent.getActivity(
116
+ context,
117
+ ring.callId.hashCode() + 6,
118
+ PoolseIncomingCall.fill(custom, ring)
119
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP),
120
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
121
+ )
122
+ } ?: incomingActivity(autoAnswer = false, requestOffset = 0)
108
123
 
109
124
  // Answer launches an ACTIVITY, not a broadcast: a background receiver
110
125
  // cannot start an activity (Android 10+), so answering from the
@@ -127,6 +142,7 @@ internal class AndroidRingSurface(
127
142
  .setOngoing(true)
128
143
  .setAutoCancel(false)
129
144
  .setFullScreenIntent(fullScreen, true)
145
+ .apply { if (look.accentFromApp) setColor(look.accentColor) }
130
146
  // Tapping the heads-up (not a button) opens the ring screen too;
131
147
  // without this the tap did nothing.
132
148
  .setContentIntent(fullScreen)
@@ -279,7 +295,16 @@ internal class AndroidRingSurface(
279
295
  override fun ringtoneStart() {
280
296
  ringtoneStop()
281
297
  runCatching {
282
- val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE) ?: return
298
+ // The app's own sound (configure / plugin `ringtone`), else the
299
+ // user's system ringtone. Played here, not by the notification
300
+ // channel, so it loops until the ring resolves and can change at
301
+ // any time — channel sounds are fixed once the channel exists.
302
+ val custom = config.ringtoneRawRes
303
+ val uri = if (custom != 0) {
304
+ Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://${context.packageName}/$custom")
305
+ } else {
306
+ RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE) ?: return
307
+ }
283
308
  ringtone = RingtoneManager.getRingtone(context, uri)?.apply {
284
309
  audioAttributes = AudioAttributes.Builder()
285
310
  .setUsage(AudioAttributes.USAGE_NOTIFICATION_RINGTONE)
@@ -380,4 +405,7 @@ data class RingSurfaceConfig(
380
405
  val smallIcon: Int,
381
406
  /** `R.raw.incallmanager_ringback`, or 0 to fall back to silence. */
382
407
  val ringbackRawRes: Int,
408
+ /** The app's incoming ringtone in `res/raw`, or 0 for the system ringtone. */
409
+ val ringtoneRawRes: Int = 0,
410
+ val incomingCall: IncomingCallLook = IncomingCallLook(),
383
411
  )
@@ -408,6 +408,9 @@ class CallCore private constructor(context: Context) {
408
408
  const val EXTRA_LAUNCH_CALL = "poolse_launch_call"
409
409
  private const val TAG = "PoolseCallCore"
410
410
  private const val PREFS = "dev.poolse.callcore"
411
+ /** Plugin `ringtone`: the raw resource name. */
412
+ internal const val META_RINGTONE = "dev.poolse.calls.ringtone"
413
+ private val INCOMING_KEYS = listOf("accentColor", "backgroundColor", "avatarUrl", "activity")
411
414
 
412
415
  @Volatile private var instance: CallCore? = null
413
416
  @Volatile private var config: CallCoreConfig? = null
@@ -432,14 +435,25 @@ class CallCore private constructor(context: Context) {
432
435
  * ring surface read it per use, so a new API origin takes effect on
433
436
  * the next request.
434
437
  */
435
- fun configure(context: Context, apiBaseUrl: String, smallIconName: String?, ringbackName: String?) {
438
+ fun configure(
439
+ context: Context,
440
+ apiBaseUrl: String,
441
+ smallIconName: String?,
442
+ ringbackName: String?,
443
+ /** Raw resource NAME of the incoming ringtone; null = the plugin's, else the system's. */
444
+ ringtoneName: String? = null,
445
+ /** `configure({ incomingCall })`: accentColor, backgroundColor, avatarUrl, activity. */
446
+ incomingCall: Map<String, String?> = emptyMap(),
447
+ ) {
436
448
  val ctx = context.applicationContext
437
- ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
449
+ val edit = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
438
450
  .putString("apiBaseUrl", apiBaseUrl)
439
451
  .putString("smallIcon", smallIconName)
440
452
  .putString("ringback", ringbackName)
441
- .apply()
442
- config = build(ctx, apiBaseUrl, smallIconName, ringbackName)
453
+ .putString("ringtone", ringtoneName)
454
+ for (key in INCOMING_KEYS) edit.putString("incoming.$key", incomingCall[key])
455
+ edit.apply()
456
+ config = build(ctx, apiBaseUrl, smallIconName, ringbackName, ringtoneName, incomingCall)
443
457
  }
444
458
 
445
459
  /** The core; throws if never configured (not even persisted). Prefer [getOrNull]. */
@@ -481,24 +495,59 @@ class CallCore private constructor(context: Context) {
481
495
  private fun restoreConfig(context: Context) {
482
496
  val p = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
483
497
  val url = p.getString("apiBaseUrl", null) ?: return
484
- config = build(context, url, p.getString("smallIcon", null), p.getString("ringback", null))
498
+ config = build(
499
+ context,
500
+ url,
501
+ p.getString("smallIcon", null),
502
+ p.getString("ringback", null),
503
+ p.getString("ringtone", null),
504
+ INCOMING_KEYS.associateWith { p.getString("incoming.$it", null) },
505
+ )
485
506
  }
486
507
 
508
+ /** The ring screen's look (restored from disk on a cold start); the built-in one if never configured. */
509
+ fun incomingCallLook(context: Context): IncomingCallLook {
510
+ if (config == null) restoreConfig(context.applicationContext)
511
+ return config?.incomingCall
512
+ ?: IncomingCallLook.resolve(context.applicationContext, null, null, null, null)
513
+ }
514
+
515
+ /** Application meta-data the config plugin writes (`dev.poolse.calls.*`), or null. */
516
+ internal fun manifestValue(context: Context, name: String): String? = runCatching {
517
+ context.packageManager
518
+ .getApplicationInfo(context.packageName, android.content.pm.PackageManager.GET_META_DATA)
519
+ .metaData?.get(name)?.toString()
520
+ }.getOrNull()?.ifEmpty { null }
521
+
487
522
  private fun build(
488
523
  context: Context,
489
524
  apiBaseUrl: String,
490
525
  smallIconName: String?,
491
526
  ringbackName: String?,
527
+ ringtoneName: String?,
528
+ incomingCall: Map<String, String?>,
492
529
  ): CallCoreConfig {
493
530
  val iconId = smallIconName
494
531
  ?.let { context.resources.getIdentifier(it, "drawable", context.packageName) } ?: 0
495
532
  val ringbackId = ringbackName
496
533
  ?.let { context.resources.getIdentifier(it, "raw", context.packageName) } ?: 0
534
+ // Runtime name first, then the plugin's; an unknown name (0) rings
535
+ // with the system ringtone rather than not at all.
536
+ val ringtoneId = (ringtoneName?.ifEmpty { null } ?: manifestValue(context, META_RINGTONE))
537
+ ?.let { context.resources.getIdentifier(it, "raw", context.packageName) } ?: 0
497
538
  return CallCoreConfig(
498
539
  apiBaseUrl = apiBaseUrl.trimEnd('/'),
499
540
  // Fall back to the app's launcher icon rather than crash on a typo.
500
541
  smallIcon = if (iconId != 0) iconId else context.applicationInfo.icon,
501
542
  ringbackRawRes = ringbackId,
543
+ ringtoneRawRes = ringtoneId,
544
+ incomingCall = IncomingCallLook.resolve(
545
+ context,
546
+ accentColor = incomingCall["accentColor"],
547
+ backgroundColor = incomingCall["backgroundColor"],
548
+ avatarUrl = incomingCall["avatarUrl"],
549
+ activity = incomingCall["activity"],
550
+ ),
502
551
  mediaFactory = resolveMediaFactory(),
503
552
  )
504
553
  }
@@ -542,6 +591,10 @@ data class CallCoreConfig(
542
591
  val apiBaseUrl: String,
543
592
  val smallIcon: Int,
544
593
  val ringbackRawRes: Int,
594
+ /** The incoming ringtone, `res/raw`; 0 = the system ringtone. */
595
+ val ringtoneRawRes: Int = 0,
596
+ /** The full-screen ring's colours, avatar source, or the app's own activity. */
597
+ val incomingCall: IncomingCallLook = IncomingCallLook(),
545
598
  /**
546
599
  * Builds the media engine for a call. Injected so the core carries no
547
600
  * SFU dependency; pass `::LiveKitMediaPortFactory` (the shipped
@@ -549,7 +602,7 @@ data class CallCoreConfig(
549
602
  */
550
603
  val mediaFactory: (Context, MediaEvents) -> MediaPort,
551
604
  ) {
552
- internal val ringSurface get() = RingSurfaceConfig(smallIcon, ringbackRawRes)
605
+ internal val ringSurface get() = RingSurfaceConfig(smallIcon, ringbackRawRes, ringtoneRawRes, incomingCall)
553
606
  }
554
607
 
555
608
  /** Media-level signals the SFU adapter reports back to the core. */
@@ -92,6 +92,13 @@ class CallMessagingService : FirebaseMessagingService() {
92
92
  media = this["media"] ?: "audio",
93
93
  grant = grant,
94
94
  ringDeadlineEpochMs = this["ring_deadline"]?.toLongOrNull() ?: 0L,
95
+ // The push's own picture if the server ever sends one, else the
96
+ // app's template filled with the caller's ids.
97
+ callerAvatarUrl = this["caller_avatar_url"]?.ifEmpty { null }
98
+ ?: CallCore.incomingCallLook(this@CallMessagingService).avatarUrlFor(
99
+ externalId = this["caller_external_id"],
100
+ userId = this["caller_user_id"],
101
+ ),
95
102
  )
96
103
  }
97
104
 
@@ -6,6 +6,8 @@ import android.content.BroadcastReceiver
6
6
  import android.content.Context
7
7
  import android.content.Intent
8
8
  import android.content.IntentFilter
9
+ import android.graphics.Bitmap
10
+ import android.graphics.BitmapFactory
9
11
  import android.graphics.Color
10
12
  import android.graphics.Typeface
11
13
  import android.graphics.drawable.GradientDrawable
@@ -15,13 +17,19 @@ import android.os.Handler
15
17
  import android.os.Looper
16
18
  import android.view.Gravity
17
19
  import android.view.View
20
+ import android.view.ViewOutlineProvider
18
21
  import android.view.WindowManager
19
22
  import android.view.animation.LinearInterpolator
20
23
  import android.widget.FrameLayout
24
+ import android.widget.ImageView
21
25
  import android.widget.LinearLayout
22
26
  import android.widget.TextView
23
27
  import androidx.core.content.ContextCompat
24
28
  import dev.poolse.callcore.RingContext
29
+ import java.io.ByteArrayOutputStream
30
+ import java.net.HttpURLConnection
31
+ import java.net.URL
32
+ import java.util.concurrent.Executors
25
33
  import dev.poolse.callcore.android.AndroidRingSurface.Companion.ACTION_RING_CLOSED
26
34
  import dev.poolse.callcore.android.AndroidRingSurface.Companion.EXTRA_CALL_ID
27
35
  import dev.poolse.callcore.android.AndroidRingSurface.Companion.EXTRA_RING
@@ -129,7 +137,7 @@ class IncomingCallActivity : Activity() {
129
137
  awaitingForward = true
130
138
  pulse?.cancel()
131
139
  pulse = null
132
- setContentView(View(this).apply { setBackgroundColor(Color.parseColor("#0B0B14")) })
140
+ setContentView(View(this).apply { setBackgroundColor(look.backgroundColor) })
133
141
  val launched = answer()
134
142
  if (!launched) { finish(); return }
135
143
  main.postDelayed({ if (!isFinishing) finish() }, FORWARD_FALLBACK_MS)
@@ -145,13 +153,92 @@ class IncomingCallActivity : Activity() {
145
153
  runCatching { unregisterReceiver(ringClosed) }
146
154
  pulse?.cancel()
147
155
  pulse = null
156
+ loader.shutdownNow()
148
157
  super.onDestroy()
149
158
  }
150
159
 
151
160
  private companion object {
152
161
  const val FORWARD_FALLBACK_MS = 4_000L
162
+ const val AVATAR_DP = 124
163
+ const val AVATAR_TIMEOUT_MS = 6_000
164
+ const val AVATAR_MAX_BYTES = 4 * 1024 * 1024
153
165
  }
154
166
 
167
+ /** The ring screen's colours and avatar source, restored from disk on a cold start. */
168
+ private val look: IncomingCallLook get() = CallCore.incomingCallLook(this)
169
+
170
+ /** Off the main thread: a slow image host must never hold up the ring. */
171
+ private val loader = Executors.newSingleThreadExecutor()
172
+
173
+ private fun loadAvatar(url: String, callId: String, into: ImageView) {
174
+ val size = px(AVATAR_DP)
175
+ runCatching {
176
+ loader.execute {
177
+ val bitmap = runCatching { fetchBitmap(url, size) }.getOrNull() ?: return@execute
178
+ main.post {
179
+ if (isFinishing || isDestroyed || ring?.callId != callId) return@post
180
+ into.setImageBitmap(bitmap)
181
+ into.visibility = View.VISIBLE
182
+ }
183
+ }
184
+ }
185
+ }
186
+
187
+ private fun fetchBitmap(url: String, size: Int): Bitmap? {
188
+ val conn = URL(url).openConnection() as? HttpURLConnection ?: return null
189
+ try {
190
+ conn.connectTimeout = AVATAR_TIMEOUT_MS
191
+ conn.readTimeout = AVATAR_TIMEOUT_MS
192
+ conn.instanceFollowRedirects = true
193
+ if (conn.responseCode !in 200..299) return null
194
+ val bytes = conn.inputStream.use { input ->
195
+ val out = ByteArrayOutputStream()
196
+ val buf = ByteArray(16 * 1024)
197
+ while (true) {
198
+ val n = input.read(buf)
199
+ if (n < 0) break
200
+ out.write(buf, 0, n)
201
+ if (out.size() > AVATAR_MAX_BYTES) return null
202
+ }
203
+ out.toByteArray()
204
+ }
205
+ // Decode at roughly the size it is drawn, not the upload's.
206
+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
207
+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
208
+ if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
209
+ var sample = 1
210
+ while (bounds.outWidth / (sample * 2) >= size && bounds.outHeight / (sample * 2) >= size) sample *= 2
211
+ return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })
212
+ } finally {
213
+ conn.disconnect()
214
+ }
215
+ }
216
+
217
+ /** "Ada Lovelace" → "AL", "ada" → "A". */
218
+ private fun initials(title: String): String {
219
+ val words = title.trim().split(Regex("\\s+")).filter { it.isNotEmpty() }
220
+ return words.take(2).mapNotNull { w -> w.firstOrNull { it.isLetterOrDigit() } }
221
+ .joinToString("").uppercase().ifEmpty { title.trim().take(1).uppercase() }
222
+ }
223
+
224
+ /** A light background (the app's) gets dark text; the default dark one keeps white. */
225
+ private fun isLight(color: Int): Boolean =
226
+ (0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color)) / 255 > 0.6
227
+
228
+ private fun onGround(ground: Int): Int = if (isLight(ground)) Color.parseColor("#14141C") else Color.WHITE
229
+
230
+ private fun onGroundMuted(ground: Int): Int =
231
+ if (isLight(ground)) Color.parseColor("#5A5A66") else Color.parseColor("#B8B8C6")
232
+
233
+ private fun withAlpha(color: Int, alpha: Int): Int =
234
+ Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color))
235
+
236
+ private fun lighten(color: Int, by: Float): Int = Color.rgb(
237
+ (Color.red(color) + (255 - Color.red(color)) * by).toInt(),
238
+ (Color.green(color) + (255 - Color.green(color)) * by).toInt(),
239
+ (Color.blue(color) + (255 - Color.blue(color)) * by).toInt(),
240
+ )
241
+
155
242
  private fun showOverKeyguard() {
156
243
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
157
244
  setShowWhenLocked(true)
@@ -167,13 +254,15 @@ class IncomingCallActivity : Activity() {
167
254
  }
168
255
 
169
256
  private fun buildScene(title: String, body: String, ring: RingContext): View {
170
- val root = FrameLayout(this).apply { setBackgroundColor(Color.parseColor("#0B0B14")) }
257
+ val accent = look.accentColor
258
+ val ground = look.backgroundColor
259
+ val root = FrameLayout(this).apply { setBackgroundColor(ground) }
171
260
 
172
261
  root.addView(
173
262
  View(this).apply {
174
263
  background = GradientDrawable(
175
264
  GradientDrawable.Orientation.TOP_BOTTOM,
176
- intArrayOf(Color.parseColor("#875B54E8"), Color.parseColor("#000B0B14")),
265
+ intArrayOf(withAlpha(accent, 0x87), withAlpha(ground, 0)),
177
266
  ).apply {
178
267
  gradientType = GradientDrawable.RADIAL_GRADIENT
179
268
  gradientRadius = 560 * density
@@ -196,40 +285,51 @@ class IncomingCallActivity : Activity() {
196
285
  background = GradientDrawable().apply {
197
286
  shape = GradientDrawable.OVAL
198
287
  setColor(Color.TRANSPARENT)
199
- setStroke(px(2), Color.parseColor("#805B54E8"))
288
+ setStroke(px(2), withAlpha(accent, 0x80))
200
289
  }
201
290
  }
202
291
  stage.addView(ringView, FrameLayout.LayoutParams(px(176), px(176), Gravity.CENTER))
203
292
  stage.addView(
204
293
  TextView(this).apply {
205
- text = title.trim().take(1).uppercase()
206
- textSize = 48f
294
+ text = initials(title)
295
+ textSize = 44f
207
296
  setTextColor(Color.WHITE)
208
297
  typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
209
298
  gravity = Gravity.CENTER
210
299
  background = GradientDrawable(
211
300
  GradientDrawable.Orientation.TL_BR,
212
- intArrayOf(Color.parseColor("#7D76FF"), Color.parseColor("#5B54E8")),
301
+ intArrayOf(lighten(accent, 0.22f), accent),
213
302
  ).apply { shape = GradientDrawable.OVAL }
214
303
  },
215
- FrameLayout.LayoutParams(px(124), px(124), Gravity.CENTER),
304
+ FrameLayout.LayoutParams(px(AVATAR_DP), px(AVATAR_DP), Gravity.CENTER),
216
305
  )
306
+ // The caller's picture covers the initials once it has loaded; until
307
+ // then (or if it never does) the initials are the avatar.
308
+ val photo = ImageView(this).apply {
309
+ scaleType = ImageView.ScaleType.CENTER_CROP
310
+ visibility = View.GONE
311
+ background = GradientDrawable().apply { shape = GradientDrawable.OVAL; setColor(accent) }
312
+ outlineProvider = ViewOutlineProvider.BACKGROUND
313
+ clipToOutline = true
314
+ }
315
+ stage.addView(photo, FrameLayout.LayoutParams(px(AVATAR_DP), px(AVATAR_DP), Gravity.CENTER))
316
+ ring.callerAvatarUrl?.let { loadAvatar(it, ring.callId, photo) }
217
317
 
218
318
  val name = TextView(this).apply {
219
319
  text = title
220
320
  textSize = 32f
221
- setTextColor(Color.WHITE)
321
+ setTextColor(onGround(ground))
222
322
  typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
223
323
  gravity = Gravity.CENTER
224
324
  }
225
325
  val sub = TextView(this).apply {
226
326
  text = body
227
327
  textSize = 15f
228
- setTextColor(Color.parseColor("#B8B8C6"))
328
+ setTextColor(onGroundMuted(ground))
229
329
  gravity = Gravity.CENTER
230
330
  background = GradientDrawable().apply {
231
331
  cornerRadius = 999f
232
- setColor(Color.parseColor("#14FFFFFF"))
332
+ setColor(withAlpha(onGround(ground), 0x14))
233
333
  }
234
334
  setPadding(px(16), px(8), px(16), px(8))
235
335
  layoutParams = LinearLayout.LayoutParams(wrap(), wrap()).apply { topMargin = px(12) }
@@ -303,7 +403,7 @@ class IncomingCallActivity : Activity() {
303
403
  TextView(this@IncomingCallActivity).apply {
304
404
  text = label
305
405
  textSize = 14f
306
- setTextColor(Color.parseColor("#B8B8C6"))
406
+ setTextColor(onGroundMuted(look.backgroundColor))
307
407
  gravity = Gravity.CENTER
308
408
  layoutParams = LinearLayout.LayoutParams(wrap(), wrap()).apply { topMargin = px(10) }
309
409
  },