some platform-specific code

This commit is contained in:
Judah Caruso 2025-11-18 19:55:33 -07:00
parent 7a36acbf9b
commit 9a061a5914
7 changed files with 106 additions and 8 deletions

2
go.mod
View file

@ -1,3 +1,5 @@
module git.brut.systems/judah/xx module git.brut.systems/judah/xx
go 1.25.0 go 1.25.0
require github.com/ebitengine/purego v0.9.1 // indirect

2
go.sum Normal file
View file

@ -0,0 +1,2 @@
github.com/ebitengine/purego v0.9.1 h1:a/k2f2HQU3Pi399RPW1MOaZyhKJL9w/xFpKAg4q1s0A=
github.com/ebitengine/purego v0.9.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=

View file

@ -50,16 +50,20 @@ func Go(fn func()) {
// Call schedules a function to be run on the main operating system thread, blocking until it returns. // Call schedules a function to be run on the main operating system thread, blocking until it returns.
func Call(fn func()) { func Call(fn func()) {
done := make(chan any) if onmainthread() {
queue <- func() {
defer func() {
done <- nil
}()
fn() fn()
} } else {
done := make(chan any)
queue <- func() {
defer func() {
done <- nil
}()
<-done fn()
}
<-done
}
} }
var queue chan func() var queue chan func()

View file

@ -0,0 +1,7 @@
//go:build !(windows || unix || darwin)
package osthread
func onmainthread() bool {
return false
}

View file

@ -0,0 +1,33 @@
//go:build darwin
package osthread
import "github.com/ebitengine/purego/objc"
func onmainthread() bool {
return objc.Send[bool](objc.ID(cls_nsthread), sel_isMainThread)
}
var (
cls_nsthread objc.Class
cls_nsapplication objc.Class
cls_nsapp objc.Class
sel_isMainThread objc.SEL
sel_sharedApplication objc.SEL
sel_run objc.SEL
)
func init() {
cls_nsthread = objc.GetClass("NSThread")
cls_nsapplication = objc.GetClass("NSApplication")
cls_nsapp = objc.GetClass("NSApp")
sel_isMainThread = objc.RegisterName("isMainThread")
sel_sharedApplication = objc.RegisterName("sharedApplication")
sel_run = objc.RegisterName("run")
// Just a bit of magic
objc.ID(cls_nsapplication).Send(sel_sharedApplication)
objc.ID(cls_nsapp).Send(sel_run)
}

View file

@ -0,0 +1,26 @@
//go:build linux
package osthread
import (
"github.com/ebitengine/purego"
)
func onmainthread() bool {
return getpid() == gettid()
}
var (
getpid func() int32
gettid func() int32
)
func init() {
libc, err := purego.Dlopen("libc.so.6", purego.RTLD_GLOBAL|purego.RTLD_NOW)
if err != nil {
panic(err)
}
purego.RegisterLibFunc(&getpid, libc, "getpid")
purego.RegisterLibFunc(&gettid, libc, "gettid")
}

View file

@ -0,0 +1,24 @@
//go:build windows
package osthread
import (
"syscall"
"github.com/ebitengine/purego"
)
func onmainthread() bool {
return mainThreadId == getCurrentThreadId()
}
var (
mainThreadId int32
getCurrentThreadId func() int32
)
func init() {
kernel32 := syscall.NewLazyDLL("kernel.dll").Handle()
purego.RegisterLibFunc(&getCurrentThreadId, kernel32, "GetCurrentThreadId")
mainThreadId = getCurrentThreadId()
}