apple

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 46 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Rendered for darwin/amd64

Overview

Package apple holds what the AppKit and UIKit backends share, called through purego without cgo: CoreFoundation strings, CoreGraphics colors and canvases, layer styles and transitions, the CoreText text engine, which prepares and lays text out on the engine goroutine for the main thread to draw, and image views, which load and decode off it.

Index

Constants

This section is empty.

Variables

View Source
var GameServicesAvailable = sync.OnceValue(func() bool {
	if _, err := purego.Dlopen(gameKitPath, purego.RTLD_LAZY|purego.RTLD_GLOBAL); err != nil {
		return false
	}
	return Class("GKLocalPlayer") != 0
})

GameServicesAvailable is Environment.CanUseGameServices: whether GameKit loads on this macOS, iOS or tvOS device and exposes GKLocalPlayer.

View Source
var HoldTransforms func(layer objc.ID)

HoldTransforms, when a backend sets it, gives layer the class of HeldTransformMethods as SetTransform first holds a transform for it. Only layers that hold one take that class: AppKit sets each layer's transform as it places its view, and the override's call into Go cost every frame change a few microseconds.

Functions

func AnimateIn

func AnimateIn(layer objc.ID, a driver.ModalAnimation, distance float64, reduceMotion bool, done func())

AnimateIn presents a modal's layer as a asks: sliding up from distance points below, or fading in, and calls done once the entrance finishes (at once when there is no animation). Reduced motion fades instead of sliding.

func AppGroupContainer

func AppGroupContainer(group string) (string, error)

AppGroupContainer returns the shared container granted by the bundle's signature. Call on the main thread, as other bundle startup work does.

func AppleSignInAvailable added in v0.2.0

func AppleSignInAvailable() bool

AppleSignInAvailable is Environment.SignInWithApple: every macOS, iOS and tvOS NSGo runs on has AuthenticationServices, which loads only once a request starts.

func ApplyAnimated

func ApplyAnimated[V comparable](a *driver.Animator, viewOf func(driver.NodeID) V, values func(V) *driver.AnimatedValues, restyle, redrawText, redrawCanvas func(V), component func(V) driver.NativeComponent, repin func())

ApplyAnimated delivers changed values to the views still on a surface. Styles and text update before canvases and native props, then sticky cells follow their animated insets.

func AudioAvailable

func AudioAvailable() bool

AudioAvailable is Environment.Audio: every macOS and iOS NSGo runs on has AVFoundation, which loads only once a sound or a player does.

func BackdropFilters added in v0.2.0

func BackdropFilters(filters []driver.Filter) objc.ID

BackdropFilters returns a CABackdropLayer's filters for filters: their widest blur, then their color filters as one matrix, the order Windows draws them in; 0 when they change nothing. CAFilter's colorMatrix reads the matrix as a CAColorMatrix under inputColorMatrix and ignores Core Image's inputRVector keys. Drop shadows are left out, as CSS's backdrop-filter has no shadow to draw. The array is autoreleased.

func BundleName

func BundleName(lang string) string

BundleName returns the app's name in lang as its bundle's InfoPlist.strings says it, in the localization that suits lang best; "" when the bundle names it in none.

func Bytes

func Bytes(data objc.ID) []byte

Bytes copies the bytes of an NSData.

func CFString

func CFString(s string) uintptr

CFString returns a new CFString (an NSString) holding s. The caller releases it.

func CGColor

func CGColor(c driver.Color) uintptr

CGColor returns a new CGColor of c. The caller releases it.

func CallBlock

func CallBlock(block objc.ID, args ...uintptr) uintptr

CallBlock calls a block another language made, such as a Swift closure Objective-C passed NSGo, with up to six object, pointer or integer arguments, and returns its result's register. purego's Block.Invoke calls only the blocks it made.

func CaptureUncaughtExceptions

func CaptureUncaughtExceptions(record func(string)) func()

CaptureUncaughtExceptions saves exceptions that reach Foundation's uncaught exception handler and chains to the previous handler.

func CheckAppStore

func CheckAppStore(c updates.Config, mac bool, id uint32, dispatch func(driver.Event))

CheckAppStore is the shared Apple path for updater.Check: capture the installed bundle's identity, version and storefront country on the main thread, then query the store off it. The Mac's lookup selects Mac software.

func Class

func Class(name string) objc.Class

Class returns the class named name, or 0 while none is loaded.

func ClearBackgroundAnimation

func ClearBackgroundAnimation(layer objc.ID)

ClearBackgroundAnimation cancels any running background color transition on layer.

func ClearBoundAnimations

func ClearBoundAnimations(layer objc.ID, bound uint16)

ClearBoundAnimations removes active style transitions on layer (and its border or cover sublayers) for properties named in bound, leaving transitions on unbound properties running.

func ClipHolder added in v0.2.0

func ClipHolder(layer objc.ID, vs *driver.ViewStyle, scrolls bool)

ClipHolder clips layer, the layer of the view holding a view's children, to the box and corners of vs, the view's style; nil or a style that does not clip leaves the children unclipped, or clipped to the holder's bounds for a scroll view's container (scrolls), as NSClipView clips. Corners of different radii take a shape mask over the current bounds; a scroll holder calls this again after committing a new bounds origin. A mask an effect set in its place, hiding the children, stays until the effect puts back HolderMask. A holder that is not a scroll view's container also takes the view's perspective (ChildPerspective), clipping or not, which would otherwise stop at the holder.

func CloseNotification

func CloseNotification(id string)

CloseNotification removes the notification called id, shown or still to show, and every one the app's notification center holds when id is empty, those earlier runs left included. A macOS app that never used notifications has none to close, and closing leaves its center untouched, as an app clearing them each time it comes to the front would otherwise make its Dock badge wait for the user to allow badges.

func CloudStorageAvailable

func CloudStorageAvailable() bool

CloudStorageAvailable is Environment.CloudStorage on Apple platforms: true when NSFileManager.defaultManager.ubiquityIdentityToken is non-nil, meaning the user is signed into iCloud and the app has iCloud access. This check never blocks on network I/O.

func CodeFromMetadata

func CodeFromMetadata(objects objc.ID, r driver.ScanRequest) *driver.ScannedCode

CodeFromMetadata returns the first requested code with a text value.

func CollectText

func CollectText(native objc.ID, out *[]string, text func(objc.ID) (string, bool))

CollectText collects visible text in native subtree order. text reports whether a managed view is text, including text with an empty label.

func CommonModes

func CommonModes() objc.ID

CommonModes returns NSRunLoopCommonModes. Run loop sources compare modes by identity, so an equal string of another object is a mode of its own that never runs.

func CompletePictureInPictureRestore

func CompletePictureInPictureRestore(token uint32)

CompletePictureInPictureRestore acknowledges an engine restoration after its mount batch has applied, even if that batch removed the view.

func ConfigureDownloads

func ConfigureDownloads(dataDir, identifier string, background bool)

ConfigureDownloads connects the app-wide transfer channel. Background sessions reconnect at launch when a previous transfer left a journal. Call on the main thread before starting the app's engine.

func ContentTypes

func ContentTypes(r driver.FilesRequest) objc.ID

ContentTypes returns the UTTypes of the files r offers, for NSOpenPanel and UIDocumentPickerViewController: every file, as public.data, when r names none or one the system has no type for.

func CroppedPNG

func CroppedPNG(image uintptr, region CGRect) ([]byte, error)

CroppedPNG encodes a region of an already composited CGImage in sRGB.

func CustomAccessibilityAction

func CustomAccessibilityAction(action objc.ID, actions []driver.AccessibilityAction, perform func(string) bool) bool

CustomAccessibilityAction resolves VoiceOver's label to the action's name. An action without a label uses its name as the spoken label.

func DiskSpace

func DiskSpace(path string, count uint32, separate bool, dispatch func(driver.Event))

DiskSpace answers a volume capacity request. The mount loop starts this off the main thread. tvOS and watchOS offer one available-space figure.

func DrawTopDown

func DrawTopDown(ctx uintptr, height float64, flip bool, draw func(baseUp bool))

DrawTopDown runs draw with ctx's state saved and its y axis pointing down over a layer height tall; flip turns a y-up context, which Core Animation gives a layer whose contents are not flipped, top down. Core Graphics offsets shadows in the context's base space, which points down when Core Animation flipped the context and up when flip did: draw learns which as baseUp.

func EdgeBlur

func EdgeBlur(s driver.Side, d driver.EdgeEffect) objc.ID

