david-swift 04c77831b5
Some checks are pending
Deploy Docs / publish (push) Waiting to run
SwiftLint / SwiftLint (push) Waiting to run
Remove Core library
2025-10-30 21:36:13 +01:00

46 lines
1.4 KiB
Swift

//
// Picture+.swift
// Adwaita
//
// Created by david-swift on 21.04.24.
//
import CAdw
import Foundation
extension Picture {
/// Load the picture from Foundation's `Data`.
/// - Parameter data: The data.
/// - Returns: The view.
public func data(_ data: Data?) -> AnyView {
let oldData = "old-data"
return inspect { storage, updateProperties in
if updateProperties {
let pointer = storage.opaquePointer
guard let data else {
if storage.fields[oldData] != nil {
g_object_unref(gtk_picture_get_paintable(pointer)?.cast())
gtk_picture_set_paintable(pointer, gdk_paintable_new_empty(0, 0))
storage.fields[oldData] = nil
}
return
}
guard data != storage.fields[oldData] as? Data else {
return
}
let bytes = data.withUnsafeBytes { ptr in
g_bytes_new(ptr.baseAddress, .init(data.count))
}
let texture = gdk_texture_new_from_bytes(bytes, nil)
if let paintable = gtk_picture_get_paintable(pointer) {
g_object_unref(paintable.cast())
}
gtk_picture_set_paintable(pointer, texture)
storage.fields[oldData] = data
}
}
}
}