feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
# Notice
This package follows PermissionFlow
(https://github.com/jaywcjlove/PermissionFlow, at cb96db4), a Swift
package for macOS: what its guide does (System Settings opened at the
page, a panel under its window that follows it, with the app to drag into
the list, and which closes with it), the panes it covers and which of
them take a drag, the pasteboard types of the dragged app, the panel's
geometry and text, and how it tells the status of each permission. The
code is MyGo's own, in Go: none of PermissionFlow's is copied.
PermissionFlow's license:
MIT License
Copyright (c) 2026 小弟调调
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+22
View File
@@ -0,0 +1,22 @@
# permissionflow
The permissions the system keeps for the user to give, such as
Accessibility, Screen Recording and the microphone, for
[MyGo](https://github.com/egoist/mygo) apps: checked, asked for with the
system's prompt, and a guide to System Settings, where a panel under its
window holds the app to drag into the list, as
[PermissionFlow](https://github.com/jaywcjlove/PermissionFlow) does for
Swift apps. macOS and Windows; it is all Go.
```go
import "github.com/egoist/mygo/plugins/permissionflow"
st, err := permissionflow.Check(permissionflow.Accessibility)
if err == nil && st != permissionflow.Granted {
st, err = permissionflow.Guide(ctx, permissionflow.Accessibility, permissionflow.GuideOptions{})
}
```
See [the documentation](../../docs/plugins/permissionflow.md), and
`examples/permissionflow`. It follows PermissionFlow (MIT, © 小弟调调;
see [NOTICE.md](NOTICE.md)).
@@ -0,0 +1,74 @@
package dev.mygo
import android.Manifest
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import org.json.JSONObject
class PermissionFlowPlugin : MyGoPlugin {
/** The manifest's names of a permission, which an app declares (android.permissions). */
private fun names(p: String): Array<String>? = when (p) {
"camera" -> arrayOf(Manifest.permission.CAMERA)
"microphone" -> arrayOf(Manifest.permission.RECORD_AUDIO)
"photos" -> if (Build.VERSION.SDK_INT >= 33) arrayOf(Manifest.permission.READ_MEDIA_IMAGES) else arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
"contacts" -> arrayOf(Manifest.permission.READ_CONTACTS)
"location" -> arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
"bluetooth" -> if (Build.VERSION.SDK_INT >= 31) arrayOf(Manifest.permission.BLUETOOTH_CONNECT) else emptyArray()
"calendars" -> arrayOf(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR)
"notifications" -> if (Build.VERSION.SDK_INT >= 33) arrayOf(Manifest.permission.POST_NOTIFICATIONS) else emptyArray()
else -> null
}
private val asked get() = PluginHost.context.getSharedPreferences("mygo.permissions", Context.MODE_PRIVATE)
private fun status(p: String, perms: Array<String>): String {
val ctx = PluginHost.context
if (p == "notifications" && !(ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).areNotificationsEnabled()) {
return if (asked.getBoolean(p, false) || perms.isEmpty()) "denied" else "notDetermined"
}
if (perms.all { ctx.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED }) return "granted"
return if (asked.getBoolean(p, false)) "denied" else "notDetermined"
}
/** Whether the app's manifest names them: Android turns down others without a word. */
private fun declared(perms: Array<String>): Boolean {
val ctx = PluginHost.context
val info = ctx.packageManager.getPackageInfo(ctx.packageName, PackageManager.GET_PERMISSIONS)
val listed = info.requestedPermissions ?: emptyArray()
return perms.all { it in listed }
}
override fun call(method: String, args: JSONObject, reply: PluginReply) {
val p = args.optString("permission")
val perms = names(p)
when (method) {
"check" -> if (perms == null) reply.failure(PluginFailure("Unsupported")) else reply.success(JSONObject().put("status", status(p, perms)))
"request" -> {
if (perms == null) {
reply.failure(PluginFailure("Unsupported"))
return
}
if (!declared(perms)) {
reply.failure(PluginFailure("NoUsageDescription", "android.permissions lacks ${perms.joinToString()}"))
return
}
PluginHost.requestPermissions(perms) {
asked.edit().putBoolean(p, true).apply()
reply.success(JSONObject().put("status", status(p, perms)))
}
}
"openSettings" -> {
val ctx = PluginHost.context
val i = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + ctx.packageName))
(PluginHost.activity ?: ctx).startActivity(i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
reply.success(null)
}
else -> reply.failure(PluginFailure("NoMethod", method))
}
}
}
+211
View File
@@ -0,0 +1,211 @@
package permissionflow
import (
"path/filepath"
"strings"
"github.com/egoist/mygo/internal/l10n"
)
// The parts of the systems' implementations that are plain computation,
// here so that every platform tests them.
// macAnchors are the anchors of System Settings' Privacy & Security pages,
// which open with x-apple.systempreferences:com.apple.preference.security?anchor.
var macAnchors = map[Permission]string{
Accessibility: "Privacy_Accessibility",
ScreenRecording: "Privacy_ScreenCapture",
InputMonitoring: "Privacy_ListenEvent",
FullDiskAccess: "Privacy_AllFiles",
AppManagement: "Privacy_AppBundles",
DeveloperTools: "Privacy_DevTools",
Microphone: "Privacy_Microphone",
Camera: "Privacy_Camera",
Calendars: "Privacy_Calendars",
Reminders: "Privacy_Reminders",
Bluetooth: "Privacy_Bluetooth",
MediaAppleMusic: "Privacy_Media",
}
func macSettingsURL(p Permission) string {
return "x-apple.systempreferences:com.apple.preference.security?" + macAnchors[p]
}
// macDraggable reports whether the list of p's page in System Settings
// takes apps dragged into it. The others list the apps that asked, with
// the system's prompt (see Request).
func macDraggable(p Permission) bool {
switch p {
case Microphone, Camera, Calendars, Reminders:
return false
}
return true
}
// windowsCapabilities are the capabilities of Windows' consent store
// (HKCU\Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore)
// that apps outside packages ("desktop apps") are kept from, and the pages
// of Settings that switch them.
var windowsCapabilities = map[Permission]struct{ capability, uri string }{
Microphone: {"microphone", "ms-settings:privacy-microphone"},
Camera: {"webcam", "ms-settings:privacy-webcam"},
}
// windowsConsent is the status of a capability from the values of its
// switches in the consent store: the device's (HKLM), the user's, and
// the user's for desktop apps (NonPackaged). Any of them off denies it;
// a switch that isn't stored is on.
func windowsConsent(values ...string) Status {
for _, v := range values {
if strings.EqualFold(v, "Deny") {
return Denied
}
}
return Granted
}
// appName is the name the panel gives the app at path.
func appName(path string) string {
name := filepath.Base(filepath.Clean(path))
return strings.TrimSuffix(name, filepath.Ext(name))
}
// A run is a part of the panel's text, in bold or not.
type run struct {
text string
bold bool
}
const (
guideAppMarker = "\x00mygo.permissionflow.app\x00"
guidePermissionMarker = "\x00mygo.permissionflow.permission\x00"
)
// panelText is what the panel says: "Drag **MyApp** to the list above to
// allow **Accessibility**.", as PermissionFlow's does, in the language of
// locale. Marker values let translated messages reorder the bold runs.
func panelText(app, permission, locale string) []run {
text := l10n.In(locale).GuideDrag(guideAppMarker, guidePermissionMarker)
return splitRuns(text,
runMarker{token: guideAppMarker, text: app},
runMarker{token: guidePermissionMarker, text: permission},
)
}
type runMarker struct {
token string
text string
}
func splitRuns(text string, markers ...runMarker) []run {
var runs []run
for len(text) > 0 {
index, marker := -1, runMarker{}
for _, candidate := range markers {
if i := strings.Index(text, candidate.token); i >= 0 && (index < 0 || i < index) {
index, marker = i, candidate
}
}
if index < 0 {
runs = append(runs, run{text: text})
break
}
if index > 0 {
runs = append(runs, run{text: text[:index]})
}
runs = append(runs, run{text: marker.text, bold: true})
text = text[index+len(marker.token):]
}
return runs
}
// rect is a rectangle in AppKit's screen coordinates: points, from the
// bottom left of the main display, y going up.
type rect struct{ X, Y, W, H float64 }
func (r rect) maxX() float64 { return r.X + r.W }
func (r rect) maxY() float64 { return r.Y + r.H }
func (r rect) intersects(o rect) bool {
return r.X < o.maxX() && o.X < r.maxX() && r.Y < o.maxY() && o.Y < r.maxY()
}
// flipRect converts r from the window server's coordinates, from the top
// left of the main display with y going down, to AppKit's, mainHeight
// being the height of the main display.
func flipRect(r rect, mainHeight float64) rect {
return rect{X: r.X, Y: mainHeight - r.Y - r.H, W: r.W, H: r.H}
}
// The panel's geometry, in points.
const (
// settingsSidebar is the width of System Settings' sidebar: the panel
// lines up with the page on its right, where the list is.
settingsSidebar = 230
panelMinWidth = 240
screenInset = 12
)
// panelWidth is the panel's width under a window of System Settings at
// settings, on a screen whose visible part is screen.
func panelWidth(settings, screen rect) float64 {
return min(max(panelMinWidth, settings.W-settingsSidebar), screen.W-2*screenInset)
}
// panelFrame places a panel of the height under the window of System
// Settings at settings: aligned with its page, right under it, and kept
// inside the screen, over the bottom of the window when there's no room
// under it.
func panelFrame(settings, screen rect, height float64) rect {
w := panelWidth(settings, screen)
x := settings.X + settingsSidebar
y := settings.Y - height
x = max(screen.X+screenInset, min(x, screen.maxX()-w-screenInset))
y = max(screen.Y+screenInset, min(y, screen.maxY()-height-screenInset))
return rect{X: x, Y: y, W: w, H: height}
}
// screenOf returns the visible part of the screen that shows most of r,
// or the first one when none does.
func screenOf(r rect, screens []rect) rect {
best, area := rect{}, -1.0
for i, s := range screens {
if i == 0 {
best = s
}
if !r.intersects(s) {
continue
}
w := min(r.maxX(), s.maxX()) - max(r.X, s.X)
h := min(r.maxY(), s.maxY()) - max(r.Y, s.Y)
if w*h > area {
best, area = s, w*h
}
}
return best
}
// A settingsWindow is what the window server says of a window of System
// Settings: its bounds in its coordinates, its layer and its alpha.
type settingsWindow struct {
bounds rect
layer int
alpha float64
}
// mainSettingsWindow picks System Settings' window among its windows: the
// largest one of the normal layer that shows, as PermissionFlow does,
// leaving out its small helper windows.
func mainSettingsWindow(windows []settingsWindow) (rect, bool) {
var best rect
found := false
for _, w := range windows {
if w.layer != 0 || w.alpha <= 0 || w.bounds.W <= 320 || w.bounds.H <= 240 {
continue
}
if !found || w.bounds.W*w.bounds.H > best.W*best.H {
best, found = w.bounds, true
}
}
return best, found
}
+632
View File
@@ -0,0 +1,632 @@
//go:build darwin && !ios
package permissionflow
import (
"context"
"math"
"os"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo"
"github.com/egoist/mygo/i18n"
"github.com/egoist/mygo/internal/l10n"
)
// Guide's panel is an NSPanel that never takes the focus, so that System
// Settings stays the active app while the user drags. A goroutine follows
// System Settings through the window server (CGWindowListCopyWindowInfo),
// which needs no permission, 30 times a second, and moves the panel on the
// main thread when the window has moved, or hides it while another app is
// in front. The card of the app is an NSView of a class of ours, the
// source of the drag, whose item is a writer of ours putting the app on
// the pasteboard as Finder does.
type nsPoint struct{ X, Y float64 }
type nsSize struct{ Width, Height float64 }
type nsRect struct {
Origin nsPoint
Size nsSize
}
func (r rect) ns() nsRect { return nsRect{nsPoint{r.X, r.Y}, nsSize{r.W, r.H}} }
func fromNS(r nsRect) rect { return rect{r.Origin.X, r.Origin.Y, r.Size.Width, r.Size.Height} }
const (
nsWindowStyleMaskBorderless = 0
nsWindowStyleMaskNonactivatingPanel = 1 << 7
nsBackingStoreBuffered = 2
nsFloatingWindowLevel = 3
nsCollectionCanJoinAllSpaces = 1 << 0
nsCollectionFullScreenAuxiliary = 1 << 8
nsVisualEffectMaterialPopover = 6
nsVisualEffectBlendingBehindWindow = 0
nsVisualEffectStateActive = 1
nsBoxCustom = 4
nsNoTitle = 0
nsDragOperationCopy = 1
nsDraggingFormationNone = 1
nsImageOnly = 1
nsImageResizingModeStretch = 1
nsTextAlignmentCenter = 2
kCGWindowListOptionOnScreenOnly = 1 << 0
kCGWindowListExcludeDesktopElements = 1 << 4
kCGEventSourceStateCombined = 0
kCGMouseButtonLeft = 0
// The panel's layout, in points.
panelPadding = 12
panelRadius = 16
cardHeight = 48
iconSize = 32
closeSize = 18
dragIconSize = 56
// trackInterval is how often the panel follows System Settings.
trackInterval = time.Second / 30
// settingsMisses is how many times in a row System Settings must be
// missing for the panel to close: it is missing for a moment while it
// opens or changes pages.
settingsMisses = 12
// settingsWait is how long System Settings may take to open.
settingsWait = 10 * time.Second
)
var (
classesOnce sync.Once
classesErr error
// active is the flow whose panel shows, which the panel's classes
// reach; one shows at a time. Main thread only, like the panel.
active *flow
// dragging is set while the app is dragged: the panel lets the mouse
// through, and the tracker restores it once the button is up.
dragging atomic.Bool
flowMu sync.Mutex
lastFlow *flow // the flow running, which a new one stops
)
// A flow is one call of Guide.
type flow struct {
p Permission
app, name, lang string
draggable bool
stop chan struct{} // closed when the user closes it, or another flow starts
stopOnce sync.Once
panel objc.ID
views panelViews
labelH float64
shown bool
dragOrigin nsPoint
dragBegan bool
}
// panelViews are the views of the panel, which its content view keeps.
type panelViews struct {
border, label, close, cardBox, icon, name, hint, hand, card objc.ID
}
func (f *flow) close() { f.stopOnce.Do(func() { close(f.stop) }) }
func registerClasses() error {
classesOnce.Do(func() {
source := objc.GetProtocol("NSDraggingSource")
writing := objc.GetProtocol("NSPasteboardWriting")
var protocols []*objc.Protocol
if source != nil {
protocols = append(protocols, source)
}
_, classesErr = objc.RegisterClass("MyGoPermissionFlowDragView", objc.GetClass("NSView"), protocols, nil, []objc.MethodDef{
{Cmd: sel("mouseDown:"), Fn: cardMouseDown},
{Cmd: sel("mouseDragged:"), Fn: cardMouseDragged},
{Cmd: sel("mouseUp:"), Fn: cardMouseUp},
{Cmd: sel("acceptsFirstMouse:"), Fn: func(objc.ID, objc.SEL, objc.ID) bool { return true }},
{Cmd: sel("mouseDownCanMoveWindow"), Fn: func(objc.ID, objc.SEL) bool { return false }},
{Cmd: sel("resetCursorRects"), Fn: cardResetCursorRects},
{Cmd: sel("draggingSession:sourceOperationMaskForDraggingContext:"), Fn: func(objc.ID, objc.SEL, objc.ID, int) uint { return nsDragOperationCopy }},
{Cmd: sel("ignoreModifierKeysForDraggingSession:"), Fn: func(objc.ID, objc.SEL, objc.ID) bool { return true }},
})
if classesErr != nil {
return
}
protocols = nil
if writing != nil {
protocols = append(protocols, writing)
}
_, classesErr = objc.RegisterClass("MyGoPermissionFlowAppWriter", objc.GetClass("NSObject"), protocols, nil, []objc.MethodDef{
{Cmd: sel("writableTypesForPasteboard:"), Fn: writerTypes},
{Cmd: sel("pasteboardPropertyListForType:"), Fn: writerPropertyList},
})
if classesErr != nil {
return
}
_, classesErr = objc.RegisterClass("MyGoPermissionFlowTarget", objc.GetClass("NSObject"), nil, nil, []objc.MethodDef{
{Cmd: sel("close:"), Fn: func(objc.ID, objc.SEL, objc.ID) {
if active != nil {
active.close()
}
}},
})
})
return classesErr
}
// The pasteboard types System Settings takes an app dragged from Finder
// with.
var appTypes = []string{
"public.file-url",
"public.url",
"NSFilenamesPboardType",
"com.apple.pasteboard.promised-file-url",
"public.utf8-plain-text",
}
func writerTypes(_ objc.ID, _ objc.SEL, _ objc.ID) objc.ID {
arr := class("NSMutableArray").Send(sel("array"))
for _, t := range appTypes {
arr.Send(sel("addObject:"), nsString(t))
}
return arr
}
func writerPropertyList(_ objc.ID, _ objc.SEL, typ objc.ID) objc.ID {
if active == nil {
return 0
}
path := active.app
switch goString(typ) {
case "public.file-url", "public.url", "com.apple.pasteboard.promised-file-url":
u := class("NSURL").Send(sel("fileURLWithPath:"), nsString(path))
return u.Send(sel("absoluteString"))
case "NSFilenamesPboardType":
return class("NSArray").Send(sel("arrayWithObject:"), nsString(path))
case "public.utf8-plain-text":
return nsString(path)
}
return 0
}
func cardResetCursorRects(self objc.ID, _ objc.SEL) {
bounds := objc.Send[nsRect](self, sel("bounds"))
self.Send(sel("addCursorRect:cursor:"), bounds, class("NSCursor").Send(sel("openHandCursor")))
}
func cardMouseDown(self objc.ID, _ objc.SEL, event objc.ID) {
if active == nil {
return
}
active.dragOrigin = objc.Send[nsPoint](event, sel("locationInWindow"))
active.dragBegan = false
}
func cardMouseUp(objc.ID, objc.SEL, objc.ID) {
if active != nil {
active.dragBegan = false
}
}
func cardMouseDragged(self objc.ID, _ objc.SEL, event objc.ID) {
f := active
if f == nil || f.dragBegan {
return
}
at := objc.Send[nsPoint](event, sel("locationInWindow"))
if math.Hypot(at.X-f.dragOrigin.X, at.Y-f.dragOrigin.Y) <= 4 {
return
}
f.dragBegan = true
writer := class("MyGoPermissionFlowAppWriter").Send(sel("alloc")).Send(sel("init"))
item := class("NSDraggingItem").Send(sel("alloc")).Send(sel("initWithPasteboardWriter:"), writer)
icon := class("NSWorkspace").Send(sel("sharedWorkspace")).Send(sel("iconForFile:"), nsString(f.app))
icon.Send(sel("setSize:"), nsSize{dragIconSize, dragIconSize})
p := objc.Send[nsPoint](self, sel("convertPoint:fromView:"), at, objc.ID(0))
item.Send(sel("setDraggingFrame:contents:"), nsRect{nsPoint{p.X - dragIconSize/2, p.Y - dragIconSize/2}, nsSize{dragIconSize, dragIconSize}}, icon)
session := self.Send(sel("beginDraggingSessionWithItems:event:source:"), class("NSArray").Send(sel("arrayWithObject:"), item), event, self)
session.Send(sel("setAnimatesToStartingPositionsOnCancelOrFail:"), true)
session.Send(sel("setDraggingFormation:"), nsDraggingFormationNone)
item.Send(sel("release"))
writer.Send(sel("release"))
// System Settings, under the pointer, takes the drop.
dragging.Store(true)
f.panel.Send(sel("setIgnoresMouseEvents:"), true)
f.panel.Send(sel("setAlphaValue:"), 0.72)
}
// endDrag restores the panel after a drag. Main thread.
func (f *flow) endDrag() {
dragging.Store(false)
f.dragBegan = false
if f.panel != 0 {
f.panel.Send(sel("setIgnoresMouseEvents:"), false)
f.panel.Send(sel("setAlphaValue:"), 1.0)
}
}
func defaultApp() string {
var path string
withPool(func() {
path = goString(class("NSBundle").Send(sel("mainBundle")).Send(sel("bundlePath")))
})
if strings.HasSuffix(path, ".app") {
return path
}
if exe, err := os.Executable(); err == nil {
return exe
}
return path
}
func guide(ctx context.Context, p Permission, opts GuideOptions) (Status, error) {
if err := loadCore(); err != nil {
return Unknown, err
}
if err := registerClasses(); err != nil {
return Unknown, err
}
f := &flow{p: p, app: opts.App, name: opts.Name, lang: i18n.Locale(), draggable: macDraggable(p), stop: make(chan struct{})}
if f.app == "" {
f.app = defaultApp()
}
if f.name == "" {
f.name = appName(f.app)
}
flowMu.Lock()
if lastFlow != nil {
lastFlow.close()
}
lastFlow = f
flowMu.Unlock()
defer func() {
flowMu.Lock()
if lastFlow == f {
lastFlow = nil
}
flowMu.Unlock()
mygo.RunOnMain(f.destroy)
}()
if err := openSettings(p); err != nil {
return Unknown, err
}
var (
t = time.NewTicker(trackInterval)
started = time.Now()
seen bool // System Settings was there
misses int // times in a row it wasn't
last rect // where its window was
front bool // whether it was in front
ticks int
)
defer t.Stop()
for {
if ticks%int(pollInterval/trackInterval) == 0 {
if st, err := check(p); err != nil || st == Granted {
return st, err
}
}
ticks++
pid, frontmost := settingsProcess()
switch {
case pid != 0:
seen, misses = true, 0
case seen:
if misses++; misses >= settingsMisses {
return check(p)
}
case time.Since(started) > settingsWait:
return check(p)
}
if dragging.Load() && !cgEventSourceButtonState(kCGEventSourceStateCombined, kCGMouseButtonLeft) {
mygo.RunOnMain(f.endDrag)
}
if f.draggable && pid != 0 {
// While a drag is on, System Settings is in front even when the
// window server doesn't say so yet.
show := frontmost || dragging.Load()
if frame, ok := settingsFrame(pid); ok && (frame != last || show != front) {
last, front = frame, show
mygo.RunOnMain(func() { f.place(frame, show) })
}
}
select {
case <-ctx.Done():
st, _ := check(p)
return st, ctx.Err()
case <-f.stop:
return check(p)
case <-t.C:
}
}
}
// settingsProcess returns the process of System Settings, 0 when it isn't
// running, and whether it is the app in front.
func settingsProcess() (pid int32, frontmost bool) {
withPool(func() {
apps := class("NSRunningApplication").Send(sel("runningApplicationsWithBundleIdentifier:"), nsString(settingsBundleID))
if sendUint(apps, sel("count")) == 0 {
return
}
app := apps.Send(sel("firstObject"))
pid = int32(sendInt(app, sel("processIdentifier")))
front := class("NSWorkspace").Send(sel("sharedWorkspace")).Send(sel("frontmostApplication"))
frontmost = front != 0 && int32(sendInt(front, sel("processIdentifier"))) == pid
})
return pid, frontmost
}
// settingsFrame returns the bounds of System Settings' window, in the
// window server's coordinates.
func settingsFrame(pid int32) (r rect, ok bool) {
withPool(func() {
list := cgWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly|kCGWindowListExcludeDesktopElements, 0)
if list == 0 {
return
}
defer cfRelease(list)
var (
kPID = nsString("kCGWindowOwnerPID")
kLayer = nsString("kCGWindowLayer")
kAlpha = nsString("kCGWindowAlpha")
kBounds = nsString("kCGWindowBounds")
windows []settingsWindow
)
n := sendUint(list, sel("count"))
for i := range n {
w := list.Send(sel("objectAtIndex:"), i)
if v := w.Send(sel("objectForKey:"), kPID); v == 0 || int32(sendInt(v, sel("integerValue"))) != pid {
continue
}
sw := settingsWindow{alpha: 1}
if v := w.Send(sel("objectForKey:"), kLayer); v != 0 {
sw.layer = sendInt(v, sel("integerValue"))
}
if v := w.Send(sel("objectForKey:"), kAlpha); v != 0 {
sw.alpha = sendFloat(v, sel("doubleValue"))
}
b := w.Send(sel("objectForKey:"), kBounds)
if b == 0 {
continue
}
num := func(k string) float64 {
v := b.Send(sel("objectForKey:"), nsString(k))
if v == 0 {
return 0
}
return sendFloat(v, sel("doubleValue"))
}
sw.bounds = rect{num("X"), num("Y"), num("Width"), num("Height")}
windows = append(windows, sw)
}
r, ok = mainSettingsWindow(windows)
})
return r, ok
}
// place shows the panel under the window of System Settings at frame (in
// the window server's coordinates), or hides it. Main thread.
func (f *flow) place(frame rect, show bool) {
if !show {
if f.panel != 0 && f.shown {
f.panel.Send(sel("orderOut:"), objc.ID(0))
f.shown = false
}
return
}
withPool(func() {
screens := class("NSScreen").Send(sel("screens"))
n := objc.Send[uint](screens, sel("count"))
if n == 0 {
return
}
mainHeight := objc.Send[nsRect](screens.Send(sel("objectAtIndex:"), uint(0)), sel("frame")).Size.Height
settings := flipRect(frame, mainHeight)
var visible []rect
for i := range n {
visible = append(visible, fromNS(objc.Send[nsRect](screens.Send(sel("objectAtIndex:"), i), sel("visibleFrame"))))
}
screen := screenOf(settings, visible)
w := panelWidth(settings, screen)
if f.panel == 0 {
f.build(w)
}
f.layout(w)
h := panelPadding + f.labelH + 8 + cardHeight + panelPadding
target := panelFrame(settings, screen, h)
f.panel.Send(sel("setFrame:display:"), target.ns(), true)
f.panel.Send(sel("invalidateShadow"))
if !f.shown {
f.panel.Send(sel("orderFrontRegardless"))
f.shown = true
}
active = f
})
}
func (f *flow) build(w float64) {
panel := class("NSPanel").Send(sel("alloc")).Send(sel("initWithContentRect:styleMask:backing:defer:"),
nsRect{Size: nsSize{w, 100}}, uint(nsWindowStyleMaskBorderless|nsWindowStyleMaskNonactivatingPanel), uint(nsBackingStoreBuffered), false)
panel.Send(sel("setLevel:"), nsFloatingWindowLevel)
panel.Send(sel("setReleasedWhenClosed:"), false)
panel.Send(sel("setOpaque:"), false)
panel.Send(sel("setBackgroundColor:"), class("NSColor").Send(sel("clearColor")))
panel.Send(sel("setHasShadow:"), true)
panel.Send(sel("setHidesOnDeactivate:"), false)
panel.Send(sel("setCollectionBehavior:"), uint(nsCollectionCanJoinAllSpaces|nsCollectionFullScreenAuxiliary))
panel.Send(sel("setMovableByWindowBackground:"), false)
effect := class("NSVisualEffectView").Send(sel("alloc")).Send(sel("initWithFrame:"), nsRect{})
effect.Send(sel("setMaterial:"), nsVisualEffectMaterialPopover)
effect.Send(sel("setBlendingMode:"), nsVisualEffectBlendingBehindWindow)
effect.Send(sel("setState:"), nsVisualEffectStateActive)
// A layer's corner radius doesn't clip what the view blurs from behind
// the window: a mask does, and the window's shadow follows it.
mask := roundedMask(panelRadius)
effect.Send(sel("setMaskImage:"), mask)
mask.Send(sel("release"))
panel.Send(sel("setContentView:"), effect)
effect.Send(sel("release"))
color := func(name string) objc.ID { return class("NSColor").Send(sel(name)) }
v := &f.views
v.border = newBox(color("clearColor"), panelRadius)
effect.Send(sel("addSubview:"), v.border)
v.border.Send(sel("release"))
label := class("NSTextField").Send(sel("wrappingLabelWithString:"), nsString(""))
text := class("NSMutableAttributedString").Send(sel("alloc")).Send(sel("init"))
for _, r := range panelText(f.name, f.p.Title(), f.lang) {
font := class("NSFont").Send(sel("systemFontOfSize:"), 13.0)
if r.bold {
font = class("NSFont").Send(sel("boldSystemFontOfSize:"), 13.0)
}
attrs := class("NSMutableDictionary").Send(sel("dictionary"))
attrs.Send(sel("setObject:forKey:"), font, nsString("NSFont"))
attrs.Send(sel("setObject:forKey:"), color("labelColor"), nsString("NSColor"))
part := class("NSAttributedString").Send(sel("alloc")).Send(sel("initWithString:attributes:"), nsString(r.text), attrs)
text.Send(sel("appendAttributedString:"), part)
part.Send(sel("release"))
}
label.Send(sel("setAttributedStringValue:"), text)
text.Send(sel("release"))
effect.Send(sel("addSubview:"), label)
v.label = label
closeButton := class("NSButton").Send(sel("alloc")).Send(sel("initWithFrame:"), nsRect{})
closeButton.Send(sel("setBordered:"), false)
closeButton.Send(sel("setImagePosition:"), nsImageOnly)
if img := symbol("xmark.circle.fill", "Close"); img != 0 {
closeButton.Send(sel("setImage:"), img)
closeButton.Send(sel("setContentTintColor:"), color("secondaryLabelColor"))
} else {
closeButton.Send(sel("setTitle:"), nsString("✕"))
}
target := class("MyGoPermissionFlowTarget").Send(sel("alloc")).Send(sel("init")) // kept, as small as it is
closeButton.Send(sel("setTarget:"), target)
closeButton.Send(sel("setAction:"), sel("close:"))
effect.Send(sel("addSubview:"), closeButton)
closeButton.Send(sel("release"))
v.close = closeButton
// The card: a box, the app's icon and name, a hint, and over them the
// view the drag starts from, which gets every click on the card.
cardBox := newBox(color("controlBackgroundColor").Send(sel("colorWithAlphaComponent:"), 0.65), 10)
effect.Send(sel("addSubview:"), cardBox)
cardBox.Send(sel("release"))
v.cardBox = cardBox
icon := class("NSImageView").Send(sel("imageViewWithImage:"),
class("NSWorkspace").Send(sel("sharedWorkspace")).Send(sel("iconForFile:"), nsString(f.app)))
effect.Send(sel("addSubview:"), icon)
v.icon = icon
name := class("NSTextField").Send(sel("labelWithString:"), nsString(f.name))
name.Send(sel("setFont:"), class("NSFont").Send(sel("systemFontOfSize:"), 15.0))
effect.Send(sel("addSubview:"), name)
v.name = name
hint := class("NSTextField").Send(sel("labelWithString:"), nsString(l10n.In(f.lang).GuideDragHint()))
hint.Send(sel("setFont:"), class("NSFont").Send(sel("systemFontOfSize:"), 9.0))
hint.Send(sel("setTextColor:"), color("secondaryLabelColor"))
hint.Send(sel("setAlignment:"), nsTextAlignmentCenter)
effect.Send(sel("addSubview:"), hint)
v.hint = hint
if img := symbol("hand.draw", "Drag"); img != 0 {
hand := class("NSImageView").Send(sel("imageViewWithImage:"), img)
hand.Send(sel("setContentTintColor:"), color("secondaryLabelColor"))
effect.Send(sel("addSubview:"), hand)
v.hand = hand
}
card := class("MyGoPermissionFlowDragView").Send(sel("alloc")).Send(sel("initWithFrame:"), nsRect{})
effect.Send(sel("addSubview:"), card)
card.Send(sel("release"))
v.card = card
f.panel = panel
}
// roundedMask returns an image of a rounded rectangle that stretches to
// any size, keeping its corners, for NSVisualEffectView's maskImage.
func roundedMask(radius float64) objc.ID {
side := 2*radius + 1
img := class("NSImage").Send(sel("alloc")).Send(sel("initWithSize:"), nsSize{side, side})
img.Send(sel("lockFocus"))
class("NSColor").Send(sel("blackColor")).Send(sel("set"))
class("NSBezierPath").Send(sel("bezierPathWithRoundedRect:xRadius:yRadius:"), nsRect{Size: nsSize{side, side}}, radius, radius).Send(sel("fill"))
img.Send(sel("unlockFocus"))
type nsEdgeInsets struct{ Top, Left, Bottom, Right float64 }
img.Send(sel("setCapInsets:"), nsEdgeInsets{radius, radius, radius, radius})
img.Send(sel("setResizingMode:"), nsImageResizingModeStretch)
return img
}
// newBox returns a rounded box with the separator's border, filled.
func newBox(fill objc.ID, radius float64) objc.ID {
box := class("NSBox").Send(sel("alloc")).Send(sel("initWithFrame:"), nsRect{})
box.Send(sel("setBoxType:"), nsBoxCustom)
box.Send(sel("setTitlePosition:"), nsNoTitle)
box.Send(sel("setBorderWidth:"), 1.0)
box.Send(sel("setCornerRadius:"), radius)
box.Send(sel("setBorderColor:"), class("NSColor").Send(sel("separatorColor")))
box.Send(sel("setFillColor:"), fill)
return box
}
// symbol returns an SF Symbol, which macOS 11 and later have, or 0.
func symbol(name, description string) objc.ID {
img := class("NSImage")
if !objc.Send[bool](img, sel("respondsToSelector:"), sel("imageWithSystemSymbolName:accessibilityDescription:")) {
return 0
}
return img.Send(sel("imageWithSystemSymbolName:accessibilityDescription:"), nsString(name), nsString(description))
}
// layout lays the panel out for the width, and measures its text.
func (f *flow) layout(w float64) {
v := &f.views
textW := w - 2*panelPadding - closeSize - 6
v.label.Send(sel("setPreferredMaxLayoutWidth:"), textW)
f.labelH = math.Ceil(objc.Send[nsSize](v.label, sel("fittingSize")).Height)
h := panelPadding + f.labelH + 8 + cardHeight + panelPadding
set := func(view objc.ID, r rect) {
if view != 0 {
view.Send(sel("setFrame:"), r.ns())
}
}
card := rect{panelPadding, panelPadding, w - 2*panelPadding, cardHeight}
set(v.border, rect{0, 0, w, h})
set(v.label, rect{panelPadding, h - panelPadding - f.labelH, textW, f.labelH})
set(v.close, rect{w - panelPadding - closeSize, h - panelPadding - closeSize + 2, closeSize, closeSize})
set(v.cardBox, card)
set(v.icon, rect{card.X + 8, card.Y + (cardHeight-iconSize)/2, iconSize, iconSize})
set(v.name, rect{card.X + 8 + iconSize + 8, card.Y + (cardHeight-20)/2, card.W - iconSize - 70, 20})
set(v.hand, rect{card.maxX() - 38, card.Y + 20, 24, 18})
set(v.hint, rect{card.maxX() - 44, card.Y + 6, 36, 12})
set(v.card, card)
f.panel.Send(sel("invalidateCursorRectsForView:"), v.card)
}
// destroy closes the panel. Main thread.
func (f *flow) destroy() {
if active == f {
active = nil
dragging.Store(false)
}
if f.panel == 0 {
return
}
f.panel.Send(sel("orderOut:"), objc.ID(0))
f.panel.Send(sel("close"))
f.panel.Send(sel("release"))
f.panel, f.views = 0, panelViews{}
}
@@ -0,0 +1,148 @@
import Foundation
import ObjectiveC
import UIKit
import UserNotifications
/// The system's permissions, by name: a binary that names the frameworks' classes
/// has to declare why it would use them, which an app that asks for one of them
/// should not have to for all.
final class PermissionFlowPlugin: MyGoPlugin {
private func load(_ framework: String) {
_ = Bundle(path: "/System/Library/Frameworks/\(framework).framework")?.load()
}
private typealias StatusFn = @convention(c) (AnyClass, Selector, AnyObject) -> Int
private typealias IntStatusFn = @convention(c) (AnyClass, Selector, Int) -> Int
// Blocks go as objects: a closure given to a C function is taken not to
// escape, and Swift traps when the framework keeps it.
private typealias AskFn = @convention(c) (AnyClass, Selector, AnyObject, AnyObject) -> Void
private func avStatus(_ media: String) -> String {
load("AVFoundation")
guard let c = NSClassFromString("AVCaptureDevice") else { return "unknown" }
let sel = NSSelectorFromString("authorizationStatusForMediaType:")
guard let m = class_getClassMethod(c, sel) else { return "unknown" }
let fn = unsafeBitCast(method_getImplementation(m), to: StatusFn.self)
switch fn(c, sel, media as NSString) {
case 0: return "notDetermined"
case 3: return "granted"
default: return "denied"
}
}
private func avRequest(_ media: String, _ done: @escaping (Bool) -> Void) {
load("AVFoundation")
let sel = NSSelectorFromString("requestAccessForMediaType:completionHandler:")
guard let c = NSClassFromString("AVCaptureDevice"), let m = class_getClassMethod(c, sel) else { return done(false) }
let fn = unsafeBitCast(method_getImplementation(m), to: AskFn.self)
let block: @convention(block) (Bool) -> Void = { done($0) }
fn(c, sel, media as NSString, unsafeBitCast(block, to: AnyObject.self))
}
private func photosStatus() -> String {
load("Photos")
let sel = NSSelectorFromString("authorizationStatusForAccessLevel:")
guard let c = NSClassFromString("PHPhotoLibrary"), let m = class_getClassMethod(c, sel) else { return "unknown" }
let fn = unsafeBitCast(method_getImplementation(m), to: IntStatusFn.self)
switch fn(c, sel, 2) { // read and write
case 0: return "notDetermined"
case 3, 4: return "granted" // authorized, or limited
default: return "denied"
}
}
private func photosRequest(_ done: @escaping (Bool) -> Void) {
load("Photos")
typealias Fn = @convention(c) (AnyClass, Selector, Int, AnyObject) -> Void
let sel = NSSelectorFromString("requestAuthorizationForAccessLevel:handler:")
guard let c = NSClassFromString("PHPhotoLibrary"), let m = class_getClassMethod(c, sel) else { return done(false) }
let fn = unsafeBitCast(method_getImplementation(m), to: Fn.self)
let block: @convention(block) (Int) -> Void = { done($0 == 3 || $0 == 4) }
fn(c, sel, 2, unsafeBitCast(block, to: AnyObject.self))
}
private func contactsStatus() -> String {
load("Contacts")
let sel = NSSelectorFromString("authorizationStatusForEntityType:")
guard let c = NSClassFromString("CNContactStore"), let m = class_getClassMethod(c, sel) else { return "unknown" }
let fn = unsafeBitCast(method_getImplementation(m), to: IntStatusFn.self)
switch fn(c, sel, 0) {
case 0: return "notDetermined"
case 3, 4: return "granted"
default: return "denied"
}
}
private func contactsRequest(_ done: @escaping (Bool) -> Void) {
load("Contacts")
typealias Fn = @convention(c) (AnyObject, Selector, Int, AnyObject) -> Void
let sel = NSSelectorFromString("requestAccessForEntityType:completionHandler:")
guard let c = NSClassFromString("CNContactStore") as? NSObject.Type, let m = class_getInstanceMethod(c, sel) else { return done(false) }
let store = c.init()
let fn = unsafeBitCast(method_getImplementation(m), to: Fn.self)
let block: @convention(block) (Bool, NSError?) -> Void = { ok, _ in
_ = store
done(ok)
}
fn(store, sel, 0, unsafeBitCast(block, to: AnyObject.self))
}
private func usage(_ key: String) -> Bool { Bundle.main.object(forInfoDictionaryKey: key) != nil }
private func status(_ p: String, _ done: @escaping (String?) -> Void) {
switch p {
case "camera": done(avStatus("vide"))
case "microphone": done(avStatus("soun"))
case "photos": done(photosStatus())
case "contacts": done(contactsStatus())
case "notifications":
UNUserNotificationCenter.current().getNotificationSettings { s in
DispatchQueue.main.async {
switch s.authorizationStatus {
case .notDetermined: done("notDetermined")
case .denied: done("denied")
default: done("granted")
}
}
}
default: done(nil)
}
}
func call(_ method: String, _ args: [String: Any], _ reply: @escaping PluginReply) {
let p = args["permission"] as? String ?? ""
let answer: (String?) -> Void = { s in
if let s {
reply(.success(["status": s]))
} else {
reply(.failure(PluginFailure("Unsupported")))
}
}
switch method {
case "check":
status(p, answer)
case "request":
let after: (Bool) -> Void = { _ in DispatchQueue.main.async { self.status(p, answer) } }
let need = ["camera": "NSCameraUsageDescription", "microphone": "NSMicrophoneUsageDescription",
"photos": "NSPhotoLibraryUsageDescription", "contacts": "NSContactsUsageDescription"][p]
if let need, !usage(need) {
reply(.failure(PluginFailure("NoUsageDescription", need)))
return
}
switch p {
case "camera": avRequest("vide", after)
case "microphone": avRequest("soun", after)
case "photos": photosRequest(after)
case "contacts": contactsRequest(after)
case "notifications":
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { ok, _ in after(ok) }
default: answer(nil)
}
case "openSettings":
if let u = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(u) }
reply(.success(nil))
default:
reply(.failure(PluginFailure("NoMethod", method)))
}
}
}
@@ -0,0 +1,7 @@
{
"mobile": {
"id": "permissionflow",
"ios": {"sources": ["ios/*.swift"], "class": "PermissionFlowPlugin"},
"android": {"sources": ["android/*.kt"], "class": "PermissionFlowPlugin"}
}
}
@@ -0,0 +1,341 @@
// Package permissionflow checks and asks for the permissions the system
// keeps for the user to give, such as Accessibility, Screen Recording and
// the microphone, and guides the user to where they give them:
//
// st, err := permissionflow.Check(permissionflow.Accessibility)
// if st != permissionflow.Granted {
// st, err = permissionflow.Guide(ctx, permissionflow.Accessibility, permissionflow.GuideOptions{})
// }
//
// On macOS, Guide opens the page of System Settings (Privacy & Security)
// and, on the pages whose list takes apps dragged into it, shows a panel
// under the window of System Settings, which follows it, with the app to
// drag into the list, as PermissionFlow does for Swift apps. On Windows,
// it opens the page of Settings (Privacy & security). On phones, Request is the
// system's prompt and Guide opens the app's page of the system's settings, for
// what the user turned down: the camera, the microphone, photos, contacts,
// notifications and on Android location and Bluetooth. Linux and browsers
// keep no such permissions for apps, and return errors.ErrUnsupported.
//
// Every function is safe to call from any goroutine. OpenSettings and
// Guide need App.Run started, and those that wait (Request, Wait and
// Guide) must not be called from the main thread, which they would block.
package permissionflow
import (
"context"
"errors"
"fmt"
"time"
"github.com/egoist/mygo/i18n"
"github.com/egoist/mygo/internal/l10n"
)
// A Permission is something the system lets the user give apps.
type Permission string
// Permissions. Which of them a system has, and which of those it can tell
// about without asking, is in the documentation of each.
const (
// Accessibility lets the app control the computer through the
// accessibility API: read other apps' windows, move them, and send
// them input. macOS only; macOS 27 names it Device Control and Data
// Access.
Accessibility Permission = "accessibility"
// ScreenRecording lets the app capture the screen and its audio.
// macOS only: Windows lets desktop apps capture it. macOS reports
// a change only after the app starts again.
ScreenRecording Permission = "screen-recording"
// InputMonitoring lets the app read the keyboard and the mouse while
// other apps are in front. macOS only.
InputMonitoring Permission = "input-monitoring"
// FullDiskAccess lets the app read the files that macOS protects, such
// as Mail's and Safari's. macOS only. macOS has no API for it: Check
// tries to read a protected file.
FullDiskAccess Permission = "full-disk-access"
// AppManagement lets the app update and delete other apps. macOS only,
// and Check can't tell.
AppManagement Permission = "app-management"
// DeveloperTools lets the app run software that doesn't meet the
// system's security policy, as debuggers do. macOS only, and Check
// can't tell.
DeveloperTools Permission = "developer-tools"
// Microphone lets the app record audio: macOS and Windows. Requesting
// it on macOS needs NSMicrophoneUsageDescription in the Info.plist
// (macos.infoPlist in mygo.config.ts).
Microphone Permission = "microphone"
// Camera lets the app record video: macOS and Windows. Requesting it
// on macOS needs NSCameraUsageDescription in the Info.plist.
Camera Permission = "camera"
// Calendars lets the app read and change the user's calendars. macOS
// only. Requesting it needs NSCalendarsUsageDescription in the
// Info.plist, and NSCalendarsFullAccessUsageDescription on macOS 14
// and later.
Calendars Permission = "calendars"
// Reminders lets the app read and change the user's reminders. macOS
// only. Requesting it needs NSRemindersUsageDescription in the
// Info.plist, and NSRemindersFullAccessUsageDescription on macOS 14
// and later.
Reminders Permission = "reminders"
// Bluetooth lets the app use Bluetooth devices. macOS only. Requesting
// it needs NSBluetoothAlwaysUsageDescription in the Info.plist.
Bluetooth Permission = "bluetooth"
// MediaAppleMusic lets the app use the user's Apple Music library.
// macOS only, and Check can't tell.
MediaAppleMusic Permission = "media-apple-music"
// Photos lets the app read the user's library of photos: iOS and Android.
// The system's picker needs it not (plugins/imagepicker). iOS needs
// NSPhotoLibraryUsageDescription in the Info.plist, and Android
// READ_MEDIA_IMAGES among android.permissions.
Photos Permission = "photos"
// Contacts lets the app read the user's contacts: iOS and Android. iOS
// needs NSContactsUsageDescription, Android READ_CONTACTS.
Contacts Permission = "contacts"
// Notifications lets the app show notifications: iOS and Android.
Notifications Permission = "notifications"
// Location lets the app know where the device is while it is in use:
// Android (plugins/location asks on both).
Location Permission = "location"
)
// All returns every permission, in the order of System Settings.
func All() []Permission {
return []Permission{
Accessibility, ScreenRecording, InputMonitoring, FullDiskAccess,
AppManagement, DeveloperTools, Microphone, Camera, Calendars,
Reminders, Bluetooth, MediaAppleMusic,
}
}
// OnPhones returns the permissions phones keep.
func OnPhones() []Permission {
return []Permission{Camera, Microphone, Photos, Contacts, Notifications, Location, Bluetooth, Calendars}
}
var titles = map[Permission]string{
Accessibility: "Accessibility",
ScreenRecording: "Screen Recording",
InputMonitoring: "Input Monitoring",
FullDiskAccess: "Full Disk Access",
AppManagement: "App Management",
DeveloperTools: "Developer Tools",
Microphone: "Microphone",
Camera: "Camera",
Calendars: "Calendars",
Reminders: "Reminders",
Bluetooth: "Bluetooth",
MediaAppleMusic: "Media & Apple Music",
}
// phoneTitles names the permissions only phones keep.
var phoneTitles = map[Permission]string{
Photos: "Photos",
Contacts: "Contacts",
Notifications: "Notifications",
Location: "Location",
}
// Title returns the name of the permission as the system's settings show
// it, in the language the app shows: "Screen Recording" in English.
func (p Permission) Title() string {
if _, ok := titles[p]; ok {
return title(p, localizedTitle(p, i18n.Locale()))
}
if t, ok := phoneTitles[p]; ok {
return t
}
return string(p)
}
func localizedTitle(p Permission, locale string) string {
msgs := l10n.In(locale)
switch p {
case Accessibility:
return msgs.PermissionAccessibility()
case ScreenRecording:
return msgs.PermissionScreenRecording()
case InputMonitoring:
return msgs.PermissionInputMonitoring()
case FullDiskAccess:
return msgs.PermissionFullDiskAccess()
case AppManagement:
return msgs.PermissionAppManagement()
case DeveloperTools:
return msgs.PermissionDeveloperTools()
case Microphone:
return msgs.PermissionMicrophone()
case Camera:
return msgs.PermissionCamera()
case Calendars:
return msgs.PermissionCalendars()
case Reminders:
return msgs.PermissionReminders()
case Bluetooth:
return msgs.PermissionBluetooth()
case MediaAppleMusic:
return msgs.PermissionMediaAppleMusic()
default:
return string(p)
}
}
func (p Permission) String() string { return string(p) }
func (p Permission) valid() bool {
if _, ok := titles[p]; ok {
return true
}
_, ok := phoneTitles[p]
return ok
}
// Status is whether the app has a permission.
type Status int
// Statuses.
const (
// Unknown is when the system can't tell without asking, or has no API
// to tell.
Unknown Status = iota
// NotDetermined is when the user hasn't been asked yet: Request asks.
// macOS doesn't tell for Accessibility, Screen Recording and Input
// Monitoring, which are Denied until granted.
NotDetermined
// Denied is when the user, or the administrator, said no: only the
// system's settings change it (see OpenSettings and Guide).
Denied
// Granted is when the app has the permission.
Granted
)
func (s Status) String() string {
switch s {
case NotDetermined:
return "not determined"
case Denied:
return "denied"
case Granted:
return "granted"
}
return "unknown"
}
// ErrUsageDescription is returned by Request on macOS when the app's
// Info.plist lacks the description of why it asks, without which macOS
// would end the app.
var ErrUsageDescription = errors.New("permissionflow: the Info.plist lacks the usage description")
// Check reports whether the app has p, without asking the user. It
// returns errors.ErrUnsupported when the system keeps no such permission
// for apps, and Unknown when it does but can't tell.
func Check(p Permission) (Status, error) {
if !p.valid() {
return Unknown, fmt.Errorf("permissionflow: unknown permission %q", p)
}
return check(p)
}
// Allowed reports whether the app may use what p guards: when it has p,
// or when the system doesn't ask for it, as Linux doesn't for the
// microphone. It is false in browsers.
func Allowed(p Permission) bool {
st, err := Check(p)
if errors.Is(err, errors.ErrUnsupported) {
return ungated
}
return st == Granted
}
// Request asks the user for p with the system's own prompt, when it has
// one and hasn't asked yet, and returns the status it then has. macOS asks
// once for each app: after that Request only reports, and the user
// changes their mind in System Settings (see OpenSettings and Guide). For
// the permissions without a prompt (Full Disk Access, App Management,
// Developer Tools, Media & Apple Music, and all of them on Windows), it
// reports what Check does.
//
// macOS adds the app to the list of Accessibility, Screen Recording and
// Input Monitoring when it asks, and opens System Settings itself from
// its prompt, with the switch off: Request returns before the user turns
// it on (see Wait).
func Request(ctx context.Context, p Permission) (Status, error) {
if !p.valid() {
return Unknown, fmt.Errorf("permissionflow: unknown permission %q", p)
}
return request(ctx, p)
}
// OpenSettings opens the page of the system's settings where the user
// gives p: Privacy & Security in System Settings on macOS, Privacy &
// security in Settings on Windows. It returns errors.ErrUnsupported when
// the system has no such page.
func OpenSettings(p Permission) error {
if !p.valid() {
return fmt.Errorf("permissionflow: unknown permission %q", p)
}
return openSettings(p)
}
// pollInterval is how often Wait and Guide check the permission.
const pollInterval = 250 * time.Millisecond
// Wait waits until the app has p, and returns Granted, or until ctx is
// done. It returns at once, with the status, when Check can't tell
// (Unknown) or returns an error.
func Wait(ctx context.Context, p Permission) (Status, error) {
return wait(ctx, func() (Status, error) { return Check(p) }, pollInterval)
}
func wait(ctx context.Context, check func() (Status, error), every time.Duration) (Status, error) {
t := time.NewTicker(every)
defer t.Stop()
for {
st, err := check()
if err != nil || st == Granted || st == Unknown {
return st, err
}
select {
case <-ctx.Done():
return st, ctx.Err()
case <-t.C:
}
}
}
// GuideOptions configures Guide.
type GuideOptions struct {
// App is the path of the app the user drags into the list of System
// Settings on macOS: the .app bundle the program runs from when it is
// empty, or the program itself when it isn't in one, as with go run
// (macOS gives the permission to the app that started it, such as
// the terminal, which is the one to drag then).
App string
// Name is the name the panel gives the app: App's without its
// extension when it is empty.
Name string
}
// Guide opens the page of the system's settings where the user gives p,
// as OpenSettings does, and waits for the user to give it.
//
// On macOS, for Accessibility, Screen Recording, Input Monitoring, Full
// Disk Access, App Management, Developer Tools, Bluetooth and Media &
// Apple Music, whose list takes apps dragged into it, it also shows a
// panel under the window of System Settings, which follows the window,
// with the app to drag ("Drag MyApp to the list above to allow
// Accessibility."). The panel stays out of the way of System Settings:
// it never takes the focus. One panel shows at a time: another Guide
// closes the one before, whose Guide returns.
//
// Guide returns when the app has p (when Check can tell), when the user
// closes the panel or System Settings, or when ctx is done, with ctx's
// error. It returns the status of p then, which is Unknown when Check
// can't tell. On Windows it returns when the app has p or when ctx is
// done.
func Guide(ctx context.Context, p Permission, opts GuideOptions) (Status, error) {
if !p.valid() {
return Unknown, fmt.Errorf("permissionflow: unknown permission %q", p)
}
return guide(ctx, p, opts)
}
@@ -0,0 +1,477 @@
//go:build darwin && !ios
package permissionflow
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"unsafe"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo"
"github.com/egoist/mygo/i18n"
"github.com/egoist/mygo/internal/l10n"
)
// macOS keeps the permissions in TCC, which the frameworks ask: the
// accessibility API (ApplicationServices), CoreGraphics for the screen and
// the input, AVFoundation for the microphone and the camera, EventKit for
// calendars and reminders, and CoreBluetooth. Their frameworks are loaded
// when a permission of theirs is first checked.
const (
applicationServicesPath = "/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices"
coreGraphicsPath = "/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics"
coreFoundationPath = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"
avFoundationPath = "/System/Library/Frameworks/AVFoundation.framework/AVFoundation"
eventKitPath = "/System/Library/Frameworks/EventKit.framework/EventKit"
coreBluetoothPath = "/System/Library/Frameworks/CoreBluetooth.framework/CoreBluetooth"
appKitPath = "/System/Library/Frameworks/AppKit.framework/AppKit"
libObjCPath = "/usr/lib/libobjc.A.dylib"
settingsBundleID = "com.apple.systempreferences"
// TCC's authorization statuses, as AVFoundation, EventKit and
// CoreBluetooth number them.
tccNotDetermined = 0
tccRestricted = 1
tccDenied = 2
tccAuthorized = 3
ekEntityTypeEvent = 0
ekEntityTypeReminder = 1
)
var (
coreOnce sync.Once
coreErr error
axIsProcessTrusted func() bool
axIsProcessTrustedWithOptions func(options objc.ID) bool
cgPreflightScreenCaptureAccess func() bool
cgRequestScreenCaptureAccess func() bool
cgPreflightListenEventAccess func() bool
cgRequestListenEventAccess func() bool
cgWindowListCopyWindowInfo func(option, relativeTo uint32) objc.ID
cgEventSourceButtonState func(state int32, button uint32) bool
cfRelease func(obj objc.ID)
// Messages of the types that Guide sends 30 times a second, which
// objc.Send would register anew each time.
sendUint func(obj objc.ID, s objc.SEL) uint
sendInt func(obj objc.ID, s objc.SEL) int
sendFloat func(obj objc.ID, s objc.SEL) float64
poolPush, poolPop uintptr
avMediaTypeAudio objc.ID
avMediaTypeVideo objc.ID
frameworks sync.Map // path → error of loading it
macMajor int // macOS's major version
)
func sel(name string) objc.SEL { return objc.RegisterName(name) }
func class(name string) objc.ID { return objc.ID(objc.GetClass(name)) }
func loadCore() error {
coreOnce.Do(func() {
libs := map[string]uintptr{}
for _, path := range []string{applicationServicesPath, coreGraphicsPath, coreFoundationPath, appKitPath, libObjCPath} {
h, err := purego.Dlopen(path, purego.RTLD_LAZY|purego.RTLD_GLOBAL)
if err != nil {
coreErr = fmt.Errorf("permissionflow: %w", err)
return
}
libs[path] = h
}
for _, f := range []struct {
fn any
lib, name string
}{
{&axIsProcessTrusted, applicationServicesPath, "AXIsProcessTrusted"},
{&axIsProcessTrustedWithOptions, applicationServicesPath, "AXIsProcessTrustedWithOptions"},
{&cgPreflightScreenCaptureAccess, coreGraphicsPath, "CGPreflightScreenCaptureAccess"},
{&cgRequestScreenCaptureAccess, coreGraphicsPath, "CGRequestScreenCaptureAccess"},
{&cgPreflightListenEventAccess, coreGraphicsPath, "CGPreflightListenEventAccess"},
{&cgRequestListenEventAccess, coreGraphicsPath, "CGRequestListenEventAccess"},
{&cgWindowListCopyWindowInfo, coreGraphicsPath, "CGWindowListCopyWindowInfo"},
{&cgEventSourceButtonState, coreGraphicsPath, "CGEventSourceButtonState"},
{&cfRelease, coreFoundationPath, "CFRelease"},
} {
p, err := purego.Dlsym(libs[f.lib], f.name)
if err != nil {
coreErr = fmt.Errorf("permissionflow: missing %s (macOS 10.15 and later): %w", f.name, errors.ErrUnsupported)
return
}
purego.RegisterFunc(f.fn, p)
}
msgSend, err := purego.Dlsym(libs[libObjCPath], "objc_msgSend")
if err != nil {
coreErr = fmt.Errorf("permissionflow: %w", err)
return
}
purego.RegisterFunc(&sendUint, msgSend)
purego.RegisterFunc(&sendInt, msgSend)
purego.RegisterFunc(&sendFloat, msgSend)
poolPush, _ = purego.Dlsym(libs[libObjCPath], "objc_autoreleasePoolPush")
poolPop, _ = purego.Dlsym(libs[libObjCPath], "objc_autoreleasePoolPop")
withPool(func() {
type osVersion struct{ Major, Minor, Patch int }
info := class("NSProcessInfo").Send(sel("processInfo"))
macMajor = objc.Send[osVersion](info, sel("operatingSystemVersion")).Major
})
})
return coreErr
}
// loadFramework loads the framework at path once, for its classes.
func loadFramework(path string) (uintptr, error) {
type loaded struct {
h uintptr
err error
}
if v, ok := frameworks.Load(path); ok {
return v.(loaded).h, v.(loaded).err
}
h, err := purego.Dlopen(path, purego.RTLD_LAZY|purego.RTLD_GLOBAL)
if err != nil {
err = fmt.Errorf("permissionflow: %w", err)
}
v, _ := frameworks.LoadOrStore(path, loaded{h, err})
return v.(loaded).h, v.(loaded).err
}
func loadAVFoundation() error {
h, err := loadFramework(avFoundationPath)
if err != nil {
return err
}
if avMediaTypeAudio == 0 {
audio, err1 := purego.Dlsym(h, "AVMediaTypeAudio")
video, err2 := purego.Dlsym(h, "AVMediaTypeVideo")
if err1 != nil || err2 != nil {
return fmt.Errorf("permissionflow: AVFoundation lacks its media types: %w", errors.ErrUnsupported)
}
avMediaTypeAudio = **(**objc.ID)(unsafe.Pointer(&audio))
avMediaTypeVideo = **(**objc.ID)(unsafe.Pointer(&video))
}
return nil
}
// withPool runs fn in an autorelease pool, on one thread.
func withPool(fn func()) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
p, _, _ := purego.SyscallN(poolPush)
defer purego.SyscallN(poolPop, p)
fn()
}
func cstr(s string) *byte {
b := append([]byte(s), 0)
return &b[0]
}
// nsString returns an autoreleased NSString.
func nsString(s string) objc.ID {
return class("NSString").Send(sel("stringWithUTF8String:"), cstr(s))
}
func goString(s objc.ID) string {
if s == 0 {
return ""
}
p := objc.Send[unsafe.Pointer](s, sel("UTF8String"))
if p == nil {
return ""
}
n := 0
for *(*byte)(unsafe.Add(p, n)) != 0 {
n++
}
return string(unsafe.Slice((*byte)(p), n))
}
const ungated = true
func title(p Permission, t string) string {
// macOS 27 renamed Accessibility; its anchor stays.
if p == Accessibility && loadCore() == nil && macMajor >= 27 {
return l10n.In(i18n.Locale()).PermissionDeviceControlAndDataAccess()
}
return t
}
// tccStatus converts a status of AVFoundation, EventKit or CoreBluetooth.
// EventKit's 4, write only, isn't the access asked for.
func tccStatus(v int) Status {
switch v {
case tccNotDetermined:
return NotDetermined
case tccAuthorized:
return Granted
}
return Denied
}
func granted(ok bool) Status {
if ok {
return Granted
}
return Denied
}
func check(p Permission) (st Status, err error) {
if err := loadCore(); err != nil {
return Unknown, err
}
switch p {
case Accessibility:
return granted(axIsProcessTrusted()), nil
case ScreenRecording:
return granted(cgPreflightScreenCaptureAccess()), nil
case InputMonitoring:
return granted(cgPreflightListenEventAccess()), nil
case FullDiskAccess:
return fullDiskAccess(), nil
case Microphone, Camera:
if err := loadAVFoundation(); err != nil {
return Unknown, err
}
withPool(func() {
st = tccStatus(objc.Send[int](class("AVCaptureDevice"), sel("authorizationStatusForMediaType:"), mediaType(p)))
})
return st, nil
case Calendars, Reminders:
if _, err := loadFramework(eventKitPath); err != nil {
return Unknown, err
}
withPool(func() {
st = tccStatus(objc.Send[int](class("EKEventStore"), sel("authorizationStatusForEntityType:"), entityType(p)))
})
return st, nil
case Bluetooth:
if _, err := loadFramework(coreBluetoothPath); err != nil {
return Unknown, err
}
cb := class("CBManager")
if cb == 0 || !objc.Send[bool](cb, sel("respondsToSelector:"), sel("authorization")) {
return Unknown, nil
}
withPool(func() { st = tccStatus(objc.Send[int](cb, sel("authorization"))) })
return st, nil
}
return Unknown, nil
}
func mediaType(p Permission) objc.ID {
if p == Camera {
return avMediaTypeVideo
}
return avMediaTypeAudio
}
func entityType(p Permission) int {
if p == Reminders {
return ekEntityTypeReminder
}
return ekEntityTypeEvent
}
// fullDiskAccess tries to read files that only apps with Full Disk Access
// read: TCC's own database of the user, then Safari's files.
func fullDiskAccess() Status {
home, err := os.UserHomeDir()
if err != nil {
return Unknown
}
f, err := os.Open(filepath.Join(home, "Library/Application Support/com.apple.TCC/TCC.db"))
if err == nil {
f.Close()
return Granted
}
if errors.Is(err, fs.ErrPermission) {
return Denied
}
if _, err := os.ReadDir(filepath.Join(home, "Library/Safari")); err == nil {
return Granted
} else if errors.Is(err, fs.ErrPermission) {
return Denied
}
return Unknown
}
// usageDescription checks that the app's Info.plist describes why it asks,
// as macOS ends apps in bundles that ask without. A program outside a
// bundle asks for the app that started it.
func usageDescription(keys ...string) error {
var err error
withPool(func() {
b := class("NSBundle").Send(sel("mainBundle"))
if !strings.HasSuffix(goString(b.Send(sel("bundlePath"))), ".app") {
return
}
for _, k := range keys {
if b.Send(sel("objectForInfoDictionaryKey:"), nsString(k)) == 0 {
err = fmt.Errorf("%w: add %s to macos.infoPlist", ErrUsageDescription, k)
return
}
}
})
return err
}
var (
eventStore objc.ID // kept: a request dies with its store
centralManager objc.ID // kept: Bluetooth asks while it lives
requestMu sync.Mutex
)
func request(ctx context.Context, p Permission) (Status, error) {
st, err := check(p)
if err != nil {
return st, err
}
switch p {
case Accessibility:
if st == Granted {
return st, nil
}
withPool(func() {
opts := class("NSDictionary").Send(sel("dictionaryWithObject:forKey:"),
class("NSNumber").Send(sel("numberWithBool:"), true), nsString("AXTrustedCheckOptionPrompt"))
st = granted(axIsProcessTrustedWithOptions(opts))
})
return st, nil
case ScreenRecording:
if st == Granted {
return st, nil
}
return granted(cgRequestScreenCaptureAccess()), nil
case InputMonitoring:
if st == Granted {
return st, nil
}
return granted(cgRequestListenEventAccess()), nil
}
if st != NotDetermined {
return st, nil
}
done := make(chan struct{}, 1)
blk := objc.NewBlock(func(objc.Block, bool, objc.ID) {
select {
case done <- struct{}{}:
default:
}
})
defer blk.Release()
switch p {
case Microphone, Camera:
key := "NSMicrophoneUsageDescription"
if p == Camera {
key = "NSCameraUsageDescription"
}
if err := usageDescription(key); err != nil {
return st, err
}
withPool(func() {
class("AVCaptureDevice").Send(sel("requestAccessForMediaType:completionHandler:"), mediaType(p), blk)
})
case Calendars, Reminders:
modern := objc.Send[bool](class("EKEventStore"), sel("instancesRespondToSelector:"), sel("requestFullAccessToEventsWithCompletion:"))
keys := []string{"NSCalendarsUsageDescription"}
if p == Reminders {
keys = []string{"NSRemindersUsageDescription"}
}
if modern {
keys[0] = strings.Replace(keys[0], "UsageDescription", "FullAccessUsageDescription", 1)
}
if err := usageDescription(keys...); err != nil {
return st, err
}
requestMu.Lock()
if eventStore == 0 {
eventStore = class("EKEventStore").Send(sel("alloc")).Send(sel("init"))
}
store := eventStore
requestMu.Unlock()
withPool(func() {
switch {
case modern && p == Calendars:
store.Send(sel("requestFullAccessToEventsWithCompletion:"), blk)
case modern:
store.Send(sel("requestFullAccessToRemindersWithCompletion:"), blk)
default:
store.Send(sel("requestAccessToEntityType:completion:"), entityType(p), blk)
}
})
case Bluetooth:
if err := usageDescription("NSBluetoothAlwaysUsageDescription"); err != nil {
return st, err
}
requestMu.Lock()
if centralManager == 0 {
// Its delegate would hear of the state of the radio:
// the prompt shows without one.
centralManager = class("CBCentralManager").Send(sel("alloc")).Send(sel("initWithDelegate:queue:"), objc.ID(0), objc.ID(0))
}
requestMu.Unlock()
// CoreBluetooth calls no block: wait for the status to change.
return waitDetermined(ctx, p)
default:
return st, nil
}
select {
case <-done:
case <-ctx.Done():
return st, ctx.Err()
}
return check(p)
}
// waitDetermined waits until the user has answered for p.
func waitDetermined(ctx context.Context, p Permission) (Status, error) {
t := time.NewTicker(pollInterval)
defer t.Stop()
for {
st, err := check(p)
if err != nil || st != NotDetermined {
return st, err
}
select {
case <-ctx.Done():
return st, ctx.Err()
case <-t.C:
}
}
}
func openSettings(p Permission) error {
if err := loadCore(); err != nil {
return err
}
ok := false
mygo.RunOnMain(func() {
withPool(func() {
u := class("NSURL").Send(sel("URLWithString:"), nsString(macSettingsURL(p)))
ws := class("NSWorkspace").Send(sel("sharedWorkspace"))
ok = objc.Send[bool](ws, sel("openURL:"), u)
})
})
if !ok {
return fmt.Errorf("permissionflow: System Settings didn't open %s", macSettingsURL(p))
}
return nil
}
@@ -0,0 +1,62 @@
//go:build ios || android
package permissionflow
import (
"context"
"errors"
"github.com/egoist/mygo"
)
// Phones keep them through the plugin's native code. It uses the system's
// frameworks by name on iOS, not to make every app that imports it declare why
// it would use the camera: an app declares what it asks for.
const ungated = false
func title(_ Permission, t string) string { return t }
func call(ctx context.Context, method string, p Permission) (Status, error) {
var r struct {
Status string `json:"status"`
}
err := mygo.Native("permissionflow").Call(ctx, method, map[string]string{"permission": string(p)}, &r)
var n *mygo.NativeError
if errors.As(err, &n) {
switch n.Code {
case "Unsupported":
return Unknown, errors.ErrUnsupported
case "NoUsageDescription":
return Unknown, ErrUsageDescription
}
return Unknown, err
}
if err != nil {
return Unknown, err
}
switch r.Status {
case "granted":
return Granted, nil
case "denied":
return Denied, nil
case "notDetermined":
return NotDetermined, nil
}
return Unknown, nil
}
func check(p Permission) (Status, error) { return call(context.Background(), "check", p) }
func request(ctx context.Context, p Permission) (Status, error) { return call(ctx, "request", p) }
func openSettings(p Permission) error {
return mygo.Native("permissionflow").Call(context.Background(), "openSettings", map[string]string{"permission": string(p)}, nil)
}
func guide(ctx context.Context, p Permission, _ GuideOptions) (Status, error) {
if err := openSettings(p); err != nil {
return Unknown, err
}
return Wait(ctx, p)
}
@@ -0,0 +1,26 @@
//go:build !darwin && !windows && !android
package permissionflow
import (
"context"
"errors"
"runtime"
)
// Linux keeps none of these permissions for apps outside sandboxes, and
// browsers keep theirs for pages.
const ungated = runtime.GOOS != "js"
func title(_ Permission, t string) string { return t }
func check(Permission) (Status, error) { return Unknown, errors.ErrUnsupported }
func request(context.Context, Permission) (Status, error) { return Unknown, errors.ErrUnsupported }
func openSettings(Permission) error { return errors.ErrUnsupported }
func guide(context.Context, Permission, GuideOptions) (Status, error) {
return Unknown, errors.ErrUnsupported
}
@@ -0,0 +1,252 @@
package permissionflow
import (
"context"
"errors"
"runtime"
"strings"
"testing"
"time"
"github.com/egoist/mygo/i18n"
_ "github.com/egoist/mygo/locales/zh-Hans"
)
func TestPermissions(t *testing.T) {
seen := map[Permission]bool{}
for _, p := range All() {
if seen[p] {
t.Errorf("%s twice", p)
}
seen[p] = true
if !p.valid() || p.Title() == "" || p.Title() == string(p) {
t.Errorf("%s has no title", p)
}
if !strings.HasPrefix(macAnchors[p], "Privacy_") {
t.Errorf("%s has no page in System Settings", p)
}
}
if len(seen) != len(titles) || len(macAnchors) != len(titles) {
t.Errorf("All has %d permissions, titles %d, anchors %d", len(seen), len(titles), len(macAnchors))
}
if got, want := macSettingsURL(ScreenRecording), "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture"; got != want {
t.Errorf("URL %q, want %q", got, want)
}
for p, c := range windowsCapabilities {
if !seen[p] || !strings.HasPrefix(c.uri, "ms-settings:privacy-") || c.capability == "" {
t.Errorf("Windows' %s: %+v", p, c)
}
}
if macDraggable(Microphone) || !macDraggable(Accessibility) || !macDraggable(FullDiskAccess) {
t.Error("the wrong pages take drags")
}
}
func TestUnknownPermission(t *testing.T) {
p := Permission("telepathy")
if _, err := Check(p); err == nil {
t.Error("Check took an unknown permission")
}
if _, err := Request(context.Background(), p); err == nil {
t.Error("Request took an unknown permission")
}
if err := OpenSettings(p); err == nil {
t.Error("OpenSettings took an unknown permission")
}
if _, err := Guide(context.Background(), p, GuideOptions{}); err == nil {
t.Error("Guide took an unknown permission")
}
if Allowed(p) {
t.Error("an unknown permission is allowed")
}
}
func TestUnsupported(t *testing.T) {
if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
t.Skip("the system has permissions")
}
for _, p := range All() {
if _, err := Check(p); !errors.Is(err, errors.ErrUnsupported) {
t.Errorf("Check(%s): %v", p, err)
}
if err := OpenSettings(p); !errors.Is(err, errors.ErrUnsupported) {
t.Errorf("OpenSettings(%s): %v", p, err)
}
if !Allowed(p) {
t.Errorf("%s isn't allowed, which nothing keeps", p)
}
}
}
func TestWindowsConsent(t *testing.T) {
for _, c := range []struct {
values []string
want Status
}{
{nil, Granted},
{[]string{"", "", ""}, Granted},
{[]string{"Allow", "Allow", "Allow"}, Granted},
{[]string{"Deny", "Allow", "Allow"}, Denied},
{[]string{"Allow", "Allow", "deny"}, Denied},
{[]string{"", "Deny", ""}, Denied},
} {
if got := windowsConsent(c.values...); got != c.want {
t.Errorf("windowsConsent(%q) = %v, want %v", c.values, got, c.want)
}
}
}
func TestWait(t *testing.T) {
ctx := context.Background()
n := 0
st, err := wait(ctx, func() (Status, error) {
if n++; n < 3 {
return Denied, nil
}
return Granted, nil
}, time.Nanosecond)
if st != Granted || err != nil || n != 3 {
t.Errorf("wait = %v, %v after %d checks", st, err, n)
}
st, err = wait(ctx, func() (Status, error) { return Unknown, nil }, time.Nanosecond)
if st != Unknown || err != nil {
t.Errorf("wait of what can't be told = %v, %v", st, err)
}
boom := errors.New("boom")
if _, err := wait(ctx, func() (Status, error) { return Unknown, boom }, time.Nanosecond); err != boom {
t.Errorf("wait's error = %v", err)
}
cancelled, cancel := context.WithCancel(ctx)
checks := 0
st, err = wait(cancelled, func() (Status, error) {
if checks++; checks == 2 {
cancel()
}
return NotDetermined, nil
}, time.Nanosecond)
if st != NotDetermined || !errors.Is(err, context.Canceled) {
t.Errorf("cancelled wait = %v, %v", st, err)
}
}
func TestPanelText(t *testing.T) {
render := func(runs []run) string {
var b strings.Builder
for _, r := range runs {
if r.bold {
b.WriteString("**" + r.text + "**")
} else {
b.WriteString(r.text)
}
}
return b.String()
}
// The localized sentence keeps the app and permission runs bold.
got := render(panelText("MyApp", "Accessibility", "en"))
if want := "Drag **MyApp** to the list above to allow **Accessibility**."; got != want {
t.Errorf("panel says %q, want %q", got, want)
}
if got, want := render(panelText("应用", "辅助功能", "zh-Hans")), "将**应用**拖入上方列表以允许**辅助功能**。"; got != want {
t.Errorf("Chinese panel says %q, want %q", got, want)
}
for path, want := range map[string]string{
"/Applications/My App.app": "My App",
"/Applications/My App.app/": "My App",
"/usr/local/bin/tool": "tool",
} {
if got := appName(path); got != want {
t.Errorf("appName(%q) = %q, want %q", path, got, want)
}
}
}
func TestPermissionTitlesFollowLocale(t *testing.T) {
i18n.SetLocaleFunc(func() string { return "zh-Hans" })
t.Cleanup(func() { i18n.SetLocaleFunc(nil) })
want := map[Permission]string{
Accessibility: "辅助功能",
ScreenRecording: "屏幕录制",
InputMonitoring: "输入监控",
FullDiskAccess: "完全磁盘访问权限",
AppManagement: "应用管理",
DeveloperTools: "开发者工具",
Microphone: "麦克风",
Camera: "相机",
Calendars: "日历",
Reminders: "提醒事项",
Bluetooth: "蓝牙",
MediaAppleMusic: "媒体与 Apple Music",
}
for p, want := range want {
if got := p.Title(); got != want {
t.Errorf("%s.Title() = %q, want %q", p, got, want)
}
}
}
func TestPanelFrame(t *testing.T) {
screen := rect{0, 0, 1512, 944} // the visible part, under the menu bar
main := 982.0 // the main display's height
// System Settings' window, 715×600, at (300, 100) from the top left.
settings := flipRect(rect{300, 100, 715, 600}, main)
if want := (rect{300, 282, 715, 600}); settings != want {
t.Fatalf("flipped %v, want %v", settings, want)
}
got := panelFrame(settings, screen, 100)
if want := (rect{530, 182, 485, 100}); got != want {
t.Errorf("panel %v, want %v: under the page, to its right edge", got, want)
}
// No room under the window: the panel stays on the screen.
low := flipRect(rect{300, 380, 715, 600}, main)
if got := panelFrame(low, screen, 100); got.Y != screenInset {
t.Errorf("panel at %v, off the bottom of the screen", got)
}
// Pushed against the right edge.
right := flipRect(rect{1300, 100, 715, 600}, main)
if got := panelFrame(right, screen, 100); got.maxX() != screen.maxX()-screenInset {
t.Errorf("panel %v leaves the screen", got)
}
// A narrow window still gets a panel wide enough to read.
narrow := flipRect(rect{300, 100, 300, 600}, main)
if got := panelFrame(narrow, screen, 100); got.W != panelMinWidth {
t.Errorf("panel %v under a narrow window", got)
}
}
func TestScreenOf(t *testing.T) {
left := rect{0, 0, 1512, 944}
right := rect{1512, -200, 1920, 1050}
if got := screenOf(rect{1600, 100, 700, 500}, []rect{left, right}); got != right {
t.Errorf("screen %v, want the right one", got)
}
if got := screenOf(rect{1400, 100, 200, 500}, []rect{left, right}); got != left {
t.Errorf("screen %v, want the left one, with most of the window", got)
}
if got := screenOf(rect{-5000, 0, 10, 10}, []rect{left, right}); got != left {
t.Errorf("screen %v for a window off every screen, want the first", got)
}
}
func TestMainSettingsWindow(t *testing.T) {
main := rect{300, 100, 715, 600}
got, ok := mainSettingsWindow([]settingsWindow{
{bounds: rect{0, 0, 30, 30}, alpha: 1}, // a helper
{bounds: rect{0, 0, 2000, 2000}, layer: 25, alpha: 1}, // a layer above
{bounds: rect{0, 0, 1000, 1000}, alpha: 0}, // not showing
{bounds: main, alpha: 1},
})
if !ok || got != main {
t.Errorf("window %v, %v, want %v", got, ok, main)
}
if _, ok := mainSettingsWindow(nil); ok {
t.Error("a window among none")
}
}
@@ -0,0 +1,93 @@
//go:build windows
package permissionflow
import (
"context"
"errors"
"fmt"
"syscall"
"unsafe"
"github.com/egoist/mygo"
)
// Windows keeps the microphone and the camera from desktop apps with the
// switches of its consent store, in the registry, which Settings' pages
// of Privacy & security turn on and off. It has no prompt for them, and
// keeps nothing else from desktop apps.
const consentStore = `Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\`
var procShellExecuteW = syscall.NewLazyDLL("shell32.dll").NewProc("ShellExecuteW")
const ungated = true
func title(_ Permission, t string) string { return t }
// registryString returns a string value of the registry, "" when it
// isn't there.
func registryString(root syscall.Handle, path, name string) string {
var key syscall.Handle
p, err := syscall.UTF16PtrFromString(path)
if err != nil {
return ""
}
if syscall.RegOpenKeyEx(root, p, 0, syscall.KEY_READ, &key) != nil {
return ""
}
defer syscall.RegCloseKey(key)
n, err := syscall.UTF16PtrFromString(name)
if err != nil {
return ""
}
var typ, size uint32
if syscall.RegQueryValueEx(key, n, nil, &typ, nil, &size) != nil || typ != syscall.REG_SZ || size == 0 {
return ""
}
buf := make([]uint16, (size+1)/2)
if syscall.RegQueryValueEx(key, n, nil, &typ, (*byte)(unsafe.Pointer(&buf[0])), &size) != nil {
return ""
}
return syscall.UTF16ToString(buf)
}
func check(p Permission) (Status, error) {
c, ok := windowsCapabilities[p]
if !ok {
return Unknown, fmt.Errorf("permissionflow: Windows has no %s permission: %w", p.Title(), errors.ErrUnsupported)
}
path := consentStore + c.capability
return windowsConsent(
registryString(syscall.HKEY_LOCAL_MACHINE, path, "Value"),
registryString(syscall.HKEY_CURRENT_USER, path, "Value"),
registryString(syscall.HKEY_CURRENT_USER, path+`\NonPackaged`, "Value"),
), nil
}
func request(_ context.Context, p Permission) (Status, error) { return check(p) }
func openSettings(p Permission) error {
c, ok := windowsCapabilities[p]
if !ok {
return fmt.Errorf("permissionflow: Windows has no %s permission: %w", p.Title(), errors.ErrUnsupported)
}
verb, _ := syscall.UTF16PtrFromString("open")
uri, _ := syscall.UTF16PtrFromString(c.uri)
var r uintptr
// The shell runs in the apartment of the main thread.
mygo.RunOnMain(func() {
r, _, _ = procShellExecuteW.Call(0, uintptr(unsafe.Pointer(verb)), uintptr(unsafe.Pointer(uri)), 0, 0, 1)
})
if r <= 32 {
return fmt.Errorf("permissionflow: Settings didn't open %s (%d)", c.uri, r)
}
return nil
}
func guide(ctx context.Context, p Permission, _ GuideOptions) (Status, error) {
if err := openSettings(p); err != nil {
return Unknown, err
}
return Wait(ctx, p)
}