EdgeBlur returns a CABackdropLayer's filters for effect d at side s: a blur growing toward a soft side, or an even one.

func Encode

func Encode(data []byte, maxPixels int, jpeg bool, quality float32) ([]byte, driver.Size, error)

Encode decodes data upright, scales it so its longer side has at most maxPixels (0: its size) and encodes it as a PNG, or as a JPEG of quality when jpeg. It returns the bytes and their size in pixels.

func FadeImage

func FadeImage(s driver.Side) uintptr

FadeImage returns a new CGImage of a soft edge's fade at side s, 64 pixels along the band and 1 across: opaque at the side, clear at the other end, for a variable blur to stretch over its band as its mask. The caller releases it.

func FillRects

func FillRects(ctx uintptr, rects []CGRect, color uintptr)

FillRects fills rects with color, a CGColor.

func FitBackdrop

func FitBackdrop(backdrop objc.ID, vs *driver.ViewStyle, w, h float64)

FitBackdrop lays backdrop, the blur of a view of style vs and size w by h, under the rim, on the view's curve: inside the border by whole points, as a blur on a fraction of a point lands between pixels, the fill closing the seam.

func FollowBounds

func FollowBounds(layer objc.ID)

FollowBounds keeps a layer's decoration on its box after its bounds origin moved, as a scroll view's does when it scrolls.

func Font

func Font(f driver.Font) uintptr

Font returns a CTFont (an NSFont or UIFont) for f: the system face unless f names a family. The caller releases it.

Fonts are immutable and few, so they are built once and handed out again by reference. Building one is seven CoreText calls through purego; a frame of a table asks for the same font forty times.

func ForEach

func ForEach(collection objc.ID, fn func(objc.ID))

ForEach calls fn with each object of an NSArray or NSSet.

func ForgetBorders

func ForgetBorders(layer objc.ID)

ForgetBorders forgets the borders of a layer that is going away.

func ForgetDecor

func ForgetDecor(layer objc.ID)

ForgetDecor forgets the decoration of a layer that is going away.

func ForgetHolder added in v0.2.0

func ForgetHolder(layer objc.ID)

ForgetHolder releases what ClipHolder made for a holder going away.

func ForgetTransform

func ForgetTransform(layer objc.ID)

ForgetTransform forgets the transform SetTransform gave a layer that is going away.

func GPUSupported

func GPUSupported() bool

GPUSupported reports whether the machine has a Metal device for gpu.View. Call it on the main thread.

func GaussianBackdrop added in v0.2.0

func GaussianBackdrop(radius float64) objc.ID

GaussianBackdrop returns a CABackdropLayer's filters for an even blur of radius points, the standard deviation as CSS's blur() has it: hard scroll edges and backdrop blurs. The array is autoreleased.

func Global

func Global(path, name string) objc.ID

Global reads the global object, such as an NSString constant, that framework at path exports as name; 0 when it has none.

func GoJSON

func GoJSON(o objc.ID) any

GoJSON returns Foundation's object o as Go's decoded JSON: maps, slices, strings, float64, bool or nil.

func GoString

func GoString(ns objc.ID) string

GoString returns the Go string of an NSString.

func HandleAppleSignIn added in v0.2.0

func HandleAppleSignIn(it *driver.MountItem, anchor objc.ID, dispatch func(driver.Event))

HandleAppleSignIn carries out an ItemSignInWithApple, its sheet shown over anchor, the window of the surface that asked, or an ItemAppleCredentialState, on the main thread, answering through dispatch.

func HandleAuthSession added in v0.2.0

func HandleAuthSession(id uint32, r driver.AuthRequest, anchor func() objc.ID, dispatch func(driver.Event))

HandleAuthSession carries out r for auth session id on the main thread: a start checks the session can catch the redirect and reports it, an open shows the URL over the window anchor returns, and a cancel ends it. dispatch runs on any goroutine.

func HandleBiometric

func HandleBiometric(it *driver.MountItem, dispatch func(driver.Event))

HandleBiometric carries out a biometric request on the main thread and dispatches its answer to the engine.

func HandleDownloadEvents

func HandleDownloadEvents(identifier string, completion objc.ID) bool

HandleDownloadEvents retains UIKit's background-session completion block until the session's events and file publications have finished. It reports whether the session identifier belongs to NSGo's transfer host.

func HandlePurchase added in v0.2.0

func HandlePurchase(it *driver.MountItem, anchor objc.ID, dispatch func(driver.Event))

HandlePurchase carries out an ItemPurchase, answering through dispatch.

func HandleSpeak added in v0.2.0

func HandleSpeak(id uint32, r driver.SpeakRequest, dispatch func(driver.Event))

HandleSpeak carries out an ItemSpeak of utterance or request id, on the main thread, reporting EventSpeak through dispatch.

func HandleSpeech

func HandleSpeech(id uint32, r driver.SpeechRequest, dispatch func(driver.Event))

HandleSpeech carries out an ItemSpeech for session id, on the main thread, reporting EventSpeech through dispatch.

func HandoffBackground

func HandoffBackground(from, to objc.ID)

HandoffBackground copies from's currently displayed background color (presentation color while transitioning, else model color) onto to without animation so a background transition on to starts from what the tint showed rather than from transparent.

func HeldTransformMethods

func HeldTransformMethods() []objc.MethodDef

HeldTransformMethods are the methods of a CALayer subclass that keeps the transform SetTransform gave it: AppKit sets its views' layers back to its own transform whenever it syncs their geometry.

func HolderMask added in v0.2.0

func HolderMask(layer objc.ID) objc.ID

HolderMask is the mask ClipHolder keeps on layer, 0 for none: what an effect that hid the holder's children puts back.

func ImageInfo

func ImageInfo(it *driver.MountItem, dispatch func(driver.Event))

ImageInfo answers an ItemImageInfo on a goroutine of its own: it loads the source, keeping its bytes for the views that show it next, and dispatches EventImageInfo with the size ImageIO reads, upright, or an SVG's in whole points.

func ImageSize added in v0.2.0

func ImageSize(image uintptr) (width, height int)

ImageSize is a CGImage's width and height in pixels.

func InLayoutGhost

func InLayoutGhost(ghosts []*LayoutGhost, native objc.ID) bool

InLayoutGhost reports whether native is inside a removed view still drawing its exit.

func JSONObject

func JSONObject(v any) objc.ID

JSONObject returns v as Foundation's objects, autoreleased, or 0 for nil or a value JSON cannot encode.

func KeepCanvasImage

func KeepCanvasImage(owner any, key string)

KeepCanvasImage pins key in the canvas and encoded image caches on behalf of owner so it is never evicted while kept; main thread only.

func KeyEvent added in v0.2.0

func KeyEvent(kind, flags uint, timestamp float64, window int, chars, ignoring string, repeat bool, code uint16) objc.ID

KeyEvent makes an AppKit key event of kind (NSEventTypeKeyDown or NSEventTypeKeyUp) for window, typing chars and ignoring without modifiers. AppKit must be loaded.

isARepeat and keyCode are the selector's last arguments and go on the stack, past the integer registers. Apple's arm64 ABI packs them by their natural size into one word, isARepeat in its low byte and keyCode from its third, which purego, giving each variadic argument a word of its own, would not; the x86-64 ABI gives each its own word, as purego does.

func KeyNames

func KeyNames(name string, flags uint) []string

KeyNames returns the names core.NormalizeKey gives a key press: the key named name with the modifier flags AppKit and UIKit share, first with Command as "mod", then as "meta".

func LanguageAttr

func LanguageAttr() objc.ID

LanguageAttr is CoreText's kCTLanguageAttributeName, which selects language-specific Han glyph forms, fallback fonts and line breaking.

func LayerBounds

func LayerBounds(layer, root objc.ID) (driver.Bounds, bool)

LayerBounds measures the border box through Core Animation's presentation hierarchy, including transforms and moving native scroll containers.

func LayerGeometry

func LayerGeometry(layer, root objc.ID) (driver.Matrix3D, driver.Size, bool)

LayerGeometry retains the native viewport's presentation transform and size.

func LayerGeometryAnimating

func LayerGeometryAnimating(layer objc.ID) bool

LayerGeometryAnimating asks only about animations that move the border box; an opacity-only animation needs no geometry refresh.

func LayerGeometryEnding

func LayerGeometryEnding(layer objc.ID) bool

LayerGeometryEnding reports finite geometry animations that an app test waits for, leaving endless keyframes out of its settling barrier.

func LayersAnimating

func LayersAnimating(observer *driver.GeometryObserver, views NativeViews) bool

