-
-
Notifications
You must be signed in to change notification settings - Fork 160
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add helper package to easier use of Cocoa API with Go (#163)
- Loading branch information
1 parent
dbfe5af
commit 4ae7826
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | ||
} |