64 Commits

Author SHA1 Message Date
611705fa0d Change icon on dropdown 2024-08-16 18:01:08 -04:00
16645eeeda Update Tomo API 2024-08-16 18:01:01 -04:00
3219cb712c Remove TODO input value in swatch.go 2024-08-16 16:28:47 -04:00
7d14a25482 Fixed ctrl+key combos on TextInput 2024-08-16 16:17:11 -04:00
e4857da22d Functions to check for common buttons/keys 2024-08-16 16:15:52 -04:00
114cbb346d Keyboard controls activate on key down instead of key up 2024-08-16 15:31:48 -04:00
43ec7a0311 Swatch accepts hex input 2024-08-16 15:17:44 -04:00
3d28c8fea1 Add functions for parsing/formatting NRGBA values 2024-08-16 15:17:15 -04:00
669c638fad Fix transparency in color pickers again 2024-08-16 13:50:22 -04:00
2fe433991d Rename ColorPicker to HSVAColorPicker 2024-08-15 17:05:19 -04:00
acec0f6222 Fix HSV.RGBA sector overflow 2024-08-15 16:51:36 -04:00
0865c28965 Update color picker code in response to HSV color changes 2024-08-15 16:42:31 -04:00
2546c338ad Separate HSVA color into HSV, HSVA, fix alpha premultiplication 2024-08-15 16:41:22 -04:00
b3e7178176 Bring TextInput in line with all the other inputs 2024-08-15 13:17:43 -04:00
080e4511f2 Add Dropdown 2024-08-14 19:06:41 -04:00
f1ac74dcbc Fix TabbedContainer not setting tags correctly 2024-08-14 11:45:30 -04:00
ce0bc5be3b Add MenuHeading 2024-08-14 11:45:10 -04:00
eb0bf58961 Improvements to menus
Major progress on #4
2024-08-14 11:44:47 -04:00
8068036219 Fix icon sizes 2024-08-12 22:06:06 -04:00
5a32b06cef Various improvements to Icon, MimeIcon 2024-08-11 22:36:10 -04:00
fe50f5783b Upgrade Tomo API 2024-08-11 22:35:50 -04:00
73a5fab0bc Icon sets its minimum size properly 2024-08-11 12:20:23 -04:00
61addc051b Button sets an icon tag 2024-08-11 12:20:12 -04:00
7e275cc70e Update Tomo API 2024-08-10 21:44:33 -04:00
9856cd327f Split MimeIcon out from Icon 2024-08-10 21:44:03 -04:00
572e0c49af LabelCheckbox sets its label as not selectable 2024-07-29 01:50:00 -04:00
e0f4ecb509 Update Tomo API to v0.41.1 2024-07-27 15:04:41 -04:00
fc51ffe33c Fix flow layout 2024-07-27 14:41:46 -04:00
987f4bfc4a Remove random semicolons 2024-07-27 02:17:41 -04:00
b883542f3b Add .editorconfig 2024-07-27 02:10:00 -04:00
c8d33a0ef4 Fix keys for Scrollbar 2024-07-27 00:54:40 -04:00
9fa764c7b9 ScrollContainer can step scroll with normal up/down 2024-07-27 00:35:17 -04:00
84ab0895f8 Fix TextView scrolling 2024-07-27 00:19:53 -04:00
b9c77fd5f7 ScrollContainer properly responds to pgup/down 2024-07-27 00:19:31 -04:00
2722d19ecd Scrollbars accept both directions of scroll 2024-07-26 21:01:18 -04:00
4fc44c11e8 Label and Heading are now selectable 2024-07-26 21:00:53 -04:00
0cdb116ec1 TextInput no longer captures scroll with a zero X 2024-07-26 18:58:16 -04:00
6ea1679112 Offload selection manipulation of TextInput to backend 2024-07-26 18:49:54 -04:00
b87f32eac9 TextInput scrolls in the proper direction 2024-07-26 18:11:02 -04:00
793526238a Scrollbar drags on mouse motion 2024-07-26 18:10:48 -04:00
884148f006 Fix ScrollContainer layout again 2024-07-26 17:56:29 -04:00
3e382da688 Fix ScrollContainer layout 2024-07-26 17:54:32 -04:00
18b8898644 Fix dialog alignment 2024-07-26 00:34:05 -04:00
85fbe9c996 Update code for objects 2024-07-25 12:58:38 -04:00
25a59d888c Update Tomo API to v0.41.0 2024-07-25 12:55:03 -04:00
6ca6771fc6 Update code for layouts, objects 2024-07-21 11:48:28 -04:00
9077015db6 Update Tomo API 2024-07-21 11:48:06 -04:00
1125d98b3d Change OnEnter to OnConfirm
Full remediation of #6
2024-06-27 14:09:58 -04:00
638fc61d83 Make value getters/setters more consistent
See #6
2024-06-27 14:01:14 -04:00
d0ee6c432c Add OnEnter to Swatch and ColorPicker 2024-06-26 11:20:53 -04:00
b9f980e7fd Fix doc comment on MenuItem 2024-06-25 02:33:36 -04:00
b7d1a0abdd Add OnEnter for Slider 2024-06-25 02:33:13 -04:00
a38cee8437 Fix RGBAToHSVA 2024-06-25 02:32:00 -04:00
48bfa05452 Color editing popups use swatch label for title 2024-06-22 18:48:54 -04:00
e8a3a376ea Introduce new layouts.Grid construct 2024-06-22 18:44:26 -04:00
ae1e62c1f2 Add swatch 2024-06-22 15:44:37 -04:00
0b7e5392f4 Add color picker 2024-06-22 15:44:24 -04:00
1efb946953 Fix issues with grid layout 2024-06-22 15:38:52 -04:00
1e8df2392d Add tabs 2024-06-22 15:38:14 -04:00
83dca60257 Fix checkboxes not initializing to desired value 2024-06-22 15:37:52 -04:00
5b60717b8f Add an HSVA color implementation 2024-06-22 15:37:20 -04:00
d01d39569b Sliders work properly when initialized to 0.0 2024-06-20 17:48:41 -04:00
55637e36db Lables come vertically aligned to the middle 2024-06-20 17:47:51 -04:00
e62afcd667 Fix calendar prev/forward month buttons 2024-06-19 00:38:54 -04:00
33 changed files with 1808 additions and 639 deletions

12
.editorconfig Normal file
View File

@@ -0,0 +1,12 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
indent_style = tab
indent_size = 8
charset = utf-8
[*.md]
indent_style = space
indent_size = 2

View File

@@ -28,17 +28,15 @@ func NewButton (text string) *Button {
ContainerBox: tomo.NewContainerBox(), ContainerBox: tomo.NewContainerBox(),
label: NewLabel(text), label: NewLabel(text),
} }
box.SetRole(tomo.R("objects", "Button", "")) box.SetRole(tomo.R("objects", "Button"))
box.label.SetAlign(tomo.AlignMiddle, tomo.AlignMiddle) box.label.SetAttr(tomo.AAlign(tomo.AlignMiddle, tomo.AlignMiddle))
box.SetLayout(buttonLayout) box.SetAttr(tomo.ALayout(buttonLayout))
box.SetText(text) box.SetText(text)
box.CaptureDND(true) box.SetInputMask(true)
box.CaptureMouse(true) box.OnButtonDown(box.handleButtonDown)
box.CaptureScroll(true) box.OnButtonUp(box.handleButtonUp)
box.CaptureKeyboard(true) box.OnKeyDown(box.handleKeyDown)
box.OnMouseUp(box.handleMouseUp)
box.OnKeyUp(box.handleKeyUp) box.OnKeyUp(box.handleKeyUp)
box.SetFocusable(true) box.SetFocusable(true)
return box return box
@@ -71,6 +69,7 @@ func (this *Button) SetIcon (id tomo.Icon) {
if this.icon != nil { if this.icon != nil {
this.Insert(this.icon, this.label) this.Insert(this.icon, this.label)
} }
this.SetTag("icon", this.icon != nil)
this.applyLayout() this.applyLayout()
} }
@@ -81,22 +80,34 @@ func (this *Button) OnClick (callback func ()) event.Cookie {
func (this *Button) applyLayout () { func (this *Button) applyLayout () {
if this.labelActive && this.icon == nil { if this.labelActive && this.icon == nil {
this.SetLayout(buttonLayout) this.SetAttr(tomo.ALayout(buttonLayout))
} else if !this.labelActive && this.icon != nil { } else if !this.labelActive && this.icon != nil {
this.SetLayout(iconButtonLayout) this.SetAttr(tomo.ALayout(iconButtonLayout))
} else { } else {
this.SetLayout(bothButtonLayout) this.SetAttr(tomo.ALayout(bothButtonLayout))
} }
} }
func (this *Button) handleKeyUp (key input.Key, numberPad bool) { func (this *Button) handleKeyDown (key input.Key, numberPad bool) bool {
if key != input.KeyEnter && key != input.Key(' ') { return } if !isClickingKey(key) { return false }
this.on.click.Broadcast() this.on.click.Broadcast()
return true
} }
func (this *Button) handleMouseUp (button input.Button) { func (this *Button) handleKeyUp (key input.Key, numberPad bool) bool {
if button != input.ButtonLeft { return } if !isClickingKey(key) { return false }
if this.MousePosition().In(this.Bounds()) { return true
}
func (this *Button) handleButtonDown (button input.Button) bool {
if !isClickingButton(button) { return false }
return true
}
func (this *Button) handleButtonUp (button input.Button) bool {
if !isClickingButton(button) { return false }
if this.Window().MousePosition().In(this.Bounds()) {
this.on.click.Broadcast() this.on.click.Broadcast()
} }
return true
} }

View File

@@ -16,7 +16,7 @@ type Calendar struct {
monthLabel *Label monthLabel *Label
on struct { on struct {
edit event.FuncBroadcaster valueChange event.FuncBroadcaster
} }
} }
@@ -26,61 +26,64 @@ func NewCalendar (tm time.Time) *Calendar {
ContainerBox: tomo.NewContainerBox(), ContainerBox: tomo.NewContainerBox(),
time: tm, time: tm,
} }
calendar.SetRole(tomo.R("objects", "Calendar", "")) calendar.SetRole(tomo.R("objects", "Calendar"))
calendar.SetLayout(layouts.ContractVertical) calendar.SetAttr(tomo.ALayout(layouts.ContractVertical))
prevButton := NewButton("") prevButton := NewButton("")
prevButton.SetIcon(tomo.IconGoPrevious) prevButton.SetIcon(tomo.IconGoPrevious)
prevButton.OnClick(func () { prevButton.OnClick(func () {
calendar.prevMonth() calendar.prevMonth()
calendar.on.edit.Broadcast() calendar.on.valueChange.Broadcast()
}) })
nextButton := NewButton("") nextButton := NewButton("")
nextButton.SetIcon(tomo.IconGoNext) nextButton.SetIcon(tomo.IconGoNext)
nextButton.OnClick(func () { nextButton.OnClick(func () {
calendar.nextMonth() calendar.nextMonth()
calendar.on.edit.Broadcast() calendar.on.valueChange.Broadcast()
}) })
calendar.monthLabel = NewLabel("") calendar.monthLabel = NewLabel("")
calendar.monthLabel.SetAlign(tomo.AlignMiddle, tomo.AlignMiddle) calendar.monthLabel.SetAttr(tomo.AAlign(tomo.AlignMiddle, tomo.AlignMiddle))
calendar.grid = tomo.NewContainerBox() calendar.grid = tomo.NewContainerBox()
calendar.grid.SetRole(tomo.R("objects", "CalendarGrid", "")) calendar.grid.SetRole(tomo.R("objects", "CalendarGrid"))
calendar.grid.SetLayout(layouts.NewGrid ( calendar.grid.SetAttr(tomo.ALayout(layouts.NewGrid (
[]bool { true, true, true, true, true, true, true }, true, true, true, true, true, true, true)()))
[]bool { }))
calendar.Add(NewInnerContainer ( calendar.Add(NewInnerContainer (
layouts.Row { false, true, false }, layouts.Row { false, true, false },
prevButton, calendar.monthLabel, nextButton)) prevButton, calendar.monthLabel, nextButton))
calendar.Add(calendar.grid) calendar.Add(calendar.grid)
calendar.OnScroll(calendar.handleScroll) calendar.OnScroll(calendar.handleScroll)
calendar.CaptureScroll(true)
calendar.refresh() calendar.refresh()
return calendar return calendar
} }
// SetTime sets the date the calendar will display. // Value returns the time this calendar is displaying.
func (this *Calendar) SetTime (tm time.Time) { func (this *Calendar) Value () time.Time {
return this.time
}
// SetValue sets the date the calendar will display.
func (this *Calendar) SetValue (tm time.Time) {
if this.time == tm { return } if this.time == tm { return }
this.time = tm this.time = tm
this.refresh() this.refresh()
} }
// OnEdit sets a function to be called when the user changes the date on the // OnValueChange sets a function to be called when the user changes the date on
// calendar. // the calendar.
func (this *Calendar) OnEdit (callback func ()) { func (this *Calendar) OnValueChange (callback func ()) {
this.on.edit.Connect(callback) this.on.valueChange.Connect(callback)
} }
func (this *Calendar) prevMonth () { func (this *Calendar) prevMonth () {
this.time = firstOfMonth(this.time.Add(24 * time.Hour * 40)) this.time = firstOfMonth(this.time.Add(24 * time.Hour * -20))
this.refresh() this.refresh()
} }
func (this *Calendar) nextMonth () { func (this *Calendar) nextMonth () {
this.time = firstOfMonth(this.time.Add(24 * time.Hour * -20)) this.time = firstOfMonth(this.time.Add(24 * time.Hour * 40))
this.refresh() this.refresh()
} }
@@ -94,9 +97,9 @@ func (this *Calendar) refresh () {
this.grid.Clear() this.grid.Clear()
for _, day := range weekdayAbbreviations { for _, day := range weekdayAbbreviations {
dayLabel := tomo.NewTextBox() dayLabel := tomo.NewTextBox()
dayLabel.SetRole(tomo.R("objects", "CalendarWeekdayHeader", "")) dayLabel.SetRole(tomo.R("objects", "CalendarWeekdayHeader"))
dayLabel.SetText(day) dayLabel.SetText(day)
dayLabel.SetAlign(tomo.AlignMiddle, tomo.AlignMiddle) dayLabel.SetAttr(tomo.AAlign(tomo.AlignMiddle, tomo.AlignMiddle))
this.grid.Add(dayLabel) this.grid.Add(dayLabel)
} }
@@ -112,9 +115,11 @@ func (this *Calendar) refresh () {
day := tomo.NewTextBox() day := tomo.NewTextBox()
day.SetText(fmt.Sprint(dayIter)) day.SetText(fmt.Sprint(dayIter))
if weekday == 1 || weekday == 0 { if weekday == 1 || weekday == 0 {
day.SetRole(tomo.R("objects", "CalendarDay", "weekend")) day.SetRole(tomo.R("objects", "CalendarDay"))
day.SetTag("weekend", true)
} else { } else {
day.SetRole(tomo.R("objects", "CalendarDay", "weekday")) day.SetRole(tomo.R("objects", "CalendarDay"))
day.SetTag("weekday", true)
} }
this.grid.Add(day) this.grid.Add(day)
} else { } else {
@@ -123,12 +128,13 @@ func (this *Calendar) refresh () {
} }
} }
func (this *Calendar) handleScroll (x, y float64) { func (this *Calendar) handleScroll (x, y float64) bool {
if y < 0 { if y < 0 {
this.nextMonth()
} else {
this.prevMonth() this.prevMonth()
} else {
this.nextMonth()
} }
return true
} }
func firstOfMonth (tm time.Time) time.Time { func firstOfMonth (tm time.Time) time.Time {

View File

@@ -18,49 +18,61 @@ func NewCheckbox (value bool) *Checkbox {
box := &Checkbox { box := &Checkbox {
Box: tomo.NewBox(), Box: tomo.NewBox(),
} }
box.SetRole(tomo.R("objects", "Checkbox", "")) box.SetRole(tomo.R("objects", "Checkbox"))
box.SetValue(false) box.SetValue(value)
box.OnMouseUp(box.handleMouseUp) box.OnButtonDown(box.handleButtonDown)
box.OnButtonUp(box.handleButtonUp)
box.OnKeyDown(box.handleKeyDown)
box.OnKeyUp(box.handleKeyUp) box.OnKeyUp(box.handleKeyUp)
box.SetFocusable(true) box.SetFocusable(true)
return box return box
} }
// SetValue sets the value of the checkbox.
func (this *Checkbox) SetValue (value bool) {
this.value = value
if this.value {
this.SetTextureCenter(tomo.IconCheckboxChecked.Texture(tomo.IconSizeSmall))
} else {
this.SetTextureCenter(tomo.IconCheckboxUnchecked.Texture(tomo.IconSizeSmall))
}
}
// Toggle toggles the value of the checkbox between true and false.
func (this *Checkbox) Toggle () {
this.SetValue(!this.Value())
}
// Value returns the value of the checkbox. // Value returns the value of the checkbox.
func (this *Checkbox) Value () bool { func (this *Checkbox) Value () bool {
return this.value return this.value
} }
// OnValueChange specifies a function to be called when the checkbox's value // SetValue sets the value of the checkbox.
// changes. func (this *Checkbox) SetValue (value bool) {
this.value = value
// the theme shall decide what checked and unchecked states look like
this.SetTag("checked", value)
this.SetTag("unchecked", !value)
}
// Toggle toggles the value of the checkbox between true and false.
func (this *Checkbox) Toggle () {
this.SetValue(!this.Value())
}
// OnValueChange specifies a function to be called when the user checks or
// unchecks the checkbox.
func (this *Checkbox) OnValueChange (callback func ()) event.Cookie { func (this *Checkbox) OnValueChange (callback func ()) event.Cookie {
return this.on.valueChange.Connect(callback) return this.on.valueChange.Connect(callback)
} }
func (this *Checkbox) handleKeyUp (key input.Key, numberPad bool) { func (this *Checkbox) handleKeyDown (key input.Key, numberPad bool) bool {
if key != input.KeyEnter && key != input.Key(' ') { return } if !isClickingKey(key) { return false }
this.Toggle() this.Toggle()
return true
} }
func (this *Checkbox) handleMouseUp (button input.Button) { func (this *Checkbox) handleKeyUp (key input.Key, numberPad bool) bool {
if button != input.ButtonLeft { return } if !isClickingKey(key) { return false}
if this.MousePosition().In(this.Bounds()) { return true
}
func (this *Checkbox) handleButtonDown (button input.Button) bool {
if !isClickingButton(button) { return false }
return true
}
func (this *Checkbox) handleButtonUp (button input.Button) bool {
if !isClickingButton(button) { return false }
if this.Window().MousePosition().In(this.Bounds()) {
this.Toggle() this.Toggle()
} }
return true
} }