LayersAnimating reports whether, while observer observes, a view's layer still animates its geometry.

func LayersEnding

func LayersEnding(views NativeViews) bool

LayersEnding reports whether a view's layer runs a finite geometry animation, which a test waits for.

func LayoutBorders

func LayoutBorders(layer objc.ID)

LayoutBorders fits a layer's per-side borders to its bounds after its frame changed.

func LayoutDecor

func LayoutDecor(layer objc.ID)

LayoutDecor fits a layer's decoration to its bounds after its frame changed.

func LinkFrameTime

func LinkFrameTime(link objc.ID) time.Time

LinkFrameTime returns when the frame of a display link (a CADisplayLink, or the one an NSView makes) will show, its targetTimestamp, on time.Now's base: a frame's time for engine.Engine.FrameAt, from within the link's callback.

func Locale

func Locale() (tag string, rtl bool)

Locale returns the user's locale as a BCP 47 tag, and whether their first preferred language is written right to left.

NSLocale says the languages the process launched with, which a language PinLanguage kept replaces until the next launch; the user's languages are read from their defaults instead, so following them again takes effect at once. A language the user chose for the app in System Settings stays theirs.

func LocaleSettings

func LocaleSettings() driver.LocaleSettings

LocaleSettings returns the regional preferences the user set in Language & Region: the first day of the week (NSCalendar's), the hours of NSDateFormatter's format for the j template, which 24-hour time changes, and NSLocale's measurement system.

func MainQueue

func MainQueue() objc.ID

MainQueue is the main dispatch queue, as AVFoundation's delegates take it.

func MediaTime

func MediaTime() time.Duration

MediaTime returns Core Animation's clock: the time since the system started, on which display links and NSEvent timestamps count too.

func MetadataKind

func MetadataKind(t string) (driver.CodeKind, bool)

MetadataKind is the kind of code of an AVMetadataObjectType, and whether it is one.

func MetadataTypes

func MetadataTypes(r driver.ScanRequest) []string

MetadataTypes are the AVMetadataObjectTypes r reads.

func Modifiers

func Modifiers(flags uint) driver.Modifiers

Modifiers returns the modifier keys among the flags AppKit and UIKit share.

func MoveBorders

func MoveBorders(layer, host objc.ID)

MoveBorders rehomes a per-side border above a backdrop's layer while keeping the view's children above it. Passing zero puts it back on layer.

func Msg

func Msg(id objc.ID, sel objc.SEL, args ...uintptr) uintptr

Msg sends sel to id with up to six arguments and a result that are objects, selectors, pointers, integers or booleans, through purego.SyscallN. objc.Send and ID.Send work each call out with reflection, which costs several times the message itself; what runs for every changed view of every frame sends with Msg.

func MsgBool

func MsgBool(id objc.ID, sel objc.SEL, args ...uintptr) bool

MsgBool is Msg for a BOOL result.

func NSData

func NSData(b []byte) objc.ID

NSData returns an autoreleased NSData holding a copy of b.

func NSString

func NSString(s string) objc.ID

NSString returns an autoreleased NSString holding s.

func NeedsClipHolder added in v0.2.0

func NeedsClipHolder(vs *driver.ViewStyle) bool

NeedsClipHolder reports whether a view that clips also draws outside its box: an outer shadow, a React Native shadow or an outline. Core Animation clips those with the children when a layer sets masksToBounds or a mask, so the backends clip such a view's children in a holder view of their own and leave the styled layer unclipped, as CSS keeps a box's own shadows and outline outside its overflow clip.

func NewChildContainer

func NewChildContainer(host, class objc.ID, layerBacked bool, child func(objc.ID) bool) objc.ID

NewChildContainer moves the host's managed children into a native view. A layer-backed AppKit container asks for a layer at creation.

func NewPhotoCapture

func NewPhotoCapture(device objc.ID) (session, output objc.ID, why string)

NewPhotoCapture configures a session to take photos with device, for macOS's TakePhoto, which shows the scanner's camera. The caller owns the returned session and photo output.

func NewScanCapture

func NewScanCapture(device objc.ID, r driver.ScanRequest) (session, output objc.ID, why string)

NewScanCapture configures a session to read the requested metadata types. The caller owns the returned session and metadata output.

func NotificationPermission

func NotificationPermission(ask bool, answer func(int))

NotificationPermission answers with whether the app may show notifications (driver.NotificationsNotAsked, ...), asking the user first when ask is set and the user was not asked yet. answer runs on any goroutine.

func NotificationsAvailable added in v0.2.0

func NotificationsAvailable() bool

NotificationsAvailable reports whether the process has a notification center, which also shows the notifications it schedules after the process ends: Environment.ScheduledNotifications. It leaves the center untouched, as the environment is read before the app uses notifications.

func NotificationsUsed added in v0.2.0

func NotificationsUsed() bool

NotificationsUsed reports whether the app checked or asked for the notification permission or showed a notification, in this run or an earlier one, without touching the center: a bundled macOS app whose process touched it has its Dock badge shown only while the user allows its badges.

func OSVersion

func OSVersion() driver.OSVersion

OSVersion returns the host operating system's major and minor versions.

func Observe

func Observe(center, name objc.ID, fn func(note objc.ID)) (stop func())

Observe calls fn on the main thread each time center posts name, until stop is called.

func ObserveProcessPower

func ObserveProcessPower(changed func()) func()

ObserveProcessPower calls changed on the main thread whenever Foundation reports a power constraint changed, until the returned function stops it.

func OnMain

func OnMain(fn func())

OnMain runs fn on the main thread after what is queued there already. It never waits, so any goroutine may call it.

func OpenAudioOutput

func OpenAudioOutput(conf driver.AudioOutputConfig) (driver.AudioOutput, error)

OpenAudioOutput opens a unit without activating the device or holding the process's audio session.

func OptionalNSString

func OptionalNSString(s string) objc.ID

OptionalNSString returns a string, or nil for an empty accessibility attribute.

func PNG

func PNG(data []byte) ([]byte, driver.Size, error)

PNG returns data as a PNG and its size in pixels: itself when it is one.

func PNGImage added in v0.2.0

func PNGImage(image uintptr) ([]byte, error)

PNGImage encodes an already composited CGImage as a PNG. The caller keeps ownership of image; this function does not retain or release it.

func PictureInPictureRestoreCompletion

func PictureInPictureRestoreCompletion(token uint32) func()

PictureInPictureRestoreCompletion reserves the native completion for a mount batch. Owner deletion during that batch cannot cancel it.

func PinLanguage

func PinLanguage(lang string)

PinLanguage keeps lang, the language the app forces, for what the system says in the app from its next launch: the bundle's name in the menu bar, the items it adds to menus, its panels and its controls' words, which follow the languages of the launch and not the app's. "" lets them follow the user's languages again, unless the user chose the app's language in System Settings since. A pseudo locale has no localization of the system's, and pins nothing; neither does a process outside a bundle.

func Play

func Play(ctx uintptr, ops []driver.DrawOp, host CanvasHost)

Play draws ops into ctx, a view's context with its y axis pointing down, as a web canvas would: CoreGraphics adds path points through the transform current when they are added, as the canvas does, and a fill, stroke or clip keeps the path.

func PlayOver

func PlayOver(ctx uintptr, ops []driver.DrawOp, split driver.CanvasSplit, host CanvasHost)

PlayOver plays ops as Play does, but over their static part drawn already (a CanvasLayer): the ops before split.At that split skips set only the state.

func PointerMatrix added in v0.2.0

func PointerMatrix(layer objc.ID) driver.Matrix3D

PointerMatrix returns the transform currently drawn by layer, around its top left. Presentation values include style transitions and additive keyframes, which a view's layout coordinates do not know.

func PreparePicked

PreparePicked returns f as r asks for it: its type and size as it shows filled in, encoded again as PNG or JPEG when r needs it.

func ProcessMemory

func ProcessMemory() (uint64, bool)

ProcessMemory returns the process' physical footprint in bytes: the dirty and compressed memory it owns, what Activity Monitor shows and what the system judges it by under memory pressure (unlike the resident size, it leaves out the frameworks' clean pages every process maps).

func ProcessPower

func ProcessPower() (driver.ThermalState, driver.LowPowerMode)

ProcessPower reads Foundation's current thermal state and Low Power Mode.

func PurchasesAvailable added in v0.2.0

func PurchasesAvailable() bool

