From 33155f7496a818a1ed83fe49cccb63be7842bc81 Mon Sep 17 00:00:00 2001 From: Pietro Gagliardi Date: Mon, 30 Jun 2014 09:57:44 -0400 Subject: [PATCH] Reverted everything back to the old API. --- area.go | 11 + button.go | 24 +- callbacks_unix.go | 7 +- checkbox.go | 20 ++ combobox.go | 23 ++ controlsize_windows.go | 1 + delegate_darwin.go | 16 +- delegateuitask_darwin.m | 23 +- dialog.go | 22 +- dialog_darwin.go | 56 ++-- dialog_darwin.m | 21 +- dialog_unix.go | 89 ++++-- dialog_windows.go | 54 ++-- grid.go | 11 + init.go | 61 ++-- label.go | 14 + lineedit.go | 14 + listbox.go | 23 ++ objc_darwin.h | 4 +- progressbar.go | 11 + stack.go | 8 + stdwndclass_windows.go | 8 +- sysdata.go | 26 +- sysdata_darwin.go | 152 +++++++-- sysdata_unix.go | 238 ++++++++++---- sysdata_windows.go | 598 ++++++++++++++++++++++-------------- test/kbtest.go | 12 +- test/main.go | 361 +++++++++------------- test/spacing.go | 5 +- uitask_darwin.go | 30 +- uitask_unix.go | 30 +- uitask_windows.go | 53 ++-- window.go | 108 +++---- zconstants_windows_386.go | 1 - zconstants_windows_amd64.go | 1 - 35 files changed, 1287 insertions(+), 849 deletions(-) diff --git a/area.go b/area.go index 1ff86ef..0871eef 100644 --- a/area.go +++ b/area.go @@ -6,6 +6,7 @@ import ( "fmt" "image" "reflect" + "sync" "unsafe" ) @@ -27,6 +28,7 @@ import ( // to lead to trouble. // [FOR FUTURE PLANNING Use TextArea instead, providing a TextAreaHandler.] type Area struct { + lock sync.Mutex created bool sysData *sysData handler AreaHandler @@ -296,6 +298,9 @@ func NewArea(width int, height int, handler AreaHandler) *Area { // SetSize will also signal the entirety of the Area to be redrawn as in RepaintAll. // It panics if width or height is zero or negative. func (a *Area) SetSize(width int, height int) { + a.lock.Lock() + defer a.lock.Unlock() + checkAreaSize(width, height, "Area.SetSize()") if a.created { a.sysData.setAreaSize(width, height) @@ -308,6 +313,9 @@ func (a *Area) SetSize(width int, height int) { // RepaintAll signals the entirety of the Area for redraw. // If called before the Window containing the Area is created, RepaintAll does nothing. func (a *Area) RepaintAll() { + a.lock.Lock() + defer a.lock.Unlock() + if !a.created { return } @@ -315,6 +323,9 @@ func (a *Area) RepaintAll() { } func (a *Area) make(window *sysData) error { + a.lock.Lock() + defer a.lock.Unlock() + a.sysData.handler = a.handler err := a.sysData.make(window) if err != nil { diff --git a/button.go b/button.go index c4143aa..96a68ed 100644 --- a/button.go +++ b/button.go @@ -2,8 +2,18 @@ package ui +import ( + "sync" +) + // A Button represents a clickable button with some text. type Button struct { + // Clicked gets a message when the button is clicked. + // You cannot change it once the Window containing the Button has been created. + // If you do not respond to this signal, nothing will happen. + Clicked chan struct{} + + lock sync.Mutex created bool sysData *sysData initText string @@ -14,11 +24,15 @@ func NewButton(text string) (b *Button) { return &Button{ sysData: mksysdata(c_button), initText: text, + Clicked: newEvent(), } } // SetText sets the button's text. func (b *Button) SetText(text string) { + b.lock.Lock() + defer b.lock.Unlock() + if b.created { b.sysData.setText(text) return @@ -28,6 +42,9 @@ func (b *Button) SetText(text string) { // Text returns the button's text. func (b *Button) Text() string { + b.lock.Lock() + defer b.lock.Unlock() + if b.created { return b.sysData.text() } @@ -35,9 +52,10 @@ func (b *Button) Text() string { } func (b *Button) make(window *sysData) error { - b.sysData.event = func() { - window.winhandler.Event(Clicked, b) - } + b.lock.Lock() + defer b.lock.Unlock() + + b.sysData.event = b.Clicked err := b.sysData.make(window) if err != nil { return err diff --git a/callbacks_unix.go b/callbacks_unix.go index 717150c..ff3e3b9 100644 --- a/callbacks_unix.go +++ b/callbacks_unix.go @@ -27,9 +27,8 @@ import "C" func our_window_delete_event_callback(widget *C.GtkWidget, event *C.GdkEvent, what C.gpointer) C.gboolean { // called when the user tries to close the window s := (*sysData)(unsafe.Pointer(what)) - b := false // TODO - s.close(&b) - return togbool(!b) // ! because TRUE means don't close + s.signal() + return C.TRUE // do not close the window } var window_delete_event_callback = C.GCallback(C.our_window_delete_event_callback) @@ -53,7 +52,7 @@ var window_configure_event_callback = C.GCallback(C.our_window_configure_event_c func our_button_clicked_callback(button *C.GtkButton, what C.gpointer) { // called when the user clicks a button s := (*sysData)(unsafe.Pointer(what)) - s.event() + s.signal() } var button_clicked_callback = C.GCallback(C.our_button_clicked_callback) diff --git a/checkbox.go b/checkbox.go index 1293dfc..934da90 100644 --- a/checkbox.go +++ b/checkbox.go @@ -2,8 +2,13 @@ package ui +import ( + "sync" +) + // A Checkbox is a clickable square with a label. The square can be either checked or unchecked. Checkboxes start out unchecked. type Checkbox struct { + lock sync.Mutex created bool sysData *sysData initText string @@ -20,6 +25,9 @@ func NewCheckbox(text string) (c *Checkbox) { // SetText sets the checkbox's text. func (c *Checkbox) SetText(text string) { + c.lock.Lock() + defer c.lock.Unlock() + if c.created { c.sysData.setText(text) return @@ -29,6 +37,9 @@ func (c *Checkbox) SetText(text string) { // Text returns the checkbox's text. func (c *Checkbox) Text() string { + c.lock.Lock() + defer c.lock.Unlock() + if c.created { return c.sysData.text() } @@ -37,6 +48,9 @@ func (c *Checkbox) Text() string { // SetChecked() changes the checked state of the Checkbox. func (c *Checkbox) SetChecked(checked bool) { + c.lock.Lock() + defer c.lock.Unlock() + if c.created { c.sysData.setChecked(checked) return @@ -46,6 +60,9 @@ func (c *Checkbox) SetChecked(checked bool) { // Checked() returns whether or not the Checkbox has been checked. func (c *Checkbox) Checked() bool { + c.lock.Lock() + defer c.lock.Unlock() + if c.created { return c.sysData.isChecked() } @@ -53,6 +70,9 @@ func (c *Checkbox) Checked() bool { } func (c *Checkbox) make(window *sysData) error { + c.lock.Lock() + defer c.lock.Unlock() + err := c.sysData.make(window) if err != nil { return err diff --git a/combobox.go b/combobox.go index e1f49af..83024ed 100644 --- a/combobox.go +++ b/combobox.go @@ -4,10 +4,12 @@ package ui import ( "fmt" + "sync" ) // A Combobox is a drop-down list of items, of which at most one can be selected at any given time. You may optionally make the combobox editable to allow custom items. Initially, no item will be selected (and no text entered in an editable Combobox's entry field). What happens to the text shown in a Combobox if its width is too small is implementation-defined. type Combobox struct { + lock sync.Mutex created bool sysData *sysData initItems []string @@ -35,6 +37,9 @@ func NewEditableCombobox(items ...string) *Combobox { // Append adds items to the end of the Combobox's list. // Append will panic if something goes wrong on platforms that do not abort themselves. func (c *Combobox) Append(what ...string) { + c.lock.Lock() + defer c.lock.Unlock() + if c.created { for _, s := range what { c.sysData.append(s) @@ -47,6 +52,9 @@ func (c *Combobox) Append(what ...string) { // InsertBefore inserts a new item in the Combobox before the item at the given position. It panics if the given index is out of bounds. // InsertBefore will also panic if something goes wrong on platforms that do not abort themselves. func (c *Combobox) InsertBefore(what string, before int) { + c.lock.Lock() + defer c.lock.Unlock() + var m []string if c.created { @@ -70,6 +78,9 @@ badrange: // Delete removes the given item from the Combobox. It panics if the given index is out of bounds. func (c *Combobox) Delete(index int) { + c.lock.Lock() + defer c.lock.Unlock() + if c.created { if index < 0 || index >= c.sysData.len() { goto badrange @@ -88,6 +99,9 @@ badrange: // Selection returns the current selection. func (c *Combobox) Selection() string { + c.lock.Lock() + defer c.lock.Unlock() + if c.created { return c.sysData.text() } @@ -96,6 +110,9 @@ func (c *Combobox) Selection() string { // SelectedIndex returns the index of the current selection in the Combobox. It returns -1 either if no selection was made or if text was manually entered in an editable Combobox. func (c *Combobox) SelectedIndex() int { + c.lock.Lock() + defer c.lock.Unlock() + if c.created { return c.sysData.selectedIndex() } @@ -106,6 +123,9 @@ func (c *Combobox) SelectedIndex() int { // // On platforms for which this function may return an error, it panics if one is returned. func (c *Combobox) Len() int { + c.lock.Lock() + defer c.lock.Unlock() + if c.created { return c.sysData.len() } @@ -113,6 +133,9 @@ func (c *Combobox) Len() int { } func (c *Combobox) make(window *sysData) (err error) { + c.lock.Lock() + defer c.lock.Unlock() + err = c.sysData.make(window) if err != nil { return err diff --git a/controlsize_windows.go b/controlsize_windows.go index 0afd209..d43599c 100644 --- a/controlsize_windows.go +++ b/controlsize_windows.go @@ -175,6 +175,7 @@ func releaseTextDC(hwnd _HWND, dc _HANDLE) { } } +// This function runs on uitask; call the functions directly. func (s *sysData) preferredSize(d *sysSizeData) (width int, height int) { // the preferred size of an Area is its size if stdDlgSizes[s.ctype].area { diff --git a/delegate_darwin.go b/delegate_darwin.go index 27031c3..7d21c3d 100644 --- a/delegate_darwin.go +++ b/delegate_darwin.go @@ -24,11 +24,9 @@ func makeAppDelegate() { } //export appDelegate_windowShouldClose -func appDelegate_windowShouldClose(win C.id) C.BOOL { +func appDelegate_windowShouldClose(win C.id) { sysData := getSysData(win) - b := false // TODO - sysData.close(&b) - return toBOOL(b) + sysData.signal() } //export appDelegate_windowDidResize @@ -44,5 +42,13 @@ func appDelegate_windowDidResize(win C.id) { //export appDelegate_buttonClicked func appDelegate_buttonClicked(button C.id) { sysData := getSysData(button) - sysData.event() + sysData.signal() +} + +//export appDelegate_applicationShouldTerminate +func appDelegate_applicationShouldTerminate() { + // asynchronous so as to return control to the event loop + go func() { + AppQuit <- struct{}{} + }() } diff --git a/delegateuitask_darwin.m b/delegateuitask_darwin.m index e30ebc2..ed912eb 100644 --- a/delegateuitask_darwin.m +++ b/delegateuitask_darwin.m @@ -63,7 +63,8 @@ extern NSRect dummyRect; - (BOOL)windowShouldClose:(id)win { - return appDelegate_windowShouldClose(win); + appDelegate_windowShouldClose(win); + return NO; // don't close } - (void)windowDidResize:(NSNotification *)n @@ -78,25 +79,13 @@ extern NSRect dummyRect; - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)app { - NSArray *windows; - NSUInteger i; - - // try to close all windows - windows = [NSApp windows]; - for (i = 0; i < [windows count]; i++) - [[windows objectAtIndex:i] performClose:self]; - // if any windows are left, cancel - if ([[NSApp windows] count] != 0) - return NSTerminateCancel; - // no windows are left; we're good - return NSTerminateNow; + appDelegate_applicationShouldTerminate(); + return NSTerminateCancel; } -- (void)alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)data +- (void)alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)chan { - NSInteger *ret = (NSInteger *) data; - - *ret = returnCode; + dialog_send(chan, (uintptr_t) returnCode); } @end diff --git a/dialog.go b/dialog.go index 6c62bfd..9c2ad2c 100644 --- a/dialog.go +++ b/dialog.go @@ -2,16 +2,8 @@ package ui -// Response denotes a response from the user to a Dialog. -type Response uint -const ( - NotDone Response = iota - OK -) - // sentinel (not nil so programmer errors don't go undetected) // this window is invalid and cannot be used directly -// notice the support it uses var dialogWindow = new(Window) // MsgBox displays an informational message box to the user with just an OK button. @@ -22,16 +14,16 @@ var dialogWindow = new(Window) // // See "On Dialogs" in the package overview for behavioral information. func MsgBox(primaryText string, secondaryText string) { - dialogWindow.msgBox(primaryText, secondaryText) + <-dialogWindow.msgBox(primaryText, secondaryText) } // MsgBox is the Window method version of the package-scope function MsgBox. // See that function's documentation and "On Dialogs" in the package overview for more information. -func (w *Window) MsgBox(primaryText string, secondaryText string) { +func (w *Window) MsgBox(primaryText string, secondaryText string) (done chan struct{}) { if !w.created { panic("parent window passed to Window.MsgBox() before it was created") } - w.msgBox(primaryText, secondaryText) + return w.msgBox(primaryText, secondaryText) } // MsgBoxError displays a message box to the user with just an OK button and an icon indicating an error. @@ -39,14 +31,14 @@ func (w *Window) MsgBox(primaryText string, secondaryText string) { // // See "On Dialogs" in the package overview for more information. func MsgBoxError(primaryText string, secondaryText string) { - dialogWindow.msgBoxError(primaryText, secondaryText) + <-dialogWindow.msgBoxError(primaryText, secondaryText) } // MsgBoxError is the Window method version of the package-scope function MsgBoxError. // See that function's documentation and "On Dialogs" in the package overview for more information. -func (w *Window) MsgBoxError(primaryText string, secondaryText string) { +func (w *Window) MsgBoxError(primaryText string, secondaryText string) (done chan struct{}) { if !w.created { - panic("parent window passed to Window.MsgBox() before it was created") + panic("parent window passed to MsgBoxError() before it was created") } - w.msgBoxError(primaryText, secondaryText) + return w.msgBoxError(primaryText, secondaryText) } diff --git a/dialog_darwin.go b/dialog_darwin.go index 421e838..038c640 100644 --- a/dialog_darwin.go +++ b/dialog_darwin.go @@ -3,7 +3,6 @@ package ui import ( - "fmt" "unsafe" ) @@ -18,32 +17,43 @@ func dialog_send(pchan unsafe.Pointer, res C.intptr_t) { }() } -func _msgBox(parent *Window, primarytext string, secondarytext string, style uintptr) Response { - var pwin C.id = nil +func _msgBox(parent *Window, primarytext string, secondarytext string, style uintptr) chan int { + ret := make(chan int) + uitask <- func() { + var pwin C.id = nil - if parent != dialogWindow { - pwin = parent.sysData.id + if parent != dialogWindow { + pwin = parent.sysData.id + } + primary := toNSString(primarytext) + secondary := C.id(nil) + if secondarytext != "" { + secondary = toNSString(secondarytext) + } + switch style { + case 0: // normal + C.msgBox(pwin, primary, secondary, unsafe.Pointer(&ret)) + case 1: // error + C.msgBoxError(pwin, primary, secondary, unsafe.Pointer(&ret)) + } } - primary := toNSString(primarytext) - secondary := C.id(nil) - if secondarytext != "" { - secondary = toNSString(secondarytext) - } - switch style { - case 0: // normal - C.msgBox(pwin, primary, secondary) - return OK - case 1: // error - C.msgBoxError(pwin, primary, secondary) - return OK - } - panic(fmt.Errorf("unknown message box style %d\n", style)) + return ret } -func (w *Window) msgBox(primarytext string, secondarytext string) { - _msgBox(w, primarytext, secondarytext, 0) +func (w *Window) msgBox(primarytext string, secondarytext string) (done chan struct{}) { + done = make(chan struct{}) + go func() { + <-_msgBox(w, primarytext, secondarytext, 0) + done <- struct{}{} + }() + return done } -func (w *Window) msgBoxError(primarytext string, secondarytext string) { - _msgBox(w, primarytext, secondarytext, 1) +func (w *Window) msgBoxError(primarytext string, secondarytext string) (done chan struct{}) { + done = make(chan struct{}) + go func() { + <-_msgBox(w, primarytext, secondarytext, 1) + done <- struct{}{} + }() + return done } diff --git a/dialog_darwin.m b/dialog_darwin.m index 226ad4b..d38e7af 100644 --- a/dialog_darwin.m +++ b/dialog_darwin.m @@ -9,7 +9,7 @@ #define to(T, x) ((T *) (x)) #define toNSWindow(x) to(NSWindow, (x)) -static intptr_t alert(id parent, NSString *primary, NSString *secondary, NSAlertStyle style) +static void alert(id parent, NSString *primary, NSString *secondary, NSAlertStyle style, void *chan) { NSAlert *box; @@ -21,25 +21,20 @@ static intptr_t alert(id parent, NSString *primary, NSString *secondary, NSAlert // TODO is there a named constant? will also need to be changed when we add different dialog types [box addButtonWithTitle:@"OK"]; if (parent == nil) - return (intptr_t) [box runModal]; - else { - NSInteger ret; - + dialog_send(chan, (intptr_t) [box runModal]); + else [box beginSheetModalForWindow:toNSWindow(parent) modalDelegate:[NSApp delegate] didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) - contextInfo:&ret]; - // TODO - return (intptr_t) ret; - } + contextInfo:chan]; } -void msgBox(id parent, id primary, id secondary) +void msgBox(id parent, id primary, id secondary, void *chan) { - alert(parent, (NSString *) primary, (NSString *) secondary, NSInformationalAlertStyle); + alert(parent, (NSString *) primary, (NSString *) secondary, NSInformationalAlertStyle, chan); } -void msgBoxError(id parent, id primary, id secondary) +void msgBoxError(id parent, id primary, id secondary, void *chan) { - alert(parent, (NSString *) primary, (NSString *) secondary, NSCriticalAlertStyle); + alert(parent, (NSString *) primary, (NSString *) secondary, NSCriticalAlertStyle, chan); } diff --git a/dialog_unix.go b/dialog_unix.go index 9728e2a..f22f1c6 100644 --- a/dialog_unix.go +++ b/dialog_unix.go @@ -9,6 +9,7 @@ import ( ) // #include "gtk_unix.h" +// extern void our_dialog_response_callback(GtkDialog *, gint, gpointer); // /* because cgo seems to choke on ... */ // /* parent will be NULL if there is no parent, so this is fine */ // static inline GtkWidget *gtkNewMsgBox(GtkWindow *parent, GtkMessageType type, GtkButtonsType buttons, char *title, char *text) @@ -22,11 +23,6 @@ import ( // } import "C" -// the actual type of these constants is GtkResponseType but gtk_dialog_run() returns a gint -var dialogResponses = map[C.gint]Response{ - C.GTK_RESPONSE_OK: OK, -} - // dialog performs the bookkeeping involved for having a GtkDialog behave the way we want. type dialog struct { parent *Window @@ -34,12 +30,13 @@ type dialog struct { hadgroup C.gboolean prevgroup *C.GtkWindowGroup newgroup *C.GtkWindowGroup - result Response + result chan int } func mkdialog(parent *Window) *dialog { return &dialog{ parent: parent, + result: make(chan int), } } @@ -62,6 +59,36 @@ func (d *dialog) prepare() { } } +func (d *dialog) run(mk func() *C.GtkWidget) { + d.prepare() + box := mk() + if d.parent == dialogWindow { + go func() { + res := make(chan C.gint) + defer close(res) + uitask <- func() { + r := C.gtk_dialog_run((*C.GtkDialog)(unsafe.Pointer(box))) + d.cleanup(box) + res <- r + } + d.send(<-res) + }() + return + } + // otherwise just connect the delete signal + g_signal_connect_pointer(box, "response", dialog_response_callback, unsafe.Pointer(d)) + C.gtk_widget_show_all(box) +} + +//export our_dialog_response_callback +func our_dialog_response_callback(box *C.GtkDialog, res C.gint, data C.gpointer) { + d := (*dialog)(unsafe.Pointer(data)) + d.cleanup((*C.GtkWidget)(unsafe.Pointer(box))) + go d.send(res) // send on another goroutine, like everything else +} + +var dialog_response_callback = C.GCallback(C.our_dialog_response_callback) + func (d *dialog) cleanup(box *C.GtkWidget) { // have to explicitly close the dialog box, otherwise wacky things will happen C.gtk_widget_destroy(box) @@ -74,33 +101,43 @@ func (d *dialog) cleanup(box *C.GtkWidget) { } } -func (d *dialog) run(mk func() *C.GtkWidget) { - d.prepare() - box := mk() - r := C.gtk_dialog_run((*C.GtkDialog)(unsafe.Pointer(box))) - d.cleanup(box) - d.result = dialogResponses[r] +func (d *dialog) send(res C.gint) { + // this is where processing would go + d.result <- int(res) } -func _msgBox(parent *Window, primarytext string, secondarytext string, msgtype C.GtkMessageType, buttons C.GtkButtonsType) (response Response) { +func _msgBox(parent *Window, primarytext string, secondarytext string, msgtype C.GtkMessageType, buttons C.GtkButtonsType) (result chan int) { + result = make(chan int) d := mkdialog(parent) - cprimarytext := C.CString(primarytext) - defer C.free(unsafe.Pointer(cprimarytext)) - csecondarytext := (*C.char)(nil) - if secondarytext != "" { - csecondarytext = C.CString(secondarytext) - defer C.free(unsafe.Pointer(csecondarytext)) + uitask <- func() { + cprimarytext := C.CString(primarytext) + defer C.free(unsafe.Pointer(cprimarytext)) + csecondarytext := (*C.char)(nil) + if secondarytext != "" { + csecondarytext = C.CString(secondarytext) + defer C.free(unsafe.Pointer(csecondarytext)) + } + d.run(func() *C.GtkWidget { + return C.gtkNewMsgBox(d.pwin, msgtype, buttons, cprimarytext, csecondarytext) + }) } - d.run(func() *C.GtkWidget { - return C.gtkNewMsgBox(d.pwin, msgtype, buttons, cprimarytext, csecondarytext) - }) return d.result } -func (w *Window) msgBox(primarytext string, secondarytext string) { - _msgBox(w, primarytext, secondarytext, C.GtkMessageType(C.GTK_MESSAGE_OTHER), C.GtkButtonsType(C.GTK_BUTTONS_OK)) +func (w *Window) msgBox(primarytext string, secondarytext string) (done chan struct{}) { + done = make(chan struct{}) + go func() { + <-_msgBox(w, primarytext, secondarytext, C.GtkMessageType(C.GTK_MESSAGE_OTHER), C.GtkButtonsType(C.GTK_BUTTONS_OK)) + done <- struct{}{} + }() + return done } -func (w *Window) msgBoxError(primarytext string, secondarytext string) { - _msgBox(w, primarytext, secondarytext, C.GtkMessageType(C.GTK_MESSAGE_ERROR), C.GtkButtonsType(C.GTK_BUTTONS_OK)) +func (w *Window) msgBoxError(primarytext string, secondarytext string) (done chan struct{}) { + done = make(chan struct{}) + go func() { + <-_msgBox(w, primarytext, secondarytext, C.GtkMessageType(C.GTK_MESSAGE_ERROR), C.GtkButtonsType(C.GTK_BUTTONS_OK)) + done <- struct{}{} + }() + return done } diff --git a/dialog_windows.go b/dialog_windows.go index 5095999..c6da94b 100644 --- a/dialog_windows.go +++ b/dialog_windows.go @@ -11,11 +11,7 @@ var ( _messageBox = user32.NewProc("MessageBoxW") ) -var dialogResponses = map[uintptr]Response{ - _IDOK: OK, -} - -func _msgBox(parent *Window, primarytext string, secondarytext string, uType uint32) Response { +func _msgBox(parent *Window, primarytext string, secondarytext string, uType uint32) (result chan int) { // http://msdn.microsoft.com/en-us/library/windows/desktop/aa511267.aspx says "Use task dialogs whenever appropriate to achieve a consistent look and layout. Task dialogs require Windows Vista® or later, so they aren't suitable for earlier versions of Windows. If you must use a message box, separate the main instruction from the supplemental instruction with two line breaks." text := primarytext if secondarytext != "" { @@ -30,21 +26,43 @@ func _msgBox(parent *Window, primarytext string, secondarytext string, uType uin } else { uType |= _MB_TASKMODAL // make modal to every window in the program (they're all windows of the uitask, which is a single thread) } - r1, _, err := _messageBox.Call( - uintptr(parenthwnd), - utf16ToArg(ptext), - utf16ToArg(ptitle), - uintptr(uType)) - if r1 == 0 { // failure - panic(fmt.Sprintf("error displaying message box to user: %v\nstyle: 0x%08X\ntitle: %q\ntext:\n%s", err, uType, os.Args[0], text)) - } - return dialogResponses[r1] + retchan := make(chan int) + go func() { + ret := make(chan uiret) + defer close(ret) + uitask <- &uimsg{ + call: _messageBox, + p: []uintptr{ + uintptr(parenthwnd), + utf16ToArg(ptext), + utf16ToArg(ptitle), + uintptr(uType), + }, + ret: ret, + } + r := <-ret + if r.ret == 0 { // failure + panic(fmt.Sprintf("error displaying message box to user: %v\nstyle: 0x%08X\ntitle: %q\ntext:\n%s", r.err, uType, os.Args[0], text)) + } + retchan <- int(r.ret) + }() + return retchan } -func (w *Window) msgBox(primarytext string, secondarytext string) { - _msgBox(w, primarytext, secondarytext, _MB_OK) +func (w *Window) msgBox(primarytext string, secondarytext string) (done chan struct{}) { + done = make(chan struct{}) + go func() { + <-_msgBox(w, primarytext, secondarytext, _MB_OK) + done <- struct{}{} + }() + return done } -func (w *Window) msgBoxError(primarytext string, secondarytext string) { - _msgBox(w, primarytext, secondarytext, _MB_OK|_MB_ICONERROR) +func (w *Window) msgBoxError(primarytext string, secondarytext string) (done chan struct{}) { + done = make(chan struct{}) + go func() { + <-_msgBox(w, primarytext, secondarytext, _MB_OK|_MB_ICONERROR) + done <- struct{}{} + }() + return done } diff --git a/grid.go b/grid.go index bc58a00..b1c2a52 100644 --- a/grid.go +++ b/grid.go @@ -4,6 +4,7 @@ package ui import ( "fmt" + "sync" ) // A Grid arranges Controls in a two-dimensional grid. @@ -15,6 +16,7 @@ import ( // A stretchy Control implicitly fills its cell. // All cooridnates in a Grid are given in (row,column) form with (0,0) being the top-left cell. type Grid struct { + lock sync.Mutex created bool controls [][]Control filling [][]bool @@ -67,6 +69,9 @@ func NewGrid(nPerRow int, controls ...Control) *Grid { // This function cannot be called after the Window that contains the Grid has been created. // It panics if the given coordinate is invalid. func (g *Grid) SetFilling(row int, column int) { + g.lock.Lock() + defer g.lock.Unlock() + if g.created { panic(fmt.Errorf("Grid.SetFilling() called after window create")) } @@ -82,6 +87,9 @@ func (g *Grid) SetFilling(row int, column int) { // This function cannot be called after the Window that contains the Grid has been created. // It panics if the given coordinate is invalid. func (g *Grid) SetStretchy(row int, column int) { + g.lock.Lock() + defer g.lock.Unlock() + if g.created { panic(fmt.Errorf("Grid.SetFilling() called after window create")) } @@ -94,6 +102,9 @@ func (g *Grid) SetStretchy(row int, column int) { } func (g *Grid) make(window *sysData) error { + g.lock.Lock() + defer g.lock.Unlock() + // commit filling for the stretchy control now (see SetStretchy() above) if g.stretchyrow != -1 && g.stretchycol != -1 { g.filling[g.stretchyrow][g.stretchycol] = true diff --git a/init.go b/init.go index 72f24ef..2e59301 100644 --- a/init.go +++ b/init.go @@ -2,53 +2,28 @@ package ui -import ( - "runtime" -) - -// Go sets up the UI environment and pulses Ready. -// If initialization fails, Go returns an error and Ready is not pulsed. -// Otherwise, Go does not return to its caller until Stop is pulsed, at which point Go() will return nil. -// After Go() returns, you cannot call future ui functions/methods meaningfully. -// Pulsing Stop will cause Go() to return immediately; the programmer is responsible for cleaning up (for instance, hiding open Windows) beforehand. +// Go sets up the UI environment and runs main in a goroutine. +// If initialization fails, Go returns an error and main is not called. +// Otherwise, Go does not return to its caller until main does, at which point it returns nil. +// After it returns, you cannot call future ui functions/methods meaningfully. // -// It is not safe to call ui.Go() in a goroutine. It must be called directly from main(). This means if your code calls other code-modal servers (such as http.ListenAndServe()), they must be run from goroutines. (This is due to limitations in various OSs, such as Mac OS X.) +// It is not safe to call ui.Go() in a goroutine. It must be called directly from main(). // -// Go() does not process the command line for flags (that is, it does not call flag.Parse()), nor does package ui add any of the underlying toolkit's supported command-line flags. +// This model is undesirable, but Cocoa limitations require it. +// +// Go does not process the command line for flags (that is, it does not call flag.Parse()), nor does package ui add any of the underlying toolkit's supported command-line flags. // If you must, and if the toolkit also has environment variable equivalents to these flags (for instance, GTK+), use those instead. -func Go() error { - runtime.LockOSThread() - if err := uiinit(); err != nil { - return err - } - Ready <- struct{}{} - close(Ready) - ui() - return nil +func Go(main func()) error { + return ui(main) } -// Ready is pulsed when Go() is ready to begin accepting requests to the safe methods. -// Go() will wait for something to receive on Ready, then Ready will be closed. -var Ready = make(chan struct{}) +// AppQuit is pulsed when the user decides to quit the program if their operating system provides a facility for quitting an entire application, rather than merely close all windows (for instance, Mac OS X via the Dock icon). +// You should assign one of your Windows's Closing to this variable so the user choosing to quit the application is treated the same as closing that window. +// If you do not respond to this signal, nothing will happen; regardless of whether or not you respond to this signal, the application will not quit. +// Do not merely check this channel alone; it is not guaranteed to be pulsed on all systems or in all conditions. +var AppQuit chan struct{} -// Stop should be pulsed when you are ready for Go() to return. -// Pulsing Stop will cause Go() to return immediately; the programmer is responsible for cleaning up (for instance, hiding open Windows) beforehand. -// Do not pulse Stop more than once. -var Stop = make(chan struct{}) - -// This function is a simple helper functionn that basically pushes the effect of a function call for later. This allows the selected safe Window methods to be safe. -// TODO make sure this acts sanely if called from uitask itself -func touitask(f func()) { - done := make(chan struct{}) - defer close(done) - go func() { // to avoid locking uitask itself - done2 := make(chan struct{}) // make the chain uitask <- f <- uitask to avoid deadlocks - defer close(done2) - uitask <- func() { - f() - done2 <- struct{}{} - } - done <- <-done2 - }() - <-done +func init() { + // don't expose this in the documentation + AppQuit = newEvent() } diff --git a/label.go b/label.go index 31c61e2..ca17aca 100644 --- a/label.go +++ b/label.go @@ -2,11 +2,16 @@ package ui +import ( + "sync" +) + // A Label is a static line of text used to mark other controls. // Label text is drawn on a single line; text that does not fit is truncated. // A Label can appear in one of two places: bound to a control or standalone. // This determines the vertical alignment of the label. type Label struct { + lock sync.Mutex created bool sysData *sysData initText string @@ -34,6 +39,9 @@ func NewStandaloneLabel(text string) *Label { // SetText sets the Label's text. func (l *Label) SetText(text string) { + l.lock.Lock() + defer l.lock.Unlock() + if l.created { l.sysData.setText(text) return @@ -43,6 +51,9 @@ func (l *Label) SetText(text string) { // Text returns the Label's text. func (l *Label) Text() string { + l.lock.Lock() + defer l.lock.Unlock() + if l.created { return l.sysData.text() } @@ -50,6 +61,9 @@ func (l *Label) Text() string { } func (l *Label) make(window *sysData) error { + l.lock.Lock() + defer l.lock.Unlock() + l.sysData.alternate = l.standalone err := l.sysData.make(window) if err != nil { diff --git a/lineedit.go b/lineedit.go index 56ac97c..a45a443 100644 --- a/lineedit.go +++ b/lineedit.go @@ -2,8 +2,13 @@ package ui +import ( + "sync" +) + // A LineEdit is a control which allows you to enter a single line of text. type LineEdit struct { + lock sync.Mutex created bool sysData *sysData initText string @@ -28,6 +33,9 @@ func NewPasswordEdit() *LineEdit { // SetText sets the LineEdit's text. func (l *LineEdit) SetText(text string) { + l.lock.Lock() + defer l.lock.Unlock() + if l.created { l.sysData.setText(text) return @@ -37,6 +45,9 @@ func (l *LineEdit) SetText(text string) { // Text returns the LineEdit's text. func (l *LineEdit) Text() string { + l.lock.Lock() + defer l.lock.Unlock() + if l.created { return l.sysData.text() } @@ -44,6 +55,9 @@ func (l *LineEdit) Text() string { } func (l *LineEdit) make(window *sysData) error { + l.lock.Lock() + defer l.lock.Unlock() + l.sysData.alternate = l.password err := l.sysData.make(window) if err != nil { diff --git a/listbox.go b/listbox.go index 774f553..fc57142 100644 --- a/listbox.go +++ b/listbox.go @@ -4,6 +4,7 @@ package ui import ( "fmt" + "sync" ) // A Listbox is a vertical list of items, of which either at most one or any number of items can be selected at any given time. @@ -11,6 +12,7 @@ import ( // For information on scrollbars, see "Scrollbars" in the Overview. // Due to implementation issues, the presence of horizontal scrollbars is currently implementation-defined. type Listbox struct { + lock sync.Mutex created bool sysData *sysData initItems []string @@ -38,6 +40,9 @@ func NewMultiSelListbox(items ...string) *Listbox { // Append adds items to the end of the Listbox's list. // Append will panic if something goes wrong on platforms that do not abort themselves. func (l *Listbox) Append(what ...string) { + l.lock.Lock() + defer l.lock.Unlock() + if l.created { for _, s := range what { l.sysData.append(s) @@ -50,6 +55,9 @@ func (l *Listbox) Append(what ...string) { // InsertBefore inserts a new item in the Listbox before the item at the given position. It panics if the given index is out of bounds. // InsertBefore will also panic if something goes wrong on platforms that do not abort themselves. func (l *Listbox) InsertBefore(what string, before int) { + l.lock.Lock() + defer l.lock.Unlock() + var m []string if l.created { @@ -73,6 +81,9 @@ badrange: // Delete removes the given item from the Listbox. It panics if the given index is out of bounds. func (l *Listbox) Delete(index int) { + l.lock.Lock() + defer l.lock.Unlock() + if l.created { if index < 0 || index >= l.sysData.len() { goto badrange @@ -91,6 +102,9 @@ badrange: // Selection returns a list of strings currently selected in the Listbox, or an empty list if none have been selected. This list will have at most one item on a single-selection Listbox. func (l *Listbox) Selection() []string { + l.lock.Lock() + defer l.lock.Unlock() + if l.created { return l.sysData.selectedTexts() } @@ -99,6 +113,9 @@ func (l *Listbox) Selection() []string { // SelectedIndices returns a list of the currently selected indexes in the Listbox, or an empty list if none have been selected. This list will have at most one item on a single-selection Listbox. func (l *Listbox) SelectedIndices() []int { + l.lock.Lock() + defer l.lock.Unlock() + if l.created { return l.sysData.selectedIndices() } @@ -109,6 +126,9 @@ func (l *Listbox) SelectedIndices() []int { // // On platforms for which this function may return an error, it panics if one is returned. func (l *Listbox) Len() int { + l.lock.Lock() + defer l.lock.Unlock() + if l.created { return l.sysData.len() } @@ -116,6 +136,9 @@ func (l *Listbox) Len() int { } func (l *Listbox) make(window *sysData) (err error) { + l.lock.Lock() + defer l.lock.Unlock() + err = l.sysData.make(window) if err != nil { return err diff --git a/objc_darwin.h b/objc_darwin.h index 8174ec1..22bafb1 100644 --- a/objc_darwin.h +++ b/objc_darwin.h @@ -68,8 +68,8 @@ extern void breakMainLoop(void); extern void cocoaMainLoop(void); /* dialog_darwin.m */ -extern void msgBox(id, id, id); -extern void msgBoxError(id, id, id); +extern void msgBox(id, id, id, void *); +extern void msgBoxError(id, id, id, void *); /* listbox_darwin.m */ extern id toListboxItem(id, id); diff --git a/progressbar.go b/progressbar.go index 875a262..e7c7149 100644 --- a/progressbar.go +++ b/progressbar.go @@ -2,11 +2,16 @@ package ui +import ( + "sync" +) + // A ProgressBar is a horizontal rectangle that fills up from left to right to indicate the progress of a long-running task. // This progress is represented by an integer within the range [0,100], representing a percentage. // Alternatively, a progressbar can show an animation indicating that progress is being made but how much is indeterminate. // Newly-created ProgressBars default to showing 0% progress. type ProgressBar struct { + lock sync.Mutex created bool sysData *sysData initProg int @@ -25,6 +30,9 @@ func NewProgressBar() *ProgressBar { // Otherwise, SetProgress panics. // Calling SetProgress(-1) repeatedly will neither leave indeterminate mode nor stop any animation involved in indeterminate mode indefinitely; any other side-effect of doing so is implementation-defined. func (p *ProgressBar) SetProgress(percent int) { + p.lock.Lock() + defer p.lock.Unlock() + if percent < -1 || percent > 100 { panic("percent value out of range") } @@ -36,6 +44,9 @@ func (p *ProgressBar) SetProgress(percent int) { } func (p *ProgressBar) make(window *sysData) error { + p.lock.Lock() + defer p.lock.Unlock() + err := p.sysData.make(window) if err != nil { return err diff --git a/stack.go b/stack.go index b421252..e8ce332 100644 --- a/stack.go +++ b/stack.go @@ -4,6 +4,7 @@ package ui import ( "fmt" + "sync" ) type orientation bool @@ -19,6 +20,7 @@ const ( // Any extra space at the end of a Stack is left blank. // Some controls may be marked as "stretchy": when the Window they are in changes size, stretchy controls resize to take up the remaining space after non-stretchy controls are laid out. If multiple controls are marked stretchy, they are alloted equal distribution of the remaining space. type Stack struct { + lock sync.Mutex created bool orientation orientation controls []Control @@ -49,6 +51,9 @@ func NewVerticalStack(controls ...Control) *Stack { // SetStretchy marks a control in a Stack as stretchy. This cannot be called once the Window containing the Stack has been created. // It panics if index is out of range. func (s *Stack) SetStretchy(index int) { + s.lock.Lock() + defer s.lock.Unlock() + if s.created { panic("call to Stack.SetStretchy() after Stack has been created") } @@ -59,6 +64,9 @@ func (s *Stack) SetStretchy(index int) { } func (s *Stack) make(window *sysData) error { + s.lock.Lock() + defer s.lock.Unlock() + for i, c := range s.controls { err := c.make(window) if err != nil { diff --git a/stdwndclass_windows.go b/stdwndclass_windows.go index ac5dfd9..3fa23c4 100644 --- a/stdwndclass_windows.go +++ b/stdwndclass_windows.go @@ -116,7 +116,7 @@ func stdWndProc(hwnd _HWND, uMsg uint32, wParam _WPARAM, lParam _LPARAM) _LRESUL switch ss.ctype { case c_button: if wParam.HIWORD() == _BN_CLICKED { - ss.event() + ss.signal() } case c_checkbox: // we opt into doing this ourselves because http://blogs.msdn.com/b/oldnewthing/archive/2014/05/22/10527522.aspx @@ -164,11 +164,7 @@ func stdWndProc(hwnd _HWND, uMsg uint32, wParam _WPARAM, lParam _LPARAM) _LRESUL } return 0 case _WM_CLOSE: - close := false // TODO decide apt default - s.close(&close) - if close { - s.hide() - } + s.signal() return 0 default: return defWindowProc(hwnd, uMsg, wParam, lParam) diff --git a/sysdata.go b/sysdata.go index 9144517..4a95591 100644 --- a/sysdata.go +++ b/sysdata.go @@ -2,16 +2,21 @@ package ui +const eventbufsiz = 100 // suggested by skelterjohn + +// newEvent returns a new channel suitable for listening for events. +func newEvent() chan struct{} { + return make(chan struct{}, eventbufsiz) +} + // The sysData type contains all system data. It provides the system-specific underlying implementation. It is guaranteed to have the following by embedding: type cSysData struct { ctype int + event chan struct{} allocate func(x int, y int, width int, height int, d *sysSizeData) []*allocation spaced bool alternate bool // editable for Combobox, multi-select for listbox, password for lineedit - handler AreaHandler // for Areas; TODO rename to areahandler - winhandler WindowHandler // for Windows - close func(*bool) // provided by each Window - event func() // provided by each control + handler AreaHandler // for Areas } // this interface is used to make sure all sysDatas are synced @@ -39,6 +44,19 @@ var _xSysData interface { setChecked(bool) } = &sysData{} // this line will error if there's an inconsistency +// signal sends the event signal. This raise is done asynchronously to avoid deadlocking the UI task. +// Thanks skelterjohn for this techinque: if we can't queue any more events, drop them +func (s *cSysData) signal() { + if s.event != nil { + go func() { + select { + case s.event <- struct{}{}: + default: + } + }() + } +} + const ( c_window = iota c_button diff --git a/sysdata_darwin.go b/sysdata_darwin.go index cd25748..48b7d44 100644 --- a/sysdata_darwin.go +++ b/sysdata_darwin.go @@ -225,9 +225,17 @@ func (s *sysData) make(window *sysData) error { if window != nil { parentWindow = window.id } - s.id = ct.make(parentWindow, s.alternate, s) + ret := make(chan C.id) + defer close(ret) + uitask <- func() { + ret <- ct.make(parentWindow, s.alternate, s) + } + s.id = <-ret if ct.getinside != nil { - addSysData(ct.getinside(s.id), s) + uitask <- func() { + ret <- ct.getinside(s.id) + } + addSysData(<-ret, s) } else { addSysData(s.id, s) } @@ -241,15 +249,33 @@ func (s *sysData) firstShow() error { } func (s *sysData) show() { - classTypes[s.ctype].show(s.id) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + classTypes[s.ctype].show(s.id) + ret <- struct{}{} + } + <-ret } func (s *sysData) hide() { - classTypes[s.ctype].hide(s.id) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + classTypes[s.ctype].hide(s.id) + ret <- struct{}{} + } + <-ret } func (s *sysData) setText(text string) { - classTypes[s.ctype].settext(s.id, toNSString(text)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + classTypes[s.ctype].settext(s.id, toNSString(text)) + ret <- struct{}{} + } + <-ret } func (s *sysData) setRect(x int, y int, width int, height int, winheight int) error { @@ -262,63 +288,147 @@ func (s *sysData) setRect(x int, y int, width int, height int, winheight int) er } func (s *sysData) isChecked() bool { - return C.isCheckboxChecked(s.id) != C.NO + ret := make(chan bool) + defer close(ret) + uitask <- func() { + ret <- C.isCheckboxChecked(s.id) != C.NO + } + return <-ret } func (s *sysData) text() string { - str := classTypes[s.ctype].text(s.id, s.alternate) - return fromNSString(str) + ret := make(chan string) + defer close(ret) + uitask <- func() { + str := classTypes[s.ctype].text(s.id, s.alternate) + ret <- fromNSString(str) + } + return <-ret } func (s *sysData) append(what string) { - classTypes[s.ctype].append(s.id, what, s.alternate) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + classTypes[s.ctype].append(s.id, what, s.alternate) + ret <- struct{}{} + } + <-ret } func (s *sysData) insertBefore(what string, before int) { - classTypes[s.ctype].insertBefore(s.id, what, before, s.alternate) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + classTypes[s.ctype].insertBefore(s.id, what, before, s.alternate) + ret <- struct{}{} + } + <-ret } func (s *sysData) selectedIndex() int { - return classTypes[s.ctype].selIndex(s.id) + ret := make(chan int) + defer close(ret) + uitask <- func() { + ret <- classTypes[s.ctype].selIndex(s.id) + } + return <-ret } func (s *sysData) selectedIndices() []int { - return classTypes[s.ctype].selIndices(s.id) + ret := make(chan []int) + defer close(ret) + uitask <- func() { + ret <- classTypes[s.ctype].selIndices(s.id) + } + return <-ret } func (s *sysData) selectedTexts() []string { - return classTypes[s.ctype].selTexts(s.id) + ret := make(chan []string) + defer close(ret) + uitask <- func() { + ret <- classTypes[s.ctype].selTexts(s.id) + } + return <-ret } func (s *sysData) setWindowSize(width int, height int) error { - C.windowSetContentSize(s.id, C.intptr_t(width), C.intptr_t(height)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + C.windowSetContentSize(s.id, C.intptr_t(width), C.intptr_t(height)) + ret <- struct{}{} + } + <-ret return nil } func (s *sysData) delete(index int) { - classTypes[s.ctype].delete(s.id, index) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + classTypes[s.ctype].delete(s.id, index) + ret <- struct{}{} + } + <-ret } func (s *sysData) setProgress(percent int) { - C.setProgress(s.id, C.intptr_t(percent)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + C.setProgress(s.id, C.intptr_t(percent)) + ret <- struct{}{} + } + <-ret } func (s *sysData) len() int { - return classTypes[s.ctype].len(s.id) + ret := make(chan int) + defer close(ret) + uitask <- func() { + ret <- classTypes[s.ctype].len(s.id) + } + return <-ret } func (s *sysData) setAreaSize(width int, height int) { - C.setAreaSize(s.id, C.intptr_t(width), C.intptr_t(height)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + C.setAreaSize(s.id, C.intptr_t(width), C.intptr_t(height)) + ret <- struct{}{} + } + <-ret } func (s *sysData) repaintAll() { - C.display(s.id) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + C.display(s.id) + ret <- struct{}{} + } + <-ret } func (s *sysData) center() { - C.center(s.id) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + C.center(s.id) + ret <- struct{}{} + } + <-ret } func (s *sysData) setChecked(checked bool) { - C.setCheckboxChecked(s.id, toBOOL(checked)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + C.setCheckboxChecked(s.id, toBOOL(checked)) + ret <- struct{}{} + } + <-ret } diff --git a/sysdata_unix.go b/sysdata_unix.go index b39df50..7814fb3 100644 --- a/sysdata_unix.go +++ b/sysdata_unix.go @@ -118,30 +118,42 @@ var classTypes = [nctypes]*classData{ func (s *sysData) make(window *sysData) error { ct := classTypes[s.ctype] - if s.alternate { - s.widget = ct.makeAlt() - } else { - s.widget = ct.make() - } - if window == nil { - fixed := gtkNewWindowLayout() - gtk_container_add(s.widget, fixed) - for signame, sigfunc := range ct.signals { - g_signal_connect(s.widget, signame, sigfunc, s) + ret := make(chan *C.GtkWidget) + defer close(ret) + uitask <- func() { + if s.alternate { + ret <- ct.makeAlt() + return } - s.container = fixed + ret <- ct.make() + } + s.widget = <-ret + if window == nil { + uitask <- func() { + fixed := gtkNewWindowLayout() + gtk_container_add(s.widget, fixed) + for signame, sigfunc := range ct.signals { + g_signal_connect(s.widget, signame, sigfunc, s) + } + ret <- fixed + } + s.container = <-ret } else { s.container = window.container - gtkAddWidgetToLayout(s.container, s.widget) - for signame, sigfunc := range ct.signals { - g_signal_connect(s.widget, signame, sigfunc, s) - } - if ct.child != nil { - child := ct.child(s.widget) - for signame, sigfunc := range ct.childsigs { - g_signal_connect(child, signame, sigfunc, s) + uitask <- func() { + gtkAddWidgetToLayout(s.container, s.widget) + for signame, sigfunc := range ct.signals { + g_signal_connect(s.widget, signame, sigfunc, s) } + if ct.child != nil { + child := ct.child(s.widget) + for signame, sigfunc := range ct.childsigs { + g_signal_connect(child, signame, sigfunc, s) + } + } + ret <- nil } + <-ret } return nil } @@ -158,17 +170,35 @@ func (s *sysData) firstShow() error { } func (s *sysData) show() { - gtk_widget_show(s.widget) - s.resetposition() + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + gtk_widget_show(s.widget) + s.resetposition() + ret <- struct{}{} + } + <-ret } func (s *sysData) hide() { - gtk_widget_hide(s.widget) - s.resetposition() + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + gtk_widget_hide(s.widget) + s.resetposition() + ret <- struct{}{} + } + <-ret } func (s *sysData) setText(text string) { - classTypes[s.ctype].setText(s.widget, text) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + classTypes[s.ctype].setText(s.widget, text) + ret <- struct{}{} + } + <-ret } func (s *sysData) setRect(x int, y int, width int, height int, winheight int) error { @@ -178,51 +208,103 @@ func (s *sysData) setRect(x int, y int, width int, height int, winheight int) er } func (s *sysData) isChecked() bool { - return gtk_toggle_button_get_active(s.widget) + ret := make(chan bool) + defer close(ret) + uitask <- func() { + ret <- gtk_toggle_button_get_active(s.widget) + } + return <-ret } func (s *sysData) text() string { - return classTypes[s.ctype].text(s.widget) + ret := make(chan string) + defer close(ret) + uitask <- func() { + ret <- classTypes[s.ctype].text(s.widget) + } + return <-ret } func (s *sysData) append(what string) { - classTypes[s.ctype].append(s.widget, what) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + classTypes[s.ctype].append(s.widget, what) + ret <- struct{}{} + } + <-ret } func (s *sysData) insertBefore(what string, before int) { - classTypes[s.ctype].insert(s.widget, before, what) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + classTypes[s.ctype].insert(s.widget, before, what) + ret <- struct{}{} + } + <-ret } func (s *sysData) selectedIndex() int { - return classTypes[s.ctype].selected(s.widget) + ret := make(chan int) + defer close(ret) + uitask <- func() { + ret <- classTypes[s.ctype].selected(s.widget) + } + return <-ret } func (s *sysData) selectedIndices() []int { - return classTypes[s.ctype].selMulti(s.widget) + ret := make(chan []int) + defer close(ret) + uitask <- func() { + ret <- classTypes[s.ctype].selMulti(s.widget) + } + return <-ret } func (s *sysData) selectedTexts() []string { - return classTypes[s.ctype].smtexts(s.widget) + ret := make(chan []string) + defer close(ret) + uitask <- func() { + ret <- classTypes[s.ctype].smtexts(s.widget) + } + return <-ret } func (s *sysData) setWindowSize(width int, height int) error { - // does not take window geometry into account (and cannot, since the window manager won't give that info away) - // thanks to TingPing in irc.gimp.net/#gtk+ - gtk_window_resize(s.widget, width, height) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + // does not take window geometry into account (and cannot, since the window manager won't give that info away) + // thanks to TingPing in irc.gimp.net/#gtk+ + gtk_window_resize(s.widget, width, height) + ret <- struct{}{} + } + <-ret return nil } func (s *sysData) delete(index int) { - classTypes[s.ctype].delete(s.widget, index) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + classTypes[s.ctype].delete(s.widget, index) + ret <- struct{}{} + } + <-ret } // With GTK+, we must manually pulse the indeterminate progressbar ourselves. This goroutine does that. func (s *sysData) progressPulse() { - // TODO this could probably be done differently... pulse := func() { - touitask(func() { + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { gtk_progress_bar_pulse(s.widget) - }) + ret <- struct{}{} + } + <-ret } var ticker *time.Ticker @@ -263,44 +345,78 @@ func (s *sysData) setProgress(percent int) { } s.pulse <- false <-s.pulse // wait for sysData.progressPulse() to register that - gtk_progress_bar_set_fraction(s.widget, percent) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + gtk_progress_bar_set_fraction(s.widget, percent) + ret <- struct{}{} + } + <-ret } func (s *sysData) len() int { - return classTypes[s.ctype].len(s.widget) + ret := make(chan int) + defer close(ret) + uitask <- func() { + ret <- classTypes[s.ctype].len(s.widget) + } + return <-ret } func (s *sysData) setAreaSize(width int, height int) { - c := gtkAreaGetControl(s.widget) - gtk_widget_set_size_request(c, width, height) - s.areawidth = width // for sysData.preferredSize() - s.areaheight = height - C.gtk_widget_queue_draw(c) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + c := gtkAreaGetControl(s.widget) + gtk_widget_set_size_request(c, width, height) + s.areawidth = width // for sysData.preferredSize() + s.areaheight = height + C.gtk_widget_queue_draw(c) + ret <- struct{}{} + } + <-ret } -// TODO should this be made safe? (TODO move to area.go) func (s *sysData) repaintAll() { - c := gtkAreaGetControl(s.widget) - C.gtk_widget_queue_draw(c) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + c := gtkAreaGetControl(s.widget) + C.gtk_widget_queue_draw(c) + ret <- struct{}{} + } + <-ret } func (s *sysData) center() { - if C.gtk_widget_get_visible(s.widget) == C.FALSE { - // hint to the WM to make it centered when it is shown again - // thanks to Jasper in irc.gimp.net/#gtk+ - C.gtk_window_set_position(togtkwindow(s.widget), C.GTK_WIN_POS_CENTER) - } else { - var width, height C.gint + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + if C.gtk_widget_get_visible(s.widget) == C.FALSE { + // hint to the WM to make it centered when it is shown again + // thanks to Jasper in irc.gimp.net/#gtk+ + C.gtk_window_set_position(togtkwindow(s.widget), C.GTK_WIN_POS_CENTER) + } else { + var width, height C.gint - s.resetposition() - //we should be able to use gravity to simplify this, but it doesn't take effect immediately, and adding show calls does nothing (thanks Jasper in irc.gimp.net/#gtk+) - C.gtk_window_get_size(togtkwindow(s.widget), &width, &height) - C.gtk_window_move(togtkwindow(s.widget), - (C.gdk_screen_width() / 2) - (width / 2), - (C.gdk_screen_height() / 2) - (width / 2)) + s.resetposition() + //we should be able to use gravity to simplify this, but it doesn't take effect immediately, and adding show calls does nothing (thanks Jasper in irc.gimp.net/#gtk+) + C.gtk_window_get_size(togtkwindow(s.widget), &width, &height) + C.gtk_window_move(togtkwindow(s.widget), + (C.gdk_screen_width() / 2) - (width / 2), + (C.gdk_screen_height() / 2) - (width / 2)) + } + ret <- struct{}{} } + <-ret } func (s *sysData) setChecked(checked bool) { - gtk_toggle_button_set_active(s.widget, checked) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + gtk_toggle_button_set_active(s.widget, checked) + ret <- struct{}{} + } + <-ret } diff --git a/sysdata_windows.go b/sysdata_windows.go index 1d3541a..504b715 100644 --- a/sysdata_windows.go +++ b/sysdata_windows.go @@ -148,52 +148,58 @@ var ( ) func (s *sysData) make(window *sysData) (err error) { - ct := classTypes[s.ctype] - cid := _HMENU(0) - pwin := uintptr(_NULL) - if window != nil { // this is a child control - cid = window.addChild(s) - pwin = uintptr(window.hwnd) - } - style := uintptr(ct.style) - if s.alternate { - style = uintptr(ct.altStyle) - } - lpParam := uintptr(_NULL) - if ct.storeSysData { - lpParam = uintptr(unsafe.Pointer(s)) - } - r1, _, err := _createWindowEx.Call( - uintptr(ct.xstyle), - utf16ToArg(ct.name), - blankString, // we set the window text later - style, - negConst(_CW_USEDEFAULT), - negConst(_CW_USEDEFAULT), - negConst(_CW_USEDEFAULT), - negConst(_CW_USEDEFAULT), - pwin, - uintptr(cid), - uintptr(hInstance), - lpParam) - if r1 == 0 { // failure - if window != nil { - window.delChild(cid) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + ct := classTypes[s.ctype] + cid := _HMENU(0) + pwin := uintptr(_NULL) + if window != nil { // this is a child control + cid = window.addChild(s) + pwin = uintptr(window.hwnd) } - panic(fmt.Errorf("error actually creating window/control: %v", err)) - } - if !ct.storeSysData { // regular control; store s.hwnd ourselves - s.hwnd = _HWND(r1) - } else if s.hwnd != _HWND(r1) { // we store sysData in storeSysData(); sanity check - panic(fmt.Errorf("hwnd mismatch creating window/control: storeSysData() stored 0x%X but CreateWindowEx() returned 0x%X", s.hwnd, r1)) - } - if !ct.doNotLoadFont { - _sendMessage.Call( - uintptr(s.hwnd), - uintptr(_WM_SETFONT), - uintptr(_WPARAM(controlFont)), - uintptr(_LPARAM(_TRUE))) + style := uintptr(ct.style) + if s.alternate { + style = uintptr(ct.altStyle) + } + lpParam := uintptr(_NULL) + if ct.storeSysData { + lpParam = uintptr(unsafe.Pointer(s)) + } + r1, _, err := _createWindowEx.Call( + uintptr(ct.xstyle), + utf16ToArg(ct.name), + blankString, // we set the window text later + style, + negConst(_CW_USEDEFAULT), + negConst(_CW_USEDEFAULT), + negConst(_CW_USEDEFAULT), + negConst(_CW_USEDEFAULT), + pwin, + uintptr(cid), + uintptr(hInstance), + lpParam) + if r1 == 0 { // failure + if window != nil { + window.delChild(cid) + } + panic(fmt.Errorf("error actually creating window/control: %v", err)) + } + if !ct.storeSysData { // regular control; store s.hwnd ourselves + s.hwnd = _HWND(r1) + } else if s.hwnd != _HWND(r1) { // we store sysData in storeSysData(); sanity check + panic(fmt.Errorf("hwnd mismatch creating window/control: storeSysData() stored 0x%X but CreateWindowEx() returned 0x%X", s.hwnd, r1)) + } + if !ct.doNotLoadFont { + _sendMessage.Call( + uintptr(s.hwnd), + uintptr(_WM_SETFONT), + uintptr(_WPARAM(controlFont)), + uintptr(_LPARAM(_TRUE))) + } + ret <- struct{}{} } + <-ret return nil } @@ -205,38 +211,63 @@ var ( // ShowWindow(hwnd, nCmdShow); // UpdateWindow(hwnd); func (s *sysData) firstShow() error { - _showWindow.Call( - uintptr(s.hwnd), - uintptr(nCmdShow)) - r1, _, err := _updateWindow.Call(uintptr(s.hwnd)) - if r1 == 0 { // failure - panic(fmt.Errorf("error updating window for the first time: %v", err)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + _showWindow.Call( + uintptr(s.hwnd), + uintptr(nCmdShow)) + r1, _, err := _updateWindow.Call(uintptr(s.hwnd)) + if r1 == 0 { // failure + panic(fmt.Errorf("error updating window for the first time: %v", err)) + } + ret <- struct{}{} } + <-ret return nil } func (s *sysData) show() { - _showWindow.Call( - uintptr(s.hwnd), - uintptr(_SW_SHOW)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + _showWindow.Call( + uintptr(s.hwnd), + uintptr(_SW_SHOW)) + ret <- struct{}{} + } + <-ret } func (s *sysData) hide() { - _showWindow.Call( - uintptr(s.hwnd), - uintptr(_SW_HIDE)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + _showWindow.Call( + uintptr(s.hwnd), + uintptr(_SW_HIDE)) + ret <- struct{}{} + } + <-ret } func (s *sysData) setText(text string) { - ptext := toUTF16(text) - r1, _, err := _setWindowText.Call( - uintptr(s.hwnd), - utf16ToArg(ptext)) - if r1 == 0 { // failure - panic(fmt.Errorf("error setting window/control text: %v", err)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + ptext := toUTF16(text) + r1, _, err := _setWindowText.Call( + uintptr(s.hwnd), + utf16ToArg(ptext)) + if r1 == 0 { // failure + panic(fmt.Errorf("error setting window/control text: %v", err)) + } + ret <- struct{}{} } + <-ret } +// runs on uitask func (s *sysData) setRect(x int, y int, width int, height int, winheight int) error { r1, _, err := _moveWindow.Call( uintptr(s.hwnd), @@ -252,61 +283,84 @@ func (s *sysData) setRect(x int, y int, width int, height int, winheight int) er } func (s *sysData) isChecked() bool { - r1, _, _ := _sendMessage.Call( - uintptr(s.hwnd), - uintptr(_BM_GETCHECK), - uintptr(0), - uintptr(0)) - return r1 == _BST_CHECKED + ret := make(chan bool) + defer close(ret) + uitask <- func() { + r1, _, _ := _sendMessage.Call( + uintptr(s.hwnd), + uintptr(_BM_GETCHECK), + uintptr(0), + uintptr(0)) + ret <- r1 == _BST_CHECKED + } + return <-ret } func (s *sysData) text() (str string) { - var tc []uint16 + ret := make(chan string) + defer close(ret) + uitask <- func() { + var tc []uint16 - r1, _, _ := _sendMessage.Call( - uintptr(s.hwnd), - uintptr(_WM_GETTEXTLENGTH), - uintptr(0), - uintptr(0)) - length := r1 + 1 // terminating null - tc = make([]uint16, length) - _sendMessage.Call( - uintptr(s.hwnd), - uintptr(_WM_GETTEXT), - uintptr(_WPARAM(length)), - uintptr(_LPARAM(unsafe.Pointer(&tc[0])))) - return syscall.UTF16ToString(tc) + r1, _, _ := _sendMessage.Call( + uintptr(s.hwnd), + uintptr(_WM_GETTEXTLENGTH), + uintptr(0), + uintptr(0)) + length := r1 + 1 // terminating null + tc = make([]uint16, length) + _sendMessage.Call( + uintptr(s.hwnd), + uintptr(_WM_GETTEXT), + uintptr(_WPARAM(length)), + uintptr(_LPARAM(unsafe.Pointer(&tc[0])))) + ret <- syscall.UTF16ToString(tc) + } + return <-ret } func (s *sysData) append(what string) { - pwhat := toUTF16(what) - r1, _, err := _sendMessage.Call( - uintptr(s.hwnd), - uintptr(classTypes[s.ctype].appendMsg), - uintptr(_WPARAM(0)), - utf16ToLPARAM(pwhat)) - if r1 == uintptr(classTypes[s.ctype].addSpaceErr) { - panic(fmt.Errorf("out of space adding item to combobox/listbox (last error: %v)", err)) - } else if r1 == uintptr(classTypes[s.ctype].selectedIndexErr) { - panic(fmt.Errorf("failed to add item to combobox/listbox (last error: %v)", err)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + pwhat := toUTF16(what) + r1, _, err := _sendMessage.Call( + uintptr(s.hwnd), + uintptr(classTypes[s.ctype].appendMsg), + uintptr(_WPARAM(0)), + utf16ToLPARAM(pwhat)) + if r1 == uintptr(classTypes[s.ctype].addSpaceErr) { + panic(fmt.Errorf("out of space adding item to combobox/listbox (last error: %v)", err)) + } else if r1 == uintptr(classTypes[s.ctype].selectedIndexErr) { + panic(fmt.Errorf("failed to add item to combobox/listbox (last error: %v)", err)) + } + ret <- struct{}{} } + <-ret } func (s *sysData) insertBefore(what string, index int) { - pwhat := toUTF16(what) - r1, _, err := _sendMessage.Call( - uintptr(s.hwnd), - uintptr(classTypes[s.ctype].insertBeforeMsg), - uintptr(_WPARAM(index)), - utf16ToLPARAM(pwhat)) - if r1 == uintptr(classTypes[s.ctype].addSpaceErr) { - panic(fmt.Errorf("out of space adding item to combobox/listbox (last error: %v)", err)) - } else if r1 == uintptr(classTypes[s.ctype].selectedIndexErr) { - panic(fmt.Errorf("failed to add item to combobox/listbox (last error: %v)", err)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + pwhat := toUTF16(what) + r1, _, err := _sendMessage.Call( + uintptr(s.hwnd), + uintptr(classTypes[s.ctype].insertBeforeMsg), + uintptr(_WPARAM(index)), + utf16ToLPARAM(pwhat)) + if r1 == uintptr(classTypes[s.ctype].addSpaceErr) { + panic(fmt.Errorf("out of space adding item to combobox/listbox (last error: %v)", err)) + } else if r1 == uintptr(classTypes[s.ctype].selectedIndexErr) { + panic(fmt.Errorf("failed to add item to combobox/listbox (last error: %v)", err)) + } + ret <- struct{}{} } + <-ret } -func (s *sysData) selectedIndex() int { +// runs on uitask +func (s *sysData) doSelectedIndex() int { r1, _, _ := _sendMessage.Call( uintptr(s.hwnd), uintptr(classTypes[s.ctype].selectedIndexMsg), @@ -318,9 +372,19 @@ func (s *sysData) selectedIndex() int { return int(r1) } -func (s *sysData) selectedIndices() []int { +func (s *sysData) selectedIndex() int { + ret := make(chan int) + defer close(ret) + uitask <- func() { + ret <- s.doSelectedIndex() + } + return <-ret +} + +// runs on uitask +func (s *sysData) doSelectedIndices() []int { if !s.alternate { // single-selection list box; use single-selection method - index := s.selectedIndex() + index := s.doSelectedIndex() if index == -1 { return nil } @@ -350,75 +414,107 @@ func (s *sysData) selectedIndices() []int { return indices } -func (s *sysData) selectedTexts() []string { - indices := s.selectedIndices() - strings := make([]string, len(indices)) - for i, v := range indices { - r1, _, err := _sendMessage.Call( - uintptr(s.hwnd), - uintptr(_LB_GETTEXTLEN), - uintptr(_WPARAM(v)), - uintptr(0)) - if r1 == negConst(_LB_ERR) { - panic(fmt.Errorf("error: LB_ERR from LB_GETTEXTLEN in what we know is a valid listbox index (came from LB_GETSELITEMS): %v", err)) - } - str := make([]uint16, r1) - r1, _, err = _sendMessage.Call( - uintptr(s.hwnd), - uintptr(_LB_GETTEXT), - uintptr(_WPARAM(v)), - uintptr(_LPARAM(unsafe.Pointer(&str[0])))) - if r1 == negConst(_LB_ERR) { - panic(fmt.Errorf("error: LB_ERR from LB_GETTEXT in what we know is a valid listbox index (came from LB_GETSELITEMS): %v", err)) - } - strings[i] = syscall.UTF16ToString(str) +func (s *sysData) selectedIndices() []int { + ret := make(chan []int) + defer close(ret) + uitask <- func() { + ret <- s.doSelectedIndices() } - return strings + return <-ret +} + +func (s *sysData) selectedTexts() []string { + ret := make(chan []string) + defer close(ret) + uitask <- func() { + indices := s.doSelectedIndices() + strings := make([]string, len(indices)) + for i, v := range indices { + r1, _, err := _sendMessage.Call( + uintptr(s.hwnd), + uintptr(_LB_GETTEXTLEN), + uintptr(_WPARAM(v)), + uintptr(0)) + if r1 == negConst(_LB_ERR) { + panic(fmt.Errorf("error: LB_ERR from LB_GETTEXTLEN in what we know is a valid listbox index (came from LB_GETSELITEMS): %v", err)) + } + str := make([]uint16, r1) + r1, _, err = _sendMessage.Call( + uintptr(s.hwnd), + uintptr(_LB_GETTEXT), + uintptr(_WPARAM(v)), + uintptr(_LPARAM(unsafe.Pointer(&str[0])))) + if r1 == negConst(_LB_ERR) { + panic(fmt.Errorf("error: LB_ERR from LB_GETTEXT in what we know is a valid listbox index (came from LB_GETSELITEMS): %v", err)) + } + strings[i] = syscall.UTF16ToString(str) + } + ret <- strings + } + return <-ret } func (s *sysData) setWindowSize(width int, height int) error { - var rect _RECT + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + var rect _RECT - r1, _, err := _getClientRect.Call( - uintptr(s.hwnd), - uintptr(unsafe.Pointer(&rect))) - if r1 == 0 { - panic(fmt.Errorf("error getting upper-left of window for resize: %v", err)) - } - // TODO AdjustWindowRect() on the result - // 0 because (0,0) is top-left so no winheight - err = s.setRect(int(rect.left), int(rect.top), width, height, 0) - if err != nil { - panic(fmt.Errorf("error actually resizing window: %v", err)) + r1, _, err := _getClientRect.Call( + uintptr(s.hwnd), + uintptr(unsafe.Pointer(&rect))) + if r1 == 0 { + panic(fmt.Errorf("error getting upper-left of window for resize: %v", err)) + } + // TODO AdjustWindowRect() on the result + // 0 because (0,0) is top-left so no winheight + err = s.setRect(int(rect.left), int(rect.top), width, height, 0) + if err != nil { + panic(fmt.Errorf("error actually resizing window: %v", err)) + } + ret <- struct{}{} } + <-ret return nil } func (s *sysData) delete(index int) { - r1, _, err := _sendMessage.Call( - uintptr(s.hwnd), - uintptr(classTypes[s.ctype].deleteMsg), - uintptr(_WPARAM(index)), - uintptr(0)) - if r1 == uintptr(classTypes[s.ctype].selectedIndexErr) { - panic(fmt.Errorf("failed to delete item from combobox/listbox (last error: %v)", err)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + r1, _, err := _sendMessage.Call( + uintptr(s.hwnd), + uintptr(classTypes[s.ctype].deleteMsg), + uintptr(_WPARAM(index)), + uintptr(0)) + if r1 == uintptr(classTypes[s.ctype].selectedIndexErr) { + panic(fmt.Errorf("failed to delete item from combobox/listbox (last error: %v)", err)) + } + ret <- struct{}{} } + <-ret } func (s *sysData) setIndeterminate() { - r1, _, err := _setWindowLongPtr.Call( - uintptr(s.hwnd), - negConst(_GWL_STYLE), - uintptr(classTypes[s.ctype].style | _PBS_MARQUEE)) - if r1 == 0 { - panic(fmt.Errorf("error setting progress bar style to enter indeterminate mode: %v", err)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + r1, _, err := _setWindowLongPtr.Call( + uintptr(s.hwnd), + negConst(_GWL_STYLE), + uintptr(classTypes[s.ctype].style | _PBS_MARQUEE)) + if r1 == 0 { + panic(fmt.Errorf("error setting progress bar style to enter indeterminate mode: %v", err)) + } + _sendMessage.Call( + uintptr(s.hwnd), + uintptr(_PBM_SETMARQUEE), + uintptr(_WPARAM(_TRUE)), + uintptr(0)) + s.isMarquee = true + ret <- struct{}{} } - _sendMessage.Call( - uintptr(s.hwnd), - uintptr(_PBM_SETMARQUEE), - uintptr(_WPARAM(_TRUE)), - uintptr(0)) - s.isMarquee = true + <-ret } func (s *sysData) setProgress(percent int) { @@ -426,100 +522,134 @@ func (s *sysData) setProgress(percent int) { s.setIndeterminate() return } - if s.isMarquee { - // turn off marquee before switching back - _sendMessage.Call( - uintptr(s.hwnd), - uintptr(_PBM_SETMARQUEE), - uintptr(_WPARAM(_FALSE)), - uintptr(0)) - r1, _, err := _setWindowLongPtr.Call( - uintptr(s.hwnd), - negConst(_GWL_STYLE), - uintptr(classTypes[s.ctype].style)) - if r1 == 0 { - panic(fmt.Errorf("error setting progress bar style to leave indeterminate mode (percent %d): %v", percent, err)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + if s.isMarquee { + // turn off marquee before switching back + _sendMessage.Call( + uintptr(s.hwnd), + uintptr(_PBM_SETMARQUEE), + uintptr(_WPARAM(_FALSE)), + uintptr(0)) + r1, _, err := _setWindowLongPtr.Call( + uintptr(s.hwnd), + negConst(_GWL_STYLE), + uintptr(classTypes[s.ctype].style)) + if r1 == 0 { + panic(fmt.Errorf("error setting progress bar style to leave indeterminate mode (percent %d): %v", percent, err)) + } + s.isMarquee = false } - s.isMarquee = false - } - send := func(msg uintptr, n int, l _LPARAM) { - _sendMessage.Call( - uintptr(s.hwnd), - msg, - uintptr(_WPARAM(n)), - uintptr(l)) - } - // Windows 7 has a non-disableable slowly-animating progress bar increment - // there isn't one for decrement, so we'll work around by going one higher and then lower again - // for the case where percent == 100, we need to increase the range temporarily - // sources: http://social.msdn.microsoft.com/Forums/en-US/61350dc7-6584-4c4e-91b0-69d642c03dae/progressbar-disable-smooth-animation http://stackoverflow.com/questions/2217688/windows-7-aero-theme-progress-bar-bug http://discuss.joelonsoftware.com/default.asp?dotnet.12.600456.2 http://stackoverflow.com/questions/22469876/progressbar-lag-when-setting-position-with-pbm-setpos http://stackoverflow.com/questions/6128287/tprogressbar-never-fills-up-all-the-way-seems-to-be-updating-too-fast - if percent == 100 { - send(_PBM_SETRANGE32, 0, 101) - } - send(_PBM_SETPOS, percent+1, 0) - send(_PBM_SETPOS, percent, 0) - if percent == 100 { - send(_PBM_SETRANGE32, 0, 100) + send := func(msg uintptr, n int, l _LPARAM) { + _sendMessage.Call( + uintptr(s.hwnd), + msg, + uintptr(_WPARAM(n)), + uintptr(l)) + } + // Windows 7 has a non-disableable slowly-animating progress bar increment + // there isn't one for decrement, so we'll work around by going one higher and then lower again + // for the case where percent == 100, we need to increase the range temporarily + // sources: http://social.msdn.microsoft.com/Forums/en-US/61350dc7-6584-4c4e-91b0-69d642c03dae/progressbar-disable-smooth-animation http://stackoverflow.com/questions/2217688/windows-7-aero-theme-progress-bar-bug http://discuss.joelonsoftware.com/default.asp?dotnet.12.600456.2 http://stackoverflow.com/questions/22469876/progressbar-lag-when-setting-position-with-pbm-setpos http://stackoverflow.com/questions/6128287/tprogressbar-never-fills-up-all-the-way-seems-to-be-updating-too-fast + if percent == 100 { + send(_PBM_SETRANGE32, 0, 101) + } + send(_PBM_SETPOS, percent+1, 0) + send(_PBM_SETPOS, percent, 0) + if percent == 100 { + send(_PBM_SETRANGE32, 0, 100) + } + ret <- struct{}{} } + <-ret } func (s *sysData) len() int { - r1, _, err := _sendMessage.Call( - uintptr(s.hwnd), - uintptr(classTypes[s.ctype].lenMsg), - uintptr(_WPARAM(0)), - uintptr(_LPARAM(0))) - if r1 == uintptr(classTypes[s.ctype].selectedIndexErr) { - panic(fmt.Errorf("unexpected error return from sysData.len(); GetLastError() says %v", err)) + ret := make(chan int) + defer close(ret) + uitask <- func() { + r1, _, err := _sendMessage.Call( + uintptr(s.hwnd), + uintptr(classTypes[s.ctype].lenMsg), + uintptr(_WPARAM(0)), + uintptr(_LPARAM(0))) + if r1 == uintptr(classTypes[s.ctype].selectedIndexErr) { + panic(fmt.Errorf("unexpected error return from sysData.len(); GetLastError() says %v", err)) + } + ret <- int(r1) } - return int(r1) + return <-ret } func (s *sysData) setAreaSize(width int, height int) { - _sendMessage.Call( - uintptr(s.hwnd), - uintptr(msgSetAreaSize), - uintptr(width), // WPARAM is UINT_PTR on Windows XP and newer at least, so we're good with this - uintptr(height)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + _sendMessage.Call( + uintptr(s.hwnd), + uintptr(msgSetAreaSize), + uintptr(width), // WPARAM is UINT_PTR on Windows XP and newer at least, so we're good with this + uintptr(height)) + ret <- struct{}{} + } + <-ret } func (s *sysData) repaintAll() { - _sendMessage.Call( - uintptr(s.hwnd), - uintptr(msgRepaintAll), - uintptr(0), - uintptr(0)) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + _sendMessage.Call( + uintptr(s.hwnd), + uintptr(msgRepaintAll), + uintptr(0), + uintptr(0)) + ret <- struct{}{} + } + <-ret } func (s *sysData) center() { - var ws _RECT + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + var ws _RECT - r1, _, err := _getWindowRect.Call( - uintptr(s.hwnd), - uintptr(unsafe.Pointer(&ws))) - if r1 == 0 { - panic(fmt.Errorf("error getting window rect for sysData.center(): %v", err)) + r1, _, err := _getWindowRect.Call( + uintptr(s.hwnd), + uintptr(unsafe.Pointer(&ws))) + if r1 == 0 { + panic(fmt.Errorf("error getting window rect for sysData.center(): %v", err)) + } + // TODO should this be using the monitor functions instead? http://blogs.msdn.com/b/oldnewthing/archive/2005/05/05/414910.aspx + // error returns from GetSystemMetrics() is meaningless because the return value, 0, is still valid + dw, _, _ := _getSystemMetrics.Call(uintptr(_SM_CXFULLSCREEN)) + dh, _, _ := _getSystemMetrics.Call(uintptr(_SM_CYFULLSCREEN)) + ww := ws.right - ws.left + wh := ws.bottom - ws.top + wx := (int32(dw) / 2) - (ww / 2) + wy := (int32(dh) / 2) - (wh / 2) + s.setRect(int(wx), int(wy), int(ww), int(wh), 0) + ret <- struct{}{} } - // TODO should this be using the monitor functions instead? http://blogs.msdn.com/b/oldnewthing/archive/2005/05/05/414910.aspx - // error returns from GetSystemMetrics() is meaningless because the return value, 0, is still valid - // TODO should this be using the client rect and not the window rect? - dw, _, _ := _getSystemMetrics.Call(uintptr(_SM_CXFULLSCREEN)) - dh, _, _ := _getSystemMetrics.Call(uintptr(_SM_CYFULLSCREEN)) - ww := ws.right - ws.left - wh := ws.bottom - ws.top - wx := (int32(dw) / 2) - (ww / 2) - wy := (int32(dh) / 2) - (wh / 2) - s.setRect(int(wx), int(wy), int(ww), int(wh), 0) + <-ret } func (s *sysData) setChecked(checked bool) { - c := uintptr(_BST_CHECKED) - if !checked { - c = uintptr(_BST_UNCHECKED) + ret := make(chan struct{}) + defer close(ret) + uitask <- func() { + c := uintptr(_BST_CHECKED) + if !checked { + c = uintptr(_BST_UNCHECKED) + } + _sendMessage.Call( + uintptr(s.hwnd), + uintptr(_BM_SETCHECK), + c, + uintptr(0)) + ret <- struct{}{} } - _sendMessage.Call( - uintptr(s.hwnd), - uintptr(_BM_SETCHECK), - c, - uintptr(0)) + <-ret } diff --git a/test/kbtest.go b/test/kbtest.go index 4e97708..df00613 100644 --- a/test/kbtest.go +++ b/test/kbtest.go @@ -73,19 +73,13 @@ func (a *keyboardArea) Key(e KeyEvent) (repaint bool) { return true } -type kbhandler struct{} -func (kbhandler) Event(e Event, d interface{}) { - if e == Closing { - *(d.(*bool)) = true - } -} - var doKeyboard = flag.Bool("kb", false, "run keyboard test (overrides -areabounds)") func kbTest() { wid, ht, ah := mkkbArea() a := NewArea(wid, ht, ah) - w := NewWindow("Hi", wid, ht, kbhandler{}) + w := NewWindow("Hi", wid, ht) w.Open(a) + <-w.Closing } var ( @@ -219,8 +213,6 @@ var modpoints = map[Modifiers]image.Point{ Super: image.Pt(61, 199), } -// TODO move the following to its own file - // source: http://openclipart.org/image/800px/svg_to_png/154537/1312973798.png (medium image) via http://openclipart.org/detail/154537/us-english-keyboard-layout-v0.1-by-nitiraseem var kbpic = []byte{ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, diff --git a/test/main.go b/test/main.go index db01d15..034d712 100644 --- a/test/main.go +++ b/test/main.go @@ -15,21 +15,18 @@ import ( . "github.com/andlabs/ui" ) -type nullwinhandler struct{} -func (nullwinhandler) Event(Event, interface{}) {} - var prefsizetest = flag.Bool("prefsize", false, "") func listboxPreferredSizeTest() *Window { lb := NewListbox("xxxxx", "y", "zzz") g := NewGrid(1, lb) - w := NewWindow("Listbox Preferred Size Test", 300, 300, nullwinhandler{}) + w := NewWindow("Listbox Preferred Size Test", 300, 300) w.Open(g) return w } var gridtest = flag.Bool("grid", false, "") func gridWindow() *Window { - w := NewWindow("Grid Test", 400, 400, nullwinhandler{}) + w := NewWindow("Grid Test", 400, 400) b00 := NewButton("0,0") b01 := NewButton("0,1") b02 := NewButton("0,2") @@ -47,11 +44,10 @@ func gridWindow() *Window { g.SetStretchy(1, 1) w.SetSpaced(*spacingTest) w.Open(g) -//TODO -// go func() {for {select { -// case <-b12.Clicked: -// c21.SetChecked(!c21.Checked()) -// }}}() + go func() {for {select { + case <-b12.Clicked: + c21.SetChecked(!c21.Checked()) + }}}() return w } @@ -209,6 +205,7 @@ func areaTest() { } img := image.NewRGBA(ximg.Bounds()) draw.Draw(img, img.Rect, ximg, image.ZP, draw.Over) + w := NewWindow("Area Test", 100, 100) areahandler := &areaHandler{ img: img, } @@ -232,54 +229,24 @@ func areaTest() { timedisp, sizeStack) layout.SetStretchy(0) - w := NewWindow("Area Test", 100, 100, &areatestwinhandler{ - areahandler: areahandler, - a: a, - timedisp: timedisp, - widthbox: widthbox, - heightbox: heightbox, - resize: resize, - modaltest: modaltest, - repainttest: repainttest, - }) w.Open(layout) - go func() { - for t := range timechan { - // TODO - _ = t -// timedisp.SetText(t.String()) - } - }() -} - -type areatestwinhandler struct { - areahandler *areaHandler - a *Area - timedisp *Label - widthbox *LineEdit - heightbox *LineEdit - resize *Button - modaltest *Button - repainttest *Button -} -func (a *areatestwinhandler) Event(e Event, d interface{}) { - switch e { - case Closing: - *(d.(*bool)) = true - Stop <- struct{}{} - case Clicked: - switch d { - case a.resize: - width, err := strconv.Atoi(a.widthbox.Text()) - if err != nil { println(err); return } - height, err := strconv.Atoi(a.heightbox.Text()) - if err != nil { println(err); return } - a.a.SetSize(width, height) - case a.modaltest: + for { + select { + case <-w.Closing: + return + case t := <-timechan: + timedisp.SetText(t.String()) + case <-resize.Clicked: + width, err := strconv.Atoi(widthbox.Text()) + if err != nil { println(err); continue } + height, err := strconv.Atoi(heightbox.Text()) + if err != nil { println(err); continue } + a.SetSize(width, height) + case <-modaltest.Clicked: MsgBox("Modal Test", "") - case a.repainttest: - a.areahandler.mutate() - a.a.RepaintAll() + case <-repainttest.Clicked: + areahandler.mutate() + a.RepaintAll() } } } @@ -308,10 +275,9 @@ func areaboundsTest() { // middle purple r.Min.Y++ draw.Draw(img, r, u(128, 0, 128), image.ZP, draw.Over) - w := NewWindow("Area Bounds Test", 320, 240, &areatestwinhandler{ - a: a, - }) + w := NewWindow("Area Bounds Test", 320, 240) w.Open(a) + <-w.Closing } var dialogTest = flag.Bool("dialog", false, "add Window.MsgBox() channel test window") @@ -319,7 +285,6 @@ var labelAlignTest = flag.Bool("label", false, "show Label Alignment test window var spacingTest = flag.Bool("spacing", false, "margins and padding on Window") func myMain() { - <-Ready if *spacetest != "" { spaceTest() return @@ -336,88 +301,58 @@ func myMain() { areaboundsTest() return } - runMainTest() -} - -type testwinhandler struct { - w *Window - b *Button - b2 *Button - bmsg *Button - c *Checkbox - cb1 *Combobox - cb2 *Combobox - e *LineEdit - l *Label - resetl func() - b3 *Button - pbar *ProgressBar - prog int - incButton *Button - decButton *Button - indetButton *Button - invalidButton *Button - password *LineEdit - lb1 *Listbox - lb2 *Listbox - i int - doAdjustments func() -} - -func runMainTest() { - handler := new(testwinhandler) - handler.w = NewWindow("Main Window", 320, 240, handler) - handler.b = NewButton("Click Me") - handler.b2 = NewButton("Or Me") - handler.bmsg = NewButton("Or Even Me!") - s2 := NewHorizontalStack(handler.b, handler.b2, handler.bmsg) + w := NewWindow("Main Window", 320, 240) + b := NewButton("Click Me") + b2 := NewButton("Or Me") + bmsg := NewButton("Or Even Me!") + s2 := NewHorizontalStack(b, b2, bmsg) s2.SetStretchy(2) - handler.c = NewCheckbox("Check Me") - handler.cb1 = NewEditableCombobox("You can edit me!", "Yes you can!", "Yes you will!") - handler.cb2 = NewCombobox("You can't edit me!", "No you can't!", "No you won't!") - handler.e = NewLineEdit("Enter text here too") - handler.l = NewLabel("This is a label") - handler.resetl = func() { - handler.l.SetText("This is a label") + c := NewCheckbox("Check Me") + cb1 := NewEditableCombobox("You can edit me!", "Yes you can!", "Yes you will!") + cb2 := NewCombobox("You can't edit me!", "No you can't!", "No you won't!") + e := NewLineEdit("Enter text here too") + l := NewLabel("This is a label") + resetl := func() { + l.SetText("This is a label") } - handler.b3 = NewButton("List Info") - s3 := NewHorizontalStack(handler.l, handler.b3) + b3 := NewButton("List Info") + s3 := NewHorizontalStack(l, b3) s3.SetStretchy(0) // s3.SetStretchy(1) - handler.pbar = NewProgressBar() - handler.prog = 0 - handler.incButton = NewButton("Inc") - handler.decButton = NewButton("Dec") - handler.indetButton = NewButton("Indeterminate") - handler.invalidButton = NewButton("Run Invalid Test") - sincdec := NewHorizontalStack(handler.incButton, handler.decButton, handler.indetButton, handler.invalidButton) - handler.password = NewPasswordEdit() - s0 := NewVerticalStack(s2, handler.c, handler.cb1, handler.cb2, handler.e, s3, handler.pbar, sincdec, Space(), handler.password) + pbar := NewProgressBar() + prog := 0 + incButton := NewButton("Inc") + decButton := NewButton("Dec") + indetButton := NewButton("Indeterminate") + invalidButton := NewButton("Run Invalid Test") + sincdec := NewHorizontalStack(incButton, decButton, indetButton, invalidButton) + password := NewPasswordEdit() + s0 := NewVerticalStack(s2, c, cb1, cb2, e, s3, pbar, sincdec, Space(), password) s0.SetStretchy(8) - handler.lb1 = NewMultiSelListbox("Select One", "Or More", "To Continue") - handler.lb2 = NewListbox("Select", "Only", "One", "Please") - handler.i = 0 - handler.doAdjustments = func() { - handler.cb1.Append("append") - handler.cb2.InsertBefore(fmt.Sprintf("before %d", handler.i), 1) - handler.lb1.InsertBefore(fmt.Sprintf("%d", handler.i), 2) - handler.lb2.Append("Please") - handler.i++ + lb1 := NewMultiSelListbox("Select One", "Or More", "To Continue") + lb2 := NewListbox("Select", "Only", "One", "Please") + i := 0 + doAdjustments := func() { + cb1.Append("append") + cb2.InsertBefore(fmt.Sprintf("before %d", i), 1) + lb1.InsertBefore(fmt.Sprintf("%d", i), 2) + lb2.Append("Please") + i++ } - handler.doAdjustments() - handler.cb1.Append("append multi 1", "append multi 2") - handler.lb2.Append("append multi 1", "append multi 2") - s1 := NewVerticalStack(handler.lb2, handler.lb1) + doAdjustments() + cb1.Append("append multi 1", "append multi 2") + lb2.Append("append multi 1", "append multi 2") + s1 := NewVerticalStack(lb2, lb1) s1.SetStretchy(0) s1.SetStretchy(1) s := NewHorizontalStack(s1, s0) s.SetStretchy(0) s.SetStretchy(1) if *invalidBefore { - invalidTest(handler.cb1, handler.lb1, s, NewGrid(1, Space())) + invalidTest(cb1, lb1, s, NewGrid(1, Space())) } - handler.w.SetSpaced(*spacingTest) - handler.w.Open(s) + w.SetSpaced(*spacingTest) + w.Open(s) if *gridtest { gridWindow() } @@ -425,17 +360,12 @@ func runMainTest() { listboxPreferredSizeTest() } -// == TODO == + ticker := time.Tick(time.Second) + dialog_bMsgBox := NewButton("MsgBox()") dialog_bMsgBoxError := NewButton("MsgBoxError()") centerButton := NewButton("Center") - dh := &dialoghandler{ - bMsgBox: dialog_bMsgBox, - bMsgBoxError: dialog_bMsgBoxError, - bCenter: centerButton, -// send: w.Send, - } - dh.w = NewWindow("Dialogs", 200, 200, dh) + dialog_win := NewWindow("Dialogs", 200, 200) if *dialogTest { s := NewVerticalStack( dialog_bMsgBox, @@ -443,9 +373,11 @@ func runMainTest() { Space(), centerButton) s.SetStretchy(2) - dh.w.Open(s) + dialog_win.Open(s) } + var dialog_sret chan struct{} = nil + if *labelAlignTest { s := NewHorizontalStack(NewStandaloneLabel("Label"), NewLineEdit("Label")) s.SetStretchy(1) @@ -475,116 +407,99 @@ func runMainTest() { NewButton("Button"), s) s.SetStretchy(4) - NewWindow("Label Align Test", 500, 300, nullwinhandler{}).Open(s) + NewWindow("Label Align Test", 500, 300).Open(s) } -} -func (handler *testwinhandler) Event(e Event, d interface{}) { - switch e { - case Closing: - println("window closed event received") - Stop <- struct{}{} - case Clicked: - switch d { - case handler.b: - handler.w.SetTitle(fmt.Sprintf("%v | %s | %s | %s | %s", - handler.c.Checked(), - handler.cb1.Selection(), - handler.cb2.Selection(), - handler.e.Text(), - handler.password.Text())) - handler.doAdjustments() - case handler.b2: - if handler.cb1.Len() > 1 { - handler.cb1.Delete(1) +mainloop: + for { + select { + case curtime := <-ticker: +// l.SetText(curtime.String()) +_=curtime + case <-w.Closing: + println("window closed event received") + break mainloop + case <-AppQuit: + println("application quit event received") + break mainloop + case <-b.Clicked: + w.SetTitle(fmt.Sprintf("%v | %s | %s | %s | %s", + c.Checked(), + cb1.Selection(), + cb2.Selection(), + e.Text(), + password.Text())) + doAdjustments() + case <-b2.Clicked: + if cb1.Len() > 1 { + cb1.Delete(1) } - if handler.cb2.Len() > 2 { - handler.cb2.Delete(2) + if cb2.Len() > 2 { + cb2.Delete(2) } - if handler.lb1.Len() > 3 || *macCrashTest { - handler.lb1.Delete(3) + if lb1.Len() > 3 || *macCrashTest { + lb1.Delete(3) } - if handler.lb2.Len() > 4 { - handler.lb2.Delete(4) + if lb2.Len() > 4 { + lb2.Delete(4) } - case handler.b3: + case <-b3.Clicked: f := MsgBox - if handler.c.Checked() { + if c.Checked() { f = MsgBoxError } f("List Info", fmt.Sprintf("cb1: %d %q (len %d)\ncb2: %d %q (len %d)\nlb1: %d %q (len %d)\nlb2: %d %q (len %d)", - handler.cb1.SelectedIndex(), handler.cb1.Selection(), handler.cb1.Len(), - handler.cb2.SelectedIndex(), handler.cb2.Selection(), handler.cb2.Len(), - handler.lb1.SelectedIndices(), handler.lb1.Selection(), handler.lb1.Len(), - handler.lb2.SelectedIndices(), handler.lb2.Selection(), handler.lb2.Len())) - case handler.incButton: - handler.prog++ - if handler.prog > 100 { - handler.prog = 100 + cb1.SelectedIndex(), cb1.Selection(), cb1.Len(), + cb2.SelectedIndex(), cb2.Selection(), cb2.Len(), + lb1.SelectedIndices(), lb1.Selection(), lb1.Len(), + lb2.SelectedIndices(), lb2.Selection(), lb2.Len())) + case <-incButton.Clicked: + prog++ + if prog > 100 { + prog = 100 } - handler.pbar.SetProgress(handler.prog) - handler.cb1.Append("append multi 1", "append multi 2") - handler.lb2.Append("append multi 1", "append multi 2") - case handler.decButton: - handler.prog-- - if handler.prog < 0 { - handler.prog = 0 + pbar.SetProgress(prog) + cb1.Append("append multi 1", "append multi 2") + lb2.Append("append multi 1", "append multi 2") + case <-decButton.Clicked: + prog-- + if prog < 0 { + prog = 0 } - handler.pbar.SetProgress(handler.prog) - case handler.indetButton: - handler.pbar.SetProgress(-1) - case handler.invalidButton: - invalidTest(handler.cb1, handler.lb1, nil, nil) - case handler.bmsg: + pbar.SetProgress(prog) + case <-indetButton.Clicked: + pbar.SetProgress(-1) + case <-invalidButton.Clicked: + invalidTest(cb1, lb1, nil, nil) + case <-bmsg.Clicked: MsgBox("Title Only, no parent", "") - handler.w.MsgBox("Title and Text", "parent") - } -// == TODO == -// case CusotmEvent: -// l.SetText("DIALOG") -// case CustomEvent + 1: -// resetl() - } -} - -type dialoghandler struct { - bMsgBox *Button - bMsgBoxError *Button - w *Window - bCenter *Button - send func(Event, interface{}) -} - -// == TODO == -func (handler *dialoghandler) Event(e Event, d interface{}) { - if e == Clicked { - switch d { - case handler.bMsgBox: -// handler.send(CustomEvent, "DIALOG") - handler.w.MsgBox("Message Box", "Dismiss") -// handler.send(CustomEvent, nil) - case handler.bMsgBoxError: -// handler.send(CustomEvent, "DIALOG") - handler.w.MsgBoxError("Message Box", "Dismiss") -// handler.send(CustomEvent, nil) - case handler.bCenter: - handler.w.Center() + MsgBox("Title and Text", "parent") + // dialogs + case <-dialog_bMsgBox.Clicked: + dialog_sret = dialog_win.MsgBox("Message Box", "Dismiss") + l.SetText("DIALOG") + case <-dialog_bMsgBoxError.Clicked: + dialog_sret = dialog_win.MsgBoxError("Message Box", "Dismiss") + l.SetText("DIALOG") + case <-dialog_sret: + dialog_sret = nil + resetl() + case <-centerButton.Clicked: + dialog_win.Center() } } + w.Hide() } func main() { flag.Parse() - go myMain() - err := Go() + err := Go(myMain) if err != nil { panic(err) } } -// TODO move to its own file - // source: https://upload.wikimedia.org/wikipedia/commons/0/06/Regensburg-donaulaende-warp-enhanced_1-320x240.jpg via https://commons.wikimedia.org/wiki/File:Regensburg-donaulaende-warp-enhanced_1-320x240.jpg (thanks Sofi) // converted to png with imagemagick because the JPG was throwing up an error about incomplete Huffman data (TODO) var imagedata = []byte{ diff --git a/test/spacing.go b/test/spacing.go index 610115f..367b0be 100644 --- a/test/spacing.go +++ b/test/spacing.go @@ -41,13 +41,14 @@ func spaceTest() { a2 := NewArea(w, h, ah) a3 := NewArea(w, h, ah) a4 := NewArea(w, h, ah) - win := NewWindow("Stack", 250, 250, nullwinhandler{}) + win := NewWindow("Stack", 250, 250) win.SetSpaced(true) win.Open(f(a1, a2)) - win = NewWindow("Grid", 250, 250, nullwinhandler{}) + win = NewWindow("Grid", 250, 250) win.SetSpaced(true) g := NewGrid(ng, a3, a4) g.SetFilling(0, 0) g.SetStretchy(gsx, gsy) win.Open(g) + select {} } diff --git a/uitask_darwin.go b/uitask_darwin.go index 317cb12..754418c 100644 --- a/uitask_darwin.go +++ b/uitask_darwin.go @@ -4,6 +4,7 @@ package ui import ( "fmt" + "runtime" "unsafe" ) @@ -15,31 +16,32 @@ import "C" var uitask chan func() -func uiinit() error { +func ui(main func()) error { + runtime.LockOSThread() + + uitask = make(chan func()) + err := initCocoa() if err != nil { return err } - // do this at the end in case something goes wrong - uitask = make(chan func()) - return nil -} - -func ui() { // Cocoa must run on the first thread created by the program, so we run our dispatcher on another thread instead go func() { - for { - select { - case f := <-uitask: - C.douitask(appDelegate, unsafe.Pointer(&f)) - case <-Stop: - C.breakMainLoop() - } + for f := range uitask { + C.douitask(appDelegate, unsafe.Pointer(&f)) + } + }() + + go func() { + main() + uitask <- func() { + C.breakMainLoop() } }() C.cocoaMainLoop() + return nil } func initCocoa() (err error) { diff --git a/uitask_unix.go b/uitask_unix.go index a8cabd2..030f096 100644 --- a/uitask_unix.go +++ b/uitask_unix.go @@ -6,6 +6,7 @@ package ui import ( "fmt" + "runtime" ) // #cgo pkg-config: gtk+-3.0 @@ -14,32 +15,19 @@ import "C" var uitask chan func() -func uiinit() error { +func ui(main func()) error { + runtime.LockOSThread() + + uitask = make(chan func()) err := gtk_init() if err != nil { return fmt.Errorf("gtk_init() failed: %v", err) } - // do this only on success, just to be safe - uitask = make(chan func()) - return nil -} - -func ui() { // thanks to tristan and Daniel_S in irc.gimp.net/#gtk // see our_idle_callback in callbacks_unix.go for details go func() { - for { - var f func() - - select { - case f = <-uitask: - // do nothing - case <-Stop: - f = func() { - C.gtk_main_quit() - } - } + for f := range uitask { done := make(chan struct{}) gdk_threads_add_idle(>kIdleOp{ what: f, @@ -50,5 +38,11 @@ func ui() { } }() + go func() { + main() + uitask <- gtk_main_quit + }() + C.gtk_main() + return nil } diff --git a/uitask_windows.go b/uitask_windows.go index ef1c213..1075b5b 100644 --- a/uitask_windows.go +++ b/uitask_windows.go @@ -4,6 +4,7 @@ package ui import ( "fmt" + "runtime" "syscall" "unsafe" ) @@ -45,51 +46,47 @@ var ( _postMessage = user32.NewProc("PostMessageW") ) -var msghwnd _HWND +func ui(main func()) error { + runtime.LockOSThread() -func uiinit() error { + uitask = make(chan interface{}) err := doWindowsInit() if err != nil { return fmt.Errorf("error doing general Windows initialization: %v", err) } - msghwnd, err = makeMessageHandler() + hwnd, err := makeMessageHandler() if err != nil { return fmt.Errorf("error making invisible window for handling events: %v", err) } - // do this only on success just to be safe - uitask = make(chan interface{}) - return nil -} - -func ui() { go func() { - for { - select { - case m := <-uitask: - r1, _, err := _postMessage.Call( - uintptr(msghwnd), - msgRequested, - uintptr(0), + for m := range uitask { + r1, _, err := _postMessage.Call( + uintptr(hwnd), + msgRequested, + uintptr(0), uintptr(unsafe.Pointer(&m))) - if r1 == 0 { // failure - panic("error sending message to message loop to call function: " + err.Error()) - } - case <-Stop: - r1, _, err := _postMessage.Call( - uintptr(msghwnd), - msgQuit, - uintptr(0), - uintptr(0)) - if r1 == 0 { // failure - panic("error sending quit message to message loop: " + err.Error()) - } + if r1 == 0 { // failure + panic("error sending message to message loop to call function: " + err.Error()) } } }() + go func() { + main() + r1, _, err := _postMessage.Call( + uintptr(hwnd), + msgQuit, + uintptr(0), + uintptr(0)) + if r1 == 0 { // failure + panic("error sending quit message to message loop: " + err.Error()) + } + }() + msgloop() + return nil } var ( diff --git a/window.go b/window.go index 57283f2..8de638a 100644 --- a/window.go +++ b/window.go @@ -4,10 +4,17 @@ package ui import ( "fmt" + "sync" ) // Window represents an on-screen window. type Window struct { + // Closing gets a message when the user clicks the window's close button. + // You cannot change it once the Window has been created. + // If you do not respond to this signal, nothing will happen; regardless of whether you handle the signal or not, the window will not be closed. + Closing chan struct{} + + lock sync.Mutex created bool sysData *sysData initTitle string @@ -15,44 +22,24 @@ type Window struct { initHeight int shownOnce bool spaced bool - handler WindowHandler } -// WindowHandler represents an event handler for a Window and all its child Controls. -// -// When an event on a Window or one of its child Controls comes in, the respect Window's handler's Event() method is called. The method call occurs on the main thread, and thus any call to any package ui method can be performed. -// -// Each Event() call takes two parameters: the event ID and a data argument. For most events, the data argument is a pointer to the Control that triggered the event. -// -// For Closing, the data argument is a pointer to a bool variable. If, after returning from Event, the value of this variable is true, the Window is closed; if false, the Window is not closed. The default value on entry to the function is [TODO]. -// -// For any event >= CustomEvent, the data argument is the argument passed to the Window's SendEvent() method. -type WindowHandler interface { - Event(e Event, data interface{}) -} - -// Event represents an event; see WindowHandler for details. -// All event values >= CustomEvent are available for program use. -type Event int -const ( - Closing Event = iota // Window close - Clicked // Button click - CustomEvent = 5000 // very high number; higher than the package would ever need, anyway -) - // NewWindow allocates a new Window with the given title and size. The window is not created until a call to Create() or Open(). -func NewWindow(title string, width int, height int, handler WindowHandler) *Window { +func NewWindow(title string, width int, height int) *Window { return &Window{ sysData: mksysdata(c_window), initTitle: title, initWidth: width, initHeight: height, - handler: handler, + Closing: newEvent(), } } // SetTitle sets the window's title. func (w *Window) SetTitle(title string) { + w.lock.Lock() + defer w.lock.Unlock() + if w.created { w.sysData.setText(title) return @@ -62,6 +49,9 @@ func (w *Window) SetTitle(title string) { // SetSize sets the window's size. func (w *Window) SetSize(width int, height int) (err error) { + w.lock.Lock() + defer w.lock.Unlock() + if w.created { err := w.sysData.setWindowSize(width, height) if err != nil { @@ -80,6 +70,9 @@ func (w *Window) SetSize(width int, height int) (err error) { // This property is visible recursively throughout the widget hierarchy of the Window. // This property cannot be set after the Window has been created. func (w *Window) SetSpaced(spaced bool) { + w.lock.Lock() + defer w.lock.Unlock() + if w.created { panic(fmt.Errorf("Window.SetSpaced() called after window created")) } @@ -88,49 +81,44 @@ func (w *Window) SetSpaced(spaced bool) { // Open creates the Window with Create and then shows the Window with Show. As with Create, you cannot call Open more than once per window. func (w *Window) Open(control Control) { - w.create(control, true) + w.Create(control) + w.Show() } // Create creates the Window, setting its control to the given control. It does not show the window. This can only be called once per window, and finalizes all initialization of the control. func (w *Window) Create(control Control) { - w.create(control, false) -} + w.lock.Lock() + defer w.lock.Unlock() -func (w *Window) create(control Control, show bool) { - touitask(func() { - if w.created { - panic("window already open") - } - w.sysData.spaced = w.spaced - w.sysData.winhandler = w.handler - w.sysData.close = func(b *bool) { - w.sysData.winhandler.Event(Closing, b) - } - err := w.sysData.make(nil) + if w.created { + panic("window already open") + } + w.sysData.spaced = w.spaced + w.sysData.event = w.Closing + err := w.sysData.make(nil) + if err != nil { + panic(fmt.Errorf("error opening window: %v", err)) + } + if control != nil { + w.sysData.allocate = control.allocate + err = control.make(w.sysData) if err != nil { - panic(fmt.Errorf("error opening window: %v", err)) + panic(fmt.Errorf("error adding window's control: %v", err)) } - if control != nil { - w.sysData.allocate = control.allocate - err = control.make(w.sysData) - if err != nil { - panic(fmt.Errorf("error adding window's control: %v", err)) - } - } - err = w.sysData.setWindowSize(w.initWidth, w.initHeight) - if err != nil { - panic(fmt.Errorf("error setting window size (in Window.Open()): %v", err)) - } - w.sysData.setText(w.initTitle) - w.created = true - if show { - w.Show() - } - }) + } + err = w.sysData.setWindowSize(w.initWidth, w.initHeight) + if err != nil { + panic(fmt.Errorf("error setting window size (in Window.Open()): %v", err)) + } + w.sysData.setText(w.initTitle) + w.created = true } // Show shows the window. func (w *Window) Show() { + w.lock.Lock() + defer w.lock.Unlock() + if !w.shownOnce { w.shownOnce = true err := w.sysData.firstShow() @@ -144,6 +132,9 @@ func (w *Window) Show() { // Hide hides the window. func (w *Window) Hide() { + w.lock.Lock() + defer w.lock.Unlock() + w.sysData.hide() } @@ -151,6 +142,9 @@ func (w *Window) Hide() { // The concept of "screen" in the case of a multi-monitor setup is implementation-defined. // It presently panics if the Window has not been created. func (w *Window) Center() { + w.lock.Lock() + defer w.lock.Unlock() + if !w.created { panic("attempt to center Window before it has been created") } diff --git a/zconstants_windows_386.go b/zconstants_windows_386.go index cdf0b4e..f19d39a 100644 --- a/zconstants_windows_386.go +++ b/zconstants_windows_386.go @@ -35,7 +35,6 @@ const _FALSE = 0 const _GWLP_USERDATA = -21 const _GWL_STYLE = -16 const _ICC_PROGRESS_CLASS = 32 -const _IDOK = 1 const _LBS_EXTENDEDSEL = 2048 const _LBS_NOINTEGRALHEIGHT = 256 const _LBS_NOTIFY = 1 diff --git a/zconstants_windows_amd64.go b/zconstants_windows_amd64.go index 256de01..ec55813 100644 --- a/zconstants_windows_amd64.go +++ b/zconstants_windows_amd64.go @@ -35,7 +35,6 @@ const _FALSE = 0 const _GWLP_USERDATA = -21 const _GWL_STYLE = -16 const _ICC_PROGRESS_CLASS = 32 -const _IDOK = 1 const _LBS_EXTENDEDSEL = 2048 const _LBS_NOINTEGRALHEIGHT = 256 const _LBS_NOTIFY = 1