160
colorpicker.go Normal file
View File

@@ -0,0 +1,160 @@
package objects
import "image/color"
import "git.tebibyte.media/tomo/tomo"
import "git.tebibyte.media/tomo/tomo/input"
import "git.tebibyte.media/tomo/tomo/event"
import "git.tebibyte.media/tomo/tomo/canvas"
import "git.tebibyte.media/tomo/objects/layouts"
import "git.tebibyte.media/tomo/objects/internal"
// HSVAColorPicker allows the user to pick a color by controlling its HSVA
// parameters.
type HSVAColorPicker struct {
tomo.ContainerBox
value internal.HSVA
pickerMap *hsvaColorPickerMap
hueSlider *Slider
alphaSlider *Slider
on struct {
valueChange event.FuncBroadcaster
}
}
// NewHSVAColorPicker creates a new color picker with the specified color.
func NewHSVAColorPicker (value color.Color) *HSVAColorPicker {
picker := &HSVAColorPicker {
ContainerBox: tomo.NewContainerBox(),
}
picker.SetRole(tomo.R("objects", "ColorPicker"))
picker.SetAttr(tomo.ALayout(layouts.Row { true, false, false }))
picker.pickerMap = newHsvaColorPickerMap(picker)
picker.Add(picker.pickerMap)
picker.hueSlider = NewVerticalSlider(0.0)
picker.Add(picker.hueSlider)
picker.hueSlider.OnValueChange(func () {
picker.value.H = picker.hueSlider.Value()
picker.on.valueChange.Broadcast()
picker.pickerMap.Invalidate()
})
picker.alphaSlider = NewVerticalSlider(0.0)
picker.Add(picker.alphaSlider)
picker.alphaSlider.OnValueChange(func () {
picker.value.A = uint16(picker.alphaSlider.Value() * 0xFFFF)
picker.on.valueChange.Broadcast()
picker.pickerMap.Invalidate()
})
if value == nil { value = color.Transparent }
picker.SetValue(value)
return picker
}
// Value returns the color of the picker.
func (this *HSVAColorPicker) Value () color.Color {
return this.value
}
// SetValue sets the color of the picker.
func (this *HSVAColorPicker) SetValue (value color.Color) {
if value == nil { value = color.Transparent }
this.value = internal.HSVAModel.Convert(value).(internal.HSVA)
this.hueSlider.SetValue(this.value.H)
this.alphaSlider.SetValue(float64(this.value.A) / 0xFFFF)
this.pickerMap.Invalidate()
}
// OnValueChange specifies a function to be called when the user changes the
// swatch's color.
func (this *HSVAColorPicker) OnValueChange (callback func ()) event.Cookie {
return this.on.valueChange.Connect(callback)
}
// RGBA satisfies the color.Color interface
func (this *HSVAColorPicker) RGBA () (r, g, b, a uint32) {
return this.value.RGBA()
}
type hsvaColorPickerMap struct {
tomo.CanvasBox
dragging bool
parent *HSVAColorPicker
}
func newHsvaColorPickerMap (parent *HSVAColorPicker) *hsvaColorPickerMap {
picker := &hsvaColorPickerMap {
CanvasBox: tomo.NewCanvasBox(),
parent: parent,
}
picker.SetDrawer(picker)
picker.SetRole(tomo.R("objects", "ColorPickerMap"))
picker.OnButtonUp(picker.handleButtonUp)
picker.OnButtonDown(picker.handleButtonDown)
picker.OnMouseMove(picker.handleMouseMove)
return picker
}
func (this *hsvaColorPickerMap) handleButtonDown (button input.Button) bool {
if button != input.ButtonLeft { return false }
this.dragging = true
this.drag()
return true
}
func (this *hsvaColorPickerMap) handleButtonUp (button input.Button) bool {
if button != input.ButtonLeft { return false }
this.dragging = false
return true
}
func (this *hsvaColorPickerMap) handleMouseMove () bool {
if !this.dragging { return false }
this.drag()
return true
}
func (this *hsvaColorPickerMap) drag () {
pointer := this.Window().MousePosition()
bounds := this.InnerBounds()
this.parent.value.S = float64(pointer.X - bounds.Min.X) / float64(bounds.Dx())
this.parent.value.V = 1 - float64(pointer.Y - bounds.Min.Y) / float64(bounds.Dy())
this.parent.value = this.parent.value.Canon()
this.parent.on.valueChange.Broadcast()
this.Invalidate()
}
func (this *hsvaColorPickerMap) Draw (can canvas.Canvas) {
bounds := can.Bounds()
for y := bounds.Min.Y; y < bounds.Max.Y; y ++ {
for x := bounds.Min.X; x < bounds.Max.X; x ++ {
xx := x - bounds.Min.X
yy := y - bounds.Min.Y
pixel := internal.HSVA {
H: this.parent.value.H,
S: float64(xx) / float64(bounds.Dx()),
V: 1 - float64(yy) / float64(bounds.Dy()),
A: 0xFFFF,
}
sPos := int( this.parent.value.S * float64(bounds.Dx()))
vPos := int((1 - this.parent.value.V) * float64(bounds.Dy()))
sDist := sPos - xx
vDist := vPos - yy
crosshair :=
(sDist == 0 || vDist == 0) &&
-8 < sDist && sDist < 8 &&
-8 < vDist && vDist < 8
if crosshair {
pixel.S = 1 - pixel.S
pixel.V = 1 - pixel.V
}
can.Set(x, y, pixel)
}}
}

View File