PurchasesAvailable is Environment.Purchases: whether the bundle has the library, which loads on macOS 12, iOS 15 and tvOS 15 and later. Loading it starts listening to Transaction.updates, as StoreKit asks apps to from their launch.

func RGBAImage

func RGBAImage(pix []byte, w, h int) uintptr

RGBAImage returns a CGImage of a copy of pix, premultiplied RGBA rows of w pixels, or 0. The caller releases it with Release.

func RaiseThread

func RaiseThread()

RaiseThread gives the calling OS thread the main thread's quality of service, as NSH gives its engine thread. The engine's thread turns input into frames; at the default class the system may run it on efficiency cores, and the quotes benchmark's commits took about 15% longer and varied with the machine's load.

func RasterStep

func RasterStep(scale float32) float64

RasterStep is how many times its pixels a layer scaled by scale draws its content at: 1 up to its own size, then in steps of a half up to 4, so its text and drawings stay sharp while a zoom redraws them only as it passes a step.

func RasterizeDrawing

func RasterizeDrawing(d *driver.Drawing, width, height, scale float64) uintptr

RasterizeDrawing renders d's top-down operations over width × height logical points at scale pixels per point into a new retained CGImage with transparent background, returning 0 when d has no operations or the size is invalid. The caller must call Release on a non-zero result.

func RegisterClass

func RegisterClass(name string, super objc.Class, protocols []*objc.Protocol, methods []objc.MethodDef) objc.Class

RegisterClass registers an Objective-C class whose methods may call SendSuper. A selector defined twice panics naming it: the runtime refuses the second method with only its index, and the class is registered at launch, so every app would fail to start.

func RegisterFont

func RegisterFont(data []byte) error

RegisterFont registers font file data with CoreText for the process, as the app runs: text prepared from then on finds its families.

func RegisterFonts

func RegisterFonts(paths []string)

RegisterFonts registers the app's font files, paths under its resources, with CoreText for the process, so text finds them by their families. Call it before the first view.

func Release

func Release(ref uintptr)

Release calls CFRelease on a CoreFoundation object.

func ReleaseCanvasImage

func ReleaseCanvasImage(owner any, key string)

ReleaseCanvasImage releases one pin of key held by owner, trimming excess unkept entries once key is no longer pinned; main thread only.

func ReleaseCanvasImages

func ReleaseCanvasImages(owner any)

ReleaseCanvasImages releases every pin held by owner as its surface closes; main thread only.

func ReleaseOffscreen

func ReleaseOffscreen(id uint64)

ReleaseOffscreen drops the cached CGImage for offscreen resource id.

func RenderDrawing

func RenderDrawing(d *driver.Drawing, size driver.Size, scale float64) (*image.RGBA, error)

RenderDrawing plays a recording into owned RGBA pixels without a window. Its synchronous image resolver has no access to the view caches or main queue.

func ReportLayerGeometry

func ReportLayerGeometry(observer *driver.GeometryObserver, root objc.ID, views NativeViews) bool

ReportLayerGeometry sends observer the presented geometry of each view's layer in root's coordinates, when it observes, and reports whether a layer still animates its geometry, so the surface keeps its frames coming.

func RequestReview

func RequestReview(scene objc.ID)

RequestReview asks StoreKit to show a rating prompt on the main thread. Pass the calling surface's foreground-active scene on iOS and zero on macOS.

func RestyleLayer

func RestyleLayer(layer objc.ID, shown, vs *driver.ViewStyle, view objc.ID, bound uint16)

RestyleLayer draws vs with a layer that shows shown, the style StyleLayer last drew there; with none it draws vs at once. When the two differ only in opacity and transform, as an animation's frames do, it sets just those: drawing every property again remade its colors, shadow, filters and gradients each frame, and the window server drew them all again. bound names the properties currently driven by animated values or appearance motions, whose transitions are skipped.

func Retain

func Retain(ref uintptr) uintptr

Retain keeps a CoreFoundation object alive past the caller's ownership.

func ReviewAvailable

func ReviewAvailable() bool

ReviewAvailable reports whether this system has a StoreKit rating prompt.

func RotateLayer

func RotateLayer(layer objc.ID, radians float64)

RotateLayer turns layer by radians around its anchor point.

func SaveType

func SaveType(name string) objc.ID

SaveType returns the UTType of a file named name, for a save dialog to keep its extension, or 0 for a name without one.

func ScanCamera

func ScanCamera() objc.ID

ScanCamera returns the default video capture device, when available.

func Sel

func Sel(name string) objc.SEL

Sel returns the selector named name.

func SendSuper

func SendSuper[T any](self objc.ID, cmd objc.SEL, args ...any) T

SendSuper sends cmd to the superclass of the NSGo class self is an instance of, whatever subclass the runtime gave self since.

func SendSuperPoint

func SendSuperPoint(self objc.ID, cmd objc.SEL, p CGPoint) objc.ID

SendSuperPoint is SendSuper for a method that takes one point and returns an object, as hitTest: does. SendSuper registers a function and works the point's layout out with reflection at every call, several times what the method costs, and a hit test calls it for every view under the pointer. This sends through one function registered once, with the point as the two doubles every 64-bit Apple target passes it as.

func SetCenterBadge

func SetCenterBadge(count uint32) bool

SetCenterBadge sets the badge through the center, as iOS 16 and later do, and reports whether it could.

func SetImageCacheLimit

func SetImageCacheLimit(maxBytes int64)

SetImageCacheLimit sets the encoded image byte budget for both imageload's shared byte cache and Apple's canvas image cache, clamping negative values to zero and evicting excess unkept entries immediately; main thread only.

func SetManualNowPlaying

func SetManualNowPlaying(active bool)

SetManualNowPlaying suspends automatic publication by controlled macOS videos while a manual publication owns the system's controls.

func SetNotificationPress

func SetNotificationPress(press func(id string))

SetNotificationPress sends the presses of notifications to press, those heard before it first.

func SetPurchaseUpdates added in v0.2.0

func SetPurchaseUpdates(fn func(driver.Event))

SetPurchaseUpdates has fn hear the transactions the store updates outside a purchase, as EventPurchaseUpdate, those it delivered before first.

func SetSublayerTranslation

func SetSublayerTranslation(layer objc.ID, dx, dy float64)

SetSublayerTranslation moves layer's sublayers by (dx, dy) points, as a scroll view shows an offset its bounds do not have yet.

func SetTransform

func SetTransform(layer objc.ID, t driver.Transform)

SetTransform sets a layer's transform to t around its transform origin: its center, moved by its style's Origin.

func ShapedCorners added in v0.2.0

func ShapedCorners(vs *driver.ViewStyle) bool

ShapedCorners reports whether vs's rounded corners differ in radius, which a layer's own corner radius cannot draw and a shape mask does.

func ShowNotification

func ShowNotification(n driver.Notification, answer func(bool))

ShowNotification shows n, or schedules it for its At, replacing a notification of its ID, delivered or pending, and answers with whether the center took it: not without the permission. answer runs on any goroutine.

func SpeakAvailable added in v0.2.0

func SpeakAvailable() bool

SpeakAvailable is Environment.Speak: every macOS, iOS and tvOS NSGo runs on has AVSpeechSynthesizer, which loads only once the app speaks.

func SpeechAvailable

func SpeechAvailable() bool

SpeechAvailable is Environment.Speech: every macOS and iOS NSGo runs on has the Speech framework, which loads only once a session starts.

func StartCapture

func StartCapture(session objc.ID, running, failed func()) (stop func())

StartCapture is StartScanCapture that also runs running on main once the session runs.

func StartImages

func StartImages[V any](pending []V, scale float64, current func(V) bool, start func(V, float64)) []V

StartImages starts the current views queued by a mount batch and clears the retained queue before reusing its storage for the next batch.

func StartScanCapture

func StartScanCapture(session objc.ID, failed func()) (stop func())

StartScanCapture takes ownership of session and starts it off the main thread. Stop releases the session after startup returns, so a quick cancellation cannot leave the camera running. Failed runs on main.

func StyleLayer

func StyleLayer(layer objc.ID, was, vs *driver.ViewStyle, view objc.ID)

StyleLayer draws vs with a view's CALayer. An NSView whose layer it is takes the layer's shadow, as AppKit copies a view's shadow onto its layer. A style with a transition animates what it lists from the values shown; was is the style last drawn, nil for none.

func StyleLayerBound

func StyleLayerBound(layer objc.ID, was, vs *driver.ViewStyle, view objc.ID, bound uint16)

StyleLayerBound draws vs with layer like StyleLayer, skipping Core Animation transitions for properties named in bound (AnimatedValues.Set) so bound animated values keep moving immediately while unbound properties run vs.Transition.

