Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add helper package to easier use of Cocoa API with Go #163

Merged
merged 1 commit into from
Aug 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions helper/helper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package helper

import "runtime"
import "reflect"
import "strings"
import "fmt"
import "github.com/progrium/macdriver/objc"
import "github.com/progrium/macdriver/cocoa"


// Adds the ActionHelper class to the objective-c system
func init() {
newClass := objc.NewClass("ActionHelper", "NSObject")
objc.RegisterClass(newClass)
}


// Creates a unique method name using a control and a Go function
func createActionName(control interface{}, callback func(sender interface{})) string {
actionName := runtime.FuncForPC(reflect.ValueOf(callback).Pointer()).Name()
actionName = fmt.Sprintf("%s%s", actionName, control)

// remove any characters that should not be in a method's name
actionName = strings.ReplaceAll(actionName, " ", "") // remove space
actionName = strings.ReplaceAll(actionName, ":", "") // remove middle colon
actionName = strings.ReplaceAll(actionName, "<", "") // remove <
actionName = strings.ReplaceAll(actionName, ">", "") // remove >
actionName = actionName + ":" // add colon at end
return actionName
}


// Sets a control's action and target for use with a Go function
// Input 1: control - NSControl subclass
// Input 2: callback - a Go function that has one argument of interface{}
func SetAction(control cocoa.NSControlRef, callback func(sender interface{})) {
actionClass := objc.Get("ActionHelper")
actionName := createActionName(control, callback)
actionClass.AddMethod(actionName, func(sender objc.Object){
callback(control)
})
theControl := cocoa.NSControl_FromRef(control)
actionObj := actionClass.Alloc()
theControl.SetTarget(actionObj)
theControl.SetAction(objc.Sel(actionName))
}
Loading