@capgo/capacitor-widget-kit 8.1.0

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.
Files changed (54) hide show
  1. package/CapgoCapacitorWidgetKit.podspec +17 -0
  2. package/LICENSE +373 -0
  3. package/Package.swift +28 -0
  4. package/README.md +1119 -0
  5. package/android/build.gradle +59 -0
  6. package/android/src/main/AndroidManifest.xml +8 -0
  7. package/android/src/main/java/app/capgo/widgetkit/CapgoNativeWidgetBridge.java +311 -0
  8. package/android/src/main/java/app/capgo/widgetkit/CapgoTemplateActionReceiver.java +36 -0
  9. package/android/src/main/java/app/capgo/widgetkit/CapgoTemplateSvgBitmapRenderer.java +25 -0
  10. package/android/src/main/java/app/capgo/widgetkit/CapgoTemplateWidgetBridge.java +31 -0
  11. package/android/src/main/java/app/capgo/widgetkit/CapgoWidgetKit.java +218 -0
  12. package/android/src/main/java/app/capgo/widgetkit/CapgoWidgetKitConstants.java +18 -0
  13. package/android/src/main/java/app/capgo/widgetkit/CapgoWidgetKitPlugin.java +370 -0
  14. package/android/src/main/java/app/capgo/widgetkit/TemplateActivityStore.java +167 -0
  15. package/android/src/main/java/app/capgo/widgetkit/TemplateJsonUtils.java +369 -0
  16. package/android/src/main/java/app/capgo/widgetkit/TemplateRuntime.java +676 -0
  17. package/android/src/main/res/.gitkeep +0 -0
  18. package/dist/docs.json +2223 -0
  19. package/dist/esm/definitions.d.ts +1117 -0
  20. package/dist/esm/definitions.js +2 -0
  21. package/dist/esm/definitions.js.map +1 -0
  22. package/dist/esm/helpers/workout.d.ts +32 -0
  23. package/dist/esm/helpers/workout.js +129 -0
  24. package/dist/esm/helpers/workout.js.map +1 -0
  25. package/dist/esm/index.d.ts +6 -0
  26. package/dist/esm/index.js +9 -0
  27. package/dist/esm/index.js.map +1 -0
  28. package/dist/esm/runtime.d.ts +25 -0
  29. package/dist/esm/runtime.js +653 -0
  30. package/dist/esm/runtime.js.map +1 -0
  31. package/dist/esm/web.d.ts +23 -0
  32. package/dist/esm/web.js +292 -0
  33. package/dist/esm/web.js.map +1 -0
  34. package/dist/plugin.cjs.js +1096 -0
  35. package/dist/plugin.cjs.js.map +1 -0
  36. package/dist/plugin.js +1099 -0
  37. package/dist/plugin.js.map +1 -0
  38. package/ios/Sources/CapgoWidgetKitPlugin/CapgoNativeWidgetBridge.swift +372 -0
  39. package/ios/Sources/CapgoWidgetKitPlugin/CapgoTemplateWidgetBridge.swift +199 -0
  40. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWidgetKit.swift +218 -0
  41. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWidgetKitPlugin.swift +322 -0
  42. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWidgetKitSharedStore.swift +47 -0
  43. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWorkoutLiveActivityComponents.swift +246 -0
  44. package/ios/Sources/CapgoWidgetKitPlugin/CapgoWorkoutLiveActivityWidget.swift +257 -0
  45. package/ios/Sources/CapgoWidgetKitPlugin/CompleteSetIntent.swift +24 -0
  46. package/ios/Sources/CapgoWidgetKitPlugin/TemplateActionIntent.swift +56 -0
  47. package/ios/Sources/CapgoWidgetKitPlugin/TemplateActivityStore.swift +239 -0
  48. package/ios/Sources/CapgoWidgetKitPlugin/TemplateLiveActivityManager.swift +251 -0
  49. package/ios/Sources/CapgoWidgetKitPlugin/TemplateRuntime.swift +1067 -0
  50. package/ios/Sources/CapgoWidgetKitPlugin/WorkoutActivityStore.swift +111 -0
  51. package/ios/Sources/CapgoWidgetKitPlugin/WorkoutLiveActivityManager.swift +263 -0
  52. package/ios/Sources/CapgoWidgetKitPlugin/WorkoutSession.swift +271 -0
  53. package/ios/Tests/CapgoWidgetKitPluginTests/CapgoWidgetKitPluginTests.swift +130 -0
  54. package/package.json +93 -0