func Subviews

func Subviews(view objc.ID) []objc.ID

Subviews returns a view's subviews, back to front.

func Super

func Super(self objc.ID, cmd objc.SEL, args ...any)

Super sends cmd to self's NSGo superclass, discarding the result.

func Tint

func Tint(ctx uintptr, r CGRect, c driver.Color)

Tint paints c over what ctx holds in r, where it holds anything: a text's bound color over all of its glyphs.

func TranslateCTM

func TranslateCTM(ctx uintptr, x, y float64)

TranslateCTM moves ctx's origin by x, y.

func UTType

func UTType() objc.ID

UTType is the UTType class, its framework loaded.

func UsesFilters

func UsesFilters(vs *driver.ViewStyle) bool

UsesFilters reports whether vs gives its layer Core Image filters.

func WatchNotifications

func WatchNotifications()

WatchNotifications makes NSGo the center's delegate; calling it again changes nothing. Call it as the app starts, before it finishes launching, so the press that launched it is heard; macOS calls it then only for an app that used notifications before (NotificationsUsed), so one that only sets a Dock badge never touches the center.

func WebCookies

func WebCookies(id uint32, r driver.WebCookiesRequest, dispatch func(driver.Event))

WebCookies carries out an ItemWebCookies in WKWebsiteDataStore's default store, whose WKHTTPCookieStore every web view but an Incognito one reads: it sets the cookies, lists them or removes every type of website data, and answers once WebKit has. The store exists without a web view, and WebKit writes it to disk, so a cookie with an expiry outlives the app. A target without WebKit, tvOS, has no store.

func WithoutAnimation

func WithoutAnimation(fn func())

WithoutAnimation runs fn with Core Animation's implicit animations off, so layers a backend adds itself change at once.

func YieldFrame

func YieldFrame()

YieldFrame passes the main goroutine through Go's scheduler. A frame clock calls it once a tick, on the main thread, which is enough for frames up to yieldWithin apart; between slower ones, a 60 Hz display's or a slowed animation's, a timer yields every yieldEvery until frames come that close again or stop.

func Z

func Z(order float64) float64

Z are those orders scaled down, so a child perspective (a sublayer transform that projects by depth) leaves these layers their size.

Types

type Audio

type Audio struct {
	// contains filtered or unexported fields
}

Audio is one engine's sounds and players, the audio package's on macOS and iOS (docs/architecture/audio.md), as NSH's speaker: a surface makes it with its first ItemAudio and closes it as it closes, so an app that makes no sound never opens the output. Its methods run on the main thread; sounds are read and decoded on goroutines of their own, whose results hop back there.

Sounds decode once, at their load, into an AVAudioPCMBuffer, through an AVAudioFile over a temporary file of their bytes as AVAudioFile reads only files, and play from memory on the engine's one AVAudioEngine: each playback is a voice, an AVAudioPlayerNode through an AVAudioUnitVarispeed, which gives the rate, and a mixer of its own, which gives the volume and stereo pan, as an effect between a player and the main mixer keeps the player's own mixing properties from it. Voices are reused once their buffer played, by sounds of their format; at the playback limit the oldest eligible voice stops. The engine starts at a playback, again after the system stopped it, as for a device change, and pauses a moment after the last playback ends, so the output is not held open; one that cannot start is silence, never an error.

Players are AVPlayers without a layer, as Video's, made at their first preload or play: their load is polled until the item is ready or fails, as a paused player reports no time, their position comes from a periodic time observer, their end from AVPlayerItemDidPlayToEndTimeNotification and a stop no command asked for from AVPlayerRateDidChangeNotification, besides the time observer. On iOS each holds the shared audio session (internal/audiosession) at the level its AudioSession asks for while it plays, and playing sounds hold it ambient; an interruption of the session pauses the players as it begins, and they stay paused as it ends.

func NewAudio

func NewAudio(dispatch func(driver.Event)) *Audio

NewAudio returns an engine's sounds and players, reporting EventAudio through dispatch.

func (*Audio) Close

func (a *Audio) Close()

Close stops every playback and player and frees the sounds; nothing is reported after it. Calling it again does nothing.

func (*Audio) Handle

func (a *Audio) Handle(id uint32, r *driver.AudioRequest)

Handle carries out an ItemAudio for sound or player id, on the main thread.

func (*Audio) PausePlayers

func (a *Audio) PausePlayers()

PausePlayers pauses the players playing, as the system would: what an iOS app does as it leaves the foreground, as NSH's do, and as an interruption begins.

type BackdropTint

type BackdropTint struct {
	// contains filtered or unexported fields
}

BackdropTint tracks and paints a view's background color on its backdrop's tint layer (macOS's tint view or iOS's UIVisualEffectView contentView), following background transitions and animated background values while leaving an active tint transition alone on frames that animate other properties.

func (*BackdropTint) Reset

func (t *BackdropTint) Reset()

Reset forgets the tint's styled state after the backdrop is removed or rebuilt, so the next style paints immediately without starting a transition.

func (*BackdropTint) Style

func (t *BackdropTint) Style(layer objc.ID, vs *driver.ViewStyle, animatedBackground bool)

Style updates layer with vs.Background, with the same transition and presentation-value retargeting as a view's own layer. Only color changes touch layer, so frames animating other properties leave an active tint transition alone. When animatedBackground is true, the bound background value takes over immediately and cancels any running background transition.

type CAFrameRateRange

type CAFrameRateRange struct {
	Minimum, Maximum, Preferred float32
}

CAFrameRateRange is the display link's range, in Hz.

func (CAFrameRateRange) Clamped

func (r CAFrameRateRange) Clamped(screen float32) CAFrameRateRange

Clamped limits the request to rates the screen can show.

type CGPoint

type CGPoint struct {
	X, Y float64
	// contains filtered or unexported fields
}

CGPoint, CGSize and CGRect match CoreGraphics' layouts on 64-bit Apple platforms.

type CGRect

type CGRect struct {
	Origin CGPoint
	Size   CGSize
	// contains filtered or unexported fields
}

func BoundsRect

func BoundsRect(bounds driver.Bounds) CGRect

BoundsRect returns a Core Graphics rectangle for the driver's box.

func Damaged

func Damaged(before, after []driver.DrawOp) (area CGRect, whole bool)

Damaged is the area of a canvas to draw again after its animated arguments played before now play after (driver.CanvasDamage), 2 points wider for anti-aliasing and rounded out to whole points; whole is set where only drawing all of it is right. An empty area draws nothing.

func IntersectRects

func IntersectRects(a, b CGRect) CGRect

IntersectRects returns the overlap of a and b, which has no size when neither extends inside the other.

func KeptContent

func KeptContent(laid, need CGRect) CGRect

KeptContent returns the frame for the content layer of a text, laid at laid, whose content needs need (ContentFrame): laid grown to hold need while that is no more than four times need's area, else need. Core Animation makes a new backing store for each new size of a layer, and a number changing every frame changes its width with it.

func Rect

func Rect(x, y, w, h float64) CGRect

Rect returns a CGRect.

type CGSize

type CGSize struct {
	Width, Height float64
	// contains filtered or unexported fields
}

func LoadStillImage

func LoadStillImage(ctx context.Context, src driver.ImageSource) (uintptr, CGSize)

LoadStillImage loads artwork upright. It blocks and returns a retained CGImage for the caller to release.

type CanvasHost

type CanvasHost struct {
	Ratio  float64
	Redraw func()
	Owner  any
	BaseUp bool
	// contains filtered or unexported fields
}

CanvasHost is the view a drawing plays in: the screen's pixels a point, what draws it again once an image it waits for loads, which Owner names so it waits once, and whether the context's base space points up (DrawTopDown).

type CanvasLayer

type CanvasLayer struct {

	// Drawing, Width and Height (in pixels) are what it was made for.
	Drawing       *driver.Drawing
	Width, Height int
	// contains filtered or unexported fields
}

CanvasLayer is what a drawing's static part (driver.CanvasSplit) paints, rasterized once into a CGLayer made for the contexts it is drawn into, as NSH's macOS Prefix: a frame then draws the layer and plays only the painting after it (PlayOver).

func NewCanvasLayer

func NewCanvasLayer(ctx uintptr, d *driver.Drawing, ops []driver.DrawOp, split driver.CanvasSplit,
	w, h, scale float64, host CanvasHost) *CanvasLayer

