Skip to content
Merged
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
8 changes: 0 additions & 8 deletions Sources/Adwaita/Generated/SpinRow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -159,11 +159,3 @@ public final class SpinRow: ActionRow {
SignalHelper.connect(self, signal: .wrapped, handler: handler)
}
}

/// Reads the text of a `GtkEditable` (which `AdwSpinRow` is) from its instance
/// pointer. Kept at file scope so the `input` signal closure can read the
/// entry's text without capturing the `SpinRow` wrapper, which would keep the
/// wrapper alive forever.
private func spinRowEditableText(_ ptr: OpaquePointer) -> String {
String(cString: gtk_editable_get_text(ptr))
}
12 changes: 12 additions & 0 deletions Sources/Adwaita/SpinRow+Editable.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: 2026 Sergey Armodin

import CAdwaita

/// Reads the text of a `GtkEditable` (which `AdwSpinRow` is) from its instance
/// pointer. Kept as a free function so the `input` signal closure can read the
/// entry's text without capturing the `SpinRow` wrapper, which would keep the
/// wrapper alive forever.
func spinRowEditableText(_ ptr: OpaquePointer) -> String {
String(cString: gtk_editable_get_text(ptr))
}
2 changes: 1 addition & 1 deletion Sources/GObjectSupport/Signal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -656,7 +656,7 @@ public enum SignalHelper {
trampoline: unsafeBitCast(
signalTrampolineDragCancel as @convention(c) (
UnsafeMutableRawPointer,
OpaquePointer,
OpaquePointer?,
UInt32,
UnsafeMutableRawPointer
) -> gboolean,
Expand Down
2 changes: 1 addition & 1 deletion Sources/GObjectSupport/SignalTrampolines.swift
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ func signalTrampolineInput(
/// animation runs; the Swift handler is invoked purely as an observer.
func signalTrampolineDragCancel(
_ instance: UnsafeMutableRawPointer,
_ drag: OpaquePointer,
_ drag: OpaquePointer?,
_ reason: UInt32,
_ userData: UnsafeMutableRawPointer
) -> gboolean {
Expand Down
19 changes: 19 additions & 0 deletions Tests/AdwaitaTests/MediaProtocolTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,25 @@ extension SerializedLifecycleSuites {
conn.disconnect()
}

@Test @MainActor func spinRowOnInputSignalDoesNotLeakRow() {
ensureAdwInit()
// Regression test for the `self` capture: when the `input`
// trampoline closure captured the `SpinRow` wrapper, the C object
// kept the closure box, the box kept the wrapper, and the wrapper
// kept the C object — a cycle the row could never break, so it
// never finalized. The handler must capture nothing, and the row
// must go away once the wrapper leaves scope.
var weakSlot: WeakPointerSlot?
do {
let row = SpinRow(title: "Volume", min: 0, max: 100, step: 1)
row.value = 1
weakSlot = WeakPointerSlot(watching: row.gobjectPointer)
row.onInput { _ in .value(1) }
}
spinMainLoop()
#expect(weakSlot?.isCleared == true, "the SpinRow must finalize once the wrapper goes out of scope")
}

@Test @MainActor func expanderRowConvenienceInit() {
ensureAdwInit()
let row = ExpanderRow(title: "Advanced")
Expand Down
46 changes: 31 additions & 15 deletions Tests/AdwaitaTests/NavigationAndTabTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,22 @@ struct NavigationAndTabTests {
conn.disconnect()
}

@Test @MainActor func tabViewOnClosePageReturnFalseClosesPage() {
ensureAdwInit()
let tabView = TabView()
let page = tabView.append(Label("x"))
var fired = false
let conn = tabView.onClosePage { p in
fired = true
_ = p
return false
}
tabView.closePage(page)
#expect(fired, "onClosePage handler should fire")
#expect(tabView.nPages == 0, "returning false must fall through to the default close")
conn.disconnect()
}

@Test @MainActor func tabViewOnCreateWindowSignal() {
ensureAdwInit()
let tabView = TabView()
Expand Down Expand Up @@ -266,7 +282,7 @@ struct NavigationAndTabTests {
ensureAdwInit()
let navView = NavigationView()
var created = false
var weakSlot: UnsafeMutableRawPointer?
var weakSlot: WeakPointerSlot?
// The handler keeps NO reference to the page it creates. This is the
// case that would use-after-free if the return-object trampoline failed
// to add its `g_object_ref` before the caller's temporary `NavigationPage`
Expand All @@ -276,19 +292,20 @@ struct NavigationAndTabTests {
navView.onGetNextPage {
created = true
let p = NavigationPage(child: Label("next"), title: "next")
weakSlot = p.pointer
g_object_add_weak_pointer(p.gobjectPointer, &weakSlot)
weakSlot = WeakPointerSlot(watching: p.gobjectPointer)
return p
}
let raw = cadw_signal_emit_get_next_page(navView.gobjectPointer)
#expect(created, "onGetNextPage handler should fire")
#expect(raw != nil, "the signal must hand back a live reference to the page")
#expect(weakSlot != nil, "the page must still be alive once handed to the caller (transfer-full ref)")
#expect(weakSlot != nil, "the handler must have registered the weak pointer")
let stillAlive = weakSlot?.isCleared == false
#expect(stillAlive, "the page must still be alive once handed to the caller (transfer-full ref)")
if let raw {
g_object_unref(raw.assumingMemoryBound(to: GObject.self))
}
spinMainLoop()
#expect(weakSlot == nil, "the page must finalize exactly once after the caller releases it")
#expect(weakSlot?.isCleared == true, "the page must finalize exactly once after the caller releases it")
}

@Test @MainActor func tabViewTransferPage() {
Expand Down Expand Up @@ -333,24 +350,23 @@ struct NavigationAndTabTests {
// With the refcount balanced the page finalizes exactly once (weak
// pointer reset to NULL); an over-release crashes and a leak keeps the
// weak pointer set.
var weakSlot: UnsafeMutableRawPointer?
var weakSlot: WeakPointerSlot?
if let page = tabView.selectedPage {
// Seed the weak slot with the live pointer and watch it: on a
// balanced refcount the page finalizes exactly once (when `page`
// and the tab view both release it on close) and the slot is reset
// to NULL; an over-release crashes earlier, a leak leaves it set.
// The check lives below the `if` so `page`'s own reference is
// dropped first — otherwise the page cannot reach refcount zero.
weakSlot = page.pointer
g_object_add_weak_pointer(page.gobjectPointer, &weakSlot)
// Watch the underlying C object from a heap slot: on a balanced
// refcount the page finalizes exactly once (when `page` and the
// tab view both release it on close) and the slot is cleared; an
// over-release crashes earlier, a leak leaves it set. The check
// lives below the `if` so `page`'s own reference is dropped
// first — otherwise the page cannot reach refcount zero.
weakSlot = WeakPointerSlot(watching: page.gobjectPointer)
tabView.onClosePage { p in
tabView.closePageFinish(p, confirm: true)
return true
}
tabView.closePage(page)
}
spinMainLoop()
#expect(weakSlot == nil, "Closed page must finalize exactly once (balanced refcount)")
#expect(weakSlot?.isCleared == true, "Closed page must finalize exactly once (balanced refcount)")
}

// MARK: - TabBar Tests
Expand Down
31 changes: 31 additions & 0 deletions Tests/AdwaitaTests/TestHelpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,37 @@ func withMainLoopDrain<T>(iterations: Int = 20, _ body: () throws -> T) rethrows
return result
}

/// A stable heap slot for `g_object_add_weak_pointer`.
///
/// `&local` addresses are only valid for the duration of the C call, but GLib
/// stores the slot for as long as the watched object can still finalize, so it
/// must live on the heap instead. When this instance goes out of scope the
/// weak pointer is removed if the watched object is still alive (so it can
/// never write into the deallocated slot), and the slot is deallocated.
final class WeakPointerSlot {
private let slot: UnsafeMutablePointer<UnsafeMutableRawPointer?>
private let object: UnsafeMutablePointer<GObject>

init(watching object: UnsafeMutablePointer<GObject>) {
self.object = object
slot = .allocate(capacity: 1)
slot.initialize(to: UnsafeMutableRawPointer(object))
g_object_add_weak_pointer(object, slot)
}

/// Whether GLib cleared the slot, i.e. the watched object finalized.
var isCleared: Bool {
slot.pointee == nil
}

deinit {
if !isCleared {
g_object_remove_weak_pointer(object, slot)
}
slot.deallocate()
}
}

actor BoolRecorder {
private var value = false

Expand Down
2 changes: 1 addition & 1 deletion Tests/AdwaitaTests/macOS/ExpandedWidgetXCTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ final class ExpandedWidgetXCTests: XCTestCase {
XCTAssertNotNil(overview.child)
}

@MainActor func test_tabOverviewCreateTabSignal() {
@MainActor func test_tabOverviewCreateTabSignalConnect() {
ensureAdwInit()
let overview = TabOverview()
let tabView = TabView()
Expand Down
15 changes: 15 additions & 0 deletions Tests/AdwaitaTests/macOS/InputDialogXCTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,21 @@ final class InputDialogXCTests: XCTestCase {
XCTAssertTrue(source.isDragging == false)
}

@MainActor func test_dragSourceOnDragCancelledSignal() {
ensureAdwInit()
let source = DragSource()
var fired = false
let conn = source.onDragCancelled {
fired = true
}
XCTAssertFalse(fired, "onDragCancelled should not fire before a drag is cancelled")
// Real `GtkDragSource::drag-cancel` is `(GdkDrag*, GdkDragCancelReason) ->
// gboolean` (see Gtk-4.0.gir); the emit shim and the C trampoline match it.
_ = cadw_signal_emit_drag_cancel(source.pointer, nil, 0)
XCTAssertTrue(fired, "onDragCancelled must fire when the drag-cancel signal is emitted")
conn.disconnect()
}

// MARK: - DropTarget

@MainActor func test_dropTargetCreation() {
Expand Down
62 changes: 62 additions & 0 deletions Tests/AdwaitaTests/macOS/MediaProtocolXCTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,68 @@ final class MediaProtocolXCTests: XCTestCase {
XCTAssertTrue(row.title == "Volume")
}

@MainActor func test_spinRowOnOutputSignalReturnsBool() {
ensureAdwInit()
let row = SpinRow(title: "Volume", min: 0, max: 100, step: 1)
row.value = 42
var called = false
let conn = row.onOutput {
called = true
return true
}
let ret = cadw_signal_emit_bool_return(row.pointer, "output")
XCTAssertTrue(called, "onOutput handler should fire")
XCTAssertTrue(ret != 0, "the handler's TRUE must become the signal's return value")
conn.disconnect()
}

@MainActor func test_spinRowOnInputSignalWritesValue() {
ensureAdwInit()
let row = SpinRow(title: "Volume", min: 0, max: 100, step: 1)
row.value = 1
var called = false
let conn = row.onInput { text in
called = true
_ = text
return .value(7)
}
var outValue: Double = -1
let ret = cadw_signal_emit_spin_row_input(row.pointer, &outValue)
XCTAssertTrue(called, "onInput handler should fire")
XCTAssertEqual(ret, 1, "a .value result must return TRUE (1)")
XCTAssertEqual(outValue, 7.0, "the handler must write the value through the out-pointer")
conn.disconnect()
}

@MainActor func test_spinRowOnInputReceivesEditableText() {
ensureAdwInit()
let row = SpinRow(title: "Volume", min: 0, max: 100, step: 1)
row.value = 42
var received: String?
let conn = row.onInput { text in
received = text
return .value(Double(text) ?? 0)
}
var outValue: Double = -1
_ = cadw_signal_emit_spin_row_input(row.pointer, &outValue)
let editableText = String(cString: gtk_editable_get_text(row.opaquePointer))
XCTAssertNotNil(received, "onInput handler should fire")
XCTAssertEqual(received, editableText, "onInput must receive the row's current editable text")
XCTAssertEqual(outValue, 42.0, "the handler must parse the text back to the row's value")
conn.disconnect()
}

@MainActor func test_spinRowOnInputSignalInvalid() {
ensureAdwInit()
let row = SpinRow(title: "Volume", min: 0, max: 100, step: 1)
let conn = row.onInput { _ in .invalid }
var outValue: Double = -1
let ret = cadw_signal_emit_spin_row_input(row.pointer, &outValue)
XCTAssertEqual(ret, -1, "an .invalid result must return GTK_INPUT_ERROR (-1)")
_ = outValue
conn.disconnect()
}

@MainActor func test_expanderRowConvenienceInit() {
ensureAdwInit()
let row = ExpanderRow(title: "Advanced")
Expand Down
Loading
Loading