@@ -0,0 +1,59 @@
1
+ ext {
2
+ junitVersion = project.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2'
3
+ androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.7.1'
4
+ androidxJunitVersion = project.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.3.0'
5
+ androidxEspressoCoreVersion = project.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.7.0'
6
+ }
7
+
8
+ buildscript {
9
+ repositories {
10
+ google()
11
+ mavenCentral()
12
+ }
13
+ dependencies {
14
+ classpath 'com.android.tools.build:gradle:8.13.0'
15
+ }
16
+ }
17
+
18
+ apply plugin: 'com.android.library'
19
+
20
+ android {
21
+ namespace = "app.capgo.widgetkit"
22
+ compileSdk = project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 36
23
+ defaultConfig {
24
+ minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 24
25
+ targetSdkVersion project.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 36
26
+ versionCode 1
27
+ versionName "1.0"
28
+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
29
+ }
30
+ buildTypes {
31
+ release {
32
+ minifyEnabled false
33
+ proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
34
+ }
35
+ }
36
+ lintOptions {
37
+ abortOnError = false
38
+ }
39
+ compileOptions {
40
+ sourceCompatibility JavaVersion.VERSION_21
41
+ targetCompatibility JavaVersion.VERSION_21
42
+ }
43
+ }
44
+
45
+ repositories {
46
+ google()
47
+ mavenCentral()
48
+ }
49
+
50
+ dependencies {
51
+ implementation fileTree(dir: 'libs', include: ['*.jar'])
52
+ implementation project(':capacitor-android')
53
+ annotationProcessor project(':capacitor-android')
54
+ implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
55
+ implementation "com.caverock:androidsvg-aar:1.4"
56
+ testImplementation "junit:junit:$junitVersion"
57
+ androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
58
+ androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
59
+ }
@@ -0,0 +1,8 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
2
+
3
+ <application>
4
+ <receiver
5
+ android:name="app.capgo.widgetkit.CapgoTemplateActionReceiver"
6
+ android:exported="false" />
7
+ </application>
8
+ </manifest>
@@ -0,0 +1,311 @@
1
+ package app.capgo.widgetkit;
2
+
3
+ import android.content.Context;
4
+ import android.content.SharedPreferences;
5
+ import java.util.ArrayList;
6
+ import java.util.HashSet;
7
+ import java.util.List;
8
+ import java.util.Set;
9
+ import org.json.JSONArray;
10
+ import org.json.JSONException;
11
+ import org.json.JSONObject;
12
+
13
+ public class CapgoNativeWidgetBridge {
14
+
15
+ public static final String DIRECTION_APP_TO_WIDGET = "appToWidget";
16
+ public static final String DIRECTION_WIDGET_TO_APP = "widgetToApp";
17
+
18
+ private static final String SESSION_IDS_KEY = "nativeSessionIds";
19
+ private static final String MESSAGE_IDS_KEY = "nativeMessageIds";
20
+
21
+ private final SharedPreferences preferences;
22
+
23
+ public CapgoNativeWidgetBridge(final Context context) {
24
+ preferences = context.getApplicationContext().getSharedPreferences(CapgoWidgetKitConstants.PREFS_NAME, Context.MODE_PRIVATE);
25
+ }
26
+
27
+ public JSONObject startSession(final String requestedWidgetId, final String kind, final JSONObject state, final JSONObject metadata)
28
+ throws JSONException {
29
+ final long nowMs = System.currentTimeMillis();
30
+ final String widgetId =
31
+ requestedWidgetId != null && !requestedWidgetId.isEmpty() ? requestedWidgetId : TemplateRuntime.createIdentifier("widget");
32
+ final JSONObject session = new JSONObject()
33
+ .put("widgetId", widgetId)
34
+ .put("kind", kind == null ? JSONObject.NULL : kind)
35
+ .put("state", TemplateJsonUtils.deepCopyValue(state != null ? state : new JSONObject()))
36
+ .put("metadata", TemplateJsonUtils.deepCopyValue(metadata != null ? metadata : new JSONObject()))
37
+ .put("status", "active")
38
+ .put("createdAt", nowMs)
39
+ .put("updatedAt", nowMs)
40
+ .put("revision", 1);
41
+ saveSession(session);
42
+ return session;
43
+ }
44
+
45
+ public JSONObject updateSession(final String widgetId, final JSONObject state, final JSONObject metadata, final boolean merge)
46
+ throws JSONException {
47
+ final JSONObject session = loadSession(widgetId);
48
+ if (session == null) {
49
+ return null;
50
+ }
51
+
52
+ if (state != null) {
53
+ session.put("state", merge ? mergeObjects(session.optJSONObject("state"), state) : TemplateJsonUtils.deepCopyObject(state));
54
+ }
55
+ if (metadata != null) {
56
+ session.put(
57
+ "metadata",
58
+ merge ? mergeObjects(session.optJSONObject("metadata"), metadata) : TemplateJsonUtils.deepCopyObject(metadata)
59
+ );
60
+ }
61
+ session.put("status", "active");
62
+ session.put("updatedAt", System.currentTimeMillis());
63
+ session.put("revision", session.optInt("revision") + 1);
64
+ saveSession(session);
65
+ return session;
66
+ }
67
+
68
+ public void stopSession(final String widgetId, final JSONObject state) throws JSONException {
69
+ final JSONObject session = loadSession(widgetId);
70
+ if (session == null) {
71
+ return;
72
+ }
73
+ if (state != null) {
74
+ session.put("state", TemplateJsonUtils.deepCopyObject(state));
75
+ }
76
+ session.put("status", "stopped");
77
+ session.put("updatedAt", System.currentTimeMillis());
78
+ session.put("revision", session.optInt("revision") + 1);
79
+ saveSession(session);
80
+ }
81
+
82
+ public JSONObject loadSession(final String widgetId) throws JSONException {
83
+ final String raw = preferences.getString(sessionKey(widgetId), null);
84
+ return raw == null ? null : new JSONObject(raw);
85
+ }
86
+
87
+ public JSONArray listSessions() throws JSONException {
88
+ final List<JSONObject> sessions = new ArrayList<>();
89
+ for (String widgetId : listIds(SESSION_IDS_KEY)) {
90
+ final JSONObject session = loadSession(widgetId);
91
+ if (session != null) {
92
+ sessions.add(session);
93
+ }
94
+ }
95
+ sessions.sort((left, right) -> Long.compare(right.optLong("updatedAt"), left.optLong("updatedAt")));
96
+ final JSONArray result = new JSONArray();
97
+ for (JSONObject session : sessions) {
98
+ result.put(session);
99
+ }
100
+ return result;
101
+ }
102
+
103
+ public JSONObject sendMessage(
104
+ final String widgetId,
105
+ final String direction,
106
+ final String name,
107
+ final JSONObject payload,
108
+ final boolean expectsResponse
109
+ ) throws JSONException {
110
+ final long nowMs = System.currentTimeMillis();
111
+ final JSONObject message = new JSONObject()
112
+ .put("messageId", TemplateRuntime.createIdentifier("message"))
113
+ .put("widgetId", widgetId)
114
+ .put("direction", normalizeDirection(direction))
115
+ .put("name", name)
116
+ .put("payload", payload == null ? JSONObject.NULL : TemplateJsonUtils.deepCopyObject(payload))
117
+ .put("expectsResponse", expectsResponse)
118
+ .put("status", "pending")
119
+ .put("createdAt", nowMs)
120
+ .put("acknowledgedAt", JSONObject.NULL)
121
+ .put("completedAt", JSONObject.NULL)
122
+ .put("response", JSONObject.NULL)
123
+ .put("error", JSONObject.NULL);
124
+ saveMessage(message);
125
+ return message;
126
+ }
127
+
128
+ public JSONArray listMessages(
129
+ final String widgetId,
130
+ final String direction,
131
+ final boolean unacknowledgedOnly,
132
+ final boolean pendingOnly
133
+ ) throws JSONException {
134
+ final List<JSONObject> messages = new ArrayList<>();
135
+ final String normalizedDirection = direction == null ? null : normalizeDirection(direction);
136
+ for (String messageId : listIds(MESSAGE_IDS_KEY)) {
137
+ final JSONObject message = loadMessage(messageId);
138
+ if (message == null) {
139
+ continue;
140
+ }
141
+ if (widgetId != null && !widgetId.equals(message.optString("widgetId"))) {
142
+ continue;
143
+ }
144
+ if (normalizedDirection != null && !normalizedDirection.equals(message.optString("direction"))) {
145
+ continue;
146
+ }
147
+ if (unacknowledgedOnly && !message.isNull("acknowledgedAt")) {
148
+ continue;
149
+ }
150
+ if (pendingOnly && !"pending".equals(message.optString("status"))) {
151
+ continue;
152
+ }
153
+ messages.add(message);
154
+ }
155
+ messages.sort((left, right) -> Long.compare(right.optLong("createdAt"), left.optLong("createdAt")));
156
+ final JSONArray result = new JSONArray();
157
+ for (JSONObject message : messages) {
158
+ result.put(message);
159
+ }
160
+ return result;
161
+ }
162
+
163
+ public void acknowledgeMessages(final JSONArray messageIds, final String widgetId, final String direction) throws JSONException {
164
+ final Set<String> targetIds = toStringSet(messageIds);
165
+ final String normalizedDirection = direction == null ? null : normalizeDirection(direction);
166
+ final long nowMs = System.currentTimeMillis();
167
+ for (String currentMessageId : listIds(MESSAGE_IDS_KEY)) {
168
+ final JSONObject message = loadMessage(currentMessageId);
169
+ if (message == null) {
170
+ continue;
171
+ }
172
+ final boolean matchesMessageId = !targetIds.isEmpty() && targetIds.contains(message.optString("messageId"));
173
+ final boolean matchesWidget = widgetId != null && widgetId.equals(message.optString("widgetId"));
174
+ final boolean matchesDirection = normalizedDirection == null || normalizedDirection.equals(message.optString("direction"));
175
+ if ((matchesMessageId || matchesWidget) && matchesDirection) {
176
+ message.put("acknowledgedAt", nowMs);
177
+ saveMessage(message);
178
+ }
179
+ }
180
+ }
181
+
182
+ public JSONObject completeMessage(final String messageId, final JSONObject response, final String error) throws JSONException {
183
+ final JSONObject message = loadMessage(messageId);
184
+ if (message == null) {
185
+ return null;
186
+ }
187
+ if (!"pending".equals(message.optString("status")) || !message.isNull("completedAt")) {
188
+ return message;
189
+ }
190
+ message.put("status", error == null ? "completed" : "failed");
191
+ message.put("completedAt", System.currentTimeMillis());
192
+ message.put("response", response == null ? JSONObject.NULL : TemplateJsonUtils.deepCopyObject(response));
193
+ message.put("error", error == null ? JSONObject.NULL : error);
194
+ saveMessage(message);
195
+ return message;
196
+ }
197
+
198
+ private void saveSession(final JSONObject session) throws JSONException {
199
+ final String widgetId = session.getString("widgetId");
200
+ final SharedPreferences.Editor editor = preferences.edit().putString(sessionKey(widgetId), session.toString());
201
+ final List<String> ids = listIds(SESSION_IDS_KEY);
202
+ if (!ids.contains(widgetId)) {
203
+ ids.add(widgetId);
204
+ editor.putString(SESSION_IDS_KEY, serializeIds(ids).toString());
205
+ }
206
+ editor.apply();
207
+ }
208
+
209
+ private JSONObject loadMessage(final String messageId) throws JSONException {
210
+ final String raw = preferences.getString(messageKey(messageId), null);
211
+ return raw == null ? null : new JSONObject(raw);
212
+ }
213
+
214
+ private void saveMessage(final JSONObject message) throws JSONException {
215
+ final String messageId = message.getString("messageId");
216
+ final SharedPreferences.Editor editor = preferences.edit().putString(messageKey(messageId), message.toString());
217
+ final List<String> ids = listIds(MESSAGE_IDS_KEY);
218
+ if (!ids.contains(messageId)) {
219
+ ids.add(messageId);
220
+ editor.putString(MESSAGE_IDS_KEY, serializeIds(ids).toString());
221
+ }
222
+ editor.apply();
223
+ }
224
+
225
+ private JSONObject mergeObjects(final JSONObject base, final JSONObject patch) throws JSONException {
226
+ final JSONObject merged = base == null ? new JSONObject() : TemplateJsonUtils.deepCopyObject(base);
227
+ final IteratorWrapper keys = new IteratorWrapper(patch.keys());
228
+ while (keys.hasNext()) {
229
+ final String key = keys.next();
230
+ final Object current = merged.opt(key);
231
+ final Object value = patch.opt(key);
232
+ if (current instanceof JSONObject currentObject && value instanceof JSONObject patchObject) {
233
+ merged.put(key, mergeObjects(currentObject, patchObject));
234
+ } else {
235
+ merged.put(key, TemplateJsonUtils.deepCopyValue(value));
236
+ }
237
+ }
238
+ return merged;
239
+ }
240
+
241
+ private Set<String> toStringSet(final JSONArray values) {
242
+ final Set<String> result = new HashSet<>();
243
+ if (values == null) {
244
+ return result;
245
+ }
246
+ for (int index = 0; index < values.length(); index += 1) {
247
+ final String value = values.optString(index, null);
248
+ if (value != null && !value.isEmpty()) {
249
+ result.add(value);
250
+ }
251
+ }
252
+ return result;
253
+ }
254
+
255
+ private List<String> listIds(final String key) {
256
+ final String raw = preferences.getString(key, null);
257
+ final List<String> ids = new ArrayList<>();
258
+ if (raw == null) {
259
+ return ids;
260
+ }
261
+ try {
262
+ final JSONArray values = new JSONArray(raw);
263
+ for (int index = 0; index < values.length(); index += 1) {
264
+ final String value = values.optString(index, null);
265
+ if (value != null && !value.isEmpty()) {
266
+ ids.add(value);
267
+ }
268
+ }
269
+ } catch (JSONException ignored) {
270
+ return new ArrayList<>();
271
+ }
272
+ return ids;
273
+ }
274
+
275
+ private JSONArray serializeIds(final List<String> ids) {
276
+ final JSONArray values = new JSONArray();
277
+ for (String id : ids) {
278
+ values.put(id);
279
+ }
280
+ return values;
281
+ }
282
+
283
+ private String normalizeDirection(final String direction) {
284
+ return DIRECTION_WIDGET_TO_APP.equals(direction) ? DIRECTION_WIDGET_TO_APP : DIRECTION_APP_TO_WIDGET;
285
+ }
286
+
287
+ private String sessionKey(final String widgetId) {
288
+ return "native-session:" + widgetId;
289
+ }
290
+
291
+ private String messageKey(final String messageId) {
292
+ return "native-message:" + messageId;
293
+ }
294
+
295
+ private static final class IteratorWrapper {
296
+
297
+ private final java.util.Iterator<String> iterator;
298
+
299
+ IteratorWrapper(final java.util.Iterator<String> iterator) {
300
+ this.iterator = iterator;
301
+ }
302
+
303
+ boolean hasNext() {
304
+ return iterator.hasNext();
305
+ }
306
+
307
+ String next() {
308
+ return iterator.next();
309
+ }
310
+ }
311
+ }
@@ -0,0 +1,36 @@
1
+ package app.capgo.widgetkit;
2
+
3
+ import android.content.BroadcastReceiver;
4
+ import android.content.Context;
5
+ import android.content.Intent;
6
+ import android.util.Log;
7
+ import org.json.JSONException;
8
+ import org.json.JSONObject;
9
+
10
+ public class CapgoTemplateActionReceiver extends BroadcastReceiver {
11
+
12
+ private static final String LOG_TAG = "CapgoWidgetKit";
13
+
14
+ @Override
15
+ public void onReceive(final Context context, final Intent intent) {
16
+ if (intent == null || !CapgoWidgetKitConstants.ACTION_PERFORM_TEMPLATE_ACTION.equals(intent.getAction())) {
17
+ return;
18
+ }
19
+
20
+ final String activityId = intent.getStringExtra(CapgoWidgetKitConstants.EXTRA_ACTIVITY_ID);
21
+ final String actionId = intent.getStringExtra(CapgoWidgetKitConstants.EXTRA_ACTION_ID);
22
+ final String sourceId = intent.getStringExtra(CapgoWidgetKitConstants.EXTRA_SOURCE_ID);
23
+ final String payloadJson = intent.getStringExtra(CapgoWidgetKitConstants.EXTRA_PAYLOAD_JSON);
24
+
25
+ if (activityId == null || actionId == null) {
26
+ return;
27
+ }
28
+
29
+ try {
30
+ final JSONObject payload = payloadJson != null && !payloadJson.isEmpty() ? new JSONObject(payloadJson) : null;
31
+ new CapgoWidgetKit(context).performTemplateAction(activityId, actionId, sourceId, payload);
32
+ } catch (JSONException exception) {
33
+ Log.e(LOG_TAG, "Failed to execute template action from widget receiver", exception);
34
+ }
35
+ }
36
+ }
@@ -0,0 +1,25 @@
1
+ package app.capgo.widgetkit;
2
+
3
+ import android.graphics.Bitmap;
4
+ import android.graphics.Canvas;
5
+ import com.caverock.androidsvg.SVG;
6
+ import org.json.JSONObject;
7
+
8
+ public final class CapgoTemplateSvgBitmapRenderer {
9
+
10
+ private CapgoTemplateSvgBitmapRenderer() {}
11
+
12
+ public static Bitmap render(final JSONObject layout, final int targetWidthPx, final int targetHeightPx) throws Exception {
13
+ final String svgMarkup = layout.optString("svg", "");
14
+ final SVG svg = SVG.getFromString(svgMarkup);
15
+ svg.setDocumentWidth("100%");
16
+ svg.setDocumentHeight("100%");
17
+
18
+ final int width = Math.max(1, targetWidthPx);
19
+ final int height = Math.max(1, targetHeightPx);
20
+ final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
21
+ final Canvas canvas = new Canvas(bitmap);
22
+ svg.renderToCanvas(canvas);
23
+ return bitmap;
24
+ }
25
+ }
@@ -0,0 +1,31 @@
1
+ package app.capgo.widgetkit;
2
+
3
+ import android.content.Context;
4
+ import org.json.JSONArray;
5
+ import org.json.JSONException;
6
+ import org.json.JSONObject;
7
+
8
+ public class CapgoTemplateWidgetBridge {
9
+
10
+ private final TemplateActivityStore store;
11
+
12
+ public CapgoTemplateWidgetBridge(final Context context) {
13
+ store = new TemplateActivityStore(context);
14
+ }
15
+
16
+ public JSONObject loadActivity(final String activityId) throws JSONException {
17
+ return store.loadActivity(activityId);
18
+ }
19
+
20
+ public JSONArray listActivities() throws JSONException {
21
+ return store.listActivities();
22
+ }
23
+
24
+ public JSONObject resolveLayout(final String activityId, final String surface) throws JSONException {
25
+ final JSONObject activity = store.loadActivity(activityId);
26
+ if (activity == null) {
27
+ return null;
28
+ }
29
+ return TemplateRuntime.resolveSurface(activity, surface, System.currentTimeMillis());
30
+ }
31
+ }
@@ -0,0 +1,218 @@
1
+ package app.capgo.widgetkit;
2
+
3
+ import android.content.Context;
4
+ import android.content.Intent;
5
+ import android.content.pm.PackageInfo;
6
+ import android.content.pm.PackageManager;
7
+ import org.json.JSONArray;
8
+ import org.json.JSONException;
9
+ import org.json.JSONObject;
10
+
11
+ public class CapgoWidgetKit {
12
+
13
+ private final Context context;
14
+ private final TemplateActivityStore store;
15
+ private final CapgoNativeWidgetBridge nativeWidgetBridge;
16
+
17
+ public CapgoWidgetKit(final Context context) {
18
+ this.context = context.getApplicationContext();
19
+ this.store = new TemplateActivityStore(this.context);
20
+ this.nativeWidgetBridge = new CapgoNativeWidgetBridge(this.context);
21
+ }
22
+
23
+ public JSONObject areActivitiesSupported() throws JSONException {
24
+ return new JSONObject()
25
+ .put("supported", true)
26
+ .put(
27
+ "reason",
28
+ "Android support uses the generic template store and widget bridge. Render the resolved SVG and hotspots in your AppWidget or Glance UI."
29
+ );
30
+ }
31
+
32
+ public JSONObject startTemplateActivity(
33
+ final String requestedActivityId,
34
+ final JSONObject definitionObject,
35
+ final JSONObject stateObject,
36
+ final String openUrl
37
+ ) throws JSONException {
38
+ final String activityId =
39
+ requestedActivityId != null && !requestedActivityId.isEmpty()
40
+ ? requestedActivityId
41
+ : TemplateRuntime.createIdentifier("activity");
42
+ final JSONObject activity = TemplateRuntime.createActivityRecord(
43
+ activityId,
44
+ definitionObject,
45
+ stateObject,
46
+ openUrl,
47
+ System.currentTimeMillis()
48
+ );
49
+ store.saveActivity(activity);
50
+ notifyStoreChanged(activityId);
51
+ return activity;
52
+ }
53
+
54
+ public JSONObject updateTemplateActivity(
55
+ final String activityId,
56
+ final JSONObject definitionObject,
57
+ final JSONObject stateObject,
58
+ final String openUrl
59
+ ) throws JSONException {
60
+ final JSONObject current = store.loadActivity(activityId);
61
+ if (current == null) {
62
+ return null;
63
+ }
64
+
65
+ final JSONObject updated = TemplateRuntime.updateActivity(
66
+ current,
67
+ definitionObject,
68
+ stateObject,
69
+ openUrl,
70
+ System.currentTimeMillis()
71
+ );
72
+ store.saveActivity(updated);
73
+ notifyStoreChanged(activityId);
74
+ return updated;
75
+ }
76
+
77
+ public void endTemplateActivity(final String activityId, final JSONObject stateObject) throws JSONException {
78
+ final JSONObject current = store.loadActivity(activityId);
79
+ if (current == null) {
80
+ return;
81
+ }
82
+
83
+ final JSONObject ended = TemplateRuntime.endActivity(current, stateObject, System.currentTimeMillis());
84
+ store.saveActivity(ended);
85
+ notifyStoreChanged(activityId);
86
+ }
87
+
88
+ public TemplateRuntime.ActionResult performTemplateAction(
89
+ final String activityId,
90
+ final String actionId,
91
+ final String sourceId,
92
+ final JSONObject payloadObject
93
+ ) throws JSONException {
94
+ final JSONObject current = store.loadActivity(activityId);
95
+ if (current == null) {
96
+ throw new JSONException("No stored template activity found for " + activityId + ".");
97
+ }
98
+
99
+ final TemplateRuntime.ActionResult result = TemplateRuntime.applyAction(
100
+ actionId,
101
+ sourceId,
102
+ payloadObject,
103
+ current,
104
+ System.currentTimeMillis()
105
+ );
106
+ store.saveActivity(result.activity);
107
+ store.appendEvent(result.event);
108
+ notifyStoreChanged(activityId);
109
+ return result;
110
+ }
111
+
112
+ public JSONObject getTemplateActivity(final String activityId) throws JSONException {
113
+ return store.loadActivity(activityId);
114
+ }
115
+
116
+ public JSONArray listTemplateActivities() throws JSONException {
117
+ return store.listActivities();
118
+ }
119
+
120
+ public JSONArray listTemplateEvents(final String activityId, final boolean unacknowledgedOnly) throws JSONException {
121
+ return store.loadEvents(activityId, unacknowledgedOnly);
122
+ }
123
+
124
+ public void acknowledgeTemplateEvents(final String activityId, final JSONArray eventIds) throws JSONException {
125
+ store.acknowledgeEvents(activityId, eventIds, System.currentTimeMillis());
126
+ notifyStoreChanged(activityId);
127
+ }
128
+
129
+ public JSONObject startWidgetSession(final String widgetId, final String kind, final JSONObject state, final JSONObject metadata)
130
+ throws JSONException {
131
+ final JSONObject session = nativeWidgetBridge.startSession(widgetId, kind, state, metadata);
132
+ notifyWidgetBridgeChanged(session.optString("widgetId"), null);
133
+ return session;
134
+ }
135
+
136
+ public JSONObject updateWidgetSession(final String widgetId, final JSONObject state, final JSONObject metadata, final boolean merge)
137
+ throws JSONException {
138
+ final JSONObject session = nativeWidgetBridge.updateSession(widgetId, state, metadata, merge);
139
+ notifyWidgetBridgeChanged(widgetId, null);
140
+ return session;
141
+ }
142
+
143
+ public void stopWidgetSession(final String widgetId, final JSONObject state) throws JSONException {
144
+ nativeWidgetBridge.stopSession(widgetId, state);
145
+ notifyWidgetBridgeChanged(widgetId, null);
146
+ }
147
+
148
+ public JSONObject getWidgetSession(final String widgetId) throws JSONException {
149
+ return nativeWidgetBridge.loadSession(widgetId);
150
+ }
151
+
152
+ public JSONArray listWidgetSessions() throws JSONException {
153
+ return nativeWidgetBridge.listSessions();
154
+ }
155
+
156
+ public JSONObject sendWidgetMessage(
157
+ final String widgetId,
158
+ final String direction,
159
+ final String name,
160
+ final JSONObject payload,
161
+ final boolean expectsResponse
162
+ ) throws JSONException {
163
+ final JSONObject message = nativeWidgetBridge.sendMessage(widgetId, direction, name, payload, expectsResponse);
164
+ notifyWidgetBridgeChanged(widgetId, message.optString("messageId"));
165
+ return message;
166
+ }
167
+
168
+ public JSONArray listWidgetMessages(
169
+ final String widgetId,
170
+ final String direction,
171
+ final boolean unacknowledgedOnly,
172
+ final boolean pendingOnly
173
+ ) throws JSONException {
174
+ return nativeWidgetBridge.listMessages(widgetId, direction, unacknowledgedOnly, pendingOnly);
175
+ }
176
+
177
+ public void acknowledgeWidgetMessages(final JSONArray messageIds, final String widgetId, final String direction) throws JSONException {
178
+ nativeWidgetBridge.acknowledgeMessages(messageIds, widgetId, direction);
179
+ notifyWidgetBridgeChanged(widgetId, null);
180
+ }
181
+
182
+ public JSONObject completeWidgetMessage(final String messageId, final JSONObject response, final String error) throws JSONException {
183
+ final JSONObject message = nativeWidgetBridge.completeMessage(messageId, response, error);
184
+ notifyWidgetBridgeChanged(message == null ? null : message.optString("widgetId"), messageId);
185
+ return message;
186
+ }
187
+
188
+ public JSONObject getPluginVersion() throws JSONException {
189
+ String versionName = "android";
190
+ try {
191
+ final PackageManager packageManager = context.getPackageManager();
192
+ final PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
193
+ versionName = packageInfo.versionName != null ? packageInfo.versionName : versionName;
194
+ } catch (PackageManager.NameNotFoundException ignored) {
195
+ // Ignore and keep the fallback.
196
+ }
197
+
198
+ return new JSONObject().put("version", versionName);
199
+ }
200
+
201
+ private void notifyStoreChanged(final String activityId) {
202
+ final Intent intent = new Intent(CapgoWidgetKitConstants.ACTION_TEMPLATE_STORE_CHANGED)
203
+ .setPackage(context.getPackageName())
204
+ .putExtra(CapgoWidgetKitConstants.EXTRA_ACTIVITY_ID, activityId);
205
+ context.sendBroadcast(intent);
206
+ }
207
+
208
+ private void notifyWidgetBridgeChanged(final String widgetId, final String messageId) {
209
+ final Intent intent = new Intent(CapgoWidgetKitConstants.ACTION_NATIVE_WIDGET_BRIDGE_CHANGED).setPackage(context.getPackageName());
210
+ if (widgetId != null) {
211
+ intent.putExtra(CapgoWidgetKitConstants.EXTRA_WIDGET_ID, widgetId);
212
+ }
213
+ if (messageId != null) {
214
+ intent.putExtra(CapgoWidgetKitConstants.EXTRA_MESSAGE_ID, messageId);
215
+ }
216
+ context.sendBroadcast(intent);
217
+ }
218
+ }