NewCanvasLayer rasterizes what ops paint before split.At into a layer made for ctx, w × h points at scale pixels each. It reports nil when an image the part draws has not loaded yet, which the layer would miss.

func (*CanvasLayer) Draw

func (l *CanvasLayer) Draw(ctx uintptr, w, h float64)

Draw draws the layer over ctx's top-down w × h points.

func (*CanvasLayer) Release

func (l *CanvasLayer) Release()

Release lets the layer go; l may be nil.

type Discovery

type Discovery struct {
	// contains filtered or unexported fields
}

Discovery holds the live Bonjour operations of a surface. Its requests, callbacks and deallocation all run on the native main queue.

func (*Discovery) Close

func (d *Discovery) Close()

Close releases the Bonjour registrations, browsers and resolvers of the surface.

func (*Discovery) Handle

func (d *Discovery) Handle(it *driver.MountItem, dispatch func(driver.Event))

Handle starts or stops the requested DNS-SD operation on the main queue.

type Effect

type Effect struct {
	// contains filtered or unexported fields
}

Effect draws a shader over native children without changing their input. The platform supplies the host and its child container, while Effect owns the shader layer, its mask and the pictures it samples.

func NewEffect

func NewEffect(ready func()) *Effect

func (*Effect) CaptureStart

func (fx *Effect) CaptureStart(target EffectTarget)

CaptureStart pictures what shows before the transition's batch applies.

func (*Effect) Close

func (fx *Effect) Close()

Close restores the host's children and releases the shader's resources.

func (*Effect) Covers

func (fx *Effect) Covers() bool

Covers reports whether the effect targets the surface's root view.

func (*Effect) Draw

func (fx *Effect) Draw(target EffectTarget)

Draw attaches the effect to its host and captures the pictures it reads.

func (*Effect) Invalidate

func (fx *Effect) Invalidate()

Invalidate marks the pictures for capture on the next draw.

func (*Effect) Navigating

func (fx *Effect) Navigating() bool

Navigating reports whether a navigation shader is drawing the transition.

func (*Effect) Set

func (fx *Effect) Set(sh *driver.Shader, scale float64, actions objc.ID) bool

Set updates the effect and reports whether Metal can draw it.

type EffectHost

type EffectHost[V comparable] struct {
	Root      V
	Scale     float64
	Actions   objc.ID
	Animator  *driver.Animator
	ID        func(V) driver.NodeID
	Native    func(V) objc.ID
	Container func(V) objc.ID
	Current   func(V) bool
	Ready     func(V)
}

EffectHost supplies the native views and animation graph of one surface.

type EffectTarget

type EffectTarget struct {
	View, Root objc.ID
	Holder     func() objc.ID
	Scale      float64
	Lanes      func([]float64)
}

EffectTarget is the native view an effect draws over for this frame. Holder makes its child container on demand.

type Effects

type Effects[V comparable] struct {
	// contains filtered or unexported fields
}

Effects owns a surface's effects, including captures made before a transition is installed. Its zero value is ready to use.

func (*Effects[V]) CaptureStart

func (effects *Effects[V]) CaptureStart(v V, host EffectHost[V])

CaptureStart preserves the pixels before a transition's batch applies.

func (*Effects[V]) Draw

func (effects *Effects[V]) Draw(host EffectHost[V])

Draw refreshes installed effects and forgets views replaced in the surface.

func (*Effects[V]) End

func (effects *Effects[V]) End(v V)

End releases an effect and any capture it retained before installation.

func (*Effects[V]) Get

func (effects *Effects[V]) Get(v V) *Effect

Get returns the effect of v, including an uninstalled transition capture.

func (*Effects[V]) Invalidate

func (effects *Effects[V]) Invalidate()

Invalidate marks installed effects for capture on the next draw.

func (*Effects[V]) Set

func (effects *Effects[V]) Set(v V, sh *driver.Shader, host EffectHost[V])

Set installs a shader and its animated lanes, or releases a removed effect.

type GPULayer

type GPULayer struct {
	Layer objc.ID
	// contains filtered or unexported fields
}

GPULayer is a gpu.View's Metal surface.

func NewGPULayer

func NewGPULayer(cfg driver.GPUViewConfig, emit func(*driver.GPUEvent)) *GPULayer

NewGPULayer makes a GPU view's layer on the main thread, or returns nil where the machine has no Metal device. emit reports the view's events from any goroutine.

func (*GPULayer) Release

func (l *GPULayer) Release()

Release detaches the layer, on the main thread; its render goroutine then lets every Metal resource go.

func (*GPULayer) Resize

func (l *GPULayer) Resize(w, h, scale float64)

Resize sizes the layer's drawable for w by h points at scale, on the main thread. The first nonzero size makes the view's device ready; later ones report a resize.

func (*GPULayer) Submit

func (l *GPULayer) Submit(frame driver.GPUFrame)

Submit queues frame for the render goroutine, from any goroutine. A frame recorded for another device is dropped.

type GPUProbe

type GPUProbe struct {
	// contains filtered or unexported fields
}

GPUProbe reads the process' GPU use from the accumulatedGPUTime its accelerator clients report in the IO registry, the counter behind Activity Monitor's GPU column.

func NewGPUProbe

func NewGPUProbe() *GPUProbe

NewGPUProbe returns a probe, or nil when the machine has no accelerator.

func (*GPUProbe) Sample

func (p *GPUProbe) Sample() *float32

Sample returns GPU time over wall time since the previous call, in percent: nil the first time, and while the process has no accelerator client.

type ImageView

type ImageView struct {
	// Dispatch reports an event to the engine if the view listens for it.
	Dispatch func(driver.Event)
	// Changed runs on the main thread after rendered content changes,
	// including an asynchronous image load, for snapshot renderers.
	Changed func()
	// AlphaChanged enables picture hit testing and invalidates a cached hit
	// when the view shows a different image.
	AlphaChanged func()
	// contains filtered or unexported fields
}

ImageView shows an image view's source, and its placeholder until the source arrives, in a picture layer framed at the fitted rectangle inside a clipping layer it adds to the view's own, as NSH's does (the tint and its mask inside the picture). It loads them with imageload and decodes them with ImageIO on goroutines, at the size the view shows them. Its methods run on the main thread.

func NewDrawnImage

func NewDrawnImage(changed func()) *ImageView

NewDrawnImage is an ImageView with no layer, for a backend that draws it itself (Draw): changed runs on the main thread each time what it shows changes.

func NewImageView

func NewImageView(host objc.ID) *ImageView

NewImageView adds an image layer to host, a view's layer.

func (*ImageView) Close

func (iv *ImageView) Close()

Close stops loading and lets the image go; the view is being deleted.

func (*ImageView) Configure

func (iv *ImageView) Configure(c *driver.ImageConfig)

Configure sets the view's source and look. Start loads what changed.

func (*ImageView) Draw

func (iv *ImageView) Draw(ctx uintptr)

Draw draws a drawn image's picture into ctx, a context of the view's box with its y axis down: fitted, clipped to the view's corners, and filled with the tint through its alpha where the style tints it.

func (*ImageView) HitTest

func (iv *ImageView) HitTest(p driver.Point) (hit, animated bool)

HitTest reports whether the picture at p takes the pointer and whether the sampled image is animated and may change at the next hit test.

func (*ImageView) Layout

func (iv *ImageView) Layout(size CGSize)

Layout fits the image to the view's new size, decoding the source again when the view outgrows the size it was decoded at.

func (*ImageView) SetStyle

func (iv *ImageView) SetStyle(vs *driver.ViewStyle)

SetStyle applies what of a view's style the image layer draws: the tint and the corners.

func (*ImageView) Start

func (iv *ImageView) Start(ratio float64)

Start loads what Configure or Layout changed, for a screen of ratio pixels per point. Backends call it once a batch has sized the view.

type Keychain added in v0.2.0

type Keychain struct{}

Keychain keeps an app's secrets as generic passwords of the keychain through Security.framework, in the process, as the item's access control trusts the binary that wrote it: kSecClassGenericPassword with the item's kSecAttrService and kSecAttrAccount, labeled with the service, as MyGo's App.Secrets and keytar keep them, so an app keeps reading what they wrote.

macOS keeps them in the login keychain, which needs no entitlement; an AccessGroup takes them to the data protection keychain instead, which needs a signed app with the keychain-access-groups entitlement (unsigned builds get errSecMissingEntitlement), and only there does Accessible apply. iOS, tvOS and watchOS have only the data protection keychain.

func (Keychain) DeleteSecret added in v0.2.0

func (Keychain) DeleteSecret(item driver.SecretItem) (err error)

