summaryrefslogtreecommitdiffstatshomepage
path: root/declarative/radiobuttongroup.go
blob: ff0a2cdd63ca9b5def80c10bc684f2390e034731 (plain) (blame)
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
// Copyright 2013 The Walk Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build windows

package declarative

import (
	"bytes"
	"errors"
)

import (
	"github.com/lxn/walk"
)

type RadioButtonGroup struct {
	Buttons    []RadioButton
	DataMember string
	Optional   bool
}

func (rbg RadioButtonGroup) Create(builder *Builder) error {
	if len(rbg.Buttons) == 0 {
		return nil
	}

	var first *walk.RadioButton

	for _, rb := range rbg.Buttons {
		if first == nil {
			if rb.AssignTo == nil {
				rb.AssignTo = &first
			}
		}

		if err := rb.Create(builder); err != nil {
			return err
		}

		if first == nil {
			first = *rb.AssignTo
		}
	}

	parent := builder.Parent()

	builder.Defer(func() error {
		group := first.Group()

		validator := newRadioButtonGroupValidator(group, parent)

		for _, rb := range group.Buttons() {
			prop := rb.AsWindowBase().Property("CheckedValue")

			if err := prop.SetSource(rbg.DataMember); err != nil {
				return err
			}
			if err := prop.SetValidator(validator); err != nil {
				return err
			}
		}

		return nil
	})

	return nil
}

type radioButtonGroupValidator struct {
	group *walk.RadioButtonGroup
	err   error
}

func newRadioButtonGroupValidator(group *walk.RadioButtonGroup, parent walk.Container) *radioButtonGroupValidator {
	b := new(bytes.Buffer)

	if gb, ok := parent.(*walk.GroupBox); ok {
		b.WriteString(gb.Title())
	} else {
		for i, rb := range group.Buttons() {
			if i > 0 {
				b.WriteString(", ")
			}

			b.WriteString(rb.Text())
		}
	}

	b.WriteString(": ")

	b.WriteString(tr("A selection is required.", "walk"))

	return &radioButtonGroupValidator{group: group, err: errors.New(b.String())}
}

func (rbgv *radioButtonGroupValidator) Validate(v interface{}) error {
	if rbgv.group.CheckedButton() == nil {
		return rbgv.err
	}

	return nil
}