Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions docs/ios-port.md
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,38 @@ long-press/right-click menu presentation and third-party keyboard suggestions
still need manual checks; calling UIKit's edit interaction programmatically did
not reproduce normal menu presentation in the simulator.

When a native gesture claims a touch, such as dragging a text selection handle,
WebKit delivers `pointerdown` but never `pointerup` or `pointercancel`, which left
the editor's selection menu hidden until the next touch. `WebTouchEnd` observes
touches natively without preventing or delaying any gesture; when every finger
lifts, pages and their frames get a `pointercancel` for touch pointers still held
after 100 ms. Touches that begin after the native end are never cancelled. The
recognizer never fails itself: a failed recognizer is not reset while WebKit's
double-tap recognizer is pending, so it would miss the second tap of a double-tap
on a word, which WebKit also swallows, leaving the menu hidden. The main
and preview WebViews install it. Simulator and happy-dom tests cover stale, released,
late-released and newly started touches, Shadow DOM and frames; dragging a handle
by hand on a physical device remains a manual check.

Selection menu buttons work around three more WebKit touch behaviours, all seen
in device logs. A touch press runs its action on that touch's `touchend`, which
normally arrives in the same millisecond as `pointerup`, so there is no visible delay. Removing
the menu on `pointerup` dropped the `touchend` and let WebKit place the caret
under the finger. If no `touchend` arrives, the action runs 100 ms after
`pointerup`. When WebKit claims a tap and sends only an emulated `mousedown`,
that `mousedown` activates the button, even when it arrives after the press was
cancelled, as `WebTouchEnd` does 100 ms after the touch ends. A new press first
runs a released press that is still waiting for its `touchend`. WebKit's native text tap can also clear or
move the selection behind a menu press with no page event, so the menu restores
the selection it saw when the press began, unless a menu action or a document
edit changed it. The restore window starts at `pointerdown`, is capped at 1.5 s,
lasts 350 ms after release, and is dropped by any tap outside the menu or a key
press in the editor. A press cancelled before release pauses it; a late emulated
`mousedown` within the 1.5 s cap resumes it and restores the selection, and
otherwise it ends unused. Presses from a secondary pointer still activate buttons, because WebKit
keeps reporting taps as secondary after some double-taps on a word even with
`WebTouchEnd` installed. A second press while one is already held is ignored.

The account API uses an iOS-only fetch/XHR URL adapter because the app's custom
scheme has an opaque browser origin. The native handler restricts requests to
the Acode API origin, retains TLS verification, honors credential omission and
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{
"name": "acode-app",
"displayName": "Acode",
"version": "1.13.7",
"versionCode": 1024,
"version": "1.13.8",
"versionCode": 1027,
"androidPackageId": "com.foxdebug.acode",
"appleAppId": "app.acode",
"description": "Powerful code editor and terminal for IOS and Android",
Expand Down
8 changes: 4 additions & 4 deletions platforms/ios/runner.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1024;
CURRENT_PROJECT_VERSION = 1027;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
Expand All @@ -396,7 +396,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.6;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MARKETING_VERSION = 1.13.7;
MARKETING_VERSION = 1.13.8;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
Expand Down Expand Up @@ -443,7 +443,7 @@
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
CURRENT_PROJECT_VERSION = 1024;
CURRENT_PROJECT_VERSION = 1027;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
Expand All @@ -458,7 +458,7 @@
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.6;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MARKETING_VERSION = 1.13.7;
MARKETING_VERSION = 1.13.8;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
Expand Down
114 changes: 114 additions & 0 deletions platforms/ios/runner/WebTouchEnd.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import UIKit
import WebKit

/// When a native gesture (such as dragging a text selection handle) takes over a touch,
/// WebKit stops delivering its pointer events, so the page never sees pointerup or
/// pointercancel. This watches touches natively and, when the touch sequence ends,
/// cancels any touch pointer the page still believes is down.
final class WebTouchEnd: UIGestureRecognizer, UIGestureRecognizerDelegate {
private weak var webView: WKWebView?
private var activeTouches = Set<UITouch>()

init(webView: WKWebView) {
self.webView = webView
super.init(target: nil, action: nil)
cancelsTouchesInView = false
delaysTouchesEnded = false
delegate = self
webView.addGestureRecognizer(self)
webView.configuration.userContentController.addUserScript(
WKUserScript(source: Self.script, injectionTime: .atDocumentStart, forMainFrameOnly: false)
)
}

override func canBePrevented(by preventingGestureRecognizer: UIGestureRecognizer) -> Bool { false }

override func canPrevent(_ preventedGestureRecognizer: UIGestureRecognizer) -> Bool { false }

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
true
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
// This recognizer is rarely reset, so drop touches whose end callback was missed;
// one stale touch would otherwise silence it for the rest of the session.
activeTouches = activeTouches.filter { [.began, .moved, .stationary].contains($0.phase) }
activeTouches.formUnion(touches)
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
release(touches)
}

override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
release(touches)
}

