Skip to content

progrium/darwinkit

Repository files navigation

DarwinKit Logo

Native Apple APIs for Golang!

GoDoc Go Report Card @progrium on Twitter Project Forum Sponsor Project

Important

July 11, 2024:MacDriver is now DarwinKit!You can also now get high-quality example starter apps when yousupport the project as a sponsor.


ScanDrop Demo SnowScape Demo MenuSpacer Demo ClipTrail Demo

DarwinKit lets you work withsupported Apple frameworksand build native applications using Go. With XCode and Go 1.18+ installed, you can write this program in amain.gofile:

packagemain

import(
"github /progrium/darwinkit/objc"
"github /progrium/darwinkit/macos"
"github /progrium/darwinkit/macos/appkit"
"github /progrium/darwinkit/macos/foundation"
"github /progrium/darwinkit/macos/webkit"
)

funcmain() {
// runs macOS application event loop with a callback on success
macos.RunApp(func(appappkit.Application,delegate*appkit.ApplicationDelegate) {
app.SetActivationPolicy(appkit.ApplicationActivationPolicyRegular)
app.ActivateIgnoringOtherApps(true)

url:=foundation.URL_URLWithString("https://github /sponsors/darwinkitdev")
req:=foundation.NewURLRequestWithURL(url)
frame:=foundation.Rect{Size:foundation.Size{1440,900}}

config:=webkit.NewWebViewConfiguration()
wv:=webkit.NewWebViewWithFrameConfiguration(frame,config)
wv.LoadRequest(req)

w:=appkit.NewWindowWithContentRectStyleMaskBackingDefer(frame,
appkit.ClosableWindowMask|appkit.TitledWindowMask,
appkit.BackingStoreBuffered,false)
objc.Retain(&w)
w.SetContentView(wv)
w.MakeKeyAndOrderFront(w)
w.Center()

delegate.SetApplicationShouldTerminateAfterLastWindowClosed(func(appkit.Application)bool{
returntrue
})
})
}

Then in this directory run:

go mod init helloworld
go get github /progrium/darwinkit@main
go run main.go

This may take a moment the first time, but once the window pops up you just made a macOS program without using XCode or Objective-C. Rungo buildto get an executable.

Although currently outside the scope of this project, if you wanted you could put this executableinto an Application bundle.You could even addentitlements,thensign and notarizethis bundle or executable to let others run it. It could theoretically even be put on the App Store. It couldtheoreticallybe put on an iOS, tvOS, or watchOS device, though you would have to use different platform specific frameworks.

Caveats

  • You still need to know or learn how Apple frameworks work, so you'll have to use Apple documentation and understand how to translate Objective-C example code to the equivalent Go with DarwinKit.
  • Your programs link against the actual Apple frameworks usingcgo,so XCode needs to be installed for the framework headers.
  • You will be using two memory management systems. Framework objects are managed byObjective-C memory management,so be sure to read our docs onmemory managementwith DarwinKit.
  • Exceptions in frameworks will segfault, giving you both an Objective-C stacktrace and a Go panic stacktrace. You will be debugging a hybrid Go and Objective-C program.
  • Goroutines that interact with GUI objects need todispatchoperations on the main thread otherwise it will segfault.

This is all tenable for simple programs, but these are the reasons we don'trecommendlarge/complex programs using DarwinKit.

Examples

There are basic usage exampleshere in this repo,but there are higher-quality full utilities you can use as examples or starter templateswhen you sponsor.

LargeType Demo ScanDrop Demo SnowScape Demo LiveTemp Demo MenuSpacer Demo ClipTrail Demo FocusTimer Demo

How it works

Brief background on Objective-C

Ever since acquiring NeXT Computer in the 90s, Apple has usedNeXTSTEPas the basis of their software stack, which is written in Objective-C. Unlike most systems languages with object orientation, Objective-C implements OOP as a runtime library. In fact, Objective-C is just C with the weird OOP specific syntax rewritten into C calls tolibobjc,which is a normal C library implementing an object runtime. This runtime could be used to bring OOP to any language that can make calls to C code. It also lets you interact with objects and classes registered by other libraries, such as the Apple frameworks.

At the heart of DarwinKit is a package wrapping the Objective-C runtime usingcgoandlibffi.This is actually all you need to interact with Objective-C objects and classes, it'll just look like this:

app:=objc.Call[objc.Object](objc.GetClass("NSApplication"),objc.Sel("sharedApplication"))
objc.Call[objc.Void](app,objc.Sel("run"))

So we wrap these calls in aGo APIthat lets us write code like this:

app:=appkit.Application_SharedApplication()
app.Run()

These bindings are great, but we need to define them for every API we want to use. Presently, Apple has around 200 frameworks of nearly 5000 classes with 77k combined methods and properties. Not to mention all the constants, functions, structs, unions, and enums we need to work with those objects.

So DarwinKit generates its bindings. This is the hard part. Making sure the generation pipeline accurately produces usable bindings for all possible symbols is quite an arduous, iterative, manual process. Then since we're moving symbols that lived in a single namespace into Go packages, we have to manually decouple dependencies between them enough to avoid circular imports. If you want to help add frameworks, read our documentation ongeneration.

Objects are passed around as typed pointer values in Objective-C. When we receive an object from a method call in Go, theobjcpackage receives it as a raw pointer, which it first puts into anunsafe.Pointer.The bindings for a class define a struct type that embeds anobjc.Objectstruct, which contains a single field to hold theunsafe.Pointer.So unless working with a primitive type, you're working with anunsafe.Pointerwrapped in anobjc.Objectwrapped in a struct type that has the methods for the class of the object of the pointer. Be sure to read our documentation onmemory management.

If you have questions, feel free to ask in thediscussion forums.

Thanks

This project was inspired by and originally based on packages written byMikkel Krautz.The latest version is based on packages written byDong Liu.

Notice

This project is not affiliated or supported by Apple.

License

MIT