summaryrefslogtreecommitdiff
path: root/new/windows/button.c
blob: fd7afa3d751d4a948240308adacf941ab4fc8627 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// 7 april 2015
#include "uipriv_windows.h"

struct button {
	uiButton b;
	void (*onClicked)(uiButton *, void *);
	void *onClickedData;
};

static BOOL onWM_COMMAND(uiControl *c, WORD code, LRESULT *lResult)
{
	struct button *b = (struct button *) c;

	if (code != BN_CLICKED)
		return FALSE;
	(*(b->onClicked))(uiButton(b), b->onClickedData);
	*lResult = 0;
	return TRUE;
}

static BOOL onWM_NOTIFY(uiControl *c, NMHDR *nm, LRESULT *lResult)
{
	return FALSE;
}

static void onWM_DESTROY(uiControl *c)
{
	struct button *b = (struct button *) c;

	uiFree(b);
}

// from http://msdn.microsoft.com/en-us/library/windows/desktop/dn742486.aspx#sizingandspacing
#define buttonHeight 14

static void preferredSize(uiControl *c, uiSizing *d, intmax_t *width, intmax_t *height)
{
	HWND hwnd;
	SIZE size;

	hwnd = uiControlHWND(c);

	// try the comctl32 version 6 way
	size.cx = 0;		// explicitly ask for ideal size
	size.cy = 0;
	if (SendMessageW(hwnd, BCM_GETIDEALSIZE, 0, (LPARAM) (&size)) != FALSE) {
		*width = size.cx;
		*height = size.cy;
		return;
	}

	// that didn't work; fall back to using Microsoft's metrics
	// Microsoft says to use a fixed width for all buttons; this isn't good enough
	// use the text width instead, with some edge padding
	*width = uiWindowsWindowTextWidth(hwnd) + (2 * GetSystemMetrics(SM_CXEDGE));
	*height = uiDlgUnitsToY(buttonHeight, d->sys->baseY);
}

static void defaultOnClicked(uiButton *b, void *data)
{
	// do nothing
}

static char *getText(uiButton *b)
{
	return uiWindowsControlText(uiControl(b));
}

static void setText(uiButton *b, const char *text)
{
	uiWindowsControlSetText(uiControl(b), text);
}

static void setOnClicked(uiButton *bb, void (*f)(uiButton *, void *), void *data)
{
	struct button *b = (struct button *) bb;

	b->onClicked = f;
	b->onClickedData = data;
}

uiButton *uiNewButton(const char *text)
{
	struct button *b;
	uiWindowsNewControlParams p;
	WCHAR *wtext;

	b = uiNew(struct button);

	p.dwExStyle = 0;
	p.lpClassName = L"button";
	wtext = toUTF16(text);
	p.lpWindowName = wtext;
	p.dwStyle = BS_PUSHBUTTON | WS_TABSTOP;
	p.hInstance = hInstance;
	p.useStandardControlFont = TRUE;
	p.onWM_COMMAND = onWM_COMMAND;
	p.onWM_NOTIFY = onWM_NOTIFY;
	p.onWM_DESTROY = onWM_DESTROY;
	uiWindowsNewControl(uiControl(b), &p);
	uiFree(wtext);

	b->onClicked = defaultOnClicked;

	uiControl(b)->PreferredSize = preferredSize;

	uiButton(b)->Text = getText;
	uiButton(b)->SetText = setText;
	uiButton(b)->OnClicked = setOnClicked;

	return uiButton(b);
}