@g9tm/app-diagnostic-tauri 0.0.0-stage → 0.6.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 (40) hide show
  1. package/Cargo.toml +18 -0
  2. package/README.md +23 -3
  3. package/android/build.gradle.kts +29 -0
  4. package/android/proguard-rules.pro +2 -0
  5. package/android/settings.gradle +2 -0
  6. package/android/src/main/AndroidManifest.xml +5 -0
  7. package/android/src/main/java/com/g9tm/appdiagnostic/G9AppDiagnosticHost.kt +131 -0
  8. package/android/src/main/java/com/g9tm/appdiagnostic/RemoteTouch.kt +67 -0
  9. package/android/src/main/java/com/g9tm/appdiagnostic/ScreenRecorder.kt +250 -0
  10. package/android/src/main/java/com/g9tm/appdiagnostic/TouchWatcher.kt +129 -0
  11. package/android/src/main/java/com/g9tm/appdiagnostic/VoiceRecorder.kt +82 -0
  12. package/android/src/main/java/com/g9tm/appdiagnostic/WindowCapture.kt +92 -0
  13. package/android/src/main/java/com/g9tm/appdiagnostic/core/TouchCore.kt +270 -0
  14. package/android/src/main/java/com/g9tm/appdiagnostic/tauri/G9DiagnosticPlugin.kt +180 -0
  15. package/build.rs +13 -0
  16. package/ios/Package.swift +20 -0
  17. package/ios/Sources/G9AppDiagnosticCore/G9AppDiagnosticHost.m +72 -0
  18. package/ios/Sources/G9AppDiagnosticCore/G9DiagnosticRecorders.m +514 -0
  19. package/ios/Sources/G9AppDiagnosticCore/include/G9AppDiagnosticHost.h +32 -0
  20. package/ios/Sources/G9AppDiagnosticCore/include/G9DiagnosticRecorders.h +36 -0
  21. package/ios/Sources/G9DiagnosticPlugin/G9DiagnosticPlugin.swift +135 -0
  22. package/package.json +43 -6
  23. package/permissions/autogenerated/commands/capabilities.toml +13 -0
  24. package/permissions/autogenerated/commands/read_chunk.toml +13 -0
  25. package/permissions/autogenerated/commands/registerListener.toml +13 -0
  26. package/permissions/autogenerated/commands/remove.toml +13 -0
  27. package/permissions/autogenerated/commands/remove_listener.toml +13 -0
  28. package/permissions/autogenerated/commands/screenshot.toml +13 -0
  29. package/permissions/autogenerated/commands/start_screen.toml +13 -0
  30. package/permissions/autogenerated/commands/start_voice.toml +13 -0
  31. package/permissions/autogenerated/commands/state.toml +13 -0
  32. package/permissions/autogenerated/commands/stop_screen.toml +13 -0
  33. package/permissions/autogenerated/commands/stop_voice.toml +13 -0
  34. package/permissions/autogenerated/commands/touch.toml +13 -0
  35. package/permissions/autogenerated/commands/watch_touches.toml +13 -0
  36. package/permissions/autogenerated/reference.md +367 -0
  37. package/permissions/default.toml +9 -0
  38. package/permissions/schemas/schema.json +462 -0
  39. package/src/index.ts +97 -0
  40. package/src/lib.rs +119 -0