override func reset() {
super.reset()
activeTouches.removeAll()
}

func send() {
webView?.evaluateJavaScript("window.acodeNativeTouchEnd?.()", completionHandler: nil)
}

private func release(_ touches: Set<UITouch>) {
activeTouches.subtract(touches)
guard activeTouches.isEmpty else { return }
// Failing here would leave this recognizer unreset, and blind to the next tap,
// while a multi-tap recognizer such as WebKit's double-tap is still pending.
send()
}

static let script = """
(() => {
const messageType = 'acode-native-touchend';
// WebKit can still deliver the real pointerup shortly after the native touch end.
const settleDelay = 100;
const active = new Map();
const track = event => {
if (event.pointerType !== 'touch') return;
if (event.type === 'pointerdown') {
active.set(event.pointerId, {
target: event.composedPath()[0], isPrimary: event.isPrimary,
clientX: event.clientX, clientY: event.clientY
});
return;
}
const pointer = active.get(event.pointerId);
if (!pointer) return;
pointer.clientX = event.clientX;
pointer.clientY = event.clientY;
};
document.addEventListener('pointerdown', track, true);
document.addEventListener('pointermove', track, true);
for (const type of ['pointerup', 'pointercancel'])
document.addEventListener(type, event => active.delete(event.pointerId), true);
const cancel = stale => {
for (const [pointerId, pointer] of stale) {
if (active.get(pointerId) !== pointer) continue;
active.delete(pointerId);
const {target, isPrimary, clientX, clientY} = pointer;
(target.isConnected ? target : document).dispatchEvent(new PointerEvent('pointercancel', {
bubbles: true, composed: true, pointerId, pointerType: 'touch', isPrimary, clientX, clientY
}));
}
};
const receive = () => {
if (active.size) {
const stale = [...active];
setTimeout(() => cancel(stale), settleDelay);
}
for (let i = 0; i < frames.length; i++)
frames[i].postMessage({type: messageType}, '*');
};
window.acodeNativeTouchEnd = receive;
window.addEventListener('message', event => {
if (event.source === parent && event.data?.type === messageType)
receive();
});
})();
"""
}
2 changes: 2 additions & 0 deletions platforms/ios/runner/WebViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ final class WebViewController: UIViewController {
var isFullscreenLayout: Bool { fullscreenLayout.first?.isActive == true }
private var scrollObservation: NSKeyValueObservation?
private var contextMenu: WebContextMenu?
private var touchEnd: WebTouchEnd?

override func viewDidLoad() {
super.viewDidLoad()
Expand All @@ -38,6 +39,7 @@ final class WebViewController: UIViewController {
config.allowsInlineMediaPlayback = true
webView = AppWebView(frame: .zero, configuration: config)
contextMenu = WebContextMenu(webView: webView)
touchEnd = WebTouchEnd(webView: webView)
webView.navigationDelegate = self
#if DEBUG
webView.isInspectable = true
Expand Down
18 changes: 18 additions & 0 deletions platforms/ios/runner/lib/FileContents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,24 @@ struct FileContents {
return String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(value))
}

/// Like Android's `new String(bytes, charset)`, malformed bytes become U+FFFD instead of failing the decode.
static func decode(_ data: Data, as name: String) throws -> String {
let target = try encoding(name)
if let text = String(data: data, encoding: target) { return text }
if target == .utf8 {
let bom: [UInt8] = [0xEF, 0xBB, 0xBF]
return String(decoding: data.starts(with: bom) ? data.dropFirst(bom.count) : data, as: UTF8.self)
}
var converted: NSString?
_ = NSString.stringEncoding(for: data, encodingOptions: [
.suggestedEncodingsKey: [target.rawValue],
.useOnlySuggestedEncodingsKey: true,
.allowLossyKey: true,
], convertedString: &converted, usedLossyConversion: nil)
guard let converted else { throw FileFailure(5) }
return converted as String
}

static func availableEncodings() -> [String: Any] {
var result: [String: Any] = [:]
for value in String.availableStringEncodings {
Expand Down
4 changes: 2 additions & 2 deletions platforms/ios/runner/lib/SystemService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ final class SystemService: BaseService {
guard let text = args[safe: 0] as? String, let data = text.data(using: try FileContents.encoding(args[safe: 1] as? String ?? "UTF-8")) else { throw FileFailure(5) }
callback.successBinary(data)
case "decode":
guard let encoded = args[safe: 0] as? String, let data = Data(base64Encoded: encoded), let text = String(data: data, encoding: try FileContents.encoding(args[safe: 1] as? String ?? "UTF-8")) else { throw FileFailure(5) }
callback.success(text)
guard let encoded = args[safe: 0] as? String, let data = Data(base64Encoded: encoded) else { throw FileFailure(5) }
callback.success(try FileContents.decode(data, as: args[safe: 1] as? String ?? "UTF-8"))
case "getInstaller": callback.success("appstore")
case "getRewardStatus": callback.success(try rewards.getRewardStatus())
case "get-android-version": callback.success(0)
Expand Down
2 changes: 2 additions & 0 deletions platforms/ios/runner/lib/preview/PreviewViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ final class PreviewViewController: UIViewController {
private(set) var isClosed = false
private var observations: [NSKeyValueObservation] = []
private var contextMenu: WebContextMenu?
private var touchEnd: WebTouchEnd?
private var contentBottom: NSLayoutConstraint?
private var contentFollowsKeyboard = true

Expand All @@ -46,6 +47,7 @@ final class PreviewViewController: UIViewController {
webView = WKWebView(frame: .zero, configuration: configuration)
super.init(nibName: nil, bundle: nil)
contextMenu = WebContextMenu(webView: webView)
touchEnd = WebTouchEnd(webView: webView)
modalPresentationStyle = .fullScreen
}

Expand Down
4 changes: 3 additions & 1 deletion platforms/ios/runnerTests/BridgeTestCase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ class BridgeTestCase: XCTestCase {
}

func appWebView() async throws -> WKWebView {
for _ in 0..<100 {
// Cold hosted simulators can take close to a minute to finish the first page load.
let deadline = ContinuousClock.now + .seconds(90)
while ContinuousClock.now < deadline {
for scene in UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene }) {
for window in scene.windows {
if let webView = findWebView(window), webView.url?.scheme == "acode", !webView.isLoading,
Expand Down
8 changes: 8 additions & 0 deletions platforms/ios/runnerTests/FileContentsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ import WebKit

@MainActor
final class FileContentsTests: BridgeTestCase {
func testDecodeReplacesMalformedBytesLikeAndroid() throws {
let binary = Data([0x89, 0x50, 0x4E, 0x47, 0x00, 0xFF, 0xFE, 0x41])
XCTAssertEqual(try FileContents.decode(binary, as: "UTF-8"), "\u{FFFD}PNG\u{0}\u{FFFD}\u{FFFD}A")
XCTAssertEqual(try FileContents.decode(Data([0xEF, 0xBB, 0xBF, 0x41, 0xFF]), as: "UTF-8"), "A\u{FFFD}")
XCTAssertEqual(try FileContents.decode(Data("Acode ✓".utf8), as: "UTF-8"), "Acode ✓")
XCTAssertEqual(try FileContents.decode(Data([0x41, 0x00, 0x00, 0xD8]), as: "UTF-16LE"), "A\u{FFFD}")
}

func testNativeReadRangesAndBinaryRepresentationsMatchBytes() async throws {
let app = try await editorWebView()
let file = AppFiles.shared.cache.appendingPathComponent("ios-read-ranges-" + UUID().uuidString + ".bin")
Expand Down
28 changes: 23 additions & 5 deletions platforms/ios/runnerTests/PreviewTransferTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,17 +77,35 @@ final class PreviewTransferTests: BridgeTestCase {
while responder != nil, !(responder is WebViewController) { responder = responder?.next }
let host = try XCTUnwrap(responder as? WebViewController)
XCTAssertNil(host.presentedViewController)
let browser = PreviewViewController(url: try XCTUnwrap(URL(string: origin)), theme: [:], console: false, dataStore: dataStore)
let url = try XCTUnwrap(URL(string: origin))
let browser = PreviewViewController(url: url, theme: [:], console: false, dataStore: dataStore)
browser.consoleEnabled = false
let loaded = expectation(description: "Initial preview navigation finished")
var loaded = XCTestExpectation(description: "Initial preview navigation finished")
loaded.assertForOverFulfill = false
browser.onPageFinished = { loaded.fulfill() }
await withCheckedContinuation { continuation in host.present(browser, animated: false) { continuation.resume() } }
addTeardownBlock { @MainActor in
if browser.presentingViewController != nil { await self.close(browser) }
}
await fulfillment(of: [loaded], timeout: 5)
browser.onPageFinished = nil
return browser
defer { browser.onPageFinished = nil }
if await XCTWaiter().fulfillment(of: [loaded], timeout: 5) == .completed { return browser }
// Hosted simulators occasionally stall a new web process's first load, which these
// tests are not about, so load once more before treating it as a failure.
let firstFailure = dismissNavigationError(browser)
loaded = XCTestExpectation(description: "Retried preview navigation finished")
loaded.assertForOverFulfill = false
browser.load(url)
if await XCTWaiter().fulfillment(of: [loaded], timeout: 10) == .completed { return browser }
let failure = dismissNavigationError(browser) ?? firstFailure ?? "no navigation error reported"
XCTFail("Preview never finished loading \(origin): \(failure)")
throw NSError(domain: "PreviewTransferTests", code: 1)
}

private func dismissNavigationError(_ browser: PreviewViewController) -> String? {
let message = browser.activeDialog?.message
browser.pendingDialog?()
browser.activeDialog?.dismiss(animated: false)
return message
}

private func finishNavigation(_ browser: PreviewViewController, _ navigate: () throws -> Void) async throws {
Expand Down
Loading
Loading