@@ -15,7 +15,7 @@ func newContainer (layout tomo.Layout, children ...tomo.Object) *Container {
this := &Container { this := &Container {
ContainerBox: tomo.NewContainerBox(), ContainerBox: tomo.NewContainerBox(),
} }
this.SetLayout(layout) this.SetAttr(tomo.ALayout(layout))
for _, child := range children { for _, child := range children {
this.Add(child) this.Add(child)
} }
@@ -27,7 +27,8 @@ func newContainer (layout tomo.Layout, children ...tomo.Object) *Container {
// window, tab pane, etc. // window, tab pane, etc.
func NewOuterContainer (layout tomo.Layout, children ...tomo.Object) *Container { func NewOuterContainer (layout tomo.Layout, children ...tomo.Object) *Container {
this := newContainer(layout, children...) this := newContainer(layout, children...)
this.SetRole(tomo.R("objects", "Container", "outer")) this.SetRole(tomo.R("objects", "Container"))
this.SetTag("outer", true)
return this return this
} }
@@ -35,14 +36,16 @@ func NewOuterContainer (layout tomo.Layout, children ...tomo.Object) *Container
// around it. It is meant to be used as a root container for a ScrollContainer. // around it. It is meant to be used as a root container for a ScrollContainer.
func NewSunkenContainer (layout tomo.Layout, children ...tomo.Object) *Container { func NewSunkenContainer (layout tomo.Layout, children ...tomo.Object) *Container {
this := newContainer(layout, children...) this := newContainer(layout, children...)
this.SetRole(tomo.R("objects", "Container", "sunken")) this.SetRole(tomo.R("objects", "Container"))
this.SetTag("sunken", true)
return this return this
} }
// NewInnerContainer creates a new container that has no padding around it. // NewInnerContainer creates a new container that has no padding around it.
func NewInnerContainer (layout tomo.Layout, children ...tomo.Object) *Container { func NewInnerContainer (layout tomo.Layout, children ...tomo.Object) *Container {
this := newContainer(layout, children...) this := newContainer(layout, children...)
this.SetRole(tomo.R("objects", "Container", "inner")) this.SetRole(tomo.R("objects", "Container"))
this.SetTag("inner", true)
return this return this
} }

View File

@@ -55,7 +55,7 @@ func NewDialog (kind DialogKind, parent tomo.Window, title, message string, opti
dialog.SetTitle(title) dialog.SetTitle(title)
icon := NewIcon(iconId, tomo.IconSizeLarge) icon := NewIcon(iconId, tomo.IconSizeLarge)
messageText := NewLabel(message) messageText := NewLabel(message)
messageText.SetAlign(tomo.AlignStart, tomo.AlignMiddle) messageText.SetAttr(tomo.AAlign(tomo.AlignStart, tomo.AlignMiddle))
for _, option := range options { for _, option := range options {
if option, ok := option.(clickable); ok { if option, ok := option.(clickable); ok {
@@ -63,10 +63,10 @@ func NewDialog (kind DialogKind, parent tomo.Window, title, message string, opti
} }
} }
dialog.controlRow = NewInnerContainer(layouts.ContractHorizontal, options...) dialog.controlRow = NewInnerContainer(layouts.ContractHorizontal, options...)
dialog.controlRow.SetAlign(tomo.AlignEnd, tomo.AlignEnd) dialog.controlRow.SetAttr(tomo.AAlign(tomo.AlignEnd, tomo.AlignEnd))
dialog.SetRoot(NewOuterContainer ( dialog.SetRoot(NewOuterContainer (
layouts.NewGrid([]bool { true }, []bool { true, false }), layouts.Column { true, false },
NewInnerContainer(layouts.ContractHorizontal, icon, messageText), NewInnerContainer(layouts.ContractHorizontal, icon, messageText),
dialog.controlRow)) dialog.controlRow))
return dialog, nil return dialog, nil

114
dropdown.go Normal file
View File

@@ -0,0 +1,114 @@
package objects
// import "image"
import "git.tebibyte.media/tomo/tomo"
import "git.tebibyte.media/tomo/tomo/input"
import "git.tebibyte.media/tomo/tomo/event"
import "git.tebibyte.media/tomo/objects/layouts"
// Dropdown is a non-editable text input that allows the user to pick a value
// from a list.
type Dropdown struct {
tomo.ContainerBox
label *Label
value string
items []string
menu *Menu
on struct {
valueChange event.FuncBroadcaster
}
}
// NewDropdown creates a new dropdown input with the specified items
func NewDropdown (items ...string) *Dropdown {
dropdown := &Dropdown {
ContainerBox: tomo.NewContainerBox(),
label: NewLabel(""),
}
dropdown.SetRole(tomo.R("objects", "Dropdown"))
dropdown.SetAttr(tomo.ALayout(layouts.Row { true, false }))
dropdown.Add(dropdown.label)
dropdown.Add(NewIcon(tomo.IconListChoose, tomo.IconSizeSmall))
dropdown.SetItems(items...)
if len(items) > 0 {
dropdown.SetValue(items[0])
}
dropdown.SetInputMask(true)
dropdown.OnButtonDown(dropdown.handleButtonDown)
dropdown.OnButtonUp(dropdown.handleButtonUp)
dropdown.OnKeyDown(dropdown.handleKeyDown)
dropdown.OnKeyUp(dropdown.handleKeyUp)
dropdown.SetFocusable(true)
return dropdown
}
// Value returns the value of the dropdown. This does not necissarily have to be
// in the list of items.
func (this *Dropdown) Value () string {
return this.value
}
// SetValue sets the value of the dropdown. This does not necissarily have to be
// in the list of items.
func (this *Dropdown) SetValue (value string) {
this.value = value
this.label.SetText(value)
}
// SetItems sets the items from which the user is able to pick.
func (this *Dropdown) SetItems (items ...string) {
this.items = items
}
// Choose creates a menu that allows the user to pick a value.
func (this *Dropdown) Choose () {
if this.menu != nil {
this.menu.Close()
}
menu, err := NewAnchoredMenu(this, this.itemList()...)
if err != nil { return }
this.menu = menu
menu.SetVisible(true)
}
func (this *Dropdown) itemList () []tomo.Object {
items := make([]tomo.Object, len(this.items))
for index, value := range this.items {
value := value
item := NewMenuItem(value)
item.OnClick(func () {
this.SetValue(value)
this.on.valueChange.Broadcast()
})
items[index] = item
}
return items
}
func (this *Dropdown) handleKeyDown (key input.Key, numberPad bool) bool {
if !isClickingKey(key) { return false }
this.Choose()
return true
}
func (this *Dropdown) handleKeyUp (key input.Key, numberPad bool) bool {
if !isClickingKey(key) { return false }
return true
}
func (this *Dropdown) handleButtonDown (button input.Button) bool {
if !isClickingButton(button) { return false }
return true
}
func (this *Dropdown) handleButtonUp (button input.Button) bool {
if !isClickingButton(button) { return false }
if this.Window().MousePosition().In(this.Bounds()) {
this.Choose()
}
return true
}

4
go.mod
View File

@@ -2,6 +2,4 @@ module git.tebibyte.media/tomo/objects
go 1.20 go 1.20
require git.tebibyte.media/tomo/tomo v0.38.0 require git.tebibyte.media/tomo/tomo v0.46.1
require golang.org/x/image v0.11.0 // indirect

37
go.sum
View File

@@ -1,35 +1,2 @@
git.tebibyte.media/tomo/tomo v0.38.0 h1:K5TP67RxnszudeNfmGZiU5cFTRjFueXiI3NCsgw+05U= git.tebibyte.media/tomo/tomo v0.46.1 h1:/8fT6I9l4TK529zokrThbNDHGRvUsNgif1Zs++0PBSQ=
git.tebibyte.media/tomo/tomo v0.38.0/go.mod h1:C9EzepS9wjkTJjnZaPBh22YvVPyA4hbBAJVU20Rdmps= git.tebibyte.media/tomo/tomo v0.46.1/go.mod h1:WrtilgKB1y8O2Yu7X4mYcRiqOlPR8NuUnoA/ynkQWrs=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/image v0.11.0 h1:ds2RoQvBvYTiJkwpSFDwCcDFNX7DqjL2WsUgTNk0Ooo=
golang.org/x/image v0.11.0/go.mod h1:bglhjqbqVuEb9e9+eNR45Jfu7D+T4Qan+NhQk8Ck2P8=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

View File

@@ -15,8 +15,17 @@ func NewHeading (level int, text string) *Heading {
if level < 0 { level = 0 } if level < 0 { level = 0 }
if level > 2 { level = 2 } if level > 2 { level = 2 }
this := &Heading { TextBox: tomo.NewTextBox() } this := &Heading { TextBox: tomo.NewTextBox() }
this.SetRole(tomo.R("objects", "Heading", fmt.Sprint(level))) this.SetRole(tomo.R("objects", "Heading"))
this.SetTag(fmt.Sprint(level), true)
this.SetText(text) this.SetText(text)
this.SetSelectable(true)
this.SetFocusable(true)
return this return this
} }
// NewMenuHeading creatss a new heading for use in menus.
func NewMenuHeading (text string) *Heading {
heading := NewHeading(0, text)
heading.SetTag("menu", true)
return heading
}

46
icon.go
View File

@@ -1,41 +1,53 @@
package objects package objects
import "image"
import "git.tebibyte.media/tomo/tomo" import "git.tebibyte.media/tomo/tomo"
import "git.tebibyte.media/tomo/tomo/data"
import "git.tebibyte.media/tomo/tomo/canvas" import "git.tebibyte.media/tomo/tomo/canvas"
// Icon displays a single icon. // Icon displays a single icon.
type Icon struct { type Icon struct {
tomo.Box tomo.Box
icon tomo.Icon
size tomo.IconSize
}
func iconSizeString (size tomo.IconSize) string {
switch size {
case tomo.IconSizeLarge: return "large"
case tomo.IconSizeMedium: return "medium"
default: return "small"
}
} }
// NewIcon creates a new icon from an icon ID. // NewIcon creates a new icon from an icon ID.
func NewIcon (id tomo.Icon, size tomo.IconSize) *Icon { func NewIcon (icon tomo.Icon, size tomo.IconSize) *Icon {
this := &Icon { this := &Icon {
Box: tomo.NewBox(), Box: tomo.NewBox(),
} }
this.SetRole(tomo.R("objects", "Icon", size.String())) this.SetRole(tomo.R("objects", "Icon"))
this.SetTexture(id.Texture(size)) this.SetIcon(icon, size)
this.OnIconSetChange(this.handleIconSetChange)
return this return this
} }
// NewMimeIcon creates a new icon from a MIME type. // SetIcon sets the icon.
func NewMimeIcon (mime data.Mime, size tomo.IconSize) *Icon { func (this *Icon) SetIcon (icon tomo.Icon, size tomo.IconSize) {
this := &Icon { if this.icon == icon { return }
Box: tomo.NewBox(), this.icon = icon
} this.size = size
this.SetRole(tomo.R("objects", "Icon", size.String())) this.setTexture(icon.Texture(size))
this.SetTexture(tomo.MimeIcon(mime, size))
return this
} }
func (this *Icon) SetTexture (texture canvas.Texture) { func (this *Icon) handleIconSetChange () {
this.Box.SetTextureCenter(texture) this.setTexture(this.icon.Texture(this.size))
}
func (this *Icon) setTexture (texture canvas.Texture) {
this.SetAttr(tomo.ATexture(texture))
this.SetAttr(tomo.ATextureMode(tomo.TextureModeCenter))
if texture == nil { if texture == nil {
this.SetMinimumSize(image.Pt(0, 0)) this.SetAttr(tomo.AMinimumSize(0, 0))
} else { } else {
bounds := texture.Bounds() bounds := texture.Bounds()
this.SetMinimumSize(bounds.Max.Sub(bounds.Min)) this.SetAttr(tomo.AttrMinimumSize(bounds.Max.Sub(bounds.Min)))
} }
} }

19
input.go Normal file
View File

@@ -0,0 +1,19 @@
package objects
import "git.tebibyte.media/tomo/tomo/input"
func isClickingKey (key input.Key) bool {
return key == input.KeyEnter || key == input.Key(' ')
}
func isConfirmationKey (key input.Key) bool {
return key == input.KeyEnter
}
func isClickingButton (button input.Button) bool {
return button == input.ButtonLeft
}
func isMenuButton (button input.Button) bool {
return button == input.ButtonLeft
}

231
internal/color.go Normal file
View File

@@ -0,0 +1,231 @@
package internal
import "fmt"
import "image/color"
// HSV represents a color with hue, saturation, and value components. Each
// component C is in range 0 <= C <= 1.
type HSV struct {
H float64
S float64
V float64
}
// HSVA is an HSV color with an added 8-bit alpha component. The alpha component
// ranges from 0x0000 (fully transparent) to 0xFFFF (opaque), and has no bearing
// on the other components.
type HSVA struct {
H float64
S float64
V float64
A uint16
}
var (
HSVModel color.Model = color.ModelFunc(hsvModel)
HSVAModel color.Model = color.ModelFunc(hsvaModel)
)
func (hsv HSV) RGBA () (r, g, b, a uint32) {
// Adapted from:
// https://www.cs.rit.edu/~ncs/color/t_convert.html
component := func (x float64) uint32 {
return uint32(float64(0xFFFF) * x)
}
s := clamp01(hsv.S)
v := clamp01(hsv.V)
if s == 0 {
light := component(v)
return light, light, light, 0xFFFF
}
h := clamp01(hsv.H) * 360
sector := int(h / 60)
// otherwise when given 1.0 for H, sector would overflow to 6
if sector > 5 { sector = 5 }
offset := (h / 60) - float64(sector)
p := component(v * (1 - s))
q := component(v * (1 - s * offset))
t := component(v * (1 - s * (1 - offset)))
va := component(v)
switch sector {
case 0: return va, t, p, 0xFFFF
case 1: return q, va, p, 0xFFFF
case 2: return p, va, t, 0xFFFF
case 3: return p, q, va, 0xFFFF
case 4: return t, p, va, 0xFFFF
default: return va, p, q, 0xFFFF
}
}
func (hsva HSVA) RGBA () (r, g, b, a uint32) {
r, g, b, a = HSV {
H: hsva.H,
S: hsva.S,
V: hsva.V,
}.RGBA()
a = uint32(hsva.A)
// alpha premultiplication
r = (r * a) / 0xFFFF
g = (g * a) / 0xFFFF
b = (b * a) / 0xFFFF
return
}
// Canon returns the color but with the H, S, and V fields are constrained to
// the range 0.0-1.0
func (hsv HSV) Canon () HSV {
hsv.H = clamp01(hsv.H)
hsv.S = clamp01(hsv.S)
hsv.V = clamp01(hsv.V)
return hsv
}
// Canon returns the color but with the H, S, and V fields are constrained to
// the range 0.0-1.0
func (hsva HSVA) Canon () HSVA {
hsva.H = clamp01(hsva.H)
hsva.S = clamp01(hsva.S)
hsva.V = clamp01(hsva.V)
return hsva
}
func clamp01 (x float64) float64 {
if x > 1.0 { return 1.0 }
if x < 0.0 { return 0.0 }
return x
}
func hsvModel (c color.Color) color.Color {
switch c := c.(type) {
case HSV: return c
case HSVA: return HSV { H: c.H, S: c.S, V: c.V }
default:
r, g, b, a := c.RGBA()
// alpha unpremultiplication
r = (r / a) * 0xFFFF
g = (g / a) * 0xFFFF
b = (b / a) * 0xFFFF
return rgbToHSV(r, g, b)
}
}
func hsvaModel (c color.Color) color.Color {
switch c := c.(type) {
case HSV: return HSVA { H: c.H, S: c.S, V: c.V, A: 0xFFFF }
case HSVA: return c
default:
r, g, b, a := c.RGBA()
hsv := rgbToHSV(r, g, b)
return HSVA {
H: hsv.H,
S: hsv.S,
V: hsv.V,
A: uint16(a),
}
}
}
func rgbToHSV (r, g, b uint32) HSV {
// Adapted from:
// https://www.cs.rit.edu/~ncs/color/t_convert.html
component := func (x uint32) float64 {
return clamp01(float64(x) / 0xFFFF)
}
cr := component(r)
cg := component(g)
cb := component(b)
var maxComponent float64
if cr > maxComponent { maxComponent = cr }
if cg > maxComponent { maxComponent = cg }
if cb > maxComponent { maxComponent = cb }
var minComponent = 1.0
if cr < minComponent { minComponent = cr }
if cg < minComponent { minComponent = cg }
if cb < minComponent { minComponent = cb }
hsv := HSV {
V: maxComponent,
}
delta := maxComponent - minComponent
if delta == 0 {
// hsva.S is undefined, so hue doesn't matter
return hsv
}
hsv.S = delta / maxComponent
switch {
case cr == maxComponent: hsv.H = (cg - cb) / delta
case cg == maxComponent: hsv.H = 2 + (cb - cr) / delta
case cb == maxComponent: hsv.H = 4 + (cr - cg) / delta
}
hsv.H *= 60
if hsv.H < 0 { hsv.H += 360 }
hsv.H /= 360
return hsv
}
// FormatNRGBA formats an NRGBA value into a hex string.
func FormatNRGBA (nrgba color.NRGBA) string {
return fmt.Sprintf("%02X%02X%02X%02X", nrgba.R, nrgba.G, nrgba.B, nrgba.A)
}
// ParseNRGBA parses an NRGBA value from a hex string. It can be of the format:
// - RGB
// - RGBA
// - RRGGBB
// - RRGGBBAA
// If none of these are specified, this function will return an opaque black
// color. Hex digits may either be upper case or lower case.
func ParseNRGBA (str string) color.NRGBA {
runes := []rune(str)
c := color.NRGBA { A: 255 }
switch len(runes) {
case 3:
c.R = fillOctet(hexDigit(runes[0]))
c.G = fillOctet(hexDigit(runes[1]))
c.B = fillOctet(hexDigit(runes[2]))
case 4:
c.R = fillOctet(hexDigit(runes[0]))
c.G = fillOctet(hexDigit(runes[1]))
c.B = fillOctet(hexDigit(runes[2]))
c.A = fillOctet(hexDigit(runes[3]))
case 6:
c.R = hexOctet(runes[0], runes[1])
c.G = hexOctet(runes[2], runes[3])
c.B = hexOctet(runes[4], runes[5])
case 8:
c.R = hexOctet(runes[0], runes[1])
c.G = hexOctet(runes[2], runes[3])
c.B = hexOctet(runes[4], runes[5])
c.A = hexOctet(runes[6], runes[7])
}
return c
}
func hexDigit (r rune) uint8 {
switch {
case r >= '0' && r <= '9': return uint8(r - '0')
case r >= 'A' && r <= 'F': return uint8(r - 'A') + 10
case r >= 'a' && r <= 'f': return uint8(r - 'a') + 10
default: return 0
}
}
func fillOctet (low uint8) uint8 {
return low << 4 | low
}
func hexOctet (high, low rune) uint8 {
return hexDigit(high) << 4 | hexDigit(low)
}

View File

@@ -10,7 +10,10 @@ type Label struct {
// NewLabel creates a new text label. // NewLabel creates a new text label.
func NewLabel (text string) *Label { func NewLabel (text string) *Label {
this := &Label { TextBox: tomo.NewTextBox() } this := &Label { TextBox: tomo.NewTextBox() }
this.SetRole(tomo.R("objects", "Label", "")) this.SetRole(tomo.R("objects", "Label"))
this.SetText(text) this.SetText(text)
this.SetAttr(tomo.AAlign(tomo.AlignStart, tomo.AlignMiddle))
this.SetSelectable(true)
this.SetFocusable(true)
return this return this
} }

View File

@@ -20,17 +20,24 @@ func NewLabelCheckbox (value bool, text string) *LabelCheckbox {
checkbox: NewCheckbox(value), checkbox: NewCheckbox(value),
label: NewLabel(text), label: NewLabel(text),
} }
box.SetRole(tomo.R("objects", "LabelCheckbox", "")) box.SetRole(tomo.R("objects", "LabelCheckbox"))
box.label.SetAlign(tomo.AlignStart, tomo.AlignMiddle) box.label.SetAttr(tomo.AAlign(tomo.AlignStart, tomo.AlignMiddle))
box.label.SetSelectable(false)
box.label.SetFocusable(false)
box.Add(box.checkbox) box.Add(box.checkbox)
box.Add(box.label) box.Add(box.label)
box.SetLayout(layouts.NewGrid([]bool { false, true }, []bool { false })) box.SetAttr(tomo.ALayout(layouts.Row { false, true }))
box.OnMouseUp(box.handleMouseUp) box.OnButtonDown(box.handleButtonDown)
box.label.OnMouseUp(box.handleMouseUp) box.OnButtonUp(box.handleButtonUp)
return box return box
} }
// Value returns the value of the checkbox.
func (this *LabelCheckbox) Value () bool {
return this.checkbox.Value()
}
// SetValue sets the value of the checkbox. // SetValue sets the value of the checkbox.
func (this *LabelCheckbox) SetValue (value bool) { func (this *LabelCheckbox) SetValue (value bool) {
this.checkbox.SetValue(value) this.checkbox.SetValue(value)
@@ -41,21 +48,22 @@ func (this *LabelCheckbox) Toggle () {
this.checkbox.Toggle() this.checkbox.Toggle()
} }
// Value returns the value of the checkbox. // OnValueChange specifies a function to be called when the user checks or
func (this *LabelCheckbox) Value () bool { // unchecks the checkbox.
return this.checkbox.Value()
}
// OnValueChange specifies a function to be called when the checkbox's value
// changes.
func (this *LabelCheckbox) OnValueChange (callback func ()) event.Cookie { func (this *LabelCheckbox) OnValueChange (callback func ()) event.Cookie {
return this.checkbox.OnValueChange(callback) return this.checkbox.OnValueChange(callback)
} }
func (this *LabelCheckbox) handleMouseUp (button input.Button) { func (this *LabelCheckbox) handleButtonDown (button input.Button) bool {
if button != input.ButtonLeft { return } if !isClickingButton(button) { return false }
if this.MousePosition().In(this.Bounds()) { return true
}
func (this *LabelCheckbox) handleButtonUp (button input.Button) bool {
if !isClickingButton(button) { return false }
if this.Window().MousePosition().In(this.Bounds()) {
this.checkbox.SetFocused(true) this.checkbox.SetFocused(true)
this.checkbox.Toggle() this.checkbox.Toggle()
} }
return true
} }

75
labelswatch.go Normal file
View File

@@ -0,0 +1,75 @@
package objects
import "image/color"
import "git.tebibyte.media/tomo/tomo"
import "git.tebibyte.media/tomo/tomo/input"
import "git.tebibyte.media/tomo/tomo/event"
import "git.tebibyte.media/tomo/objects/layouts"
// LabelSwatch is a swatch with a label.
type LabelSwatch struct {
tomo.ContainerBox
swatch *Swatch
label *Label
}
// NewLabelSwatch creates a new labeled swatch with the specified color and
// label text.
func NewLabelSwatch (value color.Color, text string) *LabelSwatch {
box := &LabelSwatch {
ContainerBox: tomo.NewContainerBox(),
swatch: NewSwatch(value),
label: NewLabel(text),
}
box.SetRole(tomo.R("objects", "LabelSwatch"))
box.swatch.label = text
box.label.SetAttr(tomo.AAlign(tomo.AlignStart, tomo.AlignMiddle))
box.Add(box.swatch)
box.Add(box.label)
box.SetAttr(tomo.ALayout(layouts.Row { false, true }))
box.OnButtonDown(box.handleButtonDown)
box.OnButtonUp(box.handleButtonUp)
return box
}
// Value returns the color of the swatch.
func (this *LabelSwatch) Value () color.Color {
return this.swatch.Value()
}
// SetValue sets the color of the swatch.
func (this *LabelSwatch) SetValue (value color.Color) {
this.swatch.SetValue(value)
}
// OnValueChange specifies a function to be called when the swatch's color
// is changed by the user.
func (this *LabelSwatch) OnValueChange (callback func ()) event.Cookie {
return this.swatch.OnValueChange(callback)
}
// RGBA satisfies the color.Color interface
func (this *LabelSwatch) RGBA () (r, g, b, a uint32) {
return this.swatch.RGBA()
}
// OnConfirm specifies a function to be called when the user selects "OK" in the
// color picker.
func (this *LabelSwatch) OnConfirm (callback func ()) event.Cookie {
return this.swatch.OnConfirm(callback)
}
func (this *LabelSwatch) handleButtonDown (button input.Button) bool {
if button != input.ButtonLeft { return true }
return true
}
func (this *LabelSwatch) handleButtonUp (button input.Button) bool {
if button != input.ButtonLeft { return true }
if this.Window().MousePosition().In(this.Bounds()) {
this.swatch.SetFocused(true)
this.swatch.Choose()
}
return true
}

View File

@@ -15,19 +15,19 @@ const ContractVertical Contract = true
// ContractHorizontal is a horizontal contracted layout. // ContractHorizontal is a horizontal contracted layout.
const ContractHorizontal Contract = false const ContractHorizontal Contract = false
func (contract Contract) MinimumSize (hints tomo.LayoutHints, boxes []tomo.Box) image.Point { func (contract Contract) MinimumSize (hints tomo.LayoutHints, boxes tomo.BoxQuerier) image.Point {
return contract.fallback().MinimumSize(hints, boxes) return contract.fallback().MinimumSize(hints, boxes)
} }
func (contract Contract) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) { func (contract Contract) Arrange (hints tomo.LayoutHints, boxes tomo.BoxArranger) {
contract.fallback().Arrange(hints, boxes) contract.fallback().Arrange(hints, boxes)
} }
func (contract Contract) RecommendedHeight (hints tomo.LayoutHints, boxes []tomo.Box, width int) int { func (contract Contract) RecommendedHeight (hints tomo.LayoutHints, boxes tomo.BoxQuerier, width int) int {
return contract.fallback().RecommendedHeight(hints, boxes, width) return contract.fallback().RecommendedHeight(hints, boxes, width)
} }
func (contract Contract) RecommendedWidth (hints tomo.LayoutHints, boxes []tomo.Box, height int) int { func (contract Contract) RecommendedWidth (hints tomo.LayoutHints, boxes tomo.BoxQuerier, height int) int {
return contract.fallback().RecommendedWidth(hints, boxes, height) return contract.fallback().RecommendedWidth(hints, boxes, height)
} }

View File

@@ -17,21 +17,21 @@ const FlowVertical Flow = true
// FlowHorizontal is a horizontal flow layout. // FlowHorizontal is a horizontal flow layout.
const FlowHorizontal Flow = false const FlowHorizontal Flow = false
func (flow Flow) MinimumSize (hints tomo.LayoutHints, boxes []tomo.Box) image.Point { func (flow Flow) MinimumSize (hints tomo.LayoutHints, boxes tomo.BoxQuerier) image.Point {
// TODO: write down somewhere that layout minimums aren't taken into // TODO: write down somewhere that layout minimums aren't taken into
// account when the respective direction is overflowed // account when the respective direction is overflowed
return flow.fallback().MinimumSize(hints, boxes) return flow.fallback().MinimumSize(hints, boxes)
} }
func (flow Flow) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) { func (flow Flow) Arrange (hints tomo.LayoutHints, boxes tomo.BoxArranger) {
if flow.v() && !hints.OverflowY || flow.h() && !hints.OverflowX { if flow.v() && !hints.OverflowY || flow.h() && !hints.OverflowX {
flow.fallback().Arrange(hints, boxes) flow.fallback().Arrange(hints, boxes)
} }
// find a minor size value that will fit all boxes // find a minor size value that will fit all boxes
minorSize := 0 minorSize := 0
for _, box := range boxes { for index := 0; index < boxes.Len(); index ++ {
boxSize := flow.minor(box.MinimumSize()) boxSize := flow.minor(boxes.MinimumSize(index))
if boxSize > minorSize { minorSize = boxSize } if boxSize > minorSize { minorSize = boxSize }
} }
if minorSize == 0 { return } if minorSize == 0 { return }
@@ -43,17 +43,17 @@ func (flow Flow) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) {
// arrange // arrange
point := hints.Bounds.Min point := hints.Bounds.Min
index := 0 index := 0
for index < len(boxes) { for index < boxes.Len() {
// get a slice of boxes for this major step // get a slice of boxes for this major step
stepIndexEnd := index + minorSteps stepIndexStart := index
if stepIndexEnd > len(boxes) { stepIndexEnd = len(boxes) } stepIndexEnd := index + minorSteps
step := boxes[index:stepIndexEnd] if stepIndexEnd > boxes.Len() { stepIndexEnd = boxes.Len() }
index += minorSteps index += minorSteps
// find a major size that will fit all boxes on this major step // find a major size that will fit all boxes on this major step
majorSize := 0 majorSize := 0
for _, box := range step { for index := stepIndexStart; index < stepIndexEnd; index ++ {
boxSize := flow.major(box.MinimumSize()) boxSize := flow.major(boxes.MinimumSize(index))
if boxSize > majorSize { majorSize = boxSize } if boxSize > majorSize { majorSize = boxSize }
} }
if majorSize == 0 { continue } if majorSize == 0 { continue }
@@ -62,9 +62,9 @@ func (flow Flow) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) {
var size image.Point var size image.Point
size = flow.incrMajor(size, majorSize) size = flow.incrMajor(size, majorSize)
size = flow.incrMinor(size, minorSize) size = flow.incrMinor(size, minorSize)
for _, box := range step { for index := stepIndexStart; index < stepIndexEnd; index ++ {
bounds := image.Rectangle { Min: point, Max: point.Add(size) } bounds := image.Rectangle { Min: point, Max: point.Add(size) }
box.SetBounds(bounds) boxes.SetBounds(index, bounds)
point = flow.incrMinor(point, minorSize + flow.minor(hints.Gap)) point = flow.incrMinor(point, minorSize + flow.minor(hints.Gap))
} }
@@ -125,12 +125,12 @@ func (flow Flow) fallback () tomo.Layout {
return Contract(flow) return Contract(flow)
} }
func (flow Flow) RecommendedHeight (hints tomo.LayoutHints, boxes []tomo.Box, width int) int { func (flow Flow) RecommendedHeight (hints tomo.LayoutHints, boxes tomo.BoxQuerier, width int) int {
// TODO // TODO
return 0 return 0
} }
func (flow Flow) RecommendedWidth (hints tomo.LayoutHints, boxes []tomo.Box, height int) int { func (flow Flow) RecommendedWidth (hints tomo.LayoutHints, boxes tomo.BoxQuerier, height int) int {
// TODO // TODO
return 0 return 0
} }

View File

@@ -18,15 +18,21 @@ type Grid struct {
// will contract. Boxes are laid out left to right, then top to bottom. Boxes // will contract. Boxes are laid out left to right, then top to bottom. Boxes
// that go beyond the lengh of rows will be laid out according to columns, but // that go beyond the lengh of rows will be laid out according to columns, but
// they will not expand vertically. // they will not expand vertically.
func NewGrid (columns, rows []bool) *Grid { //
this := &Grid { // If you aren't sure how to use this constructor, here is an example:
xExpand: columns, //
yExpand: rows, // X0 X1 X2 Y0 Y1 Y2
// NewGrid(true, false, true)(false, true, true)
func NewGrid (columns ...bool) func (rows ...bool) *Grid {
return func (rows ...bool) *Grid {
return &Grid {
xExpand: columns,
yExpand: rows,
}
} }
return this
} }
func (this *Grid) MinimumSize (hints tomo.LayoutHints, boxes []tomo.Box) image.Point { func (this *Grid) MinimumSize (hints tomo.LayoutHints, boxes tomo.BoxQuerier) image.Point {
cols, rows := this.minimums(boxes) cols, rows := this.minimums(boxes)
size := image.Pt ( size := image.Pt (
(len(cols) - 1) * hints.Gap.X, (len(cols) - 1) * hints.Gap.X,
@@ -36,7 +42,7 @@ func (this *Grid) MinimumSize (hints tomo.LayoutHints, boxes []tomo.Box) image.P
return size return size
} }
func (this *Grid) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) { func (this *Grid) Arrange (hints tomo.LayoutHints, boxes tomo.BoxArranger) {
xExpand := func (index int) bool { xExpand := func (index int) bool {
return this.xExpand[index] return this.xExpand[index]
} }
@@ -50,9 +56,9 @@ func (this *Grid) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) {
expand(hints, rows, hints.Bounds.Dy(), yExpand) expand(hints, rows, hints.Bounds.Dy(), yExpand)
position := hints.Bounds.Min position := hints.Bounds.Min
for index, box := range boxes { for index := 0; index < boxes.Len(); index ++ {
col, row := index % len(cols), index / len(cols) col, row := index % len(cols), index / len(cols)
box.SetBounds(image.Rectangle { boxes.SetBounds(index, image.Rectangle {
Min: position, Min: position,
Max: position.Add(image.Pt(cols[col], rows[row])), Max: position.Add(image.Pt(cols[col], rows[row])),
}) })
@@ -65,13 +71,13 @@ func (this *Grid) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) {
} }
} }
func (this *Grid) minimums (boxes []tomo.Box) ([]int, []int) { func (this *Grid) minimums (boxes tomo.BoxQuerier) ([]int, []int) {
nCols, nRows := this.dimensions(boxes) nCols, nRows := this.dimensions(boxes)
cols, rows := make([]int, nCols), make([]int, nRows) cols, rows := make([]int, nCols), make([]int, nRows)
for index, box := range boxes { for index := 0; index < boxes.Len(); index ++ {
col, row := index % len(cols), index / len(cols) col, row := index % len(cols), index / len(cols)
minimum := box.MinimumSize() minimum := boxes.MinimumSize(index)
if cols[col] < minimum.X { if cols[col] < minimum.X {
cols[col] = minimum.X cols[col] = minimum.X
} }
@@ -83,8 +89,8 @@ func (this *Grid) minimums (boxes []tomo.Box) ([]int, []int) {
return cols, rows return cols, rows
} }
func (this *Grid) dimensions (boxes []tomo.Box) (int, int) { func (this *Grid) dimensions (boxes tomo.BoxQuerier) (int, int) {
return len(this.xExpand), ceilDiv(len(boxes), len(this.xExpand)) return len(this.xExpand), ceilDiv(boxes.Len(), len(this.xExpand))
} }
func expand (hints tomo.LayoutHints, sizes []int, space int, expands func (int) bool) { func expand (hints tomo.LayoutHints, sizes []int, space int, expands func (int) bool) {
@@ -106,15 +112,14 @@ func expand (hints tomo.LayoutHints, sizes []int, space int, expands func (int)
} }
func ceilDiv (x, y int) int { func ceilDiv (x, y int) int {
if y == 0 { return 0 }
return int(math.Ceil(float64(x) / float64(y))) return int(math.Ceil(float64(x) / float64(y)))
} }
func (this *Grid) RecommendedHeight (hints tomo.LayoutHints, boxes []tomo.Box, width int) int { func (this *Grid) RecommendedHeight (hints tomo.LayoutHints, boxes tomo.BoxQuerier, width int) int {
// TODO return this.MinimumSize(hints, boxes).Y
return 0
} }
func (this *Grid) RecommendedWidth (hints tomo.LayoutHints, boxes []tomo.Box, height int) int { func (this *Grid) RecommendedWidth (hints tomo.LayoutHints, boxes tomo.BoxQuerier, height int) int {
// TODO return this.MinimumSize(hints, boxes).X
return 0
} }

View File

@@ -13,33 +13,33 @@ type Row []bool
// value will expand, and others will contract. // value will expand, and others will contract.
type Column []bool type Column []bool
func (column Column) MinimumSize (hints tomo.LayoutHints, boxes []tomo.Box) image.Point { func (column Column) MinimumSize (hints tomo.LayoutHints, boxes tomo.BoxQuerier) image.Point {
dot := image.Point { } dot := image.Point { }
for _, box := range boxes { for index := 0; index < boxes.Len(); index ++ {
minimum := box.MinimumSize() minimum := boxes.MinimumSize(index)
dot.Y += minimum.Y dot.Y += minimum.Y
if dot.X < minimum.X { if dot.X < minimum.X {
dot.X = minimum.X dot.X = minimum.X
} }
} }
dot.Y += hints.Gap.Y * (len(boxes) - 1) dot.Y += hints.Gap.Y * (boxes.Len() - 1)
return dot return dot
} }
func (row Row) MinimumSize (hints tomo.LayoutHints, boxes []tomo.Box) image.Point { func (row Row) MinimumSize (hints tomo.LayoutHints, boxes tomo.BoxQuerier) image.Point {
dot := image.Point { } dot := image.Point { }
for _, box := range boxes { for index := 0; index < boxes.Len(); index ++ {
minimum := box.MinimumSize() minimum := boxes.MinimumSize(index)
dot.X += minimum.X dot.X += minimum.X
if dot.Y < minimum.Y { if dot.Y < minimum.Y {
dot.Y = minimum.Y dot.Y = minimum.Y
} }
} }
dot.X += hints.Gap.X * (len(boxes) - 1) dot.X += hints.Gap.X * (boxes.Len() - 1)
return dot return dot
} }
func (column Column) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) { func (column Column) Arrange (hints tomo.LayoutHints, boxes tomo.BoxArranger) {
expands := func (index int) bool { expands := func (index int) bool {
if index >= len(column) { return false } if index >= len(column) { return false }
return column[index] return column[index]
@@ -48,13 +48,14 @@ func (column Column) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) {
// determine expanding box size // determine expanding box size
expandingSize := 0.0 expandingSize := 0.0
if !hints.OverflowY { if !hints.OverflowY {
gaps := len(boxes) - 1 gaps := boxes.Len() - 1
freeSpace := float64(hints.Bounds.Dy() - hints.Gap.Y * gaps) freeSpace := float64(hints.Bounds.Dy() - hints.Gap.Y * gaps)
nExpanding := 0; for index, box := range boxes { nExpanding := 0
for index := 0; index < boxes.Len(); index ++ {
if expands(index) { if expands(index) {
nExpanding ++ nExpanding ++
} else { } else {
freeSpace -= float64(box.MinimumSize().Y) freeSpace -= float64(boxes.MinimumSize(index).Y)
} }
} }
expandingSize = freeSpace / float64(nExpanding) expandingSize = freeSpace / float64(nExpanding)
@@ -63,8 +64,8 @@ func (column Column) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) {
// determine width // determine width
width := 0 width := 0
if hints.OverflowX { if hints.OverflowX {
for _, box := range boxes { for index := 0; index < boxes.Len(); index ++ {
minimum := box.MinimumSize() minimum := boxes.MinimumSize(index)
if width < minimum.X { width = minimum.X } if width < minimum.X { width = minimum.X }
} }
} else { } else {
@@ -73,44 +74,43 @@ func (column Column) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) {
// arrange // arrange
dot := hints.Bounds.Min dot := hints.Bounds.Min
for index, box := range boxes { bounds := make([]image.Rectangle, boxes.Len())
for index := 0; index < boxes.Len(); index ++ {
if index > 0 { dot.Y += hints.Gap.Y } if index > 0 { dot.Y += hints.Gap.Y }
// determine height // determine height
height := box.MinimumSize().Y height := boxes.MinimumSize(index).Y
if hints.OverflowY { if hints.OverflowY {
if box, ok := box.(tomo.ContentBox); ok { height = boxes.RecommendedHeight(index, width)
height = box.RecommendedHeight(width)
}
} else { } else {
if expands(index) { if expands(index) {
height = int(expandingSize) height = int(expandingSize)
} }
} }
// set bounds // store bounds of this box
box.SetBounds(image.Rectangle { bounds[index] = image.Rectangle {
Min: dot, Min: dot,
Max: dot.Add(image.Pt(width, height)), Max: dot.Add(image.Pt(width, height)),
}) }
dot.Y += height dot.Y += height
} }
// align
height := dot.Y - hints.Bounds.Min.Y height := dot.Y - hints.Bounds.Min.Y
offset := 0 offset := 0
switch hints.AlignY { switch hints.AlignY {
case tomo.AlignMiddle: case tomo.AlignMiddle:
offset = (hints.Bounds.Dy() - height) / 2 offset = (hints.Bounds.Dy() - height) / 2
case tomo.AlignEnd: case tomo.AlignEnd:
offset = hints.Bounds.Dy() - height offset = hints.Bounds.Dy() - height
} }
for _, box := range boxes { for index := 0; index < boxes.Len(); index ++ {
box.SetBounds(box.Bounds().Add(image.Pt(0, offset))) boxes.SetBounds(index, bounds[index].Add(image.Pt(0, offset)))
} }
} }
func (row Row) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) { func (row Row) Arrange (hints tomo.LayoutHints, boxes tomo.BoxArranger) {
expands := func (index int) bool { expands := func (index int) bool {
if index >= len(row) { return false } if index >= len(row) { return false }
return row[index] return row[index]
@@ -119,13 +119,14 @@ func (row Row) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) {
// determine expanding box size // determine expanding box size
expandingSize := 0.0 expandingSize := 0.0
if !hints.OverflowY { if !hints.OverflowY {
gaps := len(boxes) - 1 gaps := boxes.Len() - 1
freeSpace := float64(hints.Bounds.Dx() - hints.Gap.X * gaps) freeSpace := float64(hints.Bounds.Dx() - hints.Gap.X * gaps)
nExpanding := 0; for index, box := range boxes { nExpanding := 0
for index := 0; index < boxes.Len(); index ++ {
if expands(index) { if expands(index) {
nExpanding ++ nExpanding ++
} else { } else {
freeSpace -= float64(box.MinimumSize().X) freeSpace -= float64(boxes.MinimumSize(index).X)
} }
} }
expandingSize = freeSpace / float64(nExpanding) expandingSize = freeSpace / float64(nExpanding)
@@ -134,8 +135,8 @@ func (row Row) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) {
// determine height // determine height
height := 0 height := 0
if hints.OverflowY { if hints.OverflowY {
for _, box := range boxes { for index := 0; index < boxes.Len(); index ++ {
minimum := box.MinimumSize() minimum := boxes.MinimumSize(index)
if height < minimum.Y { height = minimum.Y } if height < minimum.Y { height = minimum.Y }
} }
} else { } else {
@@ -144,95 +145,76 @@ func (row Row) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) {
// arrange // arrange
dot := hints.Bounds.Min dot := hints.Bounds.Min
for index, box := range boxes { bounds := make([]image.Rectangle, boxes.Len())
for index := 0; index < boxes.Len(); index ++ {
if index > 0 { dot.X += hints.Gap.X } if index > 0 { dot.X += hints.Gap.X }
// determine width // determine width
width := box.MinimumSize().X width := boxes.MinimumSize(index).X
if hints.OverflowY { if hints.OverflowY {
if box, ok := box.(tomo.ContentBox); ok { width = boxes.RecommendedHeight(index, height)
width = box.RecommendedHeight(height)
}
} else { } else {
if expands(index) { if expands(index) {
width = int(expandingSize) width = int(expandingSize)
} }
} }
// set bounds // store bounds
box.SetBounds(image.Rectangle { bounds[index] = image.Rectangle {
Min: dot, Min: dot,
Max: dot.Add(image.Pt(width, height)), Max: dot.Add(image.Pt(width, height)),
}) }
dot.X += width dot.X += width
} }
// align
width := dot.X - hints.Bounds.Min.X width := dot.X - hints.Bounds.Min.X
offset := 0 offset := 0
switch hints.AlignX { switch hints.AlignX {
case tomo.AlignMiddle: case tomo.AlignMiddle:
offset = (hints.Bounds.Dx() - width) / 2 offset = (hints.Bounds.Dx() - width) / 2
case tomo.AlignEnd: case tomo.AlignEnd:
offset = hints.Bounds.Dx() - width offset = hints.Bounds.Dx() - width
} }
for _, box := range boxes { for index := 0; index < boxes.Len(); index ++ {
box.SetBounds(box.Bounds().Add(image.Pt(offset, 0))) boxes.SetBounds(index, bounds[index].Add(image.Pt(offset, 0)))
} }
} }
func (column Column) RecommendedHeight (hints tomo.LayoutHints, boxes []tomo.Box, width int) int { func (column Column) RecommendedHeight (hints tomo.LayoutHints, boxes tomo.BoxQuerier, width int) int {
height := 0 height := 0
for _, box := range boxes { for index := 0; index < boxes.Len(); index ++ {
if box, ok := box.(tomo.ContentBox); ok { height += boxes.RecommendedHeight(index, width)
height += box.RecommendedHeight(width)
} else {
height += box.MinimumSize().Y
}
} }
height += hints.Gap.Y * (len(boxes) - 1) height += hints.Gap.Y * (boxes.Len() - 1)
return height return height
} }
func (row Row) RecommendedHeight (hints tomo.LayoutHints, boxes []tomo.Box, width int) int { func (row Row) RecommendedHeight (hints tomo.LayoutHints, boxes tomo.BoxQuerier, width int) int {
height := 0 height := 0
for _, box := range boxes { for index := 0; index < boxes.Len(); index ++ {
minimum := box.MinimumSize() minimum := boxes.MinimumSize(index)
boxHeight := 0 boxHeight := boxes.RecommendedHeight(index, minimum.X)
if box, ok := box.(tomo.ContentBox); ok {
boxHeight = box.RecommendedHeight(minimum.X)
} else {
boxHeight = minimum.Y
}
if boxHeight > height { height = boxHeight } if boxHeight > height { height = boxHeight }
} }
return height return height
} }
func (column Column) RecommendedWidth (hints tomo.LayoutHints, boxes []tomo.Box, height int) int { func (column Column) RecommendedWidth (hints tomo.LayoutHints, boxes tomo.BoxQuerier, height int) int {
width := 0 width := 0
for _, box := range boxes { for index := 0; index < boxes.Len(); index ++ {
minimum := box.MinimumSize() minimum := boxes.MinimumSize(index)
boxWidth := 0 boxWidth := boxes.RecommendedWidth(index, minimum.Y)
if box, ok := box.(tomo.ContentBox); ok {
boxWidth = box.RecommendedHeight(minimum.Y)
} else {
boxWidth = minimum.X
}
if boxWidth > width { width = boxWidth } if boxWidth > width { width = boxWidth }
} }
return width return width
} }
func (row Row) RecommendedWidth (hints tomo.LayoutHints, boxes []tomo.Box, height int) int { func (row Row) RecommendedWidth (hints tomo.LayoutHints, boxes tomo.BoxQuerier, height int) int {
width := 0 width := 0
for _, box := range boxes { for index := 0; index < boxes.Len(); index ++ {
if box, ok := box.(tomo.ContentBox); ok { width += boxes.RecommendedWidth(index, height)
width += box.RecommendedWidth(height)
} else {
width += box.MinimumSize().X
}
} }
width += hints.Gap.X * (len(boxes) - 1) width += hints.Gap.X * (boxes.Len() - 1)
return width return width
} }

86
menu.go
View File

@@ -13,45 +13,38 @@ type Menu struct {
parent tomo.Window parent tomo.Window
bounds image.Rectangle bounds image.Rectangle
rootContainer tomo.ContainerBox rootContainer tomo.ContainerBox
tearLine tomo.Box tearLine tomo.Object
torn bool torn bool
} }
// NewMenu creates a new menu with the specified items. The menu will appear // NewMenu creates a new menu with the specified items. The menu will appear
// directly under the anchor Object. If the anchor is nil, it will appear // directly under the mouse pointer.
// directly under the mouse pointer instead. func NewMenu (parent tomo.Window, items ...tomo.Object) (*Menu, error) {
func NewMenu (anchor tomo.Object, items ...tomo.Object) (*Menu, error) { bounds := (image.Rectangle { }).Add(parent.MousePosition())
menu := &Menu { } return newMenu(parent, bounds, items...)
if anchor == nil { }
// TODO: *actually* put it under the mouse
window, err := tomo.NewWindow(menu.bounds)
if err != nil { return nil, err }
menu.Window = window
} else {
menu.bounds = menuBoundsFromAnchor(anchor)
menu.parent = anchor.GetBox().Window()
window, err := menu.parent.NewMenu(menu.bounds)
if err != nil { return nil, err }
menu.Window = window
}
// NewAnchoredMenu creates a new menu with the specified items. The menu will
// appear directly under the anchor.
func NewAnchoredMenu (anchor tomo.Object, items ...tomo.Object) (*Menu, error) {
parent := anchor.GetBox().Window()
bounds := menuBoundsFromAnchor(anchor)
return newMenu(parent, bounds, items...)
}
func newMenu (parent tomo.Window, bounds image.Rectangle, items ...tomo.Object) (*Menu, error) {
menu := &Menu { }
menu.bounds = bounds
menu.parent = parent
window, err := menu.parent.NewMenu(menu.bounds)
if err != nil { return nil, err }
menu.Window = window
menu.rootContainer = tomo.NewContainerBox() menu.rootContainer = tomo.NewContainerBox()
menu.rootContainer.SetLayout(layouts.ContractVertical) menu.rootContainer.SetAttr(tomo.ALayout(layouts.ContractVertical))
if !menu.torn { if !menu.torn {
menu.tearLine = tomo.NewBox() menu.tearLine = menu.newTearLine()
menu.tearLine.SetRole(tomo.R("objects", "TearLine", ""))
menu.tearLine.SetFocusable(true)
menu.tearLine.OnKeyUp(func (key input.Key, numberPad bool) {
if key != input.KeyEnter && key != input.Key(' ') { return }
menu.TearOff()
})
menu.tearLine.OnMouseUp(func (button input.Button) {
if button != input.ButtonLeft { return }
if menu.tearLine.MousePosition().In(menu.tearLine.Bounds()) {
menu.TearOff()
}
})
menu.rootContainer.Add(menu.tearLine) menu.rootContainer.Add(menu.tearLine)
} }
@@ -65,7 +58,8 @@ func NewMenu (anchor tomo.Object, items ...tomo.Object) (*Menu, error) {
}) })
} }
} }
menu.rootContainer.SetRole(tomo.R("objects", "Container", "menu")) menu.rootContainer.SetRole(tomo.R("objects", "Container"))
menu.rootContainer.SetTag("menu", true)
menu.Window.SetRoot(menu.rootContainer) menu.Window.SetRoot(menu.rootContainer)
return menu, nil return menu, nil
@@ -85,12 +79,40 @@ func (this *Menu) TearOff () {
this.Window.Close() this.Window.Close()
this.rootContainer.Remove(this.tearLine) this.rootContainer.Remove(this.tearLine)
this.rootContainer.SetTag("torn", true)
this.Window = window this.Window = window
this.Window.SetRoot(this.rootContainer) this.Window.SetRoot(this.rootContainer)
this.Window.SetVisible(visible) this.Window.SetVisible(visible)
} }
func (this *Menu) newTearLine () tomo.Object {
tearLine := tomo.NewBox()
tearLine.SetRole(tomo.R("objects", "TearLine"))
tearLine.SetFocusable(true)
tearLine.OnKeyDown(func (key input.Key, numberPad bool) bool {
if key != input.KeyEnter && key != input.Key(' ') { return false }
return true
})
tearLine.OnKeyUp(func (key input.Key, numberPad bool) bool {
if key != input.KeyEnter && key != input.Key(' ') { return false }
this.TearOff()
return true
})
tearLine.OnButtonDown(func (button input.Button) bool {
if button != input.ButtonLeft { return false }
return true
})
tearLine.OnButtonUp(func (button input.Button) bool {
if button != input.ButtonLeft { return false }
if tearLine.Window().MousePosition().In(tearLine.Bounds()) {
this.TearOff()
}
return true
})
return tearLine
}
func menuBoundsFromAnchor (anchor tomo.Object) image.Rectangle { func menuBoundsFromAnchor (anchor tomo.Object) image.Rectangle {
bounds := anchor.GetBox().Bounds() bounds := anchor.GetBox().Bounds()
return image.Rect ( return image.Rect (

View File

@@ -5,7 +5,7 @@ import "git.tebibyte.media/tomo/tomo/input"
import "git.tebibyte.media/tomo/tomo/event" import "git.tebibyte.media/tomo/tomo/event"
import "git.tebibyte.media/tomo/objects/layouts" import "git.tebibyte.media/tomo/objects/layouts"
// MenuItem is a clickable button. // MenuItem is a selectable memu item.
type MenuItem struct { type MenuItem struct {
tomo.ContainerBox tomo.ContainerBox
@@ -20,24 +20,27 @@ type MenuItem struct {
// NewMenuItem creates a new menu item with the specified text. // NewMenuItem creates a new menu item with the specified text.
func NewMenuItem (text string) *MenuItem { func NewMenuItem (text string) *MenuItem {
return NewIconMenuItem(tomo.IconUnknown, text)
}
// NewIconMenuItem creates a new menu item with the specified icon and text.
func NewIconMenuItem (icon tomo.Icon, text string) *MenuItem {
box := &MenuItem { box := &MenuItem {
ContainerBox: tomo.NewContainerBox(), ContainerBox: tomo.NewContainerBox(),
label: NewLabel(text), label: NewLabel(text),
icon: NewIcon("", tomo.IconSizeSmall), icon: NewIcon(icon, tomo.IconSizeSmall),
} }
box.SetRole(tomo.R("objects", "MenuItem", "")) box.SetRole(tomo.R("objects", "MenuItem"))
box.label.SetAlign(tomo.AlignStart, tomo.AlignMiddle) box.label.SetAttr(tomo.AAlign(tomo.AlignStart, tomo.AlignMiddle))
box.SetLayout(layouts.NewGrid([]bool { false, true }, []bool { true })) box.SetAttr(tomo.ALayout(layouts.Row { false, true }))
box.Add(box.icon) box.Add(box.icon)
box.Add(box.label) box.Add(box.label)
box.CaptureDND(true) box.SetInputMask(true)
box.CaptureMouse(true) box.OnButtonDown(box.handleButtonDown)
box.CaptureScroll(true) box.OnButtonUp(box.handleButtonUp)
box.CaptureKeyboard(true) box.OnKeyDown(box.handleKeyDown)
box.OnMouseUp(box.handleMouseUp)
box.OnKeyUp(box.handleKeyUp) box.OnKeyUp(box.handleKeyUp)
box.SetFocusable(true) box.SetFocusable(true)
return box return box
@@ -51,8 +54,7 @@ func (this *MenuItem) SetText (text string) {
// SetIcon sets an icon for this item. Setting the icon to IconUnknown will // SetIcon sets an icon for this item. Setting the icon to IconUnknown will
// remove it. // remove it.
func (this *MenuItem) SetIcon (id tomo.Icon) { func (this *MenuItem) SetIcon (id tomo.Icon) {
if this.icon != nil { this.Remove(this.icon) } this.icon.SetIcon(id, tomo.IconSizeSmall)
this.Insert(NewIcon(id, tomo.IconSizeSmall), this.label)
} }
// OnClick specifies a function to be called when the menu item is clicked. // OnClick specifies a function to be called when the menu item is clicked.
@@ -60,14 +62,26 @@ func (this *MenuItem) OnClick (callback func ()) event.Cookie {
return this.on.click.Connect(callback) return this.on.click.Connect(callback)
} }
func (this *MenuItem) handleKeyUp (key input.Key, numberPad bool) { func (this *MenuItem) handleKeyDown (key input.Key, numberPad bool) bool {
if key != input.KeyEnter && key != input.Key(' ') { return } if key != input.KeyEnter && key != input.Key(' ') { return false }
this.on.click.Broadcast() return true
} }
func (this *MenuItem) handleMouseUp (button input.Button) { func (this *MenuItem) handleKeyUp (key input.Key, numberPad bool) bool {
if button != input.ButtonLeft { return } if key != input.KeyEnter && key != input.Key(' ') { return false }
if this.MousePosition().In(this.Bounds()) { this.on.click.Broadcast()
return true
}
func (this *MenuItem) handleButtonDown (button input.Button) bool {
if button != input.ButtonLeft { return false }
return true
}
func (this *MenuItem) handleButtonUp (button input.Button) bool {
if button != input.ButtonLeft { return false }
if this.Window().MousePosition().In(this.Bounds()) {
this.on.click.Broadcast() this.on.click.Broadcast()
} }
return true
} }

46
mimeicon.go Normal file
View File

@@ -0,0 +1,46 @@
package objects
import "git.tebibyte.media/tomo/tomo"
import "git.tebibyte.media/tomo/tomo/data"
import "git.tebibyte.media/tomo/tomo/canvas"
// MimeIcon displays an icon of a MIME type.
type MimeIcon struct {
tomo.Box
mime data.Mime
size tomo.IconSize
}
// NewMimeIcon creates a new icon from a MIME type.
func NewMimeIcon (mime data.Mime, size tomo.IconSize) *MimeIcon {
this := &MimeIcon {
Box: tomo.NewBox(),
}
this.SetRole(tomo.R("objects", "MimeIcon"))
this.SetIcon(mime, size)
this.OnIconSetChange(this.handleIconSetChange)
return this
}
// SetIcon sets the MIME type and size of the icon.
func (this *MimeIcon) SetIcon (mime data.Mime, size tomo.IconSize) {
if this.mime == mime && this.size == size { return }
this.mime = mime
this.size = size
this.setTexture(tomo.MimeIconTexture(mime, size))
}
func (this *MimeIcon) handleIconSetChange () {
this.setTexture(tomo.MimeIconTexture(this.mime, this.size))
}
func (this *MimeIcon) setTexture (texture canvas.Texture) {
this.SetAttr(tomo.ATexture(texture))
this.SetAttr(tomo.ATextureMode(tomo.TextureModeCenter))
if texture == nil {
this.SetAttr(tomo.AMinimumSize(0, 0))
} else {
bounds := texture.Bounds()
this.SetAttr(tomo.AttrMinimumSize(bounds.Max.Sub(bounds.Min)))
}
}

View File

@@ -15,8 +15,8 @@ type NumberInput struct {
increment *Button increment *Button
decrement *Button decrement *Button
on struct { on struct {
enter event.FuncBroadcaster valueChange event.FuncBroadcaster
edit event.FuncBroadcaster confirm event.FuncBroadcaster
} }
} }
@@ -28,72 +28,83 @@ func NewNumberInput (value float64) *NumberInput {
increment: NewButton(""), increment: NewButton(""),
decrement: NewButton(""), decrement: NewButton(""),
} }
box.SetRole(tomo.R("objects", "NumberInput", "")) box.SetRole(tomo.R("objects", "NumberInput"))
box.Add(box.input) box.Add(box.input)
box.Add(box.decrement) box.Add(box.decrement)
box.Add(box.increment) box.Add(box.increment)
box.SetLayout(layouts.NewGrid([]bool { true, false, false }, []bool { true })) box.SetAttr(tomo.ALayout(layouts.Row { true, false, false }))
box.increment.SetIcon(tomo.IconValueIncrement) box.increment.SetIcon(tomo.IconValueIncrement)
box.decrement.SetIcon(tomo.IconValueDecrement) box.decrement.SetIcon(tomo.IconValueDecrement)
box.SetValue(value) box.SetValue(value)
box.CaptureScroll(true)
box.CaptureKeyboard(true)
box.OnScroll(box.handleScroll) box.OnScroll(box.handleScroll)
box.OnKeyDown(box.handleKeyDown) box.OnKeyDown(box.handleKeyDown)
box.input.OnEnter(box.handleEnter) box.OnKeyUp(box.handleKeyUp)
box.input.OnEdit(box.on.edit.Broadcast) box.input.OnConfirm(box.handleConfirm)
box.input.OnValueChange(box.on.valueChange.Broadcast)
box.increment.OnClick(func () { box.shift(1) }) box.increment.OnClick(func () { box.shift(1) })
box.decrement.OnClick(func () { box.shift(-1) }) box.decrement.OnClick(func () { box.shift(-1) })
return box return box
} }
// SetValue sets the value of the input.
func (this *NumberInput) SetValue (value float64) {
this.input.SetText(strconv.FormatFloat(value, 'g', -1, 64))
}
// Value returns the value of the input. // Value returns the value of the input.
func (this *NumberInput) Value () float64 { func (this *NumberInput) Value () float64 {
value, _ := strconv.ParseFloat(this.input.Text(), 64) value, _ := strconv.ParseFloat(this.input.Text(), 64)
return value return value
} }
// OnEnter specifies a function to be called when the user presses enter within // SetValue sets the value of the input.
// the text input. func (this *NumberInput) SetValue (value float64) {
func (this *NumberInput) OnEnter (callback func ()) event.Cookie { this.input.SetText(strconv.FormatFloat(value, 'g', -1, 64))
return this.on.enter.Connect(callback)
} }
// OnEdit specifies a function to be called when the user edits the input value. // OnValueChange specifies a function to be called when the user edits the input
func (this *NumberInput) OnEdit (callback func ()) event.Cookie { // value.
return this.on.edit.Connect(callback) func (this *NumberInput) OnValueChange (callback func ()) event.Cookie {
return this.on.valueChange.Connect(callback)
}
// OnConfirm specifies a function to be called when the user presses enter within
// the number input.
func (this *NumberInput) OnConfirm (callback func ()) event.Cookie {
return this.on.confirm.Connect(callback)
} }
func (this *NumberInput) shift (by int) { func (this *NumberInput) shift (by int) {
this.SetValue(this.Value() + float64(by)) this.SetValue(this.Value() + float64(by))
this.on.edit.Broadcast() this.on.valueChange.Broadcast()
} }
func (this *NumberInput) handleKeyDown (key input.Key, numpad bool) { func (this *NumberInput) handleKeyDown (key input.Key, numpad bool) bool {
switch key { switch key {
case input.KeyUp: this.shift(1) case input.KeyUp:
case input.KeyDown: this.shift(-1) this.shift(1)
default: this.input.handleKeyDown(key, numpad) return true
case input.KeyDown:
this.shift(-1)
return true
} }
return false
} }
func (this *NumberInput) handleScroll (x, y float64) { func (this *NumberInput) handleKeyUp (key input.Key, numpad bool) bool {
switch key {
case input.KeyUp: return true
case input.KeyDown: return true
}
return false
}
func (this *NumberInput) handleScroll (x, y float64) bool {
if x == 0 { if x == 0 {
this.shift(-int(math.Round(y))) this.shift(-int(math.Round(y)))
} else { return true
this.input.handleScroll(x, y)
} }
return false
} }
func (this *NumberInput) handleEnter () { func (this *NumberInput) handleConfirm () {
this.SetValue(this.Value()) this.SetValue(this.Value())
this.on.enter.Broadcast() this.on.confirm.Broadcast()
} }

View File

@@ -33,21 +33,20 @@ func newScrollbar (orient string) *Scrollbar {
} }
this.Add(this.handle) this.Add(this.handle)
this.SetFocusable(true) this.SetFocusable(true)
this.SetInputMask(true)
this.CaptureDND(true) this.OnKeyUp(this.handleKeyUp)
this.CaptureMouse(true)
this.CaptureScroll(true)
this.CaptureKeyboard(true)
this.OnKeyDown(this.handleKeyDown) this.OnKeyDown(this.handleKeyDown)
this.OnMouseDown(this.handleMouseDown) this.OnButtonDown(this.handleButtonDown)
this.OnMouseUp(this.handleMouseUp) this.OnButtonUp(this.handleButtonUp)
this.OnMouseMove(this.handleMouseMove) this.OnMouseMove(this.handleMouseMove)
this.OnScroll(this.handleScroll) this.OnScroll(this.handleScroll)
this.handle.SetRole(tomo.R("objects", "SliderHandle", orient)) this.handle.SetRole(tomo.R("objects", "SliderHandle"))
this.SetRole(tomo.R("objects", "Slider", orient)) this.handle.SetTag(orient, true)
this.SetRole(tomo.R("objects", "Slider"))
this.SetTag(orient, true)
return this return this
} }
@@ -67,7 +66,7 @@ func (this *Scrollbar) Link (box tomo.ContentObject) event.Cookie {
this.layout.linked = box this.layout.linked = box
this.linkCookie = this.newLinkCookie ( this.linkCookie = this.newLinkCookie (
box.OnContentBoundsChange(this.handleLinkedContentBoundsChange)) box.OnContentBoundsChange(this.handleLinkedContentBoundsChange))
this.SetLayout(this.layout) this.SetAttr(tomo.ALayout(this.layout))
return this.linkCookie return this.linkCookie
} }
@@ -80,12 +79,20 @@ func (this *Scrollbar) handleLinkedContentBoundsChange () {
} else { } else {
this.layout.value = this.layout.contentPos() / trackLength this.layout.value = this.layout.contentPos() / trackLength
} }
this.SetLayout(this.layout) this.SetAttr(tomo.ALayout(this.layout))
if this.layout.value != previousValue { if this.layout.value != previousValue {
this.on.valueChange.Broadcast() this.on.valueChange.Broadcast()
} }
} }
// Value returns the value of the scrollbar between 0 and 1 where 0 is scrolled
// all the way to the left/top, and 1 is scrolled all the way to the
// right/bottom.
func (this *Scrollbar) Value () float64 {
if this.layout.linked == nil { return 0 }
return this.layout.value
}
// SetValue sets the value of the scrollbar between 0 and 1, where 0 is scrolled // SetValue sets the value of the scrollbar between 0 and 1, where 0 is scrolled
// all the way to the left/top, and 1 is scrolled all the way to the // all the way to the left/top, and 1 is scrolled all the way to the
// right/bottom. // right/bottom.
@@ -106,49 +113,77 @@ func (this *Scrollbar) SetValue (value float64) {
} }
// Value returns the value of the scrollbar between 0 and 1 where 0 is scrolled // OnValueChange specifies a function to be called when the user changes the
// all the way to the left/top, and 1 is scrolled all the way to the // position of the scrollbar.
// right/bottom.
func (this *Scrollbar) Value () float64 {
if this.layout.linked == nil { return 0 }
return this.layout.value
}
// OnValueChange specifies a function to be called when the position of the
// scrollbar changes.
func (this *Scrollbar) OnValueChange (callback func ()) event.Cookie { func (this *Scrollbar) OnValueChange (callback func ()) event.Cookie {
return this.on.valueChange.Connect(callback) return this.on.valueChange.Connect(callback)
} }
func (this *Scrollbar) handleKeyDown (key input.Key, numpad bool) { // PageSize returns the scroll distance of a page.
var increment float64; if this.layout.vertical { func (this *Scrollbar) PageSize () int {
increment = -0.05 if this.layout.linked == nil { return 0 }
viewport := this.layout.linked.GetBox().InnerBounds()
if this.layout.vertical {
return viewport.Dy()
} else { } else {
increment = 0.05 return viewport.Dx()
}
switch key {
case input.KeyUp, input.KeyLeft:
if this.Modifiers().Alt {
this.SetValue(0)
} else {
this.SetValue(this.Value() - increment)
}
case input.KeyDown, input.KeyRight:
if this.Modifiers().Alt {
this.SetValue(1)
} else {
this.SetValue(this.Value() + increment)
}
case input.KeyHome:
this.SetValue(0)
case input.KeyEnd:
this.SetValue(1)
} }
} }
func (this *Scrollbar) handleMouseDown (button input.Button) { // StepSize returns the scroll distance of a step.
pointer := this.MousePosition() func (this *Scrollbar) StepSize () int {
// FIXME: this should not be hardcoded, need to get base font metrics
// from tomo somehow. should be (emspace, lineheight)
return 16
}
func (this *Scrollbar) handleKeyUp (key input.Key, numpad bool) bool {
switch key {
case input.KeyUp, input.KeyLeft: return true
case input.KeyDown, input.KeyRight: return true
case input.KeyPageUp: return true
case input.KeyPageDown: return true
case input.KeyHome: return true
case input.KeyEnd: return true
}
return false
}
func (this *Scrollbar) handleKeyDown (key input.Key, numpad bool) bool {
modifiers := this.Window().Modifiers()
switch key {
case input.KeyUp, input.KeyLeft:
if modifiers.Alt {
this.SetValue(0)
} else {
this.scrollBy(this.StepSize())
}
return true
case input.KeyDown, input.KeyRight:
if modifiers.Alt {
this.SetValue(1)
} else {
this.scrollBy(-this.StepSize())
}
case input.KeyPageUp:
this.scrollBy(this.PageSize())
return true
case input.KeyPageDown:
this.scrollBy(-this.PageSize())
return true
case input.KeyHome:
this.SetValue(0)
return true
case input.KeyEnd:
this.SetValue(1)
return true
}
return false
}
func (this *Scrollbar) handleButtonDown (button input.Button) bool {
pointer := this.Window().MousePosition()
handle := this.handle.Bounds() handle := this.handle.Bounds()
within := pointer.In(handle) within := pointer.In(handle)
@@ -173,38 +208,52 @@ func (this *Scrollbar) handleMouseDown (button input.Button) {
} }
case input.ButtonMiddle: case input.ButtonMiddle:
if above { if above {
this.scrollBy(this.pageSize()) this.scrollBy(this.PageSize())
} else { } else {
this.scrollBy(-this.pageSize()) this.scrollBy(-this.PageSize())
} }
case input.ButtonRight: case input.ButtonRight:
if above { if above {
this.scrollBy(this.stepSize()) this.scrollBy(this.StepSize())
} else { } else {
this.scrollBy(-this.stepSize()) this.scrollBy(-this.StepSize())
} }
} }
return true
} }
func (this *Scrollbar) handleMouseUp (button input.Button) { func (this *Scrollbar) handleButtonUp (button input.Button) bool {
if button != input.ButtonLeft || !this.dragging { return } if button != input.ButtonLeft || !this.dragging { return true }
this.dragging = false this.dragging = false
return true
} }
func (this *Scrollbar) handleMouseMove () { func (this *Scrollbar) handleMouseMove () bool {
if !this.dragging { return } if !this.dragging { return false }
this.drag() this.drag()
return true
} }
func (this *Scrollbar) handleScroll (x, y float64) { func (this *Scrollbar) handleScroll (x, y float64) bool {
if this.layout.linked == nil { return } if this.layout.linked == nil { return false }
delta := (x + y)
if this.layout.vertical {
x = 0
y = delta
} else {
x = delta
y = 0
}
this.layout.linked.ScrollTo ( this.layout.linked.ScrollTo (
this.layout.linked.ContentBounds().Min. this.layout.linked.ContentBounds().Min.
Sub(image.Pt(int(x), int(y)))) Sub(image.Pt(int(x), int(y))))
return true
} }
func (this *Scrollbar) drag () { func (this *Scrollbar) drag () {
pointer := this.MousePosition().Sub(this.dragOffset) pointer := this.Window().MousePosition().Sub(this.dragOffset)
gutter := this.InnerBounds() gutter := this.InnerBounds()
handle := this.handle.Bounds() handle := this.handle.Bounds()
@@ -229,22 +278,6 @@ func (this *Scrollbar) fallbackDragOffset () image.Point {
} }
} }
func (this *Scrollbar) pageSize () int {
if this.layout.linked == nil { return 0 }
viewport := this.layout.linked.GetBox().InnerBounds()
if this.layout.vertical {
return viewport.Dy()
} else {
return viewport.Dx()
}
}
func (this *Scrollbar) stepSize () int {
// FIXME: this should not be hardcoded, need to get base font metrics
// from tomo.somehow. should be (emspace, lineheight)
return 16
}
func (this *Scrollbar) scrollBy (distance int) { func (this *Scrollbar) scrollBy (distance int) {
if this.layout.linked == nil { return } if this.layout.linked == nil { return }
var vector image.Point; if this.layout.vertical { var vector image.Point; if this.layout.vertical {
@@ -274,7 +307,7 @@ func (this *scrollbarCookie) Close () {
cookie.Close() cookie.Close()
} }
this.owner.layout.linked = nil this.owner.layout.linked = nil
this.owner.SetLayout(this.owner.layout) this.owner.SetAttr(tomo.ALayout(this.owner.layout))
} }
type scrollbarLayout struct { type scrollbarLayout struct {
@@ -283,14 +316,14 @@ type scrollbarLayout struct {
linked tomo.ContentObject linked tomo.ContentObject
} }
func (scrollbarLayout) MinimumSize (hints tomo.LayoutHints, boxes []tomo.Box) image.Point { func (scrollbarLayout) MinimumSize (hints tomo.LayoutHints, boxes tomo.BoxQuerier) image.Point {
if len(boxes) != 1 { return image.Pt(0, 0) } if boxes.Len() != 1 { return image.Pt(0, 0) }
return boxes[0].MinimumSize() return boxes.MinimumSize(0)
} }
func (this scrollbarLayout) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) { func (this scrollbarLayout) Arrange (hints tomo.LayoutHints, boxes tomo.BoxArranger) {
if len(boxes) != 1 { return } if boxes.Len() != 1 { return }
handle := image.Rectangle { Max: boxes[0].MinimumSize() } handle := image.Rectangle { Max: boxes.MinimumSize(0) }
gutter := hints.Bounds gutter := hints.Bounds
var gutterLength float64; var gutterLength float64;
@@ -311,7 +344,7 @@ func (this scrollbarLayout) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) {
// and we shouldn't be adding and removing boxes, so this is // and we shouldn't be adding and removing boxes, so this is
// really the only good way to hide things. // really the only good way to hide things.
// TODO perhaps have a "Hidden" rectangle in the Tomo API? // TODO perhaps have a "Hidden" rectangle in the Tomo API?
boxes[0].SetBounds(image.Rect(-16, -16, 0, 0)) boxes.SetBounds(0, image.Rect(-32, -32, -16, -16))
return return
} }
if this.vertical { if this.vertical {
@@ -331,15 +364,15 @@ func (this scrollbarLayout) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) {
handle = handle.Sub(handleOffset).Add(gutter.Min) handle = handle.Sub(handleOffset).Add(gutter.Min)
// place handle // place handle
boxes[0].SetBounds(handle) boxes.SetBounds(0, handle)
} }
func (this scrollbarLayout) RecommendedHeight (hints tomo.LayoutHints, boxes []tomo.Box, width int) int { func (this scrollbarLayout) RecommendedHeight (hints tomo.LayoutHints, boxes tomo.BoxQuerier, width int) int {
return this.MinimumSize(hints, boxes).X return this.MinimumSize(hints, boxes).X
} }
func (this scrollbarLayout) RecommendedWidth (hints tomo.LayoutHints, boxes []tomo.Box, height int) int { func (this scrollbarLayout) RecommendedWidth (hints tomo.LayoutHints, boxes tomo.BoxQuerier, height int) int {
return this.MinimumSize(hints, boxes).Y return this.MinimumSize(hints, boxes).Y
} }

View File

@@ -2,7 +2,9 @@ package objects
import "image" import "image"
import "git.tebibyte.media/tomo/tomo" import "git.tebibyte.media/tomo/tomo"
import "git.tebibyte.media/tomo/tomo/input"
import "git.tebibyte.media/tomo/tomo/event" import "git.tebibyte.media/tomo/tomo/event"
import "git.tebibyte.media/tomo/objects/layouts"
// ScrollSide determines which Scrollbars are active in a ScrollContainer. // ScrollSide determines which Scrollbars are active in a ScrollContainer.
type ScrollSide int; const ( type ScrollSide int; const (
@@ -38,30 +40,44 @@ func (sides ScrollSide) String () string {
// ScrollContainer couples a ContentBox with one or two Scrollbars. // ScrollContainer couples a ContentBox with one or two Scrollbars.
type ScrollContainer struct { type ScrollContainer struct {
tomo.ContainerBox tomo.ContainerBox
layout *scrollContainerLayout
root tomo.ContentObject
horizontal *Scrollbar
vertical *Scrollbar
horizontalCookie event.Cookie horizontalCookie event.Cookie
verticalCookie event.Cookie verticalCookie event.Cookie
on struct {
valueChange event.FuncBroadcaster
}
} }
// NewScrollContainer creates a new scroll container. // NewScrollContainer creates a new scroll container.
func NewScrollContainer (sides ScrollSide) *ScrollContainer { func NewScrollContainer (sides ScrollSide) *ScrollContainer {
this := &ScrollContainer { this := &ScrollContainer {
ContainerBox: tomo.NewContainerBox(), ContainerBox: tomo.NewContainerBox(),
layout: &scrollContainerLayout { },
} }
if sides.Vertical() { if sides.Vertical() {
this.layout.vertical = NewVerticalScrollbar() this.vertical = NewVerticalScrollbar()
this.Add(this.layout.vertical) this.vertical.OnValueChange(this.handleValueChange)
this.Add(this.vertical)
} }
if sides.Horizontal() { if sides.Horizontal() {
this.layout.horizontal = NewHorizontalScrollbar() this.horizontal = NewHorizontalScrollbar()
this.Add(this.layout.horizontal) this.horizontal.OnValueChange(this.handleValueChange)
this.Add(this.horizontal)
} }
this.CaptureScroll(true)
this.OnScroll(this.handleScroll) this.OnScroll(this.handleScroll)
this.SetRole(tomo.R("objects", "ScrollContainer", sides.String())) this.OnKeyDown(this.handleKeyDown)
this.SetLayout(this.layout) this.OnKeyUp(this.handleKeyUp)
this.SetRole(tomo.R("objects", "ScrollContainer"))
this.SetTag(sides.String(), true)
if sides == ScrollHorizontal {
this.SetAttr(tomo.ALayout(layouts.NewGrid(true)(true, false)))
} else {
this.SetAttr(tomo.ALayout(layouts.NewGrid(true, false)(true, false)))
}
return this return this
} }
@@ -69,9 +85,9 @@ func NewScrollContainer (sides ScrollSide) *ScrollContainer {
// a time, and setting it will remove and unlink the current child if there is // a time, and setting it will remove and unlink the current child if there is
// one. // one.
func (this *ScrollContainer) SetRoot (root tomo.ContentObject) { func (this *ScrollContainer) SetRoot (root tomo.ContentObject) {
if this.layout.root != nil { if this.root != nil {
// remove root and close cookies // remove root and close cookies
this.Remove(this.layout.root) this.Remove(this.root)
if this.horizontalCookie != nil { if this.horizontalCookie != nil {
this.horizontalCookie.Close() this.horizontalCookie.Close()
this.horizontalCookie = nil this.horizontalCookie = nil
@@ -81,118 +97,143 @@ func (this *ScrollContainer) SetRoot (root tomo.ContentObject) {
this.verticalCookie = nil this.verticalCookie = nil
} }
} }
this.layout.root = root this.root = root
if root != nil { if root != nil {
// insert root at the beginning (for keynav) // insert root at the beginning (for keynav)
switch { switch {
case this.layout.vertical != nil: case this.vertical != nil:
this.Insert(root, this.layout.vertical) this.Insert(root, this.vertical)
case this.layout.horizontal != nil: case this.horizontal != nil:
this.Insert(root, this.layout.horizontal) this.Insert(root, this.horizontal)
default: default:
this.Add(root) this.Add(root)
} }
// link root and remember cookies // link root and remember cookies
if this.layout.horizontal != nil { if this.horizontal != nil {
this.horizontalCookie = this.layout.horizontal.Link(root) this.horizontalCookie = this.horizontal.Link(root)
} }
if this.layout.vertical != nil { if this.vertical != nil {
this.verticalCookie = this.layout.vertical.Link(root) this.verticalCookie = this.vertical.Link(root)
} }
} }
} }
// SetValue sets the horizontal and vertical scrollbar values where 0 is all the
// way to the left/top, and 1 is all the way to the right/bottom.
func (this *ScrollContainer) SetValue (x, y float64) {
if this.layout.horizontal != nil {
this.layout.horizontal.SetValue(x)
}
if this.layout.vertical != nil {
this.layout.vertical.SetValue(y)
}
}
// Value returns the horizontal and vertical scrollbar values where 0 is all the // Value returns the horizontal and vertical scrollbar values where 0 is all the
// way to the left/top, and 1 is all the way to the right/bottom. // way to the left/top, and 1 is all the way to the right/bottom.
func (this *ScrollContainer) Value () (x, y float64) { func (this *ScrollContainer) Value () (x, y float64) {
if this.layout.horizontal != nil { if this.horizontal != nil {
x = this.layout.horizontal.Value() x = this.horizontal.Value()
} }
if this.layout.vertical != nil { if this.vertical != nil {
y = this.layout.vertical.Value() y = this.vertical.Value()
} }
return x, y return x, y
} }
func (this *ScrollContainer) handleScroll (x, y float64) { // SetValue sets the horizontal and vertical scrollbar values where 0 is all the
if this.layout.root == nil { return } // way to the left/top, and 1 is all the way to the right/bottom.
this.layout.root.ScrollTo ( func (this *ScrollContainer) SetValue (x, y float64) {
this.layout.root.ContentBounds().Min.
Sub(image.Pt(int(x), int(y))))
}
// TODO: remove this and replace it with something from the layouts package
type scrollContainerLayout struct {
root tomo.ContentObject
horizontal *Scrollbar
vertical *Scrollbar
}
func (this *scrollContainerLayout) MinimumSize (hints tomo.LayoutHints, boxes []tomo.Box) image.Point {
var minimum image.Point; if this.root != nil {
minimum = this.root.GetBox().MinimumSize()
}
if this.horizontal != nil { if this.horizontal != nil {
minimum.Y += this.horizontal.MinimumSize().Y this.horizontal.SetValue(x)
} }
if this.vertical != nil { if this.vertical != nil {
minimum.X += this.vertical.MinimumSize().X this.vertical.SetValue(y)
minimum.Y = max(minimum.Y, this.vertical.MinimumSize().Y)
} }
if this.horizontal != nil {
minimum.X = max(minimum.X, this.horizontal.MinimumSize().X)
}
return minimum
} }
func (this *scrollContainerLayout) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) { // OnValueChange specifies a function to be called when the user changes the
rootBounds := hints.Bounds // position of the horizontal or vertical scrollbars.
func (this *ScrollContainer) OnValueChange (callback func ()) event.Cookie {
return this.on.valueChange.Connect(callback)
}
// PageSize returns the scroll distance of a page.
func (this *ScrollContainer) PageSize () image.Point {
page := image.Point { }
if this.horizontal != nil { if this.horizontal != nil {
rootBounds.Max.Y -= this.horizontal.MinimumSize().Y page.X = this.horizontal.PageSize()
} }
if this.vertical != nil { if this.vertical != nil {
rootBounds.Max.X -= this.vertical.MinimumSize().X page.Y = this.vertical.PageSize()
}
if this.root != nil {
this.root.GetBox().SetBounds(rootBounds)
} }
return page
}
// StepSize returns the scroll distance of a step.
func (this *ScrollContainer) StepSize () image.Point {
page := image.Point { }
if this.horizontal != nil { if this.horizontal != nil {
this.horizontal.SetBounds(image.Rect ( page.X = this.horizontal.StepSize()
hints.Bounds.Min.X,
rootBounds.Max.Y,
rootBounds.Max.X,
hints.Bounds.Max.Y))
} }
if this.vertical != nil { if this.vertical != nil {
this.vertical.SetBounds(image.Rect ( page.Y = this.vertical.StepSize()
rootBounds.Max.X,
hints.Bounds.Min.Y,
hints.Bounds.Max.X,
rootBounds.Max.Y))
} }
return page
} }
func (this *scrollContainerLayout) RecommendedHeight (hints tomo.LayoutHints, boxes []tomo.Box, width int) int { func (this *ScrollContainer) handleValueChange () {
return this.MinimumSize(hints, boxes).X this.on.valueChange.Broadcast()
} }
func (this *scrollContainerLayout) RecommendedWidth (hints tomo.LayoutHints, boxes []tomo.Box, height int) int { func (this *ScrollContainer) scrollBy (vector image.Point) {
return this.MinimumSize(hints, boxes).Y if this.root == nil { return }
if vector == (image.Point { }) { return }
this.root.ScrollTo (
this.root.ContentBounds().Min.
Sub(vector))
} }
func max (x, y int) int { func (this *ScrollContainer) handleScroll (x, y float64) bool {
if x > y { return x } if this.root == nil { return false }
return y this.scrollBy(image.Pt(int(x), int(y)))
return true
}
func (this *ScrollContainer) handleKeyDown (key input.Key, numpad bool) bool {
modifiers := this.Window().Modifiers()
vector := image.Point { }
switch key {
case input.KeyPageUp:
if modifiers.Shift {
vector.X -= this.PageSize().X
} else {
vector.Y -= this.PageSize().Y
}
this.scrollBy(vector)
return true
case input.KeyPageDown:
if modifiers.Shift {
vector.X += this.PageSize().X
} else {
vector.Y += this.PageSize().Y
}
this.scrollBy(vector)
return true
case input.KeyUp:
if modifiers.Shift {
vector.X -= this.StepSize().X
} else {
vector.Y -= this.StepSize().Y
}
this.scrollBy(vector)
return true
case input.KeyDown:
if modifiers.Shift {
vector.X += this.StepSize().X
} else {
vector.Y += this.StepSize().Y
}
this.scrollBy(vector)
return true
}
return false
}
func (this *ScrollContainer) handleKeyUp (key input.Key, numpad bool) bool {
switch key {
case input.KeyPageUp: return true
case input.KeyPageDown: return true
}
return false
} }

View File

@@ -12,6 +12,6 @@ func NewSeparator () *Separator {
this := &Separator { this := &Separator {
Box: tomo.NewBox(), Box: tomo.NewBox(),
} }
this.SetRole(tomo.R("objects", "Separator", "")) this.SetRole(tomo.R("objects", "Separator"))
return this return this
} }

137
slider.go
View File

@@ -1,5 +1,6 @@
package objects package objects
import "math"
import "image" import "image"
import "git.tebibyte.media/tomo/tomo" import "git.tebibyte.media/tomo/tomo"
import "git.tebibyte.media/tomo/tomo/input" import "git.tebibyte.media/tomo/tomo/input"
@@ -15,7 +16,8 @@ type Slider struct {
step float64 step float64
on struct { on struct {
slide event.FuncBroadcaster valueChange event.FuncBroadcaster
confirm event.FuncBroadcaster
} }
} }
@@ -33,27 +35,27 @@ func newSlider (orient string, value float64) *Slider {
}, },
layout: sliderLayout { layout: sliderLayout {
vertical: orient == "vertical", vertical: orient == "vertical",
value: math.NaN(),
}, },
step: 0.05, step: 0.05,
} }
this.Add(this.handle) this.Add(this.handle)
this.SetFocusable(true) this.SetFocusable(true)
this.CaptureDND(true)
this.CaptureMouse(true)
this.CaptureScroll(true)
this.CaptureKeyboard(true)
this.SetValue(value) this.SetValue(value)
this.SetInputMask(true)
this.OnKeyUp(this.handleKeyUp)
this.OnKeyDown(this.handleKeyDown) this.OnKeyDown(this.handleKeyDown)
this.OnMouseDown(this.handleMouseDown) this.OnButtonDown(this.handleButtonDown)
this.OnMouseUp(this.handleMouseUp) this.OnButtonUp(this.handleButtonUp)
this.OnMouseMove(this.handleMouseMove) this.OnMouseMove(this.handleMouseMove)
this.OnScroll(this.handleScroll) this.OnScroll(this.handleScroll)
this.handle.SetRole(tomo.R("objects", "SliderHandle", orient)) this.handle.SetRole(tomo.R("objects", "SliderHandle"))
this.SetRole(tomo.R("objects", "Slider", orient)) this.handle.SetTag(orient, true)
this.SetRole(tomo.R("objects", "Slider"))
this.SetTag(orient, true)
return this return this
} }
@@ -73,7 +75,7 @@ func (this *Slider) SetValue (value float64) {
if value > 1 { value = 1 } if value > 1 { value = 1 }
if value == this.layout.value { return } if value == this.layout.value { return }
this.layout.value = value this.layout.value = value
this.SetLayout(this.layout) this.SetAttr(tomo.ALayout(this.layout))
} }
// Value returns the value of the slider between 0 and 1. // Value returns the value of the slider between 0 and 1.
@@ -83,11 +85,17 @@ func (this *Slider) Value () float64 {
// OnValueChange specifies a function to be called when the user moves the // OnValueChange specifies a function to be called when the user moves the
// slider. // slider.
func (this *Slider) OnSlide (callback func ()) event.Cookie { func (this *Slider) OnValueChange (callback func ()) event.Cookie {
return this.on.slide.Connect(callback) return this.on.valueChange.Connect(callback)
} }
func (this *Slider) handleKeyDown (key input.Key, numpad bool) { // OnConfirm specifies a function to be called when the user stops moving the
// slider.
func (this *Slider) OnConfirm (callback func ()) event.Cookie {
return this.on.confirm.Connect(callback)
}
func (this *Slider) handleKeyDown (key input.Key, numpad bool) bool {
var increment float64; if this.layout.vertical { var increment float64; if this.layout.vertical {
increment = -0.05 increment = -0.05
} else { } else {
@@ -96,30 +104,45 @@ func (this *Slider) handleKeyDown (key input.Key, numpad bool) {
switch key { switch key {
case input.KeyUp, input.KeyLeft: case input.KeyUp, input.KeyLeft:
if this.Modifiers().Alt { if this.Window().Modifiers().Alt {
this.SetValue(0) this.SetValue(0)
} else { } else {
this.SetValue(this.Value() - increment) this.SetValue(this.Value() - increment)
} }
this.on.slide.Broadcast() this.on.valueChange.Broadcast()
return true
case input.KeyDown, input.KeyRight: case input.KeyDown, input.KeyRight:
if this.Modifiers().Alt { if this.Window().Modifiers().Alt {
this.SetValue(1) this.SetValue(1)
} else { } else {
this.SetValue(this.Value() + increment) this.SetValue(this.Value() + increment)
} }
this.on.slide.Broadcast() this.on.valueChange.Broadcast()
return true
case input.KeyHome: case input.KeyHome:
this.SetValue(0) this.SetValue(0)
this.on.slide.Broadcast() this.on.valueChange.Broadcast()
return true
case input.KeyEnd: case input.KeyEnd:
this.SetValue(1) this.SetValue(1)
this.on.slide.Broadcast() this.on.valueChange.Broadcast()
return true
} }
return false
} }
func (this *Slider) handleMouseDown (button input.Button) { func (this *Slider) handleKeyUp (key input.Key, numpad bool) bool {
pointer := this.MousePosition() switch key {
case input.KeyUp, input.KeyLeft: return true
case input.KeyDown, input.KeyRight: return true
case input.KeyHome: return true
case input.KeyEnd: return true
}
return false
}
func (this *Slider) handleButtonDown (button input.Button) bool {
pointer := this.Window().MousePosition()
handle := this.handle.Bounds() handle := this.handle.Bounds()
within := pointer.In(handle) within := pointer.In(handle)
@@ -145,40 +168,50 @@ func (this *Slider) handleMouseDown (button input.Button) {
case input.ButtonMiddle: case input.ButtonMiddle:
if above { if above {
this.SetValue(0) this.SetValue(0)
this.on.slide.Broadcast() this.on.valueChange.Broadcast()
this.on.confirm.Broadcast()
} else { } else {
this.SetValue(1) this.SetValue(1)
this.on.slide.Broadcast() this.on.valueChange.Broadcast()
this.on.confirm.Broadcast()
} }
case input.ButtonRight: case input.ButtonRight:
if above { if above {
this.SetValue(this.Value() - this.step) this.SetValue(this.Value() - this.step)
this.on.slide.Broadcast() this.on.valueChange.Broadcast()
this.on.confirm.Broadcast()
} else { } else {
this.SetValue(this.Value() + this.step) this.SetValue(this.Value() + this.step)
this.on.slide.Broadcast() this.on.valueChange.Broadcast()
this.on.confirm.Broadcast()
} }
} }
return true
} }
func (this *Slider) handleMouseUp (button input.Button) { func (this *Slider) handleButtonUp (button input.Button) bool {
if button != input.ButtonLeft || !this.dragging { return } if button != input.ButtonLeft || !this.dragging { return true }
this.dragging = false this.dragging = false
this.on.confirm.Broadcast()
return true
} }
func (this *Slider) handleMouseMove () { func (this *Slider) handleMouseMove () bool {
if !this.dragging { return } if !this.dragging { return false }
this.drag() this.drag()
return true
} }
func (this *Slider) handleScroll (x, y float64) { func (this *Slider) handleScroll (x, y float64) bool {
delta := (x + y) * 0.005 delta := (x + y) * 0.005
this.SetValue(this.Value() + delta) this.SetValue(this.Value() + delta)
this.on.slide.Broadcast() this.on.valueChange.Broadcast()
this.on.confirm.Broadcast()
return true
} }
func (this *Slider) drag () { func (this *Slider) drag () {
pointer := this.MousePosition().Sub(this.dragOffset) pointer := this.Window().MousePosition().Sub(this.dragOffset)
gutter := this.InnerBounds() gutter := this.InnerBounds()
handle := this.handle.Bounds() handle := this.handle.Bounds()
@@ -192,7 +225,7 @@ func (this *Slider) drag () {
float64(pointer.X) / float64(pointer.X) /
float64(gutter.Dx() - handle.Dx())) float64(gutter.Dx() - handle.Dx()))
} }
this.on.slide.Broadcast() this.on.valueChange.Broadcast()
} }
func (this *Slider) fallbackDragOffset () image.Point { func (this *Slider) fallbackDragOffset () image.Point {
@@ -210,39 +243,37 @@ type sliderLayout struct {
value float64 value float64
} }
func (sliderLayout) MinimumSize (hints tomo.LayoutHints, boxes []tomo.Box) image.Point { func (sliderLayout) MinimumSize (hints tomo.LayoutHints, boxes tomo.BoxQuerier) image.Point {
if len(boxes) != 1 { return image.Pt(0, 0) } if boxes.Len() != 1 { return image.Pt(0, 0) }
return boxes[0].MinimumSize() return boxes.MinimumSize(0)
} }
func (this sliderLayout) Arrange (hints tomo.LayoutHints, boxes []tomo.Box) { func (this sliderLayout) Arrange (hints tomo.LayoutHints, boxes tomo.BoxArranger) {
if len(boxes) != 1 { return } if boxes.Len() != 1 { return }
handle := image.Rectangle { Max: boxes[0].MinimumSize() } handle := image.Rectangle { Max: boxes.MinimumSize(0) }
gutter := hints.Bounds gutter := hints.Bounds
if this.vertical { if this.vertical {
height := gutter.Dy() - handle.Dy() height := gutter.Dy() - handle.Dy()
offset := int(float64(height) * (1 - this.value)) offset := int(float64(height) * (1 - this.value))
handle.Max.X = gutter.Dx() handle.Max.X = gutter.Dx()
boxes[0].SetBounds ( boxes.SetBounds (
handle. 0,
Add(image.Pt(0, offset)). handle.Add(image.Pt(0, offset)).Add(gutter.Min))
Add(gutter.Min))
} else { } else {
width := gutter.Dx() - handle.Dx() width := gutter.Dx() - handle.Dx()
offset := int(float64(width) * this.value) offset := int(float64(width) * this.value)
handle.Max.Y = gutter.Dy() handle.Max.Y = gutter.Dy()
boxes[0].SetBounds ( boxes.SetBounds (
handle. 0,
Add(image.Pt(offset, 0)). handle.Add(image.Pt(offset, 0)).Add(gutter.Min))
Add(gutter.Min))
} }
} }
func (this sliderLayout) RecommendedHeight (tomo.LayoutHints, []tomo.Box, int) int { func (this sliderLayout) RecommendedHeight (hints tomo.LayoutHints, boxes tomo.BoxQuerier, width int) int {
return 0 return this.MinimumSize(hints, boxes).X
} }
func (this sliderLayout) RecommendedWidth (tomo.LayoutHints, []tomo.Box, int) int { func (this sliderLayout) RecommendedWidth (hints tomo.LayoutHints, boxes tomo.BoxQuerier, height int) int {
return 0 return this.MinimumSize(hints, boxes).Y
} }

195
swatch.go Normal file
View File

@@ -0,0 +1,195 @@
package objects
import "log"
import "image"
import "image/color"
import "git.tebibyte.media/tomo/tomo"
import "git.tebibyte.media/tomo/tomo/input"
import "git.tebibyte.media/tomo/tomo/event"
import "git.tebibyte.media/tomo/tomo/canvas"
import "git.tebibyte.media/tomo/objects/layouts"
import "git.tebibyte.media/tomo/objects/internal"
// Swatch displays a color, allowing the user to edit it by clicking on it.
type Swatch struct {
tomo.CanvasBox
value color.Color
editing bool
label string
on struct {
valueChange event.FuncBroadcaster
confirm event.FuncBroadcaster
}
}
// NewSwatch creates a new swatch with the given color.
func NewSwatch (value color.Color) *Swatch {
swatch := &Swatch {
CanvasBox: tomo.NewCanvasBox(),
}
swatch.SetRole(tomo.R("objects", "Swatch"))
swatch.SetDrawer(swatch)
swatch.SetValue(value)
swatch.OnButtonDown(swatch.handleButtonDown)
swatch.OnButtonUp(swatch.handleButtonUp)
swatch.OnKeyDown(swatch.handleKeyDown)
swatch.OnKeyUp(swatch.handleKeyUp)
swatch.SetFocusable(true)
return swatch
}
// Value returns the color of the swatch.
func (this *Swatch) Value () color.Color {
return this.value
}
// SetValue sets the color of the swatch.
func (this *Swatch) SetValue (value color.Color) {
this.value = value
if value == nil { value = color.Transparent }
this.Invalidate()
}
// OnValueChange specifies a function to be called when the swatch's color
// is changed by the user.
func (this *Swatch) OnValueChange (callback func ()) event.Cookie {
return this.on.valueChange.Connect(callback)
}
// RGBA satisfies the color.Color interface
func (this *Swatch) RGBA () (r, g, b, a uint32) {
if this.value == nil { return }
return this.value.RGBA()
}
// OnConfirm specifies a function to be called when the user selects "OK" in the
// color picker.
func (this *Swatch) OnConfirm (callback func ()) event.Cookie {
return this.on.confirm.Connect(callback)
}
// Choose creates a modal that allows the user to edit the color of the swatch.
func (this *Swatch) Choose () {
if this.editing { return }
var err error
var window tomo.Window
if parent := this.Window(); parent != nil {
window, err = parent.NewChild(image.Rectangle { })
} else {
window, err = tomo.NewWindow(image.Rectangle { })
}
if err != nil {
log.Println("objects: could not create swatch modal:", err)
return
}
if this.label == "" {
window.SetTitle("Select Color")
} else {
window.SetTitle(this.label)
}
committed := false
colorPicker := NewHSVAColorPicker(this.Value())
colorMemory := this.value
hexInput := NewTextInput("")
hexInput.SetFocused(true)
cancelButton := NewButton("Cancel")
cancelButton.SetIcon(tomo.IconDialogCancel)
okButton := NewButton("OK")
okButton.SetIcon(tomo.IconDialogOkay)
updateHexInput := func () {
nrgba := color.NRGBAModel.Convert(colorPicker.Value()).(color.NRGBA)
hexInput.SetValue(internal.FormatNRGBA(nrgba))
}
updateHexInput()
commit := func () {
committed = true
window.Close()
}
colorPicker.OnValueChange(func () {
this.userSetValue(colorPicker.Value())
updateHexInput()
})
hexInput.OnConfirm(commit)
hexInput.OnValueChange(func () {
nrgba := internal.ParseNRGBA(hexInput.Value())
this.userSetValue(nrgba)
colorPicker.SetValue(nrgba)
})
cancelButton.OnClick(func () {
window.Close()
})
okButton.OnClick(commit)
controlRow := NewInnerContainer (
layouts.ContractHorizontal,
cancelButton,
okButton)
controlRow.SetAttr(tomo.AAlign(tomo.AlignEnd, tomo.AlignMiddle))
window.SetRoot(NewOuterContainer (
layouts.Column { true, false },
colorPicker,
NewInnerContainer(layouts.Row { false, true },
NewLabel("Hex"),
hexInput),
controlRow))
window.OnClose(func () {
if committed {
this.on.confirm.Broadcast()
} else {
this.userSetValue(colorMemory)
}
this.editing = false
})
this.editing = true
window.SetVisible(true)
}
func (this *Swatch) Draw (can canvas.Canvas) {
pen := can.Pen()
// transparency slash
pen.Stroke(color.RGBA { R: 255, A: 255 })
pen.StrokeWeight(1)
pen.Path(this.Bounds().Min, this.Bounds().Max)
// color
if this.value != nil {
pen.StrokeWeight(0)
pen.Fill(this.value)
pen.Rectangle(this.Bounds())
}
}
func (this *Swatch) userSetValue (value color.Color) {
this.SetValue(value)
this.on.valueChange.Broadcast()
}
func (this *Swatch) handleKeyDown (key input.Key, numberPad bool) bool {
if !isClickingKey(key) { return false }
this.Choose()
return true
}
func (this *Swatch) handleKeyUp (key input.Key, numberPad bool) bool {
if !isClickingKey(key) { return false }
return true
}
func (this *Swatch) handleButtonDown (button input.Button) bool {
if !isClickingButton(button) { return false }
return true
}
func (this *Swatch) handleButtonUp (button input.Button) bool {
if !isClickingButton(button) { return false }
if this.Window().MousePosition().In(this.Bounds()) {
this.Choose()
}
return true
}

135
tabbedcontainer.go Normal file
View File

@@ -0,0 +1,135 @@
package objects
import "git.tebibyte.media/tomo/tomo"
import "git.tebibyte.media/tomo/tomo/input"
import "git.tebibyte.media/tomo/objects/layouts"
type TabbedContainer struct {
tomo.ContainerBox
leftSpacer tomo.Box
rightSpacer tomo.Box
tabsRow tomo.ContainerBox
active string
tabs []*tab
}
func NewTabbedContainer () *TabbedContainer {
container := &TabbedContainer {
ContainerBox: tomo.NewContainerBox(),
}
container.SetRole(tomo.R("objects", "TabbedContainer"))
container.SetAttr(tomo.ALayout(layouts.Column { false, true }))
container.tabsRow = tomo.NewContainerBox()
container.tabsRow.SetRole(tomo.R("objects", "TabRow"))
container.Add(container.tabsRow)
container.leftSpacer = tomo.NewBox()
container.leftSpacer.SetRole(tomo.R("objects", "TabSpacer"))
container.leftSpacer.SetTag("left", true)
container.rightSpacer = tomo.NewBox()
container.rightSpacer.SetRole(tomo.R("objects", "TabSpacer"))
container.rightSpacer.SetTag("left", true)
container.ClearTabs()
container.setTabRowLayout()
return container
}
func (this *TabbedContainer) Activate (name string) {
if _, tab := this.findTab(this.active); tab != nil {
tab.setActive(false)
this.Remove(tab.root)
}
if _, tab := this.findTab(name); tab != nil {
tab.setActive(true)
this.Add(tab.root)
} else {
name = ""
}
this.active = name
}
func (this *TabbedContainer) AddTab (name string, root tomo.Object) {
tab := &tab {
TextBox: tomo.NewTextBox(),
name: name,
root: root,
}
tab.SetRole(tomo.R("objects", "Tab"))
tab.SetText(name)
tab.OnButtonDown(func (button input.Button) bool {
if button != input.ButtonLeft { return false }
this.Activate(name)
return true
})
tab.OnButtonUp(func (button input.Button) bool {
if button != input.ButtonLeft { return false }
return true
})
this.tabs = append(this.tabs, tab)
this.tabsRow.Insert(tab, this.rightSpacer)
this.setTabRowLayout()
// if the row was empty before, activate this tab
if len(this.tabs) == 1 {
this.Activate(name)
}
}
func (this *TabbedContainer) RemoveTab (name string) {
index, tab := this.findTab(name)
if index < 0 { return }
nextIndex := index - 1
this.tabsRow.Remove(tab)
this.tabs = append(this.tabs[:index], this.tabs[index - 1:]...)
this.setTabRowLayout()
if nextIndex < 0 { nextIndex = 0 }
if nextIndex >= len(this.tabs) { nextIndex = len(this.tabs) - 1 }
if nextIndex < 0 {
this.Activate("")
} else {
this.Activate(this.tabs[nextIndex].name)
}
}
func (this *TabbedContainer) ClearTabs () {
this.tabs = nil
this.tabsRow.Clear()
this.tabsRow.Add(this.leftSpacer)
this.tabsRow.Add(this.rightSpacer)
}
func (this *TabbedContainer) setTabRowLayout () {
row := make(layouts.Row, 1 + len(this.tabs) + 1)
row[len(row) - 1] = true
this.tabsRow.SetAttr(tomo.ALayout(row))
}
func (this *TabbedContainer) findTab (name string) (int, *tab) {
for index, tab := range this.tabs {
if tab.name == name { return index, tab }
}
return -1, nil
}
type tab struct {
tomo.TextBox
name string
root tomo.Object
}
func (this *tab) setActive (active bool) {
if active {
this.SetRole(tomo.R("objects", "Tab"))
this.SetTag("active", true)
} else {
this.SetRole(tomo.R("objects", "Tab"))
this.SetTag("active", false)
}
}

View File

@@ -11,97 +11,57 @@ type TextInput struct {
tomo.TextBox tomo.TextBox
text []rune text []rune
on struct { on struct {
enter event.FuncBroadcaster valueChange event.FuncBroadcaster
edit event.FuncBroadcaster confirm event.FuncBroadcaster
} }
} }
// NewTextInput creates a new text input containing the specified text. // NewTextInput creates a new text input containing the specified text.
func NewTextInput (text string) *TextInput { func NewTextInput (text string) *TextInput {
this := &TextInput { TextBox: tomo.NewTextBox() } this := &TextInput { TextBox: tomo.NewTextBox() }
this.SetRole(tomo.R("objects", "TextInput", "")) this.SetRole(tomo.R("objects", "TextInput"))
this.SetAlign(tomo.AlignStart, tomo.AlignMiddle) this.SetAttr(tomo.AAlign(tomo.AlignStart, tomo.AlignMiddle))
this.SetAttr(tomo.AOverflow(true, false))
this.SetText(text) this.SetText(text)
this.SetFocusable(true) this.SetFocusable(true)
this.SetSelectable(true) this.SetSelectable(true)
this.SetOverflow(true, false)
this.OnKeyDown(this.handleKeyDown) this.OnKeyDown(this.handleKeyDown)
this.OnKeyUp(this.handleKeyUp)
this.OnScroll(this.handleScroll) this.OnScroll(this.handleScroll)
return this return this
} }
// SetText sets the text content of the input. // SetValue sets the text content of the input.
func (this *TextInput) SetText (text string) { func (this *TextInput) SetValue (text string) {
this.text = []rune(text) this.text = []rune(text)
this.TextBox.SetText(text) this.TextBox.SetText(text)
} }
// Text returns the text content of the input. // Value returns the text content of the input.
func (this *TextInput) Text () string { func (this *TextInput) Value () string {
return string(this.text) return string(this.text)
} }
// OnEnter specifies a function to be called when the user presses enter within // SetText sets the text content of the input.
// the text input. func (this *TextInput) SetText (text string) {
func (this *TextInput) OnEnter (callback func ()) event.Cookie { this.SetValue(text)
return this.on.enter.Connect(callback)
} }
// OnEdit specifies a function to be called when the user edits the input text. // Text returns the text content of the input.
func (this *TextInput) OnEdit (callback func ()) event.Cookie { func (this *TextInput) Text () string {
return this.on.edit.Connect(callback) return this.Value()
} }
func (this *TextInput) handleKeyDown (key input.Key, numpad bool) { // OnConfirm specifies a function to be called when the user presses enter
dot := this.Dot() // within the text input.
modifiers := this.Modifiers() func (this *TextInput) OnConfirm (callback func ()) event.Cookie {
word := modifiers.Control return this.on.confirm.Connect(callback)
sel := modifiers.Shift }
changed := false
// TODO all dot control (movement, selection, etc) should be done in the // OnValueChange specifies a function to be called when the user edits the input
// backend. (editing should be done here, though) // text.
func (this *TextInput) OnValueChange (callback func ()) event.Cookie {
switch { return this.on.valueChange.Connect(callback)
case key == input.KeyEnter:
this.on.enter.Broadcast()
case key == input.KeyHome || (modifiers.Alt && key == input.KeyLeft):
dot.End = 0
if !sel { dot.Start = dot.End }
case key == input.KeyEnd || (modifiers.Alt && key == input.KeyRight):
dot.End = len(this.text)
if !sel { dot.Start = dot.End }
case key == input.KeyLeft:
if sel {
dot = text.SelectLeft(this.text, dot, word)
} else {
dot = text.MoveLeft(this.text, dot, word)
}
case key == input.KeyRight:
if sel {
dot = text.SelectRight(this.text, dot, word)
} else {
dot = text.MoveRight(this.text, dot, word)
}
case key == input.KeyBackspace:
this.text, dot = text.Backspace(this.text, dot, word)
changed = true
case key == input.KeyDelete:
this.text, dot = text.Delete(this.text, dot, word)
changed = true
case key == input.Key('a') && modifiers.Control:
dot.Start = 0
dot.End = len(this.text)
case key.Printable():
this.text, dot = text.Type(this.text, dot, rune(key))
changed = true
}
this.Select(dot)
if changed {
this.SetText(string(this.text))
this.on.edit.Broadcast()
}
} }
// Type types a character at the current dot position. // Type types a character at the current dot position.
@@ -112,6 +72,59 @@ func (this *TextInput) Type (char rune) {
this.SetText(string(this.text)) this.SetText(string(this.text))
} }
func (this *TextInput) handleScroll (x, y float64) { func (this *TextInput) handleKeyDown (key input.Key, numpad bool) bool {
this.ScrollTo(this.ContentBounds().Min.Add(image.Pt(int(x), int(y)))) dot := this.Dot()
modifiers := this.Window().Modifiers()
word := modifiers.Control
changed := false
defer func () {
this.Select(dot)
if changed {
this.SetText(string(this.text))
this.on.valueChange.Broadcast()
}
} ()
switch {
case isConfirmationKey(key):
this.on.confirm.Broadcast()
return true
case key == input.KeyBackspace:
this.text, dot = text.Backspace(this.text, dot, word)
changed = true
return true
case key == input.KeyDelete:
this.text, dot = text.Delete(this.text, dot, word)
changed = true
return true
case key.Printable() && !modifiers.Control:
this.text, dot = text.Type(this.text, dot, rune(key))
changed = true
return true
default:
return false
}
}
func (this *TextInput) handleKeyUp (key input.Key, numpad bool) bool {
modifiers := this.Window().Modifiers()
switch {
case isConfirmationKey(key):
return true
case key == input.KeyBackspace:
return true
case key == input.KeyDelete:
return true
case key.Printable() && !modifiers.Control:
return true
default:
return false
}
}
func (this *TextInput) handleScroll (x, y float64) bool {
if x == 0 { return false }
this.ScrollTo(this.ContentBounds().Min.Sub(image.Pt(int(x), int(y))))
return true
} }

View File

@@ -11,16 +11,17 @@ type TextView struct {
// NewTextView creates a new text view. // NewTextView creates a new text view.
func NewTextView (text string) *TextView { func NewTextView (text string) *TextView {
this := &TextView { TextBox: tomo.NewTextBox() } this := &TextView { TextBox: tomo.NewTextBox() }
this.SetRole(tomo.R("objects", "TextView", "")) this.SetRole(tomo.R("objects", "TextView"))
this.SetFocusable(true) this.SetFocusable(true)
this.SetSelectable(true) this.SetSelectable(true)
this.SetText(text) this.SetText(text)
this.SetOverflow(false, true) this.SetAttr(tomo.AOverflow(false, true))
this.SetWrap(true) this.SetAttr(tomo.AWrap(true))
this.OnScroll(this.handleScroll) this.OnScroll(this.handleScroll)
return this return this
} }
func (this *TextView) handleScroll (x, y float64) { func (this *TextView) handleScroll (x, y float64) bool {
this.ScrollTo(this.ContentBounds().Min.Add(image.Pt(int(x), int(y)))) this.ScrollTo(this.ContentBounds().Min.Sub(image.Pt(int(x), int(y))))
return true
} }