#import <UIKit/UIKit.h>
#import <CoreGraphics/CoreGraphics.h>
#import <CoreMotion/CoreMotion.h>
#import <Metal/Metal.h>
#import <QuartzCore/QuartzCore.h>
#import <UserNotifications/UserNotifications.h>
#import <WebKit/WebKit.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
@class EuvViewController;
@interface EuvCanvasView : UIView <UIKeyInput, WKNavigationDelegate, WKUIDelegate>
@property (nonatomic, assign) BOOL keyboardVisible;
@property (nonatomic, assign) BOOL immersiveFullscreen;
- (void)setDisplayLinkPaused:(BOOL)paused;
- (void)startDeviceMotionUpdates;
- (void)stopDeviceMotionUpdates;
- (void)ensureLiveSession;
- (void)shutdownSession;
- (void)syncSafeArea;
- (void)syncThemeTrait;
- (void)syncViewportScaleAndBounds;
- (void)presentFrameWithDt:(float)dt force:(BOOL)force;
- (void)openEmbeddedWebViewUrl:(NSString *)urlString title:(NSString *)titleString;
- (void)updateEmbeddedWebViewFrameX:(CGFloat)x y:(CGFloat)y width:(CGFloat)w height:(CGFloat)h alpha:(CGFloat)alpha;
- (void)reloadEmbeddedWebViewFallbackUrl:(NSString *)fallbackUrl;
- (void)closeEmbeddedWebView;
@end
@interface EuvViewController : UIViewController
@property (nonatomic, strong) EuvCanvasView *canvasView;
@property (nonatomic, assign) BOOL immersiveFullscreen;
- (void)applyImmersiveFullscreen:(BOOL)enabled;
@end
static __weak EuvCanvasView *gEuvActiveCanvasView = nil;
static __weak EuvViewController *gEuvActiveViewController = nil;
int32_t euv_ios_invoke_native_action(const char *kind, const char *arg1, const char *arg2) {
NSString *k = kind ? [NSString stringWithUTF8String:kind] : @"";
NSString *a1 = arg1 ? [NSString stringWithUTF8String:arg1] : @"";
NSString *a2 = arg2 ? [NSString stringWithUTF8String:arg2] : @"";
BOOL isFrameSync = [k isEqualToString:@"webview"] && [a1 isEqualToString:@"frame"];
if (!isFrameSync) {
NSLog(@"[euv-native] ios action kind=%@ arg1=%@ arg2=%@", k, a1, a2);
}
dispatch_block_t runBlock = ^{
if ([k isEqualToString:@"webview"]) {
EuvCanvasView *v = gEuvActiveCanvasView;
if (!v) return;
if ([a1 isEqualToString:@"close"]) {
[v closeEmbeddedWebView];
} else if ([a1 isEqualToString:@"reload"]) {
[v reloadEmbeddedWebViewFallbackUrl:a2];
} else if ([a1 isEqualToString:@"frame"]) {
float fx = 0.0f, fy = 0.0f, fw = 0.0f, fh = 0.0f, fa = 0.0f;
if (sscanf(a2.UTF8String, "%f,%f,%f,%f,%f", &fx, &fy, &fw, &fh, &fa) == 5) {
[v updateEmbeddedWebViewFrameX:(CGFloat)fx y:(CGFloat)fy width:(CGFloat)fw height:(CGFloat)fh alpha:(CGFloat)fa];
}
} else if (a1.length > 0) {
[v openEmbeddedWebViewUrl:a1 title:a2];
}
} else if ([k isEqualToString:@"ime"]) {
EuvCanvasView *v = gEuvActiveCanvasView;
if (v) {
if ([a1 isEqualToString:@"show"]) {
if ([v isFirstResponder] && !v.keyboardVisible) {
[v resignFirstResponder];
}
[v becomeFirstResponder];
} else {
[v resignFirstResponder];
}
}
} else if ([k isEqualToString:@"fullscreen"]) {
BOOL enableFs = [a1 isEqualToString:@"on"];
EuvViewController *vc = gEuvActiveViewController;
if (vc) {
[vc applyImmersiveFullscreen:enableFs];
} else if (gEuvActiveCanvasView) {
gEuvActiveCanvasView.immersiveFullscreen = enableFs;
[gEuvActiveCanvasView syncSafeArea];
}
} else if ([k isEqualToString:@"open_url"]) {
NSURL *targetUrl = [NSURL URLWithString:a1];
NSString *scheme = targetUrl.scheme.lowercaseString;
if (targetUrl && ([scheme isEqualToString:@"https"] || [scheme isEqualToString:@"http"])) {
[[UIApplication sharedApplication] openURL:targetUrl options:@{} completionHandler:nil];
}
} else if ([k isEqualToString:@"clipboard"]) {
if (a2.length > 0) {
[UIPasteboard generalPasteboard].string = a2;
}
} else if ([k isEqualToString:@"haptic"]) {
UIImpactFeedbackGenerator *gen = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium];
[gen prepare];
[gen impactOccurred];
} else if ([k isEqualToString:@"notify"] || [k isEqualToString:@"island"]) {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge)
completionHandler:^(BOOL granted, NSError * _Nullable err) {
if (granted) {
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.title = a1.length > 0 ? a1 : @"Euv Studio";
content.body = a2.length > 0 ? a2 : @"Native iOS notification dispatched";
UNNotificationRequest *req = [UNNotificationRequest requestWithIdentifier:[[NSUUID UUID] UUIDString] content:content trigger:nil];
[center addNotificationRequest:req withCompletionHandler:nil];
}
}];
}
};
if ([k isEqualToString:@"webview"] && [NSThread isMainThread]) {
runBlock();
} else {
dispatch_async(dispatch_get_main_queue(), runBlock);
}
return 1;
}
typedef struct EuvIosHandle EuvIosHandle;
typedef struct {
uint32_t x;
uint32_t y;
uint32_t width;
uint32_t height;
} EuvIosDirtyRect;
typedef struct {
uint32_t base_instance;
uint32_t instance_count;
uint32_t scissor_x;
uint32_t scissor_y;
uint32_t scissor_w;
uint32_t scissor_h;
float scroll_x;
float scroll_y;
uint8_t texture_slot;
uint8_t layer_id;
uint8_t pad[2];
} EuvIosBatchRange;
typedef struct {
uint32_t viewport_w;
uint32_t viewport_h;
float clear_rgba[4];
const void *primitives_ptr;
size_t primitives_len;
const EuvIosBatchRange *ranges_ptr;
size_t ranges_len;
const uint8_t *glyph_r8_ptr;
uint32_t glyph_r8_w;
uint32_t glyph_r8_h;
uint64_t glyph_r8_rev;
const uint8_t *image_rgba8_ptr;
uint32_t image_rgba8_w;
uint32_t image_rgba8_h;
uint64_t upload_bytes;
} EuvIosDirectFrameDesc;
typedef struct {
float viewport_w;
float viewport_h;
float scroll_x;
float scroll_y;
} EuvIosLayerUniform;
extern EuvIosHandle *euv_ios_create(uint32_t phys_width, uint32_t phys_height, float scale, int32_t is_ipad, float refresh_hz, float safe_top, float safe_right, float safe_bottom, float safe_left);
extern void euv_ios_destroy(EuvIosHandle *handle);
extern int32_t euv_ios_is_running(EuvIosHandle *handle);
extern void euv_ios_update_refresh_rate(EuvIosHandle *handle, float refresh_hz);
extern void euv_ios_ime_disabled(EuvIosHandle *handle);
extern void euv_ios_system_lifecycle(EuvIosHandle *handle, int32_t tag);
extern void euv_ios_focus(EuvIosHandle *handle, int32_t focused);
extern void euv_ios_keyboard(EuvIosHandle *handle, int32_t visible, float height);
extern void euv_ios_theme(EuvIosHandle *handle, int32_t is_dark);
extern void euv_ios_memory_warning(EuvIosHandle *handle);
extern void euv_ios_low_power(EuvIosHandle *handle, int32_t enabled);
extern void euv_ios_locale(EuvIosHandle *handle, const char *locale);
extern void euv_ios_deep_link(EuvIosHandle *handle, const char *uri);
extern void euv_ios_clipboard_changed(EuvIosHandle *handle);
extern void euv_ios_device_motion(EuvIosHandle *handle, float gx, float gy, float gz, float lx, float ly, float lz, float wx, float wy, float wz, float pitch, float roll, float yaw, uint64_t timestamp_ns);
extern void euv_ios_network(EuvIosHandle *handle, int32_t status_tag);
extern void euv_ios_resize(EuvIosHandle *handle, uint32_t phys_width, uint32_t phys_height, float scale);
extern void euv_ios_set_safe_area(EuvIosHandle *handle, float top, float right, float bottom, float left);
extern void euv_ios_touch_down(EuvIosHandle *handle, uint64_t pointer_id, float x, float y);
extern void euv_ios_touch_move(EuvIosHandle *handle, uint64_t pointer_id, float x, float y);
extern void euv_ios_touch_up(EuvIosHandle *handle, uint64_t pointer_id, float x, float y);
extern void euv_ios_touch_cancel(EuvIosHandle *handle, uint64_t pointer_id);
extern void euv_ios_touch_sync(EuvIosHandle *handle, const uint64_t *ids, size_t count);
extern void euv_ios_text_input(EuvIosHandle *handle, const char *text);
extern void euv_ios_key_down(EuvIosHandle *handle, int32_t key_tag);
extern int32_t euv_ios_step(EuvIosHandle *handle, float dt, const uint8_t **out_ptr, uint32_t *out_w, uint32_t *out_h, uint32_t *out_dx, uint32_t *out_dy, uint32_t *out_dw, uint32_t *out_dh);
extern const char *euv_ios_msl_ui_shader_source(EuvIosHandle *handle);
extern int32_t euv_ios_configure_metal_capabilities(EuvIosHandle *handle, int32_t direct_gpu_ready, int32_t upload_ready);
extern void euv_ios_record_display_link(EuvIosHandle *handle, double timestamp_secs, double target_timestamp_secs);
extern void euv_ios_record_metal_presented(EuvIosHandle *handle, double presented_time_secs, uint64_t gpu_exec_us);
extern int32_t euv_ios_handle_metal_fault(EuvIosHandle *handle, int32_t fault_tag);
extern int32_t euv_ios_active_present_path(EuvIosHandle *handle);
extern int32_t euv_ios_cpu_mirror_active(EuvIosHandle *handle);
extern int32_t euv_ios_upload_strategy(EuvIosHandle *handle);
extern uint64_t euv_ios_last_upload_bytes(EuvIosHandle *handle);
extern int32_t euv_ios_timing_source(EuvIosHandle *handle);
extern int32_t euv_ios_step_direct_gpu(EuvIosHandle *handle, float dt, int32_t force, EuvIosDirectFrameDesc *out_desc);
extern void euv_ios_commit_direct_gpu_present(EuvIosHandle *handle, uint64_t glyph_rev);
extern int32_t euv_ios_step_upload_plan(EuvIosHandle *handle, float dt, int32_t force, const uint8_t **out_ptr, uint32_t *out_w, uint32_t *out_h, const EuvIosDirtyRect **out_rects_ptr, size_t *out_rects_len, int32_t *out_strategy);
extern void euv_ios_commit_fallback_present(EuvIosHandle *handle, int32_t used_metal_upload);
@interface EuvCanvasView ()
@property (nonatomic, assign) EuvIosHandle *handle;
@property (nonatomic, strong) CADisplayLink *displayLink;
@property (nonatomic, assign) CFTimeInterval lastTimestamp;
@property (nonatomic, assign) CGColorSpaceRef colorSpace;
@property (nonatomic, strong) id<MTLDevice> metalDevice;
@property (nonatomic, strong) id<MTLCommandQueue> metalQueue;
@property (nonatomic, strong) id<MTLRenderPipelineState> directUiPipeline;
@property (nonatomic, strong) id<MTLRenderPipelineState> blitPipeline;
@property (nonatomic, strong) id<MTLBuffer> directInstanceBuf0;
@property (nonatomic, strong) id<MTLBuffer> directInstanceBuf1;
@property (nonatomic, strong) id<MTLBuffer> directInstanceBuf2;
@property (nonatomic, strong) id<MTLTexture> glyphR8Tex;
@property (nonatomic, strong) id<MTLTexture> glyphRgba8Tex;
@property (nonatomic, strong) id<MTLTexture> imageTex;
@property (nonatomic, strong) id<MTLTexture> externalTex;
@property (nonatomic, strong) id<MTLTexture> uploadTex;
@property (nonatomic, assign) uint32_t stagingSlot;
@property (nonatomic, assign) uint32_t stagingW;
@property (nonatomic, assign) uint32_t stagingH;
@property (nonatomic, strong) dispatch_semaphore_t inFlightSemaphore;
@property (nonatomic, assign) BOOL hasPresentedFirstFrame;
@property (nonatomic, assign) uint32_t lastPhysW;
@property (nonatomic, assign) uint32_t lastPhysH;
@property (nonatomic, assign) CGFloat lastLogicalW;
@property (nonatomic, assign) CGFloat lastLogicalH;
@property (nonatomic, assign) CGFloat lastScale;
@property (nonatomic, assign) float targetRefreshHz;
@property (nonatomic, assign) UIEdgeInsets lastDispatchedSafeArea;
@property (nonatomic, assign) UIEdgeInsets cachedHardwareSafeArea;
@property (nonatomic, assign) CGSize cachedHardwareSafeSize;
@property (nonatomic, assign) uint64_t renderedFrames;
@property (nonatomic, assign) double accumRenderMs;
@property (nonatomic, assign) double maxRenderMs;
@property (nonatomic, assign) uint64_t droppedFrames;
@property (nonatomic, strong) CMMotionManager *motionManager;
@property (nonatomic, strong) UIView *webContainerView;
@property (nonatomic, strong) WKWebView *embeddedWebView;
@property (nonatomic, strong) UIProgressView *webProgressView;
@property (nonatomic, copy) NSString *activeWebUrl;
@property (nonatomic, assign) BOOL webSheetOpen;
@property (nonatomic, assign) NSUInteger webNavGeneration;
@end
@implementation EuvCanvasView
+ (Class)layerClass {
return [CAMetalLayer class];
}
- (void)startDeviceMotionUpdates {
if (!_motionManager) {
_motionManager = [[CMMotionManager alloc] init];
}
if (!_motionManager.isDeviceMotionAvailable || _motionManager.isDeviceMotionActive) {
return;
}
double maxHz = fmax((double)_targetRefreshHz, 60.0);
_motionManager.deviceMotionUpdateInterval = 1.0 / maxHz;
__weak EuvCanvasView *weakSelf = self;
[_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]
withHandler:^(CMDeviceMotion *motion, NSError *error) {
EuvCanvasView *strongSelf = weakSelf;
if (!strongSelf || !strongSelf.handle || !motion || error) {
return;
}
const float G = 9.80665f;
float dx = (float)motion.gravity.x;
float dy = (float)motion.gravity.y;
float dz = (float)motion.gravity.z;
float ux = (float)motion.userAcceleration.x;
float uy = (float)motion.userAcceleration.y;
float uz = (float)motion.userAcceleration.z;
float rx = (float)motion.rotationRate.x;
float ry = (float)motion.rotationRate.y;
float rz = (float)motion.rotationRate.z;
UIInterfaceOrientation orient = UIInterfaceOrientationPortrait;
if (strongSelf.window && strongSelf.window.windowScene) {
orient = strongSelf.window.windowScene.interfaceOrientation;
}
float sx = dx, sy = dy;
float sux = ux, suy = uy;
float srx = rx, sry = ry;
if (orient == UIInterfaceOrientationLandscapeRight) {
sx = -dy; sy = dx;
sux = -uy; suy = ux;
srx = -ry; sry = rx;
} else if (orient == UIInterfaceOrientationLandscapeLeft) {
sx = dy; sy = -dx;
sux = uy; suy = -ux;
srx = ry; sry = -rx;
} else if (orient == UIInterfaceOrientationPortraitUpsideDown) {
sx = -dx; sy = -dy;
sux = -ux; suy = -uy;
srx = -rx; sry = -ry;
}
float gx = sx * G;
float gy = -sy * G;
float gz = dz * G;
float lx = sux * G;
float ly = -suy * G;
float lz = uz * G;
float roll = atan2f(gx, gy);
float pitch = atan2f(-gz, hypotf(gx, gy));
float yaw = (float)motion.attitude.yaw;
uint64_t tsNs = (uint64_t)(fmax(0.0, motion.timestamp) * 1e9);
euv_ios_device_motion(strongSelf.handle, gx, gy, gz, lx, ly, lz, srx, sry, rz, pitch, roll, yaw, tsNs);
}];
}
- (void)stopDeviceMotionUpdates {
if (_motionManager && _motionManager.isDeviceMotionActive) {
[_motionManager stopDeviceMotionUpdates];
}
}
- (void)shutdownSession {
[self closeEmbeddedWebView];
if (_embeddedWebView) {
_embeddedWebView.navigationDelegate = nil;
_embeddedWebView.UIDelegate = nil;
[_embeddedWebView removeFromSuperview];
_embeddedWebView = nil;
}
if (_webContainerView) {
[_webContainerView removeFromSuperview];
_webContainerView = nil;
}
_webProgressView = nil;
[self stopDeviceMotionUpdates];
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (_displayLink) {
[_displayLink invalidate];
_displayLink = nil;
}
if (gEuvActiveCanvasView == self) {
gEuvActiveCanvasView = nil;
}
if (_handle) {
EuvIosHandle *closing = _handle;
_handle = NULL;
euv_ios_touch_cancel(closing, 0);
euv_ios_system_lifecycle(closing, 6);
euv_ios_destroy(closing);
}
_uploadTex = nil;
_directInstanceBuf0 = nil;
_directInstanceBuf1 = nil;
_directInstanceBuf2 = nil;
_stagingW = 0;
_stagingH = 0;
_hasPresentedFirstFrame = NO;
_lastPhysW = 0;
_lastPhysH = 0;
}
- (void)ensureLiveSession {
if (_handle && euv_ios_is_running(_handle) != 0) {
return;
}
if (_handle) {
EuvIosHandle *stale = _handle;
_handle = NULL;
euv_ios_destroy(stale);
}
CGFloat rawScale = self.traitCollection.displayScale > 0
? self.traitCollection.displayScale
: (self.window.screen.scale > 0 ? self.window.screen.scale : UIScreen.mainScreen.scale);
CGFloat scale = fmin(4.5, rawScale);
CGFloat w = self.bounds.size.width > 0 ? self.bounds.size.width : 393.0;
CGFloat h = self.bounds.size.height > 0 ? self.bounds.size.height : 852.0;
uint32_t physW = (uint32_t)llround(w * scale);
uint32_t physH = (uint32_t)llround(h * scale);
int32_t isIpad = (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) ? 1 : 0;
UIEdgeInsets initSafe = [self resolveEffectiveSafeArea];
_lastDispatchedSafeArea = initSafe;
_handle = euv_ios_create(
physW,
physH,
(float)scale,
isIpad,
_targetRefreshHz,
(float)initSafe.top,
(float)initSafe.right,
(float)initSafe.bottom,
(float)initSafe.left
);
if (_handle) {
euv_ios_configure_metal_capabilities(
_handle,
(_directUiPipeline != nil && _metalQueue != nil) ? 1 : 0,
(_blitPipeline != nil && _metalQueue != nil) ? 1 : 0
);
}
[self syncThemeTrait];
[self startDeviceMotionUpdates];
}
- (void)dealloc {
[self shutdownSession];
if (_colorSpace) {
CGColorSpaceRelease(_colorSpace);
_colorSpace = NULL;
}
}
- (void)setDisplayLinkPaused:(BOOL)paused {
if (_displayLink) {
_displayLink.paused = paused;
if (!paused) {
_lastTimestamp = 0.0;
}
}
}
- (float)nominalFrameDt {
float hz = _targetRefreshHz >= 24.0f ? _targetRefreshHz : 60.0f;
return 1.0f / hz;
}
- (void)onStatusBarOrCaptureChanged:(NSNotification *)note {
(void)note;
[self syncSafeArea];
[self presentFrameWithDt:[self nominalFrameDt] force:YES];
}
- (void)onKeyboardWillShow:(NSNotification *)note {
_keyboardVisible = YES;
CGFloat kbH = 0.0;
NSValue *rectVal = note.userInfo[UIKeyboardFrameEndUserInfoKey];
if (rectVal) {
kbH = [rectVal CGRectValue].size.height;
}
if (_handle) {
euv_ios_keyboard(_handle, 1, (float)kbH);
}
}
- (void)onKeyboardDidHide:(NSNotification *)note {
(void)note;
_keyboardVisible = NO;
if (_handle) {
euv_ios_keyboard(_handle, 0, 0.0f);
euv_ios_ime_disabled(_handle);
}
}
- (void)onMemoryWarning:(NSNotification *)note {
(void)note;
if (_handle) {
euv_ios_memory_warning(_handle);
}
}
- (void)onPowerStateChanged:(NSNotification *)note {
(void)note;
if (_handle) {
BOOL lowPower = [[NSProcessInfo processInfo] isLowPowerModeEnabled];
euv_ios_low_power(_handle, lowPower ? 1 : 0);
}
}
- (void)onPasteboardChanged:(NSNotification *)note {
(void)note;
if (_handle) {
euv_ios_clipboard_changed(_handle);
}
}
- (void)onLocaleChanged:(NSNotification *)note {
(void)note;
if (_handle) {
NSString *loc = [[NSLocale currentLocale] localeIdentifier];
if (loc.length > 0) {
euv_ios_locale(_handle, [loc UTF8String]);
}
}
}
- (void)syncThemeTrait {
if (!_handle) return;
BOOL isDark = (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark);
euv_ios_theme(_handle, isDark ? 1 : 0);
}
- (UIEdgeInsets)resolveEffectiveSafeArea {
UIEdgeInsets insets = self.safeAreaInsets;
if (self.window) {
UIEdgeInsets winInsets = self.window.safeAreaInsets;
if (winInsets.top > insets.top) insets.top = winInsets.top;
if (winInsets.right > insets.right) insets.right = winInsets.right;
if (winInsets.bottom > insets.bottom) insets.bottom = winInsets.bottom;
if (winInsets.left > insets.left) insets.left = winInsets.left;
if (self.window.windowScene && self.window.windowScene.statusBarManager) {
CGRect sbFrame = self.window.windowScene.statusBarManager.statusBarFrame;
CGSize winSize = self.window.bounds.size;
if (sbFrame.size.width >= 8.0 && sbFrame.size.height >= 8.0) {
if (sbFrame.size.width >= sbFrame.size.height) {
if (sbFrame.origin.y <= 10.0 && sbFrame.size.height > insets.top) {
insets.top = sbFrame.size.height;
} else if (sbFrame.origin.y + sbFrame.size.height >= winSize.height - 10.0
&& sbFrame.size.height > insets.bottom) {
insets.bottom = sbFrame.size.height;
}
} else {
if (sbFrame.origin.x <= 10.0 && sbFrame.size.width > insets.left) {
insets.left = sbFrame.size.width;
} else if (sbFrame.origin.x + sbFrame.size.width >= winSize.width - 10.0
&& sbFrame.size.width > insets.right) {
insets.right = sbFrame.size.width;
}
}
}
}
}
BOOL isIpad = (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad);
CGSize curSize = self.bounds.size;
if (curSize.width < 1.0 && self.window) {
curSize = self.window.bounds.size;
}
if (!_immersiveFullscreen) {
if (insets.top >= 20.0 || insets.right >= 20.0 || insets.left >= 20.0) {
_cachedHardwareSafeArea = insets;
_cachedHardwareSafeSize = curSize;
}
} else if (_cachedHardwareSafeSize.width > 1.0 && _cachedHardwareSafeSize.height > 1.0) {
BOOL sameSize = fabs(curSize.width - _cachedHardwareSafeSize.width) <= 2.0
&& fabs(curSize.height - _cachedHardwareSafeSize.height) <= 2.0;
if (sameSize) {
if (_cachedHardwareSafeArea.top > insets.top) insets.top = _cachedHardwareSafeArea.top;
if (_cachedHardwareSafeArea.right > insets.right) insets.right = _cachedHardwareSafeArea.right;
if (_cachedHardwareSafeArea.bottom > insets.bottom) insets.bottom = _cachedHardwareSafeArea.bottom;
if (_cachedHardwareSafeArea.left > insets.left) insets.left = _cachedHardwareSafeArea.left;
} else if (insets.top < 20.0 && insets.right < 20.0 && insets.left < 20.0) {
CGFloat maxCutout = fmax(_cachedHardwareSafeArea.top, fmax(_cachedHardwareSafeArea.right, _cachedHardwareSafeArea.left));
if (maxCutout >= 72.0) {
if (curSize.width > curSize.height) {
insets.right = maxCutout;
} else {
insets.top = maxCutout;
}
}
}
}
BOOL hasSideOrBottomRail = (insets.left >= 20.0 || insets.right >= 20.0 || insets.bottom >= 44.0);
if (isIpad) {
if (insets.top < 1.0 && !hasSideOrBottomRail) {
insets.top = 24.0;
}
} else if (insets.top < 20.0 && !hasSideOrBottomRail) {
CGSize refBounds = (curSize.width > 1.0 && curSize.height > 1.0) ? curSize : UIScreen.mainScreen.bounds.size;
CGFloat screenH = fmax(refBounds.width, refBounds.height);
insets.top = (screenH >= 812.0) ? 47.0 : 20.0;
if (insets.bottom < 1.0 && screenH >= 812.0) {
insets.bottom = 34.0;
}
}
return insets;
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor systemBackgroundColor];
self.opaque = YES;
self.multipleTouchEnabled = YES;
gEuvActiveCanvasView = self;
_keyboardVisible = NO;
_immersiveFullscreen = NO;
_lastDispatchedSafeArea = UIEdgeInsetsMake(-1, -1, -1, -1);
_cachedHardwareSafeArea = UIEdgeInsetsZero;
_cachedHardwareSafeSize = CGSizeZero;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onKeyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onKeyboardDidHide:)
name:UIKeyboardDidHideNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onMemoryWarning:)
name:UIApplicationDidReceiveMemoryWarningNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onPowerStateChanged:)
name:NSProcessInfoPowerStateDidChangeNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onPasteboardChanged:)
name:UIPasteboardChangedNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onLocaleChanged:)
name:NSCurrentLocaleDidChangeNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onStatusBarOrCaptureChanged:)
name:UIScreenCapturedDidChangeNotification
object:nil];
_colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat scale = fmin(4.5, UIScreen.mainScreen.scale);
self.layer.contentsScale = scale;
self.layer.magnificationFilter = kCAFilterNearest;
self.layer.minificationFilter = kCAFilterLinear;
if ([self.layer isKindOfClass:[CAMetalLayer class]]) {
_metalDevice = MTLCreateSystemDefaultDevice();
if (_metalDevice) {
CAMetalLayer *ml = (CAMetalLayer *)self.layer;
ml.device = _metalDevice;
ml.pixelFormat = MTLPixelFormatBGRA8Unorm;
ml.framebufferOnly = YES;
ml.maximumDrawableCount = 3;
ml.presentsWithTransaction = NO;
ml.contentsScale = scale;
_metalQueue = [_metalDevice newCommandQueue];
_inFlightSemaphore = dispatch_semaphore_create(2);
NSString *msl = @"#include <metal_stdlib>\nusing namespace metal;\nstruct VsOut{float4 pos [[position]];float2 uv;};\nvertex VsOut euv_ios_blit_vs(uint vid [[vertex_id]]){float2 p=float2((vid==1)?3.0:-1.0,(vid==2)?-3.0:1.0);VsOut o;o.pos=float4(p,0.0,1.0);o.uv=float2(p.x*0.5+0.5,0.5-p.y*0.5);return o;}\nfragment float4 euv_ios_blit_fs(VsOut in [[stage_in]],texture2d<float> tex [[texture(0)]]){constexpr sampler s(filter::nearest,address::clamp_to_edge);return tex.sample(s,in.uv);}\n";
NSError *err = nil;
id<MTLLibrary> lib = [_metalDevice newLibraryWithSource:msl options:nil error:&err];
if (lib) {
MTLRenderPipelineDescriptor *pdesc = [[MTLRenderPipelineDescriptor alloc] init];
pdesc.vertexFunction = [lib newFunctionWithName:@"euv_ios_blit_vs"];
pdesc.fragmentFunction = [lib newFunctionWithName:@"euv_ios_blit_fs"];
pdesc.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm;
_blitPipeline = [_metalDevice newRenderPipelineStateWithDescriptor:pdesc error:&err];
}
}
}
NSInteger maxHz = UIScreen.mainScreen.maximumFramesPerSecond;
if (maxHz < 60) maxHz = 120;
_targetRefreshHz = (float)maxHz;
CGFloat w = frame.size.width > 0 ? frame.size.width : 393.0;
CGFloat h = frame.size.height > 0 ? frame.size.height : 852.0;
uint32_t physW = (uint32_t)llround(w * scale);
uint32_t physH = (uint32_t)llround(h * scale);
int32_t isIpad = (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad) ? 1 : 0;
UIEdgeInsets initSafe = [self resolveEffectiveSafeArea];
_lastDispatchedSafeArea = initSafe;
_lastLogicalW = w;
_lastLogicalH = h;
_lastScale = scale;
_lastPhysW = physW;
_lastPhysH = physH;
_hasPresentedFirstFrame = NO;
_handle = euv_ios_create(
physW,
physH,
(float)scale,
isIpad,
_targetRefreshHz,
(float)initSafe.top,
(float)initSafe.right,
(float)initSafe.bottom,
(float)initSafe.left
);
if (_metalDevice && _handle) {
const char *directSrcC = euv_ios_msl_ui_shader_source(_handle);
if (directSrcC && directSrcC[0] != '\0') {
NSString *directMsl = [NSString stringWithUTF8String:directSrcC];
NSError *dErr = nil;
id<MTLLibrary> dLib = [_metalDevice newLibraryWithSource:directMsl options:nil error:&dErr];
if (dLib) {
MTLRenderPipelineDescriptor *dpd = [[MTLRenderPipelineDescriptor alloc] init];
dpd.vertexFunction = [dLib newFunctionWithName:@"euv_ui_vertex"];
dpd.fragmentFunction = [dLib newFunctionWithName:@"euv_ui_fragment"];
MTLRenderPipelineColorAttachmentDescriptor *att = dpd.colorAttachments[0];
att.pixelFormat = MTLPixelFormatBGRA8Unorm;
att.blendingEnabled = YES;
att.rgbBlendOperation = MTLBlendOperationAdd;
att.alphaBlendOperation = MTLBlendOperationAdd;
att.sourceRGBBlendFactor = MTLBlendFactorSourceAlpha;
att.destinationRGBBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
att.sourceAlphaBlendFactor = MTLBlendFactorOne;
att.destinationAlphaBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
_directUiPipeline = [_metalDevice newRenderPipelineStateWithDescriptor:dpd error:&dErr];
}
}
MTLTextureDescriptor *r8d = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatR8Unorm width:1 height:1 mipmapped:NO];
r8d.usage = MTLTextureUsageShaderRead;
r8d.storageMode = MTLStorageModeShared;
_glyphR8Tex = [_metalDevice newTextureWithDescriptor:r8d];
uint8_t oneR8 = 255;
[_glyphR8Tex replaceRegion:MTLRegionMake2D(0, 0, 1, 1) mipmapLevel:0 withBytes:&oneR8 bytesPerRow:1];
MTLTextureDescriptor *rgbaD = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm width:1 height:1 mipmapped:NO];
rgbaD.usage = MTLTextureUsageShaderRead;
rgbaD.storageMode = MTLStorageModeShared;
uint8_t oneRgba[4] = {255, 255, 255, 255};
_glyphRgba8Tex = [_metalDevice newTextureWithDescriptor:rgbaD];
[_glyphRgba8Tex replaceRegion:MTLRegionMake2D(0, 0, 1, 1) mipmapLevel:0 withBytes:oneRgba bytesPerRow:4];
_imageTex = [_metalDevice newTextureWithDescriptor:rgbaD];
[_imageTex replaceRegion:MTLRegionMake2D(0, 0, 1, 1) mipmapLevel:0 withBytes:oneRgba bytesPerRow:4];
_externalTex = [_metalDevice newTextureWithDescriptor:rgbaD];
[_externalTex replaceRegion:MTLRegionMake2D(0, 0, 1, 1) mipmapLevel:0 withBytes:oneRgba bytesPerRow:4];
euv_ios_configure_metal_capabilities(
_handle,
(_directUiPipeline != nil && _metalQueue != nil) ? 1 : 0,
(_blitPipeline != nil && _metalQueue != nil) ? 1 : 0
);
} else if (_handle) {
euv_ios_configure_metal_capabilities(_handle, 0, 0);
}
if (@available(iOS 17.0, *)) {
[self registerForTraitChanges:@[UITraitDisplayScale.class] withTarget:self action:@selector(syncViewportScaleAndBounds)];
[self registerForTraitChanges:@[UITraitUserInterfaceStyle.class] withTarget:self action:@selector(syncThemeTrait)];
}
[self syncThemeTrait];
_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(onDisplayLink:)];
if (@available(iOS 15.0, *)) {
float maxRangeHz = fmaxf(_targetRefreshHz, 480.0f);
_displayLink.preferredFrameRateRange = CAFrameRateRangeMake(60.0f, maxRangeHz, _targetRefreshHz);
} else {
_displayLink.preferredFramesPerSecond = (NSInteger)_targetRefreshHz;
}
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}
return self;
}
- (void)syncSafeArea {
if (!_handle) return;
UIEdgeInsets insets = [self resolveEffectiveSafeArea];
if (fabs(insets.top - _lastDispatchedSafeArea.top) < 0.25
&& fabs(insets.right - _lastDispatchedSafeArea.right) < 0.25
&& fabs(insets.bottom - _lastDispatchedSafeArea.bottom) < 0.25
&& fabs(insets.left - _lastDispatchedSafeArea.left) < 0.25) {
return;
}
_lastDispatchedSafeArea = insets;
UIEdgeInsets selfIn = self.safeAreaInsets;
UIEdgeInsets winIn = self.window ? self.window.safeAreaInsets : UIEdgeInsetsZero;
CGRect sbRect = (self.window && self.window.windowScene && self.window.windowScene.statusBarManager)
? self.window.windowScene.statusBarManager.statusBarFrame
: CGRectZero;
NSLog(@"[euv-safe-area] vp=%.1fx%.1f self=(%.1f,%.1f,%.1f,%.1f) win=(%.1f,%.1f,%.1f,%.1f) sb=(%.1f,%.1f,%.1f,%.1f) resolved=(%.1f,%.1f,%.1f,%.1f)",
self.bounds.size.width, self.bounds.size.height,
selfIn.top, selfIn.right, selfIn.bottom, selfIn.left,
winIn.top, winIn.right, winIn.bottom, winIn.left,
sbRect.origin.x, sbRect.origin.y, sbRect.size.width, sbRect.size.height,
insets.top, insets.right, insets.bottom, insets.left);
euv_ios_set_safe_area(_handle, (float)insets.top, (float)insets.right, (float)insets.bottom, (float)insets.left);
}
- (void)safeAreaInsetsDidChange {
[super safeAreaInsetsDidChange];
[self syncSafeArea];
if (_hasPresentedFirstFrame) {
[self presentFrameWithDt:[self nominalFrameDt] force:YES];
}
}
- (void)didMoveToWindow {
[super didMoveToWindow];
if (!self.window && _handle) {
euv_ios_touch_cancel(_handle, 0);
return;
}
if (self.window.screen) {
NSInteger maxHz = self.window.screen.maximumFramesPerSecond;
if (maxHz >= 60 && fabs((float)maxHz - _targetRefreshHz) > 0.5f) {
_targetRefreshHz = (float)maxHz;
if (_handle) {
euv_ios_update_refresh_rate(_handle, _targetRefreshHz);
}
if (_displayLink) {
if (@available(iOS 15.0, *)) {
float maxRangeHz = fmaxf(_targetRefreshHz, 480.0f);
_displayLink.preferredFrameRateRange = CAFrameRateRangeMake(60.0f, maxRangeHz, _targetRefreshHz);
} else {
_displayLink.preferredFramesPerSecond = (NSInteger)_targetRefreshHz;
}
}
}
}
[self syncViewportScaleAndBounds];
}
- (void)syncViewportScaleAndBounds {
if (!_handle) return;
if (self.window) {
CGRect wb = self.window.bounds;
if (wb.size.width > 0 && wb.size.height > 0 && !CGRectEqualToRect(self.frame, wb)) {
[super setFrame:wb];
}
}
if (self.bounds.size.width <= 0 || self.bounds.size.height <= 0) return;
CGFloat rawScale = self.traitCollection.displayScale > 0
? self.traitCollection.displayScale
: (self.window.screen.scale > 0 ? self.window.screen.scale : UIScreen.mainScreen.scale);
CGFloat scale = fmin(4.5, rawScale);
uint32_t physW = (uint32_t)llround(self.bounds.size.width * scale);
uint32_t physH = (uint32_t)llround(self.bounds.size.height * scale);
BOOL geomChanged = (physW != _lastPhysW) || (physH != _lastPhysH) || (fabs(scale - _lastScale) > 0.01);
if (!geomChanged && _hasPresentedFirstFrame) {
[self syncSafeArea];
return;
}
_lastLogicalW = self.bounds.size.width;
_lastLogicalH = self.bounds.size.height;
_lastScale = scale;
_lastPhysW = physW;
_lastPhysH = physH;
self.layer.contentsScale = scale;
if ([self.layer isKindOfClass:[CAMetalLayer class]]) {
CAMetalLayer *ml = (CAMetalLayer *)self.layer;
ml.contentsScale = scale;
ml.drawableSize = CGSizeMake(physW, physH);
}
euv_ios_resize(_handle, physW, physH, (float)scale);
[self syncSafeArea];
if (_hasPresentedFirstFrame) {
[self presentFrameWithDt:[self nominalFrameDt] force:YES];
}
}
- (void)layoutSubviews {
[super layoutSubviews];
[self syncViewportScaleAndBounds];
if (!_hasPresentedFirstFrame && self.window && self.bounds.size.width > 0 && self.bounds.size.height > 0) {
_hasPresentedFirstFrame = YES;
[self presentFrameWithDt:[self nominalFrameDt] force:YES];
}
}
- (void)setBounds:(CGRect)bounds {
[super setBounds:bounds];
if (_hasPresentedFirstFrame) {
[self syncViewportScaleAndBounds];
}
}
- (void)setFrame:(CGRect)frame {
[super setFrame:frame];
if (_hasPresentedFirstFrame) {
[self syncViewportScaleAndBounds];
}
}
- (void)onDisplayLink:(CADisplayLink *)link {
CFTimeInterval now = link.timestamp;
if (_handle) {
euv_ios_record_display_link(_handle, (double)now, (double)link.targetTimestamp);
}
float fallbackHz = _targetRefreshHz > 0.0f ? _targetRefreshHz : 60.0f;
float dt = (_lastTimestamp > 0.0) ? (float)(now - _lastTimestamp) : (1.0f / fallbackHz);
_lastTimestamp = now;
CGFloat curW = self.window && self.window.bounds.size.width > 0 ? self.window.bounds.size.width : self.bounds.size.width;
CGFloat curH = self.window && self.window.bounds.size.height > 0 ? self.window.bounds.size.height : self.bounds.size.height;
CGFloat rawScale = self.traitCollection.displayScale > 0
? self.traitCollection.displayScale
: (self.window.screen.scale > 0 ? self.window.screen.scale : UIScreen.mainScreen.scale);
CGFloat curScale = fmin(4.5, rawScale);
if (fabs(curW - _lastLogicalW) > 0.5 || fabs(curH - _lastLogicalH) > 0.5 || fabs(curScale - _lastScale) > 0.01) {
[self syncViewportScaleAndBounds];
return;
}
if (!_hasPresentedFirstFrame && self.window && curW > 0 && curH > 0) {
_hasPresentedFirstFrame = YES;
[self presentFrameWithDt:dt force:YES];
return;
}
[self presentFrameWithDt:dt force:NO];
}
- (id<MTLBuffer>)acquireDirectInstanceBufferForBytes:(NSUInteger)neededBytes {
NSUInteger allocBytes = neededBytes < 4096 ? 4096 : neededBytes;
uint32_t slot = _stagingSlot % 3u;
_stagingSlot += 1u;
id<MTLBuffer> current = (slot == 0u) ? _directInstanceBuf0 : ((slot == 1u) ? _directInstanceBuf1 : _directInstanceBuf2);
if (!current || current.length < allocBytes) {
NSUInteger grow = allocBytes;
if (current && current.length * 2 > grow) {
grow = current.length * 2;
}
current = [_metalDevice newBufferWithLength:grow options:MTLResourceStorageModeShared];
if (slot == 0u) {
_directInstanceBuf0 = current;
} else if (slot == 1u) {
_directInstanceBuf1 = current;
} else {
_directInstanceBuf2 = current;
}
}
return current;
}
- (BOOL)presentMetalDirectFrame:(const EuvIosDirectFrameDesc *)frame {
if (!frame || !_metalDevice || !_metalQueue || !_directUiPipeline || ![self.layer isKindOfClass:[CAMetalLayer class]]) {
return NO;
}
uint32_t w = frame->viewport_w;
uint32_t h = frame->viewport_h;
if (w == 0 || h == 0) {
return NO;
}
CAMetalLayer *ml = (CAMetalLayer *)self.layer;
if ((uint32_t)llround(ml.drawableSize.width) != w || (uint32_t)llround(ml.drawableSize.height) != h) {
ml.drawableSize = CGSizeMake(w, h);
}
if (_inFlightSemaphore) {
dispatch_semaphore_wait(_inFlightSemaphore, DISPATCH_TIME_FOREVER);
}
if (frame->glyph_r8_ptr && frame->glyph_r8_w > 0 && frame->glyph_r8_h > 0) {
if (!_glyphR8Tex || _glyphR8Tex.width != frame->glyph_r8_w || _glyphR8Tex.height != frame->glyph_r8_h) {
MTLTextureDescriptor *gd = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatR8Unorm
width:frame->glyph_r8_w
height:frame->glyph_r8_h
mipmapped:NO];
gd.usage = MTLTextureUsageShaderRead;
gd.storageMode = MTLStorageModeShared;
_glyphR8Tex = [_metalDevice newTextureWithDescriptor:gd];
}
if (_glyphR8Tex) {
[_glyphR8Tex replaceRegion:MTLRegionMake2D(0, 0, frame->glyph_r8_w, frame->glyph_r8_h)
mipmapLevel:0
withBytes:frame->glyph_r8_ptr
bytesPerRow:frame->glyph_r8_w];
}
}
if (frame->image_rgba8_ptr && frame->image_rgba8_w > 0 && frame->image_rgba8_h > 0) {
if (!_imageTex || _imageTex.width != frame->image_rgba8_w || _imageTex.height != frame->image_rgba8_h) {
MTLTextureDescriptor *idsc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
width:frame->image_rgba8_w
height:frame->image_rgba8_h
mipmapped:NO];
idsc.usage = MTLTextureUsageShaderRead;
idsc.storageMode = MTLStorageModeShared;
_imageTex = [_metalDevice newTextureWithDescriptor:idsc];
}
if (_imageTex) {
[_imageTex replaceRegion:MTLRegionMake2D(0, 0, frame->image_rgba8_w, frame->image_rgba8_h)
mipmapLevel:0
withBytes:frame->image_rgba8_ptr
bytesPerRow:(NSUInteger)frame->image_rgba8_w * 4];
}
}
NSUInteger primBytes = (NSUInteger)frame->primitives_len * 64u;
id<MTLBuffer> instBuf = nil;
if (primBytes > 0 && frame->primitives_ptr) {
instBuf = [self acquireDirectInstanceBufferForBytes:primBytes];
if (!instBuf || !instBuf.contents) {
if (_inFlightSemaphore) dispatch_semaphore_signal(_inFlightSemaphore);
return NO;
}
memcpy(instBuf.contents, frame->primitives_ptr, primBytes);
}
id<CAMetalDrawable> drawable = [ml nextDrawable];
if (!drawable || !drawable.texture) {
if (_inFlightSemaphore) dispatch_semaphore_signal(_inFlightSemaphore);
return NO;
}
NSUInteger drawW = drawable.texture.width;
NSUInteger drawH = drawable.texture.height;
MTLRenderPassDescriptor *rpd = [MTLRenderPassDescriptor renderPassDescriptor];
rpd.colorAttachments[0].texture = drawable.texture;
rpd.colorAttachments[0].loadAction = MTLLoadActionClear;
rpd.colorAttachments[0].storeAction = MTLStoreActionStore;
rpd.colorAttachments[0].clearColor = MTLClearColorMake(
frame->clear_rgba[0],
frame->clear_rgba[1],
frame->clear_rgba[2],
frame->clear_rgba[3]
);
id<MTLCommandBuffer> cmd = [_metalQueue commandBuffer];
if (!cmd) {
if (_inFlightSemaphore) dispatch_semaphore_signal(_inFlightSemaphore);
return NO;
}
id<MTLRenderCommandEncoder> enc = [cmd renderCommandEncoderWithDescriptor:rpd];
if (enc && instBuf && frame->ranges_ptr && frame->ranges_len > 0) {
[enc setRenderPipelineState:_directUiPipeline];
[enc setVertexBuffer:instBuf offset:0 atIndex:0];
if (_glyphR8Tex) [enc setFragmentTexture:_glyphR8Tex atIndex:0];
if (_glyphRgba8Tex) [enc setFragmentTexture:_glyphRgba8Tex atIndex:1];
if (_imageTex) [enc setFragmentTexture:_imageTex atIndex:2];
if (_externalTex) [enc setFragmentTexture:_externalTex atIndex:3];
for (size_t i = 0; i < frame->ranges_len; ++i) {
EuvIosBatchRange r = frame->ranges_ptr[i];
if (r.instance_count == 0) continue;
EuvIosLayerUniform u = { (float)drawW, (float)drawH, r.scroll_x, r.scroll_y };
[enc setVertexBytes:&u length:sizeof(EuvIosLayerUniform) atIndex:1];
NSUInteger sx = r.scissor_x < drawW ? r.scissor_x : (drawW > 0 ? drawW - 1 : 0);
NSUInteger sy = r.scissor_y < drawH ? r.scissor_y : (drawH > 0 ? drawH - 1 : 0);
NSUInteger sw = r.scissor_w;
if (sx + sw > drawW) sw = drawW - sx;
if (sw == 0) sw = 1;
NSUInteger sh = r.scissor_h;
if (sy + sh > drawH) sh = drawH - sy;
if (sh == 0) sh = 1;
MTLScissorRect sc = { sx, sy, sw, sh };
[enc setScissorRect:sc];
[enc drawPrimitives:MTLPrimitiveTypeTriangle
vertexStart:0
vertexCount:6
instanceCount:r.instance_count
baseInstance:r.base_instance];
}
}
[enc endEncoding];
__weak EuvCanvasView *weakSelf = self;
#if !TARGET_OS_SIMULATOR
if ([drawable respondsToSelector:@selector(addPresentedHandler:)]) {
[(id<MTLDrawable>)drawable addPresentedHandler:^(id<MTLDrawable> _Nonnull presentedDrawable) {
double presentedSec = (double)presentedDrawable.presentedTime;
dispatch_async(dispatch_get_main_queue(), ^{
EuvCanvasView *strongSelf = weakSelf;
if (strongSelf && strongSelf.handle) {
euv_ios_record_metal_presented(strongSelf.handle, presentedSec, 0);
}
});
}];
}
#else
dispatch_async(dispatch_get_main_queue(), ^{
EuvCanvasView *strongSelf = weakSelf;
if (strongSelf && strongSelf.handle) {
euv_ios_record_metal_presented(strongSelf.handle, 0.0, 0);
}
});
#endif
dispatch_semaphore_t sem = _inFlightSemaphore;
[cmd addCompletedHandler:^(id<MTLCommandBuffer> _Nonnull buf) {
uint64_t execUs = 0;
if (buf.GPUEndTime > buf.GPUStartTime) {
execUs = (uint64_t)((buf.GPUEndTime - buf.GPUStartTime) * 1000000.0);
}
BOOL gpuErr = (buf.status == MTLCommandBufferStatusError);
if (sem) dispatch_semaphore_signal(sem);
if (gpuErr || execUs > 0) {
dispatch_async(dispatch_get_main_queue(), ^{
EuvCanvasView *strongSelf = weakSelf;
if (!strongSelf || !strongSelf.handle) return;
if (gpuErr) {
euv_ios_handle_metal_fault(strongSelf.handle, 0);
} else {
euv_ios_record_metal_presented(strongSelf.handle, 0.0, execUs);
}
});
}
}];
[cmd presentDrawable:drawable];
[cmd commit];
return YES;
}
- (BOOL)presentMetalUploadPixels:(const uint8_t *)pixels
width:(uint32_t)w
height:(uint32_t)h
rects:(const EuvIosDirtyRect *)rects
rectCount:(size_t)rectCount
strategy:(int32_t)strategy {
if (!_metalDevice || !_metalQueue || !_blitPipeline || ![self.layer isKindOfClass:[CAMetalLayer class]]) {
return NO;
}
CAMetalLayer *ml = (CAMetalLayer *)self.layer;
if ((uint32_t)llround(ml.drawableSize.width) != w || (uint32_t)llround(ml.drawableSize.height) != h) {
ml.drawableSize = CGSizeMake(w, h);
}
if (_inFlightSemaphore) {
dispatch_semaphore_wait(_inFlightSemaphore, DISPATCH_TIME_FOREVER);
}
BOOL resized = (!_uploadTex || _stagingW != w || _stagingH != h);
if (resized) {
MTLTextureDescriptor *desc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
width:w
height:h
mipmapped:NO];
desc.usage = MTLTextureUsageShaderRead;
desc.storageMode = MTLStorageModeShared;
_uploadTex = [_metalDevice newTextureWithDescriptor:desc];
_stagingW = w;
_stagingH = h;
}
if (!_uploadTex) {
if (_inFlightSemaphore) dispatch_semaphore_signal(_inFlightSemaphore);
return NO;
}
NSUInteger rowBytes = (NSUInteger)w * 4;
if (resized || strategy == 3 || !rects || rectCount == 0) {
[_uploadTex replaceRegion:MTLRegionMake2D(0, 0, w, h)
mipmapLevel:0
withBytes:pixels
bytesPerRow:rowBytes];
} else {
for (size_t i = 0; i < rectCount; ++i) {
EuvIosDirtyRect r = rects[i];
if (r.width == 0 || r.height == 0 || r.x >= w || r.y >= h) continue;
uint32_t cw = (r.x + r.width > w) ? (w - r.x) : r.width;
uint32_t ch = (r.y + r.height > h) ? (h - r.y) : r.height;
size_t byteOff = ((size_t)r.y * (size_t)w + (size_t)r.x) * 4u;
[_uploadTex replaceRegion:MTLRegionMake2D(r.x, r.y, cw, ch)
mipmapLevel:0
withBytes:pixels + byteOff
bytesPerRow:rowBytes];
}
}
id<CAMetalDrawable> drawable = [ml nextDrawable];
if (!drawable || !drawable.texture || drawable.texture.width != w || drawable.texture.height != h) {
if (_inFlightSemaphore) dispatch_semaphore_signal(_inFlightSemaphore);
return NO;
}
MTLRenderPassDescriptor *rpd = [MTLRenderPassDescriptor renderPassDescriptor];
rpd.colorAttachments[0].texture = drawable.texture;
rpd.colorAttachments[0].loadAction = MTLLoadActionDontCare;
rpd.colorAttachments[0].storeAction = MTLStoreActionStore;
id<MTLCommandBuffer> cmd = [_metalQueue commandBuffer];
if (!cmd) {
if (_inFlightSemaphore) dispatch_semaphore_signal(_inFlightSemaphore);
return NO;
}
id<MTLRenderCommandEncoder> enc = [cmd renderCommandEncoderWithDescriptor:rpd];
if (!enc) {
if (_inFlightSemaphore) dispatch_semaphore_signal(_inFlightSemaphore);
return NO;
}
[enc setRenderPipelineState:_blitPipeline];
[enc setFragmentTexture:_uploadTex atIndex:0];
[enc drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
[enc endEncoding];
__weak EuvCanvasView *weakSelf = self;
#if !TARGET_OS_SIMULATOR
if ([drawable respondsToSelector:@selector(addPresentedHandler:)]) {
[(id<MTLDrawable>)drawable addPresentedHandler:^(id<MTLDrawable> _Nonnull presentedDrawable) {
double presentedSec = (double)presentedDrawable.presentedTime;
dispatch_async(dispatch_get_main_queue(), ^{
EuvCanvasView *strongSelf = weakSelf;
if (strongSelf && strongSelf.handle) {
euv_ios_record_metal_presented(strongSelf.handle, presentedSec, 0);
}
});
}];
}
#else
dispatch_async(dispatch_get_main_queue(), ^{
EuvCanvasView *strongSelf = weakSelf;
if (strongSelf && strongSelf.handle) {
euv_ios_record_metal_presented(strongSelf.handle, 0.0, 0);
}
});
#endif
dispatch_semaphore_t sem = _inFlightSemaphore;
if (sem) {
[cmd addCompletedHandler:^(id<MTLCommandBuffer> _Nonnull buf) {
(void)buf;
dispatch_semaphore_signal(sem);
}];
}
[cmd presentDrawable:drawable];
[cmd commit];
return YES;
}
- (void)presentFrameWithDt:(float)dt force:(BOOL)force {
if (!_handle) return;
CFTimeInterval t0 = CACurrentMediaTime();
uint32_t w = 0, h = 0;
BOOL presented = NO;
int32_t activePath = euv_ios_active_present_path(_handle);
if (activePath == 0) {
EuvIosDirectFrameDesc frameDesc;
memset(&frameDesc, 0, sizeof(frameDesc));
int32_t hasDirect = euv_ios_step_direct_gpu(_handle, dt, force ? 1 : 0, &frameDesc);
if (hasDirect && frameDesc.viewport_w > 0 && frameDesc.viewport_h > 0) {
w = frameDesc.viewport_w;
h = frameDesc.viewport_h;
if ([self presentMetalDirectFrame:&frameDesc]) {
euv_ios_commit_direct_gpu_present(_handle, frameDesc.glyph_r8_rev);
presented = YES;
} else {
activePath = euv_ios_handle_metal_fault(_handle, 3);
}
}
}
if (!presented && activePath != 0) {
const uint8_t *pixels = NULL;
const EuvIosDirtyRect *rects = NULL;
size_t rectCount = 0;
int32_t strategy = 3;
int32_t hasFallback = euv_ios_step_upload_plan(
_handle,
dt,
force ? 1 : 0,
&pixels,
&w,
&h,
&rects,
&rectCount,
&strategy
);
if (hasFallback && pixels && w > 0 && h > 0) {
BOOL metalOk = NO;
if (activePath == 1) {
metalOk = [self presentMetalUploadPixels:pixels
width:w
height:h
rects:rects
rectCount:rectCount
strategy:strategy];
if (!metalOk) {
activePath = euv_ios_handle_metal_fault(_handle, 3);
}
}
if (metalOk) {
euv_ios_commit_fallback_present(_handle, 1);
presented = YES;
} else {
size_t bytes = (size_t)w * (size_t)h * 4;
NSData *copyData = [NSData dataWithBytes:pixels length:bytes];
CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)copyData);
if (provider) {
CGBitmapInfo info = kCGBitmapByteOrder32Big | kCGImageAlphaLast;
CGImageRef img = CGImageCreate(w, h, 8, 32, (size_t)w * 4, _colorSpace, info, provider, NULL, false, kCGRenderingIntentDefault);
if (img) {
self.layer.contents = (__bridge id)img;
self.layer.contentsGravity = kCAGravityResize;
CGImageRelease(img);
euv_ios_commit_fallback_present(_handle, 0);
presented = YES;
}
CGDataProviderRelease(provider);
}
}
}
}
if (presented) {
double renderMs = (CACurrentMediaTime() - t0) * 1000.0;
_renderedFrames += 1;
_accumRenderMs += renderMs;
if (renderMs > _maxRenderMs) _maxRenderMs = renderMs;
double budgetMs = 1000.0 / (_targetRefreshHz > 0.0f ? _targetRefreshHz : 60.0f);
if (renderMs > budgetMs) _droppedFrames += 1;
if (_renderedFrames % 60 == 0) {
double avg = _accumRenderMs / 60.0;
NSLog(@"[euv-fps] ios rendered=%llu path=%d cpu_mirror=%d upload_strategy=%d upload_bytes=%llu timing_src=%d avg=%.2fms max=%.2fms dropped=%llu target=%.0fHz res=%ux%u",
_renderedFrames,
euv_ios_active_present_path(_handle),
euv_ios_cpu_mirror_active(_handle),
euv_ios_upload_strategy(_handle),
euv_ios_last_upload_bytes(_handle),
euv_ios_timing_source(_handle),
avg,
_maxRenderMs,
_droppedFrames,
_targetRefreshHz,
w,
h);
_accumRenderMs = 0.0;
_maxRenderMs = 0.0;
}
}
}
- (void)syncLiveTouchesFromEvent:(UIEvent *)event forceInclude:(NSSet<UITouch *> *)forced {
if (!_handle) return;
uint64_t liveIds[32];
size_t count = 0;
if (event) {
for (UITouch *t in event.allTouches) {
UITouchPhase phase = t.phase;
if ((phase == UITouchPhaseBegan || phase == UITouchPhaseMoved || phase == UITouchPhaseStationary) && count < 32) {
liveIds[count++] = (uint64_t)(uintptr_t)t;
}
}
}
if (forced) {
for (UITouch *t in forced) {
uint64_t tid = (uint64_t)(uintptr_t)t;
BOOL present = NO;
for (size_t i = 0; i < count; i++) {
if (liveIds[i] == tid) {
present = YES;
break;
}
}
if (!present && count < 32) {
liveIds[count++] = tid;
}
}
}
euv_ios_touch_sync(_handle, liveIds, count);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if (!_handle) return;
for (UITouch *t in touches) {
CGPoint p = [t locationInView:self];
euv_ios_touch_down(_handle, (uint64_t)(uintptr_t)t, (float)p.x, (float)p.y);
}
[self syncLiveTouchesFromEvent:event forceInclude:touches];
}
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if (!_handle) return;
for (UITouch *t in touches) {
CGPoint p = [t locationInView:self];
euv_ios_touch_move(_handle, (uint64_t)(uintptr_t)t, (float)p.x, (float)p.y);
}
[self syncLiveTouchesFromEvent:event forceInclude:touches];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if (!_handle) return;
for (UITouch *t in touches) {
CGPoint p = [t locationInView:self];
euv_ios_touch_up(_handle, (uint64_t)(uintptr_t)t, (float)p.x, (float)p.y);
}
[self syncLiveTouchesFromEvent:event forceInclude:nil];
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
if (!_handle) return;
for (UITouch *t in touches) {
euv_ios_touch_cancel(_handle, (uint64_t)(uintptr_t)t);
}
[self syncLiveTouchesFromEvent:event forceInclude:nil];
BOOL anyLive = NO;
if (event) {
for (UITouch *t in event.allTouches) {
UITouchPhase phase = t.phase;
if (phase == UITouchPhaseBegan || phase == UITouchPhaseMoved || phase == UITouchPhaseStationary) {
anyLive = YES;
break;
}
}
}
if (!anyLive) {
euv_ios_touch_cancel(_handle, 0);
}
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (BOOL)hasText {
return YES;
}
- (void)insertText:(NSString *)text {
if (!_handle || text.length == 0) return;
if ([text isEqualToString:@"\n"]) {
euv_ios_key_down(_handle, 2);
return;
}
const char *utf8 = [text UTF8String];
if (utf8) {
euv_ios_text_input(_handle, utf8);
}
}
- (void)deleteBackward {
if (!_handle) return;
euv_ios_key_down(_handle, 1);
}
- (void)ensureEmbeddedWebView {
if (_webContainerView && _embeddedWebView) return;
_webContainerView = [[UIView alloc] initWithFrame:CGRectZero];
_webContainerView.backgroundColor = [UIColor clearColor];
_webContainerView.clipsToBounds = YES;
_webContainerView.hidden = YES;
_webContainerView.alpha = 0.0;
_webContainerView.userInteractionEnabled = NO;
WKWebViewConfiguration *cfg = [[WKWebViewConfiguration alloc] init];
cfg.allowsInlineMediaPlayback = YES;
cfg.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
_embeddedWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:cfg];
_embeddedWebView.navigationDelegate = self;
_embeddedWebView.UIDelegate = self;
_embeddedWebView.allowsBackForwardNavigationGestures = YES;
_embeddedWebView.opaque = NO;
_embeddedWebView.backgroundColor = [UIColor clearColor];
_embeddedWebView.scrollView.backgroundColor = [UIColor clearColor];
_embeddedWebView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
[_webContainerView addSubview:_embeddedWebView];
_webProgressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
_webProgressView.trackTintColor = [UIColor clearColor];
_webProgressView.progressTintColor = [UIColor systemBlueColor];
_webProgressView.hidden = YES;
_webProgressView.progress = 0.0f;
[_webContainerView addSubview:_webProgressView];
[self addSubview:_webContainerView];
}
- (void)openEmbeddedWebViewUrl:(NSString *)urlString title:(NSString *)titleString {
(void)titleString;
NSURL *targetUrl = [NSURL URLWithString:urlString];
NSString *scheme = targetUrl.scheme.lowercaseString;
if (!targetUrl || !([scheme isEqualToString:@"https"] || [scheme isEqualToString:@"http"])) {
return;
}
[self ensureEmbeddedWebView];
_webSheetOpen = YES;
[self bringSubviewToFront:_webContainerView];
if (![_activeWebUrl isEqualToString:urlString]) {
_webNavGeneration += 1;
_activeWebUrl = [urlString copy];
_embeddedWebView.backgroundColor = [UIColor clearColor];
_embeddedWebView.scrollView.backgroundColor = [UIColor clearColor];
_webProgressView.hidden = NO;
[_webProgressView setProgress:0.20f animated:NO];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:targetUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:20.0];
[_embeddedWebView loadRequest:req];
}
}
- (void)updateEmbeddedWebViewFrameX:(CGFloat)x y:(CGFloat)y width:(CGFloat)w height:(CGFloat)h alpha:(CGFloat)alpha {
if (!_webSheetOpen || !_webContainerView || !_embeddedWebView) return;
[CATransaction begin];
[CATransaction setDisableActions:YES];
if (w < 1.0 || h < 1.0 || alpha <= 0.005) {
_webContainerView.hidden = YES;
_webContainerView.alpha = 0.0;
_webContainerView.userInteractionEnabled = NO;
} else {
_webContainerView.hidden = NO;
_webContainerView.frame = CGRectMake(x, y, w, h);
_webContainerView.alpha = alpha;
_webContainerView.userInteractionEnabled = (alpha >= 0.98);
_embeddedWebView.frame = _webContainerView.bounds;
_webProgressView.frame = CGRectMake(0.0, 0.0, w, 2.5);
}
[CATransaction commit];
}
- (void)reloadEmbeddedWebViewFallbackUrl:(NSString *)fallbackUrl {
if (!_webSheetOpen || !_embeddedWebView) return;
_webNavGeneration += 1;
_webProgressView.hidden = NO;
[_webProgressView setProgress:0.20f animated:NO];
if (_embeddedWebView.URL && ![[_embeddedWebView.URL.absoluteString lowercaseString] isEqualToString:@"about:blank"]) {
[_embeddedWebView reload];
} else if (fallbackUrl.length > 0) {
_activeWebUrl = nil;
[self openEmbeddedWebViewUrl:fallbackUrl title:@""];
}
}
- (void)closeEmbeddedWebView {
_webSheetOpen = NO;
_webNavGeneration += 1;
_activeWebUrl = nil;
if (_webProgressView) {
_webProgressView.hidden = YES;
_webProgressView.progress = 0.0f;
}
if (_embeddedWebView) {
[_embeddedWebView stopLoading];
[_embeddedWebView loadHTMLString:@"" baseURL:nil];
_embeddedWebView.backgroundColor = [UIColor clearColor];
_embeddedWebView.scrollView.backgroundColor = [UIColor clearColor];
}
if (_webContainerView) {
[CATransaction begin];
[CATransaction setDisableActions:YES];
_webContainerView.hidden = YES;
_webContainerView.alpha = 0.0;
_webContainerView.userInteractionEnabled = NO;
[CATransaction commit];
}
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
(void)webView;
NSURL *url = navigationAction.request.URL;
NSString *scheme = url.scheme.lowercaseString;
if (!url || [scheme isEqualToString:@"https"] || [scheme isEqualToString:@"http"] || [scheme isEqualToString:@"about"] || [scheme isEqualToString:@"data"]) {
decisionHandler(WKNavigationActionPolicyAllow);
return;
}
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
decisionHandler(WKNavigationActionPolicyCancel);
}
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
(void)configuration;
(void)windowFeatures;
if (navigationAction.targetFrame == nil && navigationAction.request.URL) {
[webView loadRequest:navigationAction.request];
}
return nil;
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
(void)navigation;
if (!_webSheetOpen) return;
if (webView.URL && [[webView.URL.absoluteString lowercaseString] isEqualToString:@"about:blank"]) return;
if (_webProgressView) {
_webProgressView.hidden = NO;
[_webProgressView setProgress:0.35f animated:YES];
}
}
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
(void)navigation;
if (!_webSheetOpen) return;
if (webView.URL && [[webView.URL.absoluteString lowercaseString] isEqualToString:@"about:blank"]) return;
webView.backgroundColor = [UIColor systemBackgroundColor];
webView.scrollView.backgroundColor = [UIColor systemBackgroundColor];
if (_webProgressView) {
[_webProgressView setProgress:0.75f animated:YES];
}
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
(void)navigation;
if (!_webSheetOpen) return;
if (webView.URL && [[webView.URL.absoluteString lowercaseString] isEqualToString:@"about:blank"]) return;
if (_webProgressView) {
NSUInteger finishedGen = _webNavGeneration;
[_webProgressView setProgress:1.0f animated:YES];
__weak EuvCanvasView *weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.18 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
EuvCanvasView *strongSelf = weakSelf;
if (strongSelf && strongSelf.webProgressView && strongSelf.webNavGeneration == finishedGen) {
strongSelf.webProgressView.hidden = YES;
strongSelf.webProgressView.progress = 0.0f;
}
});
}
}
- (void)presentWebViewError:(NSError *)error inWebView:(WKWebView *)webView {
if (!error || error.code == NSURLErrorCancelled) {
return;
}
if (_webProgressView) {
_webProgressView.hidden = YES;
_webProgressView.progress = 0.0f;
}
if (!_webSheetOpen) return;
webView.backgroundColor = [UIColor systemBackgroundColor];
webView.scrollView.backgroundColor = [UIColor systemBackgroundColor];
NSString *failedUrl = _activeWebUrl ?: @"";
NSString *escUrl = [[failedUrl stringByReplacingOccurrencesOfString:@"&" withString:@"&"]
stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
NSString *escMsg = [[error.localizedDescription ?: @"Unable to load webpage." stringByReplacingOccurrencesOfString:@"&" withString:@"&"]
stringByReplacingOccurrencesOfString:@"<" withString:@"<"];
NSString *jsUrl = [failedUrl stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
NSString *html = [NSString stringWithFormat:
@"<!doctype html><html><head><meta name='viewport' content='width=device-width,initial-scale=1'>"
"<style>:root{color-scheme:light dark}body{margin:0;padding:24px;font-family:-apple-system,sans-serif;background:Canvas;color:CanvasText}"
".card{border:1px solid rgba(127,127,127,.25);border-radius:12px;padding:18px;max-width:480px}"
"h3{margin:0 0 8px;font-size:16px}p{margin:0 0 12px;font-size:13px;opacity:.78;word-break:break-all}"
"button{border:0;border-radius:8px;padding:9px 16px;font-size:13px;font-weight:600;background:#2563eb;color:#fff}</style>"
"</head><body><div class='card'><h3>Page Load Failed</h3><p>%@</p><p>%@</p>"
"<button onclick=\"window.location.href='%@'\">Retry</button></div></body></html>",
escMsg, escUrl, jsUrl];
[webView loadHTMLString:html baseURL:nil];
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
(void)navigation;
[self presentWebViewError:error inWebView:webView];
}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
(void)navigation;
[self presentWebViewError:error inWebView:webView];
}
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
if (_webSheetOpen && _activeWebUrl.length > 0) {
[webView reload];
}
}
@end
@implementation EuvViewController
- (void)loadView {
gEuvActiveViewController = self;
CGRect initialFrame = UIScreen.mainScreen.bounds;
self.canvasView = [[EuvCanvasView alloc] initWithFrame:initialFrame];
self.canvasView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.view = self.canvasView;
}
- (void)applyImmersiveFullscreen:(BOOL)enabled {
self.immersiveFullscreen = enabled;
self.canvasView.immersiveFullscreen = enabled;
[self setNeedsStatusBarAppearanceUpdate];
[self setNeedsUpdateOfHomeIndicatorAutoHidden];
[self setNeedsUpdateOfScreenEdgesDeferringSystemGestures];
[self.canvasView syncSafeArea];
[self.canvasView presentFrameWithDt:(1.0f / (self.canvasView.targetRefreshHz > 0.0f ? self.canvasView.targetRefreshHz : 60.0f)) force:YES];
}
- (BOOL)prefersStatusBarHidden {
return self.immersiveFullscreen;
}
- (BOOL)prefersHomeIndicatorAutoHidden {
return self.immersiveFullscreen;
}
- (UIRectEdge)preferredScreenEdgesDeferringSystemGestures {
return UIRectEdgeAll;
}
- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
return UIStatusBarAnimationFade;
}
- (void)viewSafeAreaInsetsDidChange {
[super viewSafeAreaInsetsDidChange];
[self.canvasView syncSafeArea];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self setNeedsUpdateOfScreenEdgesDeferringSystemGestures];
[self.canvasView syncViewportScaleAndBounds];
}
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
[self.canvasView syncViewportScaleAndBounds];
}
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> ctx) {
[self.canvasView syncViewportScaleAndBounds];
} completion:^(id<UIViewControllerTransitionCoordinatorContext> ctx) {
[self setNeedsUpdateOfScreenEdgesDeferringSystemGestures];
[self.canvasView syncViewportScaleAndBounds];
}];
}
@end
@interface EuvSceneDelegate : UIResponder <UIWindowSceneDelegate>
@property (nonatomic, strong) UIWindow *window;
@end
@implementation EuvSceneDelegate
- (void)syncWindowGeometry:(UIWindowScene *)windowScene {
(void)windowScene;
if (!self.window) return;
[self.window layoutIfNeeded];
if ([self.window.rootViewController isKindOfClass:[EuvViewController class]]) {
EuvViewController *vc = (EuvViewController *)self.window.rootViewController;
[vc setNeedsUpdateOfScreenEdgesDeferringSystemGestures];
[vc.canvasView syncViewportScaleAndBounds];
}
}
static void euvSyncHotUpdateEnvKey(const char *envKey, NSString *defaultsKey) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
const char *cur = getenv(envKey);
if (cur != NULL && cur[0] != '\0') {
NSString *val = [NSString stringWithUTF8String:cur];
if (val.length > 0) {
[defaults setObject:val forKey:defaultsKey];
}
} else {
NSString *saved = [defaults stringForKey:defaultsKey];
if (saved.length > 0) {
setenv(envKey, [saved UTF8String], 1);
}
}
}
static void euvApplyHotUpdateBootstrapConfig(void) {
NSArray<NSString *> *caches = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *baseCache = caches.firstObject ?: NSTemporaryDirectory();
NSString *otaDir = [baseCache stringByAppendingPathComponent:@"euv-ota"];
[[NSFileManager defaultManager] createDirectoryAtPath:otaDir
withIntermediateDirectories:YES
attributes:nil
error:nil];
setenv("EUV_UPDATE_CACHE_DIR", [otaDir UTF8String], 0);
euvSyncHotUpdateEnvKey("EUV_UPDATE_URL", @"euv_ota_server_url");
euvSyncHotUpdateEnvKey("EUV_PROXY_URL", @"euv_ota_proxy_url");
euvSyncHotUpdateEnvKey("EUV_UPDATE_CHANNEL", @"euv_ota_channel");
}
static void euvPersistHotUpdateDeepLinkConfig(NSURL *url) {
if (!url) return;
if (![[url.scheme lowercaseString] isEqualToString:@"euv"]) return;
if (![[url.host lowercaseString] isEqualToString:@"hot-update"]) return;
NSURLComponents *comps = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
for (NSURLQueryItem *item in comps.queryItems) {
NSString *name = [item.name lowercaseString];
NSString *val = item.value ?: @"";
if ([name isEqualToString:@"server"]) {
if (val.length > 0) {
[defaults setObject:val forKey:@"euv_ota_server_url"];
setenv("EUV_UPDATE_URL", [val UTF8String], 1);
} else {
[defaults removeObjectForKey:@"euv_ota_server_url"];
unsetenv("EUV_UPDATE_URL");
}
} else if ([name isEqualToString:@"proxy"]) {
if (val.length > 0) {
[defaults setObject:val forKey:@"euv_ota_proxy_url"];
setenv("EUV_PROXY_URL", [val UTF8String], 1);
} else {
[defaults removeObjectForKey:@"euv_ota_proxy_url"];
unsetenv("EUV_PROXY_URL");
}
} else if ([name isEqualToString:@"channel"] && val.length > 0) {
[defaults setObject:val forKey:@"euv_ota_channel"];
setenv("EUV_UPDATE_CHANNEL", [val UTF8String], 1);
}
}
[defaults synchronize];
}
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
if (![scene isKindOfClass:[UIWindowScene class]]) return;
euvApplyHotUpdateBootstrapConfig();
if (connectionOptions && connectionOptions.URLContexts.count > 0) {
for (UIOpenURLContext *ctx in connectionOptions.URLContexts) {
euvPersistHotUpdateDeepLinkConfig(ctx.URL);
}
}
UIWindowScene *windowScene = (UIWindowScene *)scene;
if (UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad && windowScene.sizeRestrictions != nil) {
windowScene.sizeRestrictions.minimumSize = CGSizeMake(320.0, 320.0);
windowScene.sizeRestrictions.maximumSize = CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX);
}
self.window = [[UIWindow alloc] initWithWindowScene:windowScene];
self.window.backgroundColor = [UIColor systemBackgroundColor];
self.window.rootViewController = [[EuvViewController alloc] init];
[self.window makeKeyAndVisible];
[self syncWindowGeometry:windowScene];
if (connectionOptions && connectionOptions.URLContexts.count > 0) {
[self scene:scene openURLContexts:connectionOptions.URLContexts];
}
}
- (void)sceneWillEnterForeground:(UIScene *)scene {
(void)scene;
if (self.window && [self.window.rootViewController isKindOfClass:[EuvViewController class]]) {
EuvViewController *vc = (EuvViewController *)self.window.rootViewController;
if (vc.canvasView) {
[vc.canvasView ensureLiveSession];
if (vc.canvasView.handle) {
[vc.canvasView setDisplayLinkPaused:NO];
euv_ios_system_lifecycle(vc.canvasView.handle, 1);
euv_ios_system_lifecycle(vc.canvasView.handle, 3);
[vc.canvasView syncViewportScaleAndBounds];
[vc.canvasView syncSafeArea];
[vc.canvasView syncThemeTrait];
}
}
}
}
- (void)sceneDidBecomeActive:(UIScene *)scene {
if ([scene isKindOfClass:[UIWindowScene class]]) {
[self syncWindowGeometry:(UIWindowScene *)scene];
}
if (self.window && [self.window.rootViewController isKindOfClass:[EuvViewController class]]) {
EuvViewController *vc = (EuvViewController *)self.window.rootViewController;
if (vc.canvasView) {
[vc.canvasView ensureLiveSession];
if (vc.canvasView.handle) {
[vc.canvasView setDisplayLinkPaused:NO];
[vc.canvasView startDeviceMotionUpdates];
euv_ios_system_lifecycle(vc.canvasView.handle, 3);
euv_ios_focus(vc.canvasView.handle, 1);
[vc.canvasView syncSafeArea];
}
}
}
}
- (void)sceneDidDisconnect:(UIScene *)scene {
(void)scene;
if (self.window && [self.window.rootViewController isKindOfClass:[EuvViewController class]]) {
EuvViewController *vc = (EuvViewController *)self.window.rootViewController;
if (vc.canvasView) {
[vc.canvasView shutdownSession];
}
if (gEuvActiveViewController == vc) {
gEuvActiveViewController = nil;
}
}
self.window = nil;
}
- (void)sceneWillResignActive:(UIScene *)scene {
(void)scene;
if (self.window && [self.window.rootViewController isKindOfClass:[EuvViewController class]]) {
EuvViewController *vc = (EuvViewController *)self.window.rootViewController;
if (vc.canvasView && vc.canvasView.handle) {
euv_ios_touch_cancel(vc.canvasView.handle, 0);
euv_ios_focus(vc.canvasView.handle, 0);
euv_ios_system_lifecycle(vc.canvasView.handle, 4);
}
}
}
- (void)sceneDidEnterBackground:(UIScene *)scene {
(void)scene;
if (self.window && [self.window.rootViewController isKindOfClass:[EuvViewController class]]) {
EuvViewController *vc = (EuvViewController *)self.window.rootViewController;
if (vc.canvasView && vc.canvasView.handle) {
euv_ios_touch_cancel(vc.canvasView.handle, 0);
[vc.canvasView stopDeviceMotionUpdates];
[vc.canvasView setDisplayLinkPaused:YES];
euv_ios_system_lifecycle(vc.canvasView.handle, 5);
}
}
}
- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts {
(void)scene;
if (!self.window || ![self.window.rootViewController isKindOfClass:[EuvViewController class]]) return;
EuvViewController *vc = (EuvViewController *)self.window.rootViewController;
if (!vc.canvasView || !vc.canvasView.handle) return;
for (UIOpenURLContext *ctx in URLContexts) {
euvPersistHotUpdateDeepLinkConfig(ctx.URL);
NSString *urlStr = ctx.URL.absoluteString;
if (urlStr.length > 0) {
euv_ios_deep_link(vc.canvasView.handle, [urlStr UTF8String]);
}
}
}
- (void)windowScene:(UIWindowScene *)windowScene didUpdateEffectiveGeometry:(UIWindowSceneGeometry *)previousEffectiveGeometry {
[self syncWindowGeometry:windowScene];
}
@end
@interface EuvAppDelegate : UIResponder <UIApplicationDelegate>
@end
@implementation EuvAppDelegate
- (UISceneConfiguration *)application:(UIApplication *)application
configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession
options:(UISceneConnectionOptions *)options {
UISceneConfiguration *cfg = [[UISceneConfiguration alloc] initWithName:@"Default Configuration"
sessionRole:connectingSceneSession.role];
cfg.delegateClass = [EuvSceneDelegate class];
return cfg;
}
- (void)applicationWillTerminate:(UIApplication *)application {
(void)application;
EuvCanvasView *v = gEuvActiveCanvasView;
if (v && v.handle) {
euv_ios_system_lifecycle(v.handle, 6);
}
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([EuvAppDelegate class]));
}
}