func (Keychain) ReadSecret added in v0.2.0

func (Keychain) ReadSecret(item driver.SecretItem) (value string, ok bool, err error)

func (Keychain) WriteSecret added in v0.2.0

func (Keychain) WriteSecret(item driver.SecretItem, value string) (err error)

type Layout

type Layout struct {
	// contains filtered or unexported fields
}

Layout is text CoreText laid out on the engine goroutine, drawn on the main thread.

func (*Layout) Attachment

func (l *Layout) Attachment(i int) (driver.Bounds, bool)

Attachment implements core.AttachmentLayout.

func (*Layout) CaretRect

func (l *Layout) CaretRect(c driver.Caret) (driver.Bounds, bool)

CaretRect implements driver.TextHitTester.

func (*Layout) ContentFrame

func (l *Layout) ContentFrame(w, h float64, box CGRect) CGRect

ContentFrame is the frame of the layer a text view of size w by h draws l into, its text in box: the view's bounds, grown to hold the decoration lines, backgrounds and shadow that reach past them, as a browser draws a text's ink outside its box. It is in whole points.

func (*Layout) Draw

func (l *Layout) Draw(ctx uintptr, viewHeight float64, box CGRect, baseUp bool)

Draw draws l in box of a flipped context of a view viewHeight tall, whose base space points up when baseUp is set (DrawTopDown).

func (*Layout) DrawBackgrounds

func (l *Layout) DrawBackgrounds(ctx uintptr, at CGRect)

DrawBackgrounds fills the backgrounds of l's spans in box of a flipped context, behind the selection and the glyphs.

func (*Layout) HitTest

func (l *Layout) HitTest(p driver.Point) driver.Caret

HitTest implements driver.TextHitTester.

func (*Layout) IndexAt

func (l *Layout) IndexAt(p CGPoint, box CGRect) int

IndexAt returns the UTF-8 byte offset of the character at p, a point of the view Draw drew l in at box, or -1 when no character is there.

func (*Layout) OffsetAt

func (l *Layout) OffsetAt(p CGPoint, box CGRect) int

OffsetAt returns the UTF-16 offset of the caret nearest p, a point of the view Draw drew l in at box: on the line nearest p, before the line's break.

func (*Layout) RangeRects

func (l *Layout) RangeRects(start, end int, out []driver.Bounds) []driver.Bounds

RangeRects implements driver.TextHitTester.

func (*Layout) Release

func (l *Layout) Release()

Release implements core.TextLayout.

func (*Layout) SelectionRects

func (l *Layout) SelectionRects(start, end int, box CGRect) []CGRect

SelectionRects returns the boxes of the UTF-16 range from start to end in the view Draw draws l in at box: per line, a box per run of adjacent characters. A range that goes on past a line covers the rest of it.

func (*Layout) TextLines

func (l *Layout) TextLines() []driver.TextLine

TextLines implements core.LineLayout: each line's range, box and its first run's font metrics.

type LayoutBatch

type LayoutBatch struct {
	Animation *driver.LayoutAnimation
	Created   map[driver.NodeID]bool
	Deleted   map[objc.ID]bool
}

LayoutBatch tracks views inserted or retained by one animated commit.

type LayoutGhost

type LayoutGhost struct {
	// contains filtered or unexported fields
}

LayoutGhost is a removed view kept alive until its exit ends.

func NewLayoutGhost

func NewLayoutGhost(native objc.ID, transition *driver.LayoutTransition, start time.Duration) *LayoutGhost

NewLayoutGhost takes the caller's retain on native and records its opacity.

func StepLayoutMotions

func StepLayoutMotions[V comparable](now time.Duration, motions map[V]*LayoutMotion, ghosts []*LayoutGhost, current func(V) bool, place func(V, driver.Bounds), restyle func(V)) []*LayoutGhost

StepLayoutMotions advances the mounted views and retires completed exits. The caller supplies view identity, placement and restyling for its toolkit.

func (*LayoutGhost) Release

func (g *LayoutGhost) Release()

Release takes g's native view away and lets go of it, at the end of its exit or as its surface closes.

type LayoutHost

type LayoutHost[V comparable] struct {
	Motions map[V]*LayoutMotion
	Ghosts  *[]*LayoutGhost
	ID      func(V) driver.NodeID
	Native  func(V) objc.ID
	Framed  func(V) bool
	Frame   func(V) driver.Bounds
	Shift   func(V) driver.Point
	Place   func(V, driver.Bounds)
	Restyle func(V)
	Disable func(V)
	Now     func() time.Duration
	Start   func(*driver.LayoutTransition) time.Duration
	Tick    func()
}

LayoutHost supplies a backend's native views and placement to the shared layout transition lifecycle. Now is the frame clock; Start is when a new frame motion on a transition starts, which UIKit moves back to when the keyboard started moving.

func (LayoutHost[V]) Appear

func (host LayoutHost[V]) Appear(v V, batch *LayoutBatch, parent driver.NodeID)

Appear starts only the top inserted view of an appearing subtree.

func (LayoutHost[V]) Match

func (host LayoutHost[V]) Match(v, old V, batch *LayoutBatch)

Match moves a replacement from its predecessor's box in the new parent.

func (LayoutHost[V]) SetFrame

func (host LayoutHost[V]) SetFrame(v V, item *driver.MountItem, batch *LayoutBatch)

SetFrame animates a changed frame from where it shows when the batch or the item asks for it, retargeting a running motion with its velocity.

func (LayoutHost[V]) Vanish

func (host LayoutHost[V]) Vanish(v V, batch *LayoutBatch) bool

Vanish retains one exit per deleted subtree and lets UIKit disable its input.

type LayoutMotion

type LayoutMotion struct {
	Frame       *driver.LayoutMotion
	Appear      *driver.LayoutTransition
	AppearStart time.Duration
}

LayoutMotion is a view's part of a layout animation on the frame clock: its frame moving, its velocity kept as a spring retargets, or the view appearing.

type NSRange

type NSRange struct {
	Location, Length uint
	// contains filtered or unexported fields
}

NSRange is Foundation's range of UTF-16 units.

type NativeViews

type NativeViews = func(yield func(driver.NodeID, objc.ID) bool)

NativeViews yields a surface's mounted views, each ID with its native view, for the geometry helpers below that macOS and iOS share.

type NetworkWatcher

type NetworkWatcher struct{}

NetworkWatcher supplies the system's default Network.framework path.

func (NetworkWatcher) WatchNetwork

func (NetworkWatcher) WatchNetwork(changed func(driver.Network)) (driver.Network, func())

WatchNetwork reads and follows the current default path.

type Picture

type Picture struct {
	// contains filtered or unexported fields
}

Picture is what a shader effect or transition reads of views: a layer tree drawn with renderInContext: into a bitmap it keeps, made again only when its size changes, and the Metal texture the bitmap goes into. renderInContext: draws no Metal layer, video, web page, backdrop blur or glass.

func (*Picture) Release

func (p *Picture) Release()

Release lets the picture's bitmap and texture go.

func (*Picture) Take

func (p *Picture) Take(layer objc.ID, x, y, w, h, scale float64, hide objc.ID) bool

Take draws layer's tree into the picture: the rectangle of w by h points from (x, y) in layer's coordinates, at scale pixels a point, hiding hide's layer (0 for none) and lifting layer's mask while it draws. It reports whether it drew.

func (*Picture) Texture

func (p *Picture) Texture() (objc.ID, int, int)

Texture returns the picture's texture and its size in pixels, 0 before it was taken.

type PictureInPicture

type PictureInPicture struct {
	// contains filtered or unexported fields
}

PictureInPicture owns AVKit's session and its source layer. Only the main thread mutates it. The sample playback delegate reads an atomic snapshot, so AVKit never waits for the engine while it is suspended.

func NewPictureInPicture

func NewPictureInPicture(layer objc.ID, dispatch func(driver.Event)) *PictureInPicture

NewPictureInPicture creates a player-layer session. A nil layer creates a sample-buffer session whose independent NSGo tree supplies frames.

func (*PictureInPicture) Close

func (p *PictureInPicture) Close(done func())

Close stops PiP and retains every source object until AVKit's stop callback. done releases the owning player's native objects afterward.

func (*PictureInPicture) Command

func (p *PictureInPicture) Command(command uint32)

Command starts or stops the native session. Repeated commands while a transition or session is already active do not start another one.

func (*PictureInPicture) Configure

Configure updates the sample delegate's state without calling Go from an AVKit queue. Automatically is opt-in for either source kind.