@@ -0,0 +1,72 @@
1
+ #import "G9AppDiagnosticHost.h"
2
+
3
+ static NSURLSession * (^gSession)(void);
4
+ static NSArray<NSString *> * (^gRoots)(void);
5
+ static BOOL (^gExcluded)(UIView *);
6
+
7
+ @implementation G9AppDiagnosticHost
8
+
9
+ + (NSURLSession * (^)(void))urlSession { return gSession; }
10
+ + (void)setUrlSession:(NSURLSession * (^)(void))b { gSession = [b copy]; }
11
+ + (NSArray<NSString *> * (^)(void))allowedRoots { return gRoots; }
12
+ + (void)setAllowedRoots:(NSArray<NSString *> * (^)(void))b { gRoots = [b copy]; }
13
+ + (BOOL (^)(UIView *))isExcludedView { return gExcluded; }
14
+ + (void)setIsExcludedView:(BOOL (^)(UIView *))b { gExcluded = [b copy]; }
15
+
16
+ + (NSArray<NSString *> *)roots {
17
+ NSArray<NSString *> *raw = gRoots ? gRoots() : @[
18
+ NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES).firstObject ?: NSTemporaryDirectory(),
19
+ NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject ?: NSTemporaryDirectory(),
20
+ NSTemporaryDirectory(),
21
+ ];
22
+ NSMutableArray<NSString *> *out = [NSMutableArray array];
23
+ for (NSString *r in raw) {
24
+ NSString *p = r.stringByStandardizingPath.stringByResolvingSymlinksInPath;
25
+ while (p.length > 1 && [p hasSuffix:@"/"]) p = [p substringToIndex:p.length - 1];
26
+ if (p.length) [out addObject:p];
27
+ }
28
+ return out;
29
+ }
30
+
31
+ + (NSString *)inside:(NSString *)path folder:(BOOL)folder {
32
+ if (path.length == 0) return nil;
33
+ NSString *p = path.stringByStandardizingPath.stringByResolvingSymlinksInPath;
34
+ while (p.length > 1 && [p hasSuffix:@"/"]) p = [p substringToIndex:p.length - 1];
35
+ for (NSString *root in [self roots]) {
36
+ if ([p hasPrefix:[root stringByAppendingString:@"/"]]) return p; // strictly inside: never «/rootX» for «/root»
37
+ if (folder && [p isEqualToString:root]) return p;
38
+ }
39
+ return nil;
40
+ }
41
+
42
+ + (UIWindow *)keyWindow {
43
+ UIWindow *any = nil;
44
+ for (UIScene *scene in UIApplication.sharedApplication.connectedScenes) {
45
+ if (![scene isKindOfClass:UIWindowScene.class]) continue;
46
+ for (UIWindow *w in ((UIWindowScene *)scene).windows) {
47
+ if (w.isKeyWindow) return w;
48
+ if (!any && !w.hidden) any = w;
49
+ }
50
+ }
51
+ return any;
52
+ }
53
+
54
+ + (CGSize)windowSize {
55
+ UIWindow *w = [self keyWindow];
56
+ return w ? w.bounds.size : CGSizeZero;
57
+ }
58
+
59
+ + (UIImage *)captureWindowAtScale:(CGFloat)scale {
60
+ UIWindow *window = [self keyWindow];
61
+ if (window == nil || CGRectIsEmpty(window.bounds)) return nil;
62
+ UIGraphicsImageRendererFormat *format = [UIGraphicsImageRendererFormat preferredFormat];
63
+ format.scale = scale;
64
+ format.opaque = YES;
65
+ // drawViewHierarchyInRect snapshots the composited screen, Metal layers included (a MapLibre map) — what PixelCopy
66
+ // and the SurfaceView composite give on Android.
67
+ return [[[UIGraphicsImageRenderer alloc] initWithSize:window.bounds.size format:format] imageWithActions:^(UIGraphicsImageRendererContext *ctx) {
68
+ [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:NO];
69
+ }];
70
+ }
71
+
72
+ @end
@@ -0,0 +1,514 @@
1
+ #import "G9DiagnosticRecorders.h"
2
+
3
+ #import <AVFoundation/AVFoundation.h>
4
+ #import <CoreVideo/CoreVideo.h>
5
+ #import <UIKit/UIGestureRecognizerSubclass.h>
6
+
7
+ #import "G9AppDiagnosticHost.h"
8
+
9
+ // The screen rate is ADAPTIVE and bounded: it starts at the caller's ceiling (a fleet's tester_capture_max_fps, at most 20)
10
+ // and lowers itself — never below kMinFps — the moment a frame costs most of its slot, climbing back one step after a run of
11
+ // cheap frames: an app slowed by its own recorder records a slowness that is not the defect. Frames carry their own
12
+ // presentation times, so a lower rate is a slower video, never a faster one.
13
+ static const int kMinFps = 4;
14
+ static const int kMaxFps = 20;
15
+ static const CGFloat kMaxEdge = 960;
16
+ static const int kBitRate = 2000000;
17
+ static const NSTimeInterval kMaxDuration = 10 * 60;
18
+
19
+ static long long G9NowMs(void) { return (long long)(NSDate.date.timeIntervalSince1970 * 1000); }
20
+
21
+ @implementation G9DiagnosticError
22
+ + (instancetype)code:(NSString *)code message:(NSString *)message {
23
+ G9DiagnosticError *e = [[G9DiagnosticError alloc] initWithDomain:@"g9.appdiagnostic" code:1 userInfo:@{NSLocalizedDescriptionKey : message ?: code}];
24
+ e->_diagnosticCode = [code copy];
25
+ return e;
26
+ }
27
+ @end
28
+
29
+ // ── the screen: the app's OWN window, no ReplayKit (no consent alert, nothing of other apps, the simulator too) ─────────
30
+
31
+ @implementation G9ScreenRecorder {
32
+ dispatch_queue_t _queue;
33
+ AVAssetWriter *_writer;
34
+ AVAssetWriterInput *_input;
35
+ AVAssetWriterInputPixelBufferAdaptor *_adaptor;
36
+ dispatch_source_t _timer;
37
+ NSString *_path;
38
+ CGSize _size;
39
+ CFTimeInterval _started;
40
+ int _frames;
41
+ BOOL _busy;
42
+ int _fps;
43
+ int _ceiling;
44
+ double _costMs;
45
+ int _cheap;
46
+ BOOL _capped;
47
+ NSDictionary *_finished; // a recording the 10-minute cap finished, waiting for stop
48
+ }
49
+
50
+ + (instancetype)shared {
51
+ static G9ScreenRecorder *r;
52
+ static dispatch_once_t once;
53
+ dispatch_once(&once, ^{ r = [[G9ScreenRecorder alloc] init]; });
54
+ return r;
55
+ }
56
+
57
+ - (instancetype)init {
58
+ if ((self = [super init])) _queue = dispatch_queue_create("g9.appdiagnostic.screen", DISPATCH_QUEUE_SERIAL);
59
+ return self;
60
+ }
61
+
62
+ - (BOOL)recording {
63
+ __block BOOL r;
64
+ dispatch_sync(_queue, ^{ r = self->_writer != nil; });
65
+ return r;
66
+ }
67
+
68
+ /** ≤ 960 px long edge, both sides even (H.264). */
69
+ static CGSize G9OutputSize(CGSize points, CGFloat screenScale) {
70
+ CGFloat w = points.width * screenScale, h = points.height * screenScale;
71
+ CGFloat k = MIN(1.0, kMaxEdge / MAX(w, h));
72
+ return CGSizeMake(MAX(2, ((int)(w * k) / 2) * 2), MAX(2, ((int)(h * k) / 2) * 2));
73
+ }
74
+
75
+ - (BOOL)startIn:(NSString *)dir maxFps:(int)maxFps error:(NSError **)error {
76
+ int ceiling = MAX(kMinFps, MIN(kMaxFps, maxFps));
77
+ __block CGSize points = CGSizeZero;
78
+ __block CGFloat screenScale = 1;
79
+ void (^read)(void) = ^{
80
+ points = G9AppDiagnosticHost.windowSize;
81
+ screenScale = UIScreen.mainScreen.scale;
82
+ };
83
+ if (NSThread.isMainThread) read(); else dispatch_sync(dispatch_get_main_queue(), read);
84
+ if (points.width <= 0 || points.height <= 0) {
85
+ if (error) *error = [G9DiagnosticError code:@"unavailable" message:@"The window is not laid out"];
86
+ return NO;
87
+ }
88
+ __block NSError *failure = nil;
89
+ dispatch_sync(_queue, ^{
90
+ if (self->_writer) { failure = [G9DiagnosticError code:@"busy" message:@"A screen recording is already running"]; return; }
91
+ self->_finished = nil;
92
+ CGSize size = G9OutputSize(points, screenScale);
93
+ NSString *path = [dir stringByAppendingPathComponent:[NSString stringWithFormat:@"screen-%lld.mp4", G9NowMs()]];
94
+ NSError *e = nil;
95
+ AVAssetWriter *writer = [AVAssetWriter assetWriterWithURL:[NSURL fileURLWithPath:path] fileType:AVFileTypeMPEG4 error:&e];
96
+ if (!writer) { failure = [G9DiagnosticError code:@"unavailable" message:e.localizedDescription ?: @"No writer"]; return; }
97
+ NSDictionary *settings = @{
98
+ AVVideoCodecKey : AVVideoCodecTypeH264, AVVideoWidthKey : @(size.width), AVVideoHeightKey : @(size.height),
99
+ AVVideoCompressionPropertiesKey : @{AVVideoAverageBitRateKey : @(kBitRate), AVVideoMaxKeyFrameIntervalKey : @(ceiling), AVVideoExpectedSourceFrameRateKey : @(ceiling)}
100
+ };
101
+ AVAssetWriterInput *input = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:settings];
102
+ input.expectsMediaDataInRealTime = YES;
103
+ NSDictionary *attrs = @{
104
+ (id)kCVPixelBufferPixelFormatTypeKey : @(kCVPixelFormatType_32BGRA), (id)kCVPixelBufferWidthKey : @(size.width),
105
+ (id)kCVPixelBufferHeightKey : @(size.height), (id)kCVPixelBufferCGBitmapContextCompatibilityKey : @YES
106
+ };
107
+ AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:input sourcePixelBufferAttributes:attrs];
108
+ if (![writer canAddInput:input]) { failure = [G9DiagnosticError code:@"unavailable" message:@"The H.264 input was refused"]; return; }
109
+ [writer addInput:input];
110
+ if (![writer startWriting]) { failure = [G9DiagnosticError code:@"unavailable" message:writer.error.localizedDescription ?: @"startWriting failed"]; return; }
111
+ [writer startSessionAtSourceTime:kCMTimeZero];
112
+ self->_writer = writer;
113
+ self->_input = input;
114
+ self->_adaptor = adaptor;
115
+ self->_path = path;
116
+ self->_size = size;
117
+ self->_started = CACurrentMediaTime();
118
+ self->_frames = 0;
119
+ self->_busy = NO;
120
+ self->_capped = NO;
121
+ self->_fps = ceiling;
122
+ self->_ceiling = ceiling;
123
+ self->_costMs = 0;
124
+ self->_cheap = 0;
125
+ self->_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
126
+ dispatch_source_set_timer(self->_timer, DISPATCH_TIME_NOW, NSEC_PER_SEC / ceiling, NSEC_PER_SEC / 40);
127
+ __weak G9ScreenRecorder *weak = self;
128
+ dispatch_source_set_event_handler(self->_timer, ^{ [weak tick]; });
129
+ dispatch_resume(self->_timer);
130
+ });
131
+ if (failure) { if (error) *error = failure; return NO; }
132
+ return YES;
133
+ }
134
+
135
+ /** Main queue: snapshot the window (drawViewHierarchy needs main), then hand the frame to the writer queue. */
136
+ - (void)tick {
137
+ if (_busy) return; // a slow capture overran its slot: skip, never queue
138
+ CFTimeInterval elapsed = CACurrentMediaTime() - _started;
139
+ if (elapsed >= kMaxDuration) {
140
+ dispatch_async(_queue, ^{
141
+ if (!self->_writer) return;
142
+ self->_capped = YES;
143
+ self->_finished = [self finishLocked];
144
+ });
145
+ return;
146
+ }
147
+ CFTimeInterval began = CACurrentMediaTime();
148
+ CGFloat scale = _size.width / MAX(G9AppDiagnosticHost.windowSize.width, 1);
149
+ UIImage *image = [G9AppDiagnosticHost captureWindowAtScale:scale];
150
+ if (!image) return;
151
+ _busy = YES;
152
+ dispatch_async(_queue, ^{
153
+ [self appendLocked:image at:elapsed];
154
+ [self adaptLocked:(CACurrentMediaTime() - began) * 1000];
155
+ dispatch_async(dispatch_get_main_queue(), ^{ self->_busy = NO; });
156
+ });
157
+ }
158
+
159
+ - (void)adaptLocked:(double)costMs {
160
+ if (!_writer || !_timer) return;
161
+ _costMs = _costMs <= 0 ? costMs : _costMs * 0.7 + costMs * 0.3;
162
+ double slot = 1000.0 / _fps;
163
+ int next = _fps;
164
+ if (_costMs > slot * 0.85 && _fps > kMinFps) { next = MAX(kMinFps, (int)floor(1000.0 / (_costMs * 1.25))); _cheap = 0; }
165
+ else if (_costMs < slot * 0.5 && _fps < _ceiling && ++_cheap >= _fps * 3) { next = _fps + 1; _cheap = 0; }
166
+ if (next == _fps) return;
167
+ _fps = next;
168
+ dispatch_source_set_timer(_timer, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(NSEC_PER_SEC / next)), NSEC_PER_SEC / next, NSEC_PER_SEC / 40);
169
+ }
170
+
171
+ - (void)appendLocked:(UIImage *)image at:(CFTimeInterval)elapsed {
172
+ if (!_writer || !_input.readyForMoreMediaData) return;
173
+ CVPixelBufferRef buffer = NULL;
174
+ if (CVPixelBufferPoolCreatePixelBuffer(NULL, _adaptor.pixelBufferPool, &buffer) != kCVReturnSuccess || !buffer) return;
175
+ CVPixelBufferLockBaseAddress(buffer, 0);
176
+ CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB();
177
+ CGContextRef ctx = CGBitmapContextCreate(CVPixelBufferGetBaseAddress(buffer), (size_t)_size.width, (size_t)_size.height, 8,
178
+ CVPixelBufferGetBytesPerRow(buffer), space, kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little);
179
+ CGContextSetFillColorWithColor(ctx, UIColor.blackColor.CGColor);
180
+ CGContextFillRect(ctx, CGRectMake(0, 0, _size.width, _size.height));
181
+ // A rotation after the first frame: fitted (letterboxed) into the geometry locked at the first frame.
182
+ CGFloat k = MIN(_size.width / MAX(image.size.width * image.scale, 1), _size.height / MAX(image.size.height * image.scale, 1));
183
+ CGFloat w = image.size.width * image.scale * k, h = image.size.height * image.scale * k;
184
+ CGContextDrawImage(ctx, CGRectMake((_size.width - w) / 2, (_size.height - h) / 2, w, h), image.CGImage);
185
+ CGContextRelease(ctx);
186
+ CGColorSpaceRelease(space);
187
+ CVPixelBufferUnlockBaseAddress(buffer, 0);
188
+ if ([_adaptor appendPixelBuffer:buffer withPresentationTime:CMTimeMakeWithSeconds(elapsed, 600)]) _frames++;
189
+ CVPixelBufferRelease(buffer);
190
+ }
191
+
192
+ - (NSDictionary *)finishLocked {
193
+ if (!_writer) return nil;
194
+ if (_timer) { dispatch_source_cancel(_timer); _timer = nil; }
195
+ AVAssetWriter *writer = _writer;
196
+ NSString *path = _path;
197
+ CGSize size = _size;
198
+ int frames = _frames;
199
+ BOOL capped = _capped;
200
+ long long durationMs = (long long)((CACurrentMediaTime() - _started) * 1000);
201
+ NSLog(@"[G9AppDiagnostic] screen recording: %d frames in %.1f s, last rate %d fps, ceiling %d", frames, durationMs / 1000.0, _fps, _ceiling);
202
+ _writer = nil;
203
+ _input = nil;
204
+ _adaptor = nil;
205
+ [writer.inputs.firstObject markAsFinished];
206
+ dispatch_semaphore_t done = dispatch_semaphore_create(0);
207
+ [writer finishWritingWithCompletionHandler:^{ dispatch_semaphore_signal(done); }];
208
+ dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 20 * NSEC_PER_SEC));
209
+ unsigned long long bytes = [[NSFileManager.defaultManager attributesOfItemAtPath:path error:nil] fileSize];
210
+ if (writer.status != AVAssetWriterStatusCompleted || frames == 0 || bytes == 0) {
211
+ [NSFileManager.defaultManager removeItemAtPath:path error:nil];
212
+ return nil;
213
+ }
214
+ return @{@"path" : path, @"bytes" : @(bytes), @"durationMs" : @(durationMs), @"width" : @(size.width), @"height" : @(size.height), @"capped" : @(capped)};
215
+ }
216
+
217
+ - (NSDictionary *)stop {
218
+ __block NSDictionary *result = nil;
219
+ dispatch_sync(_queue, ^{
220
+ if (self->_writer) result = [self finishLocked];
221
+ else { result = self->_finished; self->_finished = nil; }
222
+ });
223
+ return result;
224
+ }
225
+
226
+ @end
227
+
228
+ // ── the voice: the microphone into AAC .m4a, mono 44.1 kHz 96 kbit/s, 10 minutes at most ──────────────────────────────
229
+
230
+ @implementation G9VoiceRecorder {
231
+ AVAudioRecorder *_recorder;
232
+ CFTimeInterval _started;
233
+ }
234
+
235
+ + (instancetype)shared {
236
+ static G9VoiceRecorder *r;
237
+ static dispatch_once_t once;
238
+ dispatch_once(&once, ^{ r = [[G9VoiceRecorder alloc] init]; });
239
+ return r;
240
+ }
241
+
242
+ - (BOOL)recording { @synchronized(self) { return _recorder != nil; } }
243
+
244
+ /** The microphone permission: asked once (blocks this background thread until the person answers). */
245
+ static NSString *G9MicrophonePermission(void) {
246
+ AVAudioSession *session = AVAudioSession.sharedInstance;
247
+ switch (session.recordPermission) {
248
+ case AVAudioSessionRecordPermissionGranted: return @"granted";
249
+ case AVAudioSessionRecordPermissionDenied: return @"denied";
250
+ default: break;
251
+ }
252
+ dispatch_semaphore_t done = dispatch_semaphore_create(0);
253
+ __block BOOL ok = NO;
254
+ [session requestRecordPermission:^(BOOL granted) { ok = granted; dispatch_semaphore_signal(done); }];
255
+ dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 120 * NSEC_PER_SEC));
256
+ return ok ? @"granted" : @"denied";
257
+ }
258
+
259
+ - (BOOL)startIn:(NSString *)dir error:(NSError **)error {
260
+ NSString *permission = G9MicrophonePermission();
261
+ if (![permission isEqualToString:@"granted"]) {
262
+ if (error) *error = [G9DiagnosticError code:@"permission" message:[@"Microphone permission: " stringByAppendingString:permission]];
263
+ return NO;
264
+ }
265
+ @synchronized(self) {
266
+ if (_recorder) { if (error) *error = [G9DiagnosticError code:@"busy" message:@"A voice note is already being recorded"]; return NO; }
267
+ NSError *e = nil;
268
+ AVAudioSession *session = AVAudioSession.sharedInstance;
269
+ [session setCategory:AVAudioSessionCategoryPlayAndRecord mode:AVAudioSessionModeDefault
270
+ options:AVAudioSessionCategoryOptionDefaultToSpeaker | AVAudioSessionCategoryOptionMixWithOthers error:&e];
271
+ [session setActive:YES error:&e];
272
+ NSString *path = [dir stringByAppendingPathComponent:[NSString stringWithFormat:@"voice-%lld.m4a", G9NowMs()]];
273
+ NSDictionary *settings = @{AVFormatIDKey : @(kAudioFormatMPEG4AAC), AVSampleRateKey : @44100, AVNumberOfChannelsKey : @1, AVEncoderBitRateKey : @96000};
274
+ AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:path] settings:settings error:&e];
275
+ if (!recorder || ![recorder recordForDuration:kMaxDuration]) {
276
+ if (error) *error = [G9DiagnosticError code:@"unavailable" message:e.localizedDescription ?: @"The microphone could not start"];
277
+ return NO;
278
+ }
279
+ _recorder = recorder;
280
+ _started = CACurrentMediaTime();
281
+ }
282
+ return YES;
283
+ }
284
+
285
+ - (NSDictionary *)stop {
286
+ AVAudioRecorder *recorder;
287
+ CFTimeInterval started;
288
+ @synchronized(self) { recorder = _recorder; started = _started; _recorder = nil; }
289
+ if (!recorder) return nil;
290
+ [recorder stop];
291
+ [AVAudioSession.sharedInstance setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
292
+ NSString *path = recorder.url.path;
293
+ unsigned long long bytes = [[NSFileManager.defaultManager attributesOfItemAtPath:path error:nil] fileSize];
294
+ if (bytes == 0) { [NSFileManager.defaultManager removeItemAtPath:path error:nil]; return nil; }
295
+ return @{@"path" : path, @"bytes" : @(bytes), @"durationMs" : @((long long)((CACurrentMediaTime() - started) * 1000))};
296
+ }
297
+
298
+ @end
299
+
300
+ // ── the tester gesture ─────────────────────────────────────────────────────────────────────────────────────────────
301
+ //
302
+ // ONE recogniser on the key window that watches every touch and never recognises — it does not cancel, delay or block a
303
+ // touch and runs beside every other recogniser, so the app's own pinch / tap / pan and every Lynx view behave exactly as
304
+ // before. A completed multi-finger tap (all fingers down and up within 350 ms, none moved off its OWN landing point) is
305
+ // {type:"tap", fingers, x, y, cx, cy, excluded}; with `touches` every first finger down is {type:"down"} and every touch
306
+ // that could have been a tap ends with {type:"seq", …, info:{why…}}. x, y are fractions of the window.
307
+ // HOLD (`consume`): a SECOND finger landing within 250 ms of the first, unmoved and not over an excluded surface, makes the
308
+ // recogniser BEGIN with cancelsTouchesInView, so the views get touchesCancelled and the gesture never also presses what is
309
+ // under it. iOS cannot replay a held touch to the views, so a two-finger pan off the excluded surface ends the hold and is
310
+ // lost there (a map, where pinch and pan matter, is excluded and never held). TWIN: android core/TouchCore.kt.
311
+
312
+ @interface G9TesterTouchObserver : UIGestureRecognizer <UIGestureRecognizerDelegate>
313
+ @property(nonatomic) BOOL taps;
314
+ @property(nonatomic) BOOL touches;
315
+ @property(nonatomic) BOOL consume;
316
+ @property(nonatomic) BOOL excludeSurfaces;
317
+ @property(nonatomic, copy, nullable) void (^sink)(NSString *json);
318
+ @end
319
+
320
+ static const CGFloat kSlopPoints = 12;
321
+ static const CFTimeInterval kMaxTapSeconds = 0.35;
322
+ static const CFTimeInterval kSecondFingerSeconds = 0.25;
323
+
324
+ @implementation G9TesterTouchObserver {
325
+ CFTimeInterval _down;
326
+ NSUInteger _maxTouches;
327
+ BOOL _moved;
328
+ CGPoint _first;
329
+ NSMapTable<UITouch *, NSValue *> *_starts;
330
+ CGPoint _mid;
331
+ CGFloat _maxMove;
332
+ CGFloat _maxRadius;
333
+ CFTimeInterval _secondAt;
334
+ CFTimeInterval _firstUpAt;
335
+ BOOL _firstOnlyMoved;
336
+ BOOL _held;
337
+ BOOL _traced;
338
+ }
339
+
340
+ - (instancetype)init {
341
+ if ((self = [super initWithTarget:nil action:nil])) {
342
+ self.cancelsTouchesInView = NO;
343
+ self.delaysTouchesBegan = NO;
344
+ self.delaysTouchesEnded = NO;
345
+ self.delegate = self;
346
+ _starts = [NSMapTable strongToStrongObjectsMapTable];
347
+ }
348
+ return self;
349
+ }
350
+
351
+ - (BOOL)gestureRecognizer:(UIGestureRecognizer *)a shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)b { return YES; }
352
+
353
+ - (void)emit:(NSString *)type fingers:(NSUInteger)fingers at:(CGPoint)p mid:(CGPoint)mid excluded:(BOOL)excluded info:(NSDictionary *)info {
354
+ CGSize size = self.view.bounds.size;
355
+ if (size.width <= 0 || size.height <= 0 || !self.sink) return;
356
+ NSMutableDictionary *e = [@{@"type" : type, @"fingers" : @(fingers), @"x" : @(p.x / size.width), @"y" : @(p.y / size.height),
357
+ @"cx" : @(mid.x / size.width), @"cy" : @(mid.y / size.height), @"excluded" : @(excluded)} mutableCopy];
358
+ if (info) e[@"info"] = info;
359
+ NSData *d = [NSJSONSerialization dataWithJSONObject:e options:0 error:nil];
360
+ if (d) self.sink([[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding]);
361
+ }
362
+
363
+ /** A visible view the host excludes under the point (window points). A tap is rare, so walking the tree is fine. */
364
+ static BOOL G9OverExcluded(UIView *view, CGPoint p) {
365
+ BOOL (^excluded)(UIView *) = G9AppDiagnosticHost.isExcludedView;
366
+ if (!excluded || view.hidden || view.alpha <= 0.01) return NO;
367
+ if (excluded(view)) return CGRectContainsPoint([view convertRect:view.bounds toView:nil], p);
368
+ for (UIView *child in view.subviews) if (G9OverExcluded(child, p)) return YES;
369
+ return NO;
370
+ }
371
+
372
+ static NSArray<UITouch *> *G9Down(NSSet<UITouch *> *all) {
373
+ NSMutableArray<UITouch *> *down = [NSMutableArray array];
374
+ for (UITouch *t in all) if (t.phase != UITouchPhaseEnded && t.phase != UITouchPhaseCancelled) [down addObject:t];
375
+ return down;
376
+ }
377
+
378
+ - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
379
+ [super touchesBegan:touches withEvent:event];
380
+ NSUInteger all = event.allTouches.count ?: touches.count;
381
+ if (_maxTouches == 0) {
382
+ _down = CACurrentMediaTime();
383
+ _moved = NO;
384
+ [_starts removeAllObjects];
385
+ _maxMove = 0;
386
+ _maxRadius = 0;
387
+ _secondAt = -1;
388
+ _firstUpAt = -1;
389
+ _firstOnlyMoved = NO;
390
+ _held = NO;
391
+ _traced = NO;
392
+ UITouch *touch = touches.anyObject;
393
+ if (touch && self.view) {
394
+ _first = [touch locationInView:self.view];
395
+ _mid = _first;
396
+ if (self.touches) [self emit:@"down" fingers:1 at:_first mid:_first excluded:NO info:nil];
397
+ }
398
+ }
399
+ for (UITouch *t in touches) {
400
+ if (self.view) [_starts setObject:[NSValue valueWithCGPoint:[t locationInView:self.view]] forKey:t];
401
+ _maxRadius = MAX(_maxRadius, t.majorRadius);
402
+ }
403
+ if (_secondAt < 0 && all >= 2) _secondAt = CACurrentMediaTime() - _down;
404
+ if (all > _maxTouches && self.view) {
405
+ // The midpoint at the most fingers: which finger lands first changes from tap to tap, the midpoint does not.
406
+ NSArray<UITouch *> *down = G9Down(event.allTouches ?: touches);
407
+ if (down.count > 0) {
408
+ CGFloat sx = 0, sy = 0;
409
+ for (UITouch *t in down) { CGPoint q = [t locationInView:self.view]; sx += q.x; sy += q.y; }
410
+ _mid = CGPointMake(sx / down.count, sy / down.count);
411
+ }
412
+ }
413
+ _maxTouches = MAX(_maxTouches, all);
414
+ // The hold: two fingers, quickly, unmoved, and never over an excluded surface (in any mode: a map's pinch is the map's).
415
+ if (self.consume && self.taps && all == 2 && !_moved && self.state == UIGestureRecognizerStatePossible &&
416
+ CACurrentMediaTime() - _down <= kSecondFingerSeconds && !G9OverExcluded(self.view, _first)) {
417
+ self.cancelsTouchesInView = YES;
418
+ self.state = UIGestureRecognizerStateBegan;
419
+ _held = YES;
420
+ }
421
+ }
422
+
423
+ - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
424
+ [super touchesMoved:touches withEvent:event];
425
+ if (!self.view) return;
426
+ for (UITouch *touch in touches) {
427
+ CGPoint now = [touch locationInView:self.view];
428
+ CGPoint before = [touch previousLocationInView:self.view];
429
+ _maxRadius = MAX(_maxRadius, touch.majorRadius);
430
+ // EVERY FINGER AGAINST ITS OWN LANDING POINT: compared with the FIRST finger's, the second finger's first tremor
431
+ // «moved» the tap and a two-finger double tap failed most of the time on an iPhone.
432
+ NSValue *start = [_starts objectForKey:touch];
433
+ CGPoint from = start ? start.CGPointValue : now;
434
+ CGFloat d = MAX(fabs(now.x - from.x), fabs(now.y - from.y));
435
+ _maxMove = MAX(_maxMove, d);
436
+ if (!_firstOnlyMoved && (fabs(now.x - _first.x) > kSlopPoints * 2 || fabs(now.y - _first.y) > kSlopPoints * 2)) _firstOnlyMoved = YES;
437
+ if (_moved) continue;
438
+ if (fabs(now.x - before.x) + fabs(now.y - before.y) > kSlopPoints || d > kSlopPoints * 2) {
439
+ _moved = YES;
440
+ if (self.state == UIGestureRecognizerStateBegan || self.state == UIGestureRecognizerStateChanged) self.state = UIGestureRecognizerStateEnded;
441
+ }
442
+ }
443
+ }
444
+
445
+ - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
446
+ [super touchesEnded:touches withEvent:event];
447
+ if (_firstUpAt < 0) _firstUpAt = CACurrentMediaTime() - _down;
448
+ for (UITouch *t in event.allTouches) if (t.phase != UITouchPhaseEnded && t.phase != UITouchPhaseCancelled) return; // not all up
449
+ CFTimeInterval held = CACurrentMediaTime() - _down;
450
+ BOOL tap = self.taps && !_moved && _maxTouches >= 2 && held <= kMaxTapSeconds;
451
+ BOOL excluded = G9OverExcluded(self.view, _first);
452
+ // «except the excluded surface»: a tap that landed on it is not the tester's gesture.
453
+ if (tap && !(self.excludeSurfaces && excluded)) [self emit:@"tap" fingers:_maxTouches at:_first mid:_mid excluded:excluded info:nil];
454
+ [self trace:held tap:tap cancelled:NO lost:NO excluded:excluded];
455
+ BOOL holding = self.state == UIGestureRecognizerStateBegan || self.state == UIGestureRecognizerStateChanged;
456
+ self.state = holding ? UIGestureRecognizerStateEnded : UIGestureRecognizerStateFailed;
457
+ }
458
+
459
+ - (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
460
+ [super touchesCancelled:touches withEvent:event];
461
+ [self trace:CACurrentMediaTime() - _down tap:NO cancelled:YES lost:NO excluded:G9OverExcluded(self.view, _first)];
462
+ BOOL holding = self.state == UIGestureRecognizerStateBegan || self.state == UIGestureRecognizerStateChanged;
463
+ self.state = holding ? UIGestureRecognizerStateCancelled : UIGestureRecognizerStateFailed;
464
+ }
465
+
466
+ /** THE TRACE (with `touches` on): every touch that could have been a tap ends with one `seq` report saying why it was or was not. */
467
+ - (void)trace:(CFTimeInterval)seconds tap:(BOOL)tap cancelled:(BOOL)cancelled lost:(BOOL)lost excluded:(BOOL)excluded {
468
+ if (!self.touches || _traced || _maxTouches == 0) return;
469
+ _traced = YES;
470
+ if (_maxTouches < 2 && (seconds > 0.6 || _moved)) return;
471
+ NSString *why = tap ? @"tap" : lost ? @"lost" : cancelled ? @"cancelled" : _maxTouches < 2 ? @"one-finger" : _moved ? @"moved"
472
+ : seconds > kMaxTapSeconds ? @"too-long" : !self.taps ? @"not-watching" : @"other";
473
+ [self emit:@"seq" fingers:_maxTouches at:_first mid:_mid excluded:excluded info:@{
474
+ @"ms" : @(llround(seconds * 1000)), @"secondMs" : @(_secondAt < 0 ? -1 : llround(_secondAt * 1000)),
475
+ @"firstUpMs" : @(_firstUpAt < 0 ? -1 : llround(_firstUpAt * 1000)), @"movePx" : @(llround(_maxMove)), @"slopPx" : @(llround(kSlopPoints * 2)),
476
+ @"radius" : @(llround(_maxRadius)), @"held" : @(_held), @"oldRuleMoved" : @(_firstOnlyMoved), @"why" : why,
477
+ }];
478
+ }
479
+
480
+ - (void)reset {
481
+ if (!_traced && _maxTouches > 0) [self trace:CACurrentMediaTime() - _down tap:NO cancelled:NO lost:YES excluded:NO];
482
+ [super reset];
483
+ _maxTouches = 0;
484
+ _moved = NO;
485
+ [_starts removeAllObjects];
486
+ self.cancelsTouchesInView = NO; // back to watching only: the next touch is the views' until a hold begins
487
+ }
488
+
489
+ @end
490
+
491
+ static G9TesterTouchObserver *gObserver;
492
+
493
+ @implementation G9TouchWatcher
494
+
495
+ + (void)watchTaps:(BOOL)taps touches:(BOOL)touches consume:(BOOL)consume excludeSurfaces:(BOOL)exclude sink:(void (^)(NSString *))sink {
496
+ UIWindow *window = (taps || touches) ? G9AppDiagnosticHost.keyWindow : nil;
497
+ if (!window) {
498
+ if (gObserver.view) [gObserver.view removeGestureRecognizer:gObserver];
499
+ gObserver = nil;
500
+ return;
501
+ }
502
+ if (!gObserver) gObserver = [[G9TesterTouchObserver alloc] init];
503
+ gObserver.taps = taps;
504
+ gObserver.touches = touches;
505
+ gObserver.consume = consume;
506
+ gObserver.excludeSurfaces = exclude;
507
+ gObserver.sink = sink;
508
+ if (gObserver.view != window) {
509
+ if (gObserver.view) [gObserver.view removeGestureRecognizer:gObserver];
510
+ [window addGestureRecognizer:gObserver]; // a scene rebuild replaces the key window: attach to the current one
511
+ }
512
+ }
513
+
514
+ @end
@@ -0,0 +1,32 @@
1
+ // The host's hooks for G9AppDiagnosticModule on iOS (TWIN: android/…/G9AppDiagnosticHost.kt). Set them before the first
2
+ // call, typically in application:didFinishLaunchingWithOptions:. Every hook has a default; none names a product.
3
+ //
4
+ // G9AppDiagnosticHost.urlSession = ^{ return myTrustedSession; }; // its trust rules for the range PUT
5
+ // G9AppDiagnosticHost.allowedRoots = ^{ return @[ supportDir, cachesDir ]; }; // the folders a path may be inside
6
+ // G9AppDiagnosticHost.isExcludedView = ^BOOL(UIView *v) { return [v isKindOfClass:MyMapHost.class]; }; // «except the map»
7
+ #import <Foundation/Foundation.h>
8
+ #import <UIKit/UIKit.h>
9
+
10
+ NS_ASSUME_NONNULL_BEGIN
11
+
12
+ @interface G9AppDiagnosticHost : NSObject
13
+ /** The session sendRange uses (the host's trust, proxy and certificates). Default: NSURLSession.sharedSession. */
14
+ @property(class, nonatomic, copy, nullable) NSURLSession *_Nonnull (^urlSession)(void);
15
+ /** The folders a recording, a screenshot or a sent file may live in. Default: Application Support, Caches, tmp. */
16
+ @property(class, nonatomic, copy, nullable) NSArray<NSString *> *_Nonnull (^allowedRoots)(void);
17
+ /** A view the tester gesture never holds a touch over (a map's own pinch and pan). Default: none. */
18
+ @property(class, nonatomic, copy, nullable) BOOL (^isExcludedView)(UIView *view);
19
+
20
+ /** The folders a path may be inside, resolved (symlinks, «..»). */
21
+ + (NSArray<NSString *> *)roots;
22
+ /** The path resolved, when strictly inside one of the roots (or a root itself, for a folder); else nil. */
23
+ + (nullable NSString *)inside:(nullable NSString *)path folder:(BOOL)folder;
24
+ /** The key window of the foreground scene. */
25
+ + (nullable UIWindow *)keyWindow;
26
+ /** The window as the user sees it (Metal and GL layers included), at a scale (1 = points). */
27
+ + (nullable UIImage *)captureWindowAtScale:(CGFloat)scale;
28
+ /** The window's size in points (zero when there is none). */
29
+ + (CGSize)windowSize;
30
+ @end
31
+
32
+ NS_ASSUME_NONNULL_END
@@ -0,0 +1,36 @@
1
+ // The iOS recorders and the tester gesture of G9AppDiagnosticModule (TWIN: android/…/ScreenRecorder.kt, VoiceRecorder.kt,
2
+ // TouchWatcher.kt + core/TouchCore.kt). Moved here from the first Lynx app's own ios/Platform/AGMedia.mm (2026-11-20) so
3
+ // every Lynx app gets them; no product name, the excluded surface is the host's (G9AppDiagnosticHost.isExcludedView).
4
+ #import <Foundation/Foundation.h>
5
+ #import <UIKit/UIKit.h>
6
+
7
+ NS_ASSUME_NONNULL_BEGIN
8
+
9
+ /** A failure the JS side reads as DiagnosticNativeError(code, message) — the codes of types/g9-app-diagnostic-module.d.ts. */
10
+ @interface G9DiagnosticError : NSError
11
+ + (instancetype)code:(NSString *)code message:(NSString *)message;
12
+ @property(nonatomic, readonly) NSString *diagnosticCode;
13
+ @end
14
+
15
+ @interface G9ScreenRecorder : NSObject
16
+ @property(nonatomic, readonly) BOOL recording;
17
+ + (instancetype)shared;
18
+ - (BOOL)startIn:(NSString *)dir maxFps:(int)maxFps error:(NSError **)error;
19
+ /** Blocks until the file is finalised (call off the main thread). {path, bytes, durationMs, width, height, capped} or nil. */
20
+ - (nullable NSDictionary *)stop;
21
+ @end
22
+
23
+ @interface G9VoiceRecorder : NSObject
24
+ + (instancetype)shared;
25
+ @property(nonatomic, readonly) BOOL recording;
26
+ - (BOOL)startIn:(NSString *)dir error:(NSError **)error;
27
+ /** {path, bytes, durationMs} or nil. */
28
+ - (nullable NSDictionary *)stop;
29
+ @end
30
+
31
+ /** The tester gesture's watcher on the key window; events go to [sink] as JSON text («g9:diagnostic-touch»). */
32
+ @interface G9TouchWatcher : NSObject
33
+ + (void)watchTaps:(BOOL)taps touches:(BOOL)touches consume:(BOOL)consume excludeSurfaces:(BOOL)exclude sink:(void (^)(NSString *json))sink;
34
+ @end
35
+
36
+ NS_ASSUME_NONNULL_END