func (*PictureInPicture) ContinuesInBackground

func (p *PictureInPicture) ContinuesInBackground() bool

ContinuesInBackground says whether the session plays on as the app enters the background: it is active or starting, or AVKit is about to start it automatically.

func (*PictureInPicture) Dirty

func (p *PictureInPicture) Dirty()

Dirty coalesces tree changes until the next display frame.

func (*PictureInPicture) DrawFrame

func (p *PictureInPicture) DrawFrame(tree objc.ID, scale float64) bool

DrawFrame draws a custom tree's layer only when AVKit can accept it. It returns true while a pending frame needs a display tick to retry.

func (*PictureInPicture) HoldAudio

func (p *PictureInPicture) HoldAudio(session driver.AudioSession)

HoldAudio holds the shared audio session in the playback category PiP needs while the session lives, paused or not: mixing with other apps' audio for AudioSessionMixWithOthers, which a video asks for, and pausing it otherwise.

func (*PictureInPicture) Layer

func (p *PictureInPicture) Layer() objc.ID

Layer returns the source layer a custom session must mount inline for AVKit to recognize it as a possible PiP source.

type ScrollEdge

type ScrollEdge struct {
	Tint, Line objc.ID
}

ScrollEdge is what macOS and iOS draw of a scroll edge effect over their blur, alike: the tint of the background the content scrolls over and a hard edge's hairline. Its layers are in the band's own space; the platform puts them over its blur.

func (*ScrollEdge) Paint

func (p *ScrollEdge) Paint(e *driver.ScrollEdge, s driver.Side, w, h float64)

Paint lays the layers out for edge e at side s, in a band of w by h points, y growing down.

func (*ScrollEdge) Release

func (p *ScrollEdge) Release()

Release releases the layers.

type Sensors added in v0.2.0

type Sensors struct {
	// contains filtered or unexported fields
}

Sensors owns a surface's providers, on the main thread. Core Motion's handlers only copy samples into bounded packets; app code runs in core.

func (*Sensors) Close added in v0.2.0

func (s *Sensors) Close()

Close releases every provider when a surface closes, even without a last batch.

func (*Sensors) Handle added in v0.2.0

func (s *Sensors) Handle(it *driver.MountItem, dispatch func(driver.Event), motion, continuous bool)

Handle applies ItemSensor on the main thread. Motion and continuous location are separately disabled on platforms whose SDK omits them.

type ShaderLayer

type ShaderLayer struct {
	// Layer is the CAMetalLayer.
	Layer objc.ID
	// Ready is called when the program compiled after Set, to draw.
	Ready func()
	// contains filtered or unexported fields
}

ShaderLayer draws a shader view with Metal: a CAMetalLayer the view's layer holds below its children, drawn when the uniforms, the size or the animated lanes change, never on a timer of its own. Metal loads with the first shader, and each program compiles once for the process on a goroutine of its own, as Metal takes a tenth of a second for a library; the layer draws once it is ready.

The main thread only writes the uniforms (Draw); a render goroutine of the layer's own waits for a drawable, encodes and presents. Waiting for a drawable blocks until the display frees one, a whole refresh when frames come faster, so the main thread must never wait for it.

func NewShaderLayer

func NewShaderLayer(scale float64) *ShaderLayer

NewShaderLayer returns a shader view's layer at scale pixels a point, or nil where the machine has no Metal device: the view stays empty.

func (*ShaderLayer) Draw

func (l *ShaderLayer) Draw(animated func(lanes []float64))

Draw has the render goroutine draw the shader with its uniforms, animated writing the lanes animated nodes drive over them. It never waits.

func (*ShaderLayer) Drawable

func (l *ShaderLayer) Drawable() bool

Drawable reports whether the layer has a program ready to draw.

func (*ShaderLayer) Release

func (l *ShaderLayer) Release()

Release lets the layer go, with the view holding it, once its render goroutine finished the frame it draws.

func (*ShaderLayer) Resize

func (l *ShaderLayer) Resize(w, h, scale float64)

Resize sizes the layer's drawable for w by h points at scale.

func (*ShaderLayer) Set

func (l *ShaderLayer) Set(sh *driver.Shader)

Set gives the layer what it draws, compiling its program the first time a view shows it.

func (*ShaderLayer) SetPictures

func (l *ShaderLayer) SetPictures(p [4]*Picture)

SetPictures gives a WGSL program the pictures it reads; a nil one, or one not taken yet, reads as transparent.

type TextEngine

type TextEngine struct{}

TextEngine implements core.TextEngine with CoreText. Strikethrough and span backgrounds, which CoreText has no attributes for, are drawn from the lines' offsets; attachments' placeholders are sized by run delegates.

func (TextEngine) Prepare

Prepare implements core.TextEngine. It is safe off the main thread.

type Video

type Video struct {
	// Dispatch reports the video's events.
	Dispatch func(driver.Event)
	// Parent is the view controller an iOS player's controls join when
	// the view is not in one yet.
	Parent objc.ID
	// contains filtered or unexported fields
}

Video is a video's AVPlayer, filling the view that holds it: in an AVPlayerLayer, or with the platform's controls in an AVPlayerView (macOS) or an AVPlayerViewController (iOS). AVFoundation and AVKit load on the first video, so apps without one do not pay for them. The layer is not opaque, so HEVC with alpha shows what is behind it; a local WebM file with alpha, which AVFoundation cannot open, reports EventError saying so.

func NewVideo

func NewVideo(holder objc.ID) *Video

NewVideo returns the video of holder, empty until configured.

func (*Video) ClearHitTestAlpha

func (v *Video) ClearHitTestAlpha()

ClearHitTestAlpha releases the frame output when macOS stops sampling.

func (*Video) Close

func (v *Video) Close()

Close stops the player. The view keeps the last frame while it still shows.

func (*Video) Configure

func (v *Video) Configure(c *driver.VideoConfig)

Configure applies c, opening the source again when it changed.

func (*Video) HitTestAlpha

func (v *Video) HitTestAlpha(p driver.Point) bool

HitTestAlpha reports whether a cached video pixel takes the pointer in a painted macOS window. Before the first mask, the whole view counts.

func (*Video) Layout

func (v *Video) Layout()

Layout keeps an iOS player layer at the view's size.

func (*Video) PictureInPictureCommand

func (v *Video) PictureInPictureCommand(command uint32)

PictureInPictureCommand starts or stops the video's PiP session.

func (*Video) SampleHitTestAlpha

func (v *Video) SampleHitTestAlpha() bool

SampleHitTestAlpha reads the latest frame for macOS's painted-window timer. It returns true when a new mask may change the hit under a still pointer.

func (*Video) Seek

func (v *Video) Seek(position time.Duration)

Seek jumps to position exactly.

func (*Video) SetHolder

func (v *Video) SetHolder(holder objc.ID)

SetHolder moves the existing player layer or controls into holder.

func (*Video) SetPictureInPictureOwner

func (v *Video) SetPictureInPictureOwner(owner *PictureInPicture, wake func())

SetPictureInPictureOwner selects the custom PiP tree that renders this video, or nil when the video returns to the ordinary view hierarchy.

func (*Video) UpdatePictureInPictureFrame

func (v *Video) UpdatePictureInPictureFrame(background bool) bool

UpdatePictureInPictureFrame brings the detached video layer up to the player's current time. It returns whether another video tick is needed.

func (*Video) View

func (v *Video) View() objc.ID

View returns the AppKit view showing the player (macOS), 0 before one.

type Web

type Web struct {
	// Dispatch reports the web view's events.
	Dispatch func(driver.Event)
	// contains filtered or unexported fields
}

Web is a web view's WKWebView, filling the view that holds it. WebKit loads on the first web view, so apps without one do not pay for it. The WKWebView is made on the first Configure.

func NewWeb

func NewWeb(holder objc.ID) *Web

NewWeb returns the web view of holder, empty until configured.

func (*Web) Close

func (w *Web) Close()

Close stops the page and lets the WKWebView go.

func (*Web) Command

func (w *Web) Command(c driver.WebCommand, value string, data any)

Command does c, with value for messages and scripts.

func (*Web) Configure

func (w *Web) Configure(c *driver.WebConfig)

Configure applies c, loading the source again when it or the scripts changed.

func (*Web) SetHolder

func (w *Web) SetHolder(holder objc.ID)

SetHolder moves the web view into holder, keeping its page and history.

func (*Web) View

func (w *Web) View() objc.ID

View returns the WKWebView, 0 before the first Configure.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL