Compare commits

...

109 Commits

Author SHA1 Message Date
cf092b4447 Add UnsetAttr
Fully address #20
2024-07-31 00:19:39 -04:00
8403d621a8 AttrKind values are now part of the API 2024-07-30 18:23:37 -04:00
92660ef7de AttrLayout no longer attempts to compare itself 2024-07-25 18:09:10 -04:00
140de5917f Make text wrapping an attribute 2024-07-25 04:01:46 -04:00
3bd9de9110 AttrSet is now just a map 2024-07-25 03:57:55 -04:00
89f49fee71 Removed Tag from BoxQuerier 2024-07-25 02:59:32 -04:00
f561b71c56 Layouts are now attributes 2024-07-24 20:06:20 -04:00
75fd31bb24 Way better event API for objects 2024-07-24 18:37:45 -04:00
5eeb03b113 Replace the catch methods on ContainerBox with SetInputMask 2024-07-24 14:21:39 -04:00
3b3ea6d837 Various attribute improvements 2024-07-24 14:17:31 -04:00
ab4728144f Tags are now used for checking hover, focus, pressed status 2024-07-24 14:15:35 -04:00
1bc85775b8 Add equality checking for attributes 2024-07-21 22:06:10 -04:00
2b2dca77c8 Fix grammar in readme 2024-07-21 22:06:01 -04:00
d6229459c5 Fix ATextureMode 2024-07-21 10:59:35 -04:00
9914cdeb9c Add TextureMode attribute 2024-07-21 02:55:29 -04:00
ba31748b2e Add convenience constructors for attributes 2024-07-21 00:19:16 -04:00
4b56306bd2 Fix spelling of recommended 2024-07-21 00:10:16 -04:00
6859a2b0f7 Fix BoxQuerier interface 2024-07-21 00:00:00 -04:00
469b27bdfb Rename Icons to IconSize 2024-07-20 23:09:32 -04:00
70aaa79b7d Changed Rule contstructor to Ru 2024-07-20 17:12:54 -04:00
e2017f04ff Create constructor for rules 2024-07-20 17:12:31 -04:00
a8c72f7391 Remove the map of named textures from Style 2024-07-20 14:37:06 -04:00
1d4bc03a7d Remove unnecessary String methods 2024-07-20 14:32:59 -04:00
1030bede90 Clean up Box methods a bit 2024-07-20 14:21:41 -04:00
2570fada95 Redid style system with a focus on attributes 2024-07-20 14:18:49 -04:00
8894b98c8b Add BoxQuerier and BoxArranger for use in Layout 2024-07-20 01:23:46 -04:00
1c20acd993 Revise event API for boxes 2024-07-20 01:14:31 -04:00
87494c014a Change Text, Bytes to FromText, FromBytes 2024-07-19 15:26:03 -04:00
f6556aa57f Fix mergedData.Supported 2024-07-19 15:24:44 -04:00
35b52c6a3f Completely redo the data API 2024-07-19 15:24:16 -04:00
109283f520 Dont't crash if tomo.Run callback calls tomo.Stop 2024-07-19 13:40:56 -04:00
dc50e7290d Remove Window.Widget 2024-06-11 23:41:06 -04:00
e102c032cb Layout recommended size takes in layout hints and boxes 2024-06-07 23:07:15 -04:00
d35b0532a1 Speaks english for 21 years and still has no idea how to spell 2024-06-07 19:22:13 -04:00
dffe766328 Rename theme.go to style.go 2024-06-07 19:19:35 -04:00
c1d77028b4 Add a note that reccomended sizes arent always respected 2024-06-07 19:15:33 -04:00
83b2c3c665 Add system for reccomending widths/heights
Remedy #6
2024-06-07 19:13:22 -04:00
89307e0dd6 Slight wording fix 2024-06-07 19:06:18 -04:00
5d9c584743 Document that windows are supposed to be transparent
Remedy #16
2024-06-07 19:05:38 -04:00
fd7d2b7ead Add Window.SetBounds
Remedy #17
2024-06-07 18:59:43 -04:00
ca4d3e62c4 Remedy #10 2024-06-07 18:57:16 -04:00
d587e39506 Separate icon functionality out of Style and into Icons 2024-06-07 18:27:26 -04:00
f0c092be8a Break some scalars, vectors, and enums into a separate file 2024-06-07 18:21:15 -04:00
06f45c80e2 Change Theme to Style 2024-06-07 18:19:43 -04:00
71171d762c Add a "SetResizable" behavior to Window 2024-06-07 14:11:36 -04:00
341eea5b5d Remove references to MainWindow 2024-06-07 00:56:29 -04:00
453953bbcd Unify Window and MainWindow 2024-06-07 00:54:14 -04:00
31ce286bc7 Window icons are set using textures 2024-06-06 20:15:00 -04:00
26cf1f4a88 Roles are stored in Boxes now 2024-06-03 19:57:20 -04:00
6ef1f7ba78 Add OnSizeChange to SurfaceBox
Remedy #15
2024-06-03 19:37:34 -04:00
d7093be696 Update go.sum 2024-06-03 19:33:07 -04:00
64bf8f3b2d NewCanvas actually returns a Canvas 2024-06-03 19:32:47 -04:00
50cbac17a9 CanvasCloser is now actually a valid type 2024-06-03 19:32:06 -04:00
d096d40c57 Add a way for applications to request canvases
Makes fix to #14 useful
2024-06-03 19:29:41 -04:00
34358da6eb Add canvas.CanvasCloser
Remedy #14
2024-06-03 19:28:03 -04:00
be1b9d77e8 Instruct themes to return nil icons if the icon doesn't exist 2024-05-28 22:01:56 -04:00
d71ac02748 Add unchecked checkbox icon 2024-05-27 15:10:11 -04:00
2bbf85ebd8 Add more missing icons 2024-05-27 04:02:22 -04:00
320535e7f3 Remove Box.Visible, box.SetVisible
It was a bad idea. Remedy #12.
2024-05-26 17:42:11 -04:00
775fb84e9b Add back some missing icons 2024-05-26 17:42:04 -04:00
6bf3450799 Add link to XDG icon specification in icon.go 2024-05-25 00:57:26 -04:00
874171c9de Un-export backend Initialize() function 2024-05-25 00:52:25 -04:00
6cfb16f9fe Change theme variable from current -> theme 2024-05-25 00:51:34 -04:00
73e9b28eeb Redo standard icon set around the XDG icon naming spec
https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html
Remedy #11
2024-05-25 00:50:15 -04:00
17039059ce Merge theme package into central package 2024-05-24 21:45:16 -04:00
a6b115b591 Replace SetTexture with SetTextureTile and SetTextureCenter
Remedy #8
2024-05-24 14:47:43 -04:00
7c8b419c65 Elaborate on the difference between Object and Box 2024-05-20 00:30:28 -04:00
ca512af1a5 Add ContentObject, remedy #7 2024-05-20 00:25:41 -04:00
b4f8d11817 Don't downplay the usefulness of ContentBox 2024-05-20 00:23:24 -04:00
9c3ae7afa5 Add API for using platform dependent graphics contexts 2024-05-20 00:18:49 -04:00
a18628c26d Changed the wording of the coment describing canvas.Drawer 2024-05-20 00:18:26 -04:00
a9fc52c55b Change clip behaviors to sub behaviors
Remedies #4
2024-05-15 01:37:21 -04:00
e745e80f09 Add more information to README.md 2024-05-14 12:43:40 -04:00
748996c789 Be more descriptive with what a path is 2024-05-14 12:34:42 -04:00
d4aac7e26c Set CapRound as the default cap style 2024-05-14 12:32:44 -04:00
3d645b8064 Tweak doc comments for canvas.Pen 2024-05-14 12:32:09 -04:00
bde1a2bc34 Remove wierd spacing from box interface definitions
Seemed like a good idea at the time
2024-05-14 12:20:44 -04:00
d43ba6b1af Replace Window's Show/Hide methods with Visible/SetVisible 2024-05-14 12:18:21 -04:00
096c1b5e1b Add Visible() and SetVisible() to Box 2024-05-14 12:17:14 -04:00
c44ff4a34a Change ContainerBox.Delete() to Remove()
Remedy #3
2024-05-14 12:11:00 -04:00
dc02f4dfb4 Remedy #1 2024-05-14 12:09:34 -04:00
7c30b2bac0 Add requirement for ContainerBox.Add to remove a previously
parented object first
2024-05-14 12:03:10 -04:00
24264bbc91 Fix capitalization errors with previous commit 2024-05-14 11:58:48 -04:00
f167af3281 Describe the canvas used by CanvasBox in detail 2024-05-14 11:57:48 -04:00
9a5b4ee7e8 Add home icon 2024-05-05 02:53:07 -04:00
3e561d7bf0 Fix wording of theme.Theme doc comment 2024-05-03 13:46:50 -04:00
b96e8f744f Namespace icon IDs 2024-05-03 13:21:35 -04:00
9aa6f2900e Added application role icons 2024-05-03 13:10:44 -04:00
a3fc0ce66d Remove ApplicationIcon from Theme
Since Icon can now take in arbitrary strings, we can just have it
serve application icons as well.
2024-05-03 13:08:14 -04:00
65bf341514 Icon IDs are now strings 2024-05-03 13:07:27 -04:00
042f2f0131 Completely remove plugin system
Plugins may be moved to Nasin
2024-04-30 13:12:34 -04:00
4fd5e54e42 Add editorconfig 2024-04-29 16:23:46 -04:00
9a9e546b37 Remove application framework stuff 2024-04-29 00:39:17 -04:00
a2a5c16e38 Changed the semantics of ContentBounds 2023-09-14 14:47:33 -04:00
28cd889254 Removed tiler for now, needs to be rethought a bit 2023-09-08 20:57:15 -04:00
e682fdd9d8 Add icon for switch 2023-09-08 20:57:00 -04:00
9719391e5d NewApplicationWindow returns MainWindow nows 2023-09-08 16:29:03 -04:00
8a531986eb What??? 2023-09-07 18:25:35 -04:00
c3c6ff61f5 Add Tiler interface 2023-09-05 18:14:36 -04:00
89f7bf47ce Add ability to create an undecorated window 2023-09-05 13:21:59 -04:00
bebd58dac1 Added event capturing to containers 2023-09-05 13:10:35 -04:00
f9a85fd949 Added filesystems for application data 2023-09-04 13:48:03 -04:00
6ac653adb6 Made ownership of textures more explicit 2023-09-04 12:21:17 -04:00
7b28419432 Texture must now implement Image 2023-09-04 12:07:29 -04:00
57e6a9ff21 lolll whoops 2023-09-04 02:56:00 -04:00
a06f94e41b Added support for defining applications as objects 2023-09-04 02:26:21 -04:00
4d157756eb Added a String method to a bunch of stuff 2023-09-04 01:47:03 -04:00
63a67e40d1 Added a Bounds() method to Texture 2023-09-04 01:28:04 -04:00
b629b4eb4e Cleared up wording around theme textures 2023-08-29 15:52:07 -04:00
17 changed files with 1328 additions and 768 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

@@ -1,6 +1,8 @@
# tomo
WIP rewrite of tomo.
[![Go Reference](https://pkg.go.dev/badge/git.tebibyte.media/tomo/tomo.svg)](https://pkg.go.dev/git.tebibyte.media/tomo/tomo)
This module will serve as a wafer-thin collection of interfaces and glue code so
that plugins will be an actual viable concept.
Tomo is a lightweight GUI toolkit written in pure Go. This repository defines
the API that other components of the toolkit agree upon. In order to use Tomo in
an application, use [Nasin](https://git.tebibyte.media/tomo/nasin), which builds
an application framework on top of Tomo.

306
attribute.go Normal file
View File

@@ -0,0 +1,306 @@
package tomo
import "image"
import "image/color"
import "golang.org/x/image/font"
import "git.tebibyte.media/tomo/tomo/canvas"
// AttrSet is a set of attributes wherein only one/zero of each attribute type
// can exist. It is keyed by the AttrKind of each attribute and must not be
// modified directly.
type AttrSet map[AttrKind] Attr
// AS builds an AttrSet out of a vararg list of Attr values. If multiple Attrs
// of the same kind are specified, the last one will override the others.
func AS (attrs ...Attr) AttrSet {
set := AttrSet { }
set.Add(attrs...)
return set
}
// Add adds attributes to the set.
func (this AttrSet) Add (attrs ...Attr) {
for _, attr := range attrs {
this[attr.Kind()] = attr
}
}
// MergeUnder takes attributes from another set and adds them if they don't
// already exist in this one.
func (this AttrSet) MergeUnder (other AttrSet) {
if other == nil { return }
for _, attr := range other {
if _, exists := this[attr.Kind()]; !exists {
this.Add(attr)
}
}
}
// MergeOver takes attributes from another set and adds them, overriding this
// one.
func (this AttrSet) MergeOver (other AttrSet) {
if other == nil { return }
for _, attr := range other {
this.Add(attr)
}
}
// Attr modifies one thing about a box's style.
type Attr interface {
// Equals returns true if both attributes can reasonably be declared
// equal.
Equals (Attr) bool
Kind () AttrKind
attr ()
}
type AttrKind int; const (
AttrKindColor AttrKind = iota
AttrKindTexture
AttrKindTextureMode
AttrKindBorder
AttrKindMinimumSize
AttrKindPadding
AttrKindGap
AttrKindTextColor
AttrKindDotColor
AttrKindFace
AttrKindWrap
AttrKindAlign
AttrKindOverflow
AttrKindLayout
)
// AttrColor sets the background color of a box.
type AttrColor struct { color.Color }
// AttrTexture sets the texture of a box to a named texture.
type AttrTexture struct { canvas.Texture }
// AttrTextureMode sets the rendering mode of a box's texture.
type AttrTextureMode TextureMode
// AttrBorder sets the border of a box.
type AttrBorder []Border
// AttrMinimumSize sets the minimum size of a box.
type AttrMinimumSize image.Point
// AttrPadding sets the inner padding of a box.
type AttrPadding Inset
// AttrGap sets the gap between child boxes, if the box is a ContainerBox.
type AttrGap image.Point
// AttrTextColor sets the text color, if the box is a TextBox.
type AttrTextColor struct { color.Color }
// AttrDotColor sets the text selection color, if the box is a TextBox.
type AttrDotColor struct { color.Color }
// AttrFace sets the font face, if the box is a TextBox.
type AttrFace struct { font.Face }
// AttrWrap sets if the text wraps, if the box is a TextBox.
type AttrWrap bool
// AttrAlign sets the alignment, if the box is a ContentBox.
type AttrAlign struct { X, Y Align }
// AttrOverflow sets the overflow, if the box is a ContentBox.
type AttrOverflow struct { X, Y bool }
// AttrLayout sets the layout, if the box is a ContentBox.
type AttrLayout struct { Layout }
// AColor is a convenience constructor for the color attribute.
func AColor (col color.Color) AttrColor {
return AttrColor { Color: col }
}
// ATexture is a convenience constructor for the texture attribute.
func ATexture (texture canvas.Texture) AttrTexture {
return AttrTexture { Texture: texture }
}
// ATextureMode is a convenience constructor for the texture mode attribute.
func ATextureMode (mode TextureMode) AttrTextureMode {
return AttrTextureMode(mode)
}
// ABorder is a convenience constructor for the border attribute.
func ABorder (borders ...Border) AttrBorder {
return AttrBorder(borders)
}
// AMinimumSize is a convenience constructor for the minimum size attribute.
func AMinimumSize (x, y int) AttrMinimumSize {
return AttrMinimumSize(image.Pt(x, y))
}
// APadding is a convenience constructor for the padding attribute.
func APadding (sides ...int) AttrPadding {
return AttrPadding(I(sides...))
}
// AGap is a convenience constructor for the gap attribute.
func AGap (x, y int) AttrGap {
return AttrGap(image.Pt(x, y))
}
// ATextColor is a convenience constructor for the text color attribute.
func ATextColor (col color.Color) AttrTextColor {
return AttrTextColor { Color: col }
}
// ADotColor is a convenience constructor for the dot color attribute.
func ADotColor (col color.Color) AttrDotColor {
return AttrDotColor { Color: col }
}
// AFace is a convenience constructor for the face attribute.
func AFace (face font.Face) AttrFace {
return AttrFace { Face: face }
}
// AWrap is a convenience constructor for the wrap attribute.
func AWrap (wrap bool) AttrWrap {
return AttrWrap(wrap)
}
// AAlign is a convenience constructor for the align attribute.
func AAlign (x, y Align) AttrAlign {
return AttrAlign { X: x, Y: y }
}
// AOverflow is a convenience constructor for the overflow attribute.
func AOverflow (x, y bool) AttrOverflow {
return AttrOverflow { X: x, Y: y }
}
// ALayout is a convenience constructor for the overflow attribute.
func ALayout (layout Layout) AttrLayout {
return AttrLayout { Layout: layout }
}
// Equals returns true if both attributes can reasonably be declared equal.
func (this AttrColor) Equals (other Attr) bool {
if other, ok := other.(AttrColor); ok {
return this == other
} else {
return false
}
}
// Equals returns true if both attributes can reasonably be declared equal.
func (this AttrTexture) Equals (other Attr) bool {
if other, ok := other.(AttrTexture); ok {
return this == other
} else {
return false
}
}
// Equals returns true if both attributes can reasonably be declared equal.
func (this AttrTextureMode) Equals (other Attr) bool {
if other, ok := other.(AttrTextureMode); ok {
return this == other
} else {
return false
}
}
// Equals returns true if both attributes can reasonably be declared equal.
func (this AttrBorder) Equals (other Attr) bool {
if other, ok := other.(AttrBorder); ok {
if len(this) != len(other) { return false }
for index := range this {
thisBorder := this[index]
otherBorder := other[index]
if thisBorder != otherBorder { return false }
}
return true
} else {
return false
}
}
// Equals returns true if both attributes can reasonably be declared equal.
func (this AttrMinimumSize) Equals (other Attr) bool {
if other, ok := other.(AttrMinimumSize); ok {
return this == other
} else {
return false
}
}
// Equals returns true if both attributes can reasonably be declared equal.
func (this AttrPadding) Equals (other Attr) bool {
if other, ok := other.(AttrPadding); ok {
return this == other
} else {
return false
}
}
// Equals returns true if both attributes can reasonably be declared equal.
func (this AttrGap) Equals (other Attr) bool {
if other, ok := other.(AttrGap); ok {
return this == other
} else {
return false
}
}
// Equals returns true if both attributes can reasonably be declared equal.
func (this AttrTextColor) Equals (other Attr) bool {
if other, ok := other.(AttrTextColor); ok {
return this == other
} else {
return false
}
}
// Equals returns true if both attributes can reasonably be declared equal.
func (this AttrDotColor) Equals (other Attr) bool {
if other, ok := other.(AttrDotColor); ok {
return this == other
} else {
return false
}
}
// Equals returns true if both attributes can reasonably be declared equal.
func (this AttrFace) Equals (other Attr) bool {
if other, ok := other.(AttrFace); ok {
return this == other
} else {
return false
}
}
// Equals returns true if both attributes can reasonably be declared equal.
func (this AttrWrap) Equals (other Attr) bool {
if other, ok := other.(AttrWrap); ok {
return this == other
} else {
return false
}
}
// Equals returns true if both attributes can reasonably be declared equal.
func (this AttrAlign) Equals (other Attr) bool {
if other, ok := other.(AttrAlign); ok {
return this == other
} else {
return false
}
}
// Equals returns true if both attributes can reasonably be declared equal.
func (this AttrOverflow) Equals (other Attr) bool {
if other, ok := other.(AttrOverflow); ok {
return this == other
} else {
return false
}
}
// Equals returns true if both attributes can reasonably be declared equal.
func (this AttrLayout) Equals (other Attr) bool {
// for some goofy reason if we try to compare two AttrLayouts we get a
// fucking runtime error????? its probably for the best anyways because
// two layouts cannot "reasonably" be declared equal
return false
}
func (AttrColor) Kind () AttrKind { return AttrKindColor }
func (AttrTexture) Kind () AttrKind { return AttrKindTexture }
func (AttrTextureMode) Kind () AttrKind { return AttrKindTextureMode }
func (AttrBorder) Kind () AttrKind { return AttrKindBorder }
func (AttrMinimumSize) Kind () AttrKind { return AttrKindMinimumSize }
func (AttrPadding) Kind () AttrKind { return AttrKindPadding }
func (AttrGap) Kind () AttrKind { return AttrKindGap }
func (AttrTextColor) Kind () AttrKind { return AttrKindTextColor }
func (AttrDotColor) Kind () AttrKind { return AttrKindDotColor }
func (AttrFace) Kind () AttrKind { return AttrKindFace }
func (AttrWrap) Kind () AttrKind { return AttrKindWrap }
func (AttrAlign) Kind () AttrKind { return AttrKindAlign }
func (AttrOverflow) Kind () AttrKind { return AttrKindOverflow }
func (AttrLayout) Kind () AttrKind { return AttrKindLayout }
func (AttrColor) attr () { }
func (AttrTexture) attr () { }
func (AttrTextureMode) attr () { }
func (AttrBorder) attr () { }
func (AttrMinimumSize) attr () { }
func (AttrPadding) attr () { }
func (AttrGap) attr () { }
func (AttrTextColor) attr () { }
func (AttrDotColor) attr () { }
func (AttrFace) attr () { }
func (AttrWrap) attr () { }
func (AttrAlign) attr () { }
func (AttrOverflow) attr () { }
func (AttrLayout) attr () { }

View File

@@ -11,15 +11,38 @@ import "git.tebibyte.media/tomo/tomo/canvas"
type Backend interface {
// These methods create new objects. The backend must reject any object
// that was not made by it.
NewWindow (image.Rectangle) (MainWindow, error)
NewBox () Box
NewTextBox () TextBox
NewCanvasBox () CanvasBox
NewSurfaceBox () (SurfaceBox, error)
NewContainerBox () ContainerBox
// NewWindow creates a normal Window and returns it.
NewWindow (image.Rectangle) (Window, error)
// NewPlainWindow creates an undecorated window that does not appear in
// window lists and returns it. This is intended for making things like
// panels, docks, etc.
NewPlainWindow (image.Rectangle) (Window, error)
// NewTexture creates a new texture from an image. The backend must
// reject any texture that was not made by it.
NewTexture (image.Image) canvas.Texture
NewTexture (image.Image) canvas.TextureCloser
// NewCanvas creates a new canvas with the specified bounds. The backend
// must reject any canvas that was not made by it.
NewCanvas (image.Rectangle) canvas.CanvasCloser
// SetStyle sets the style that will be used on objects. The backend is
// in charge of applying the style to objects. When this method is
// called, it must propagate a StyleChange event to all boxes it is
// keeping track of.
SetStyle (*Style)
// SetIconSet sets the icon set that icons will be pulled from. When
// this method is called, it must propagate an IconChange event to all
// boxes it is keeping track of.
SetIconSet (IconSet)
// Run runs the event loop until Stop() is called, or the backend
// experiences a fatal error.
@@ -52,11 +75,11 @@ func Register (priority int, factory Factory) {
})
}
// Initialize instantiates a backend. The first backend (sorted by priority)
// initialize instantiates a backend. The first backend (sorted by priority)
// that does not throw an error when initialized is used. If no backend could be
// instantiated, this function returns an error. This function should be called
// only once.
func Initialize () (Backend, error) {
func initialize () (Backend, error) {
backend, err := instantiate()
if err != nil { return nil, err }
return backend, err

View File

@@ -2,15 +2,16 @@
// primitives.
package canvas
import "io"
import "image"
import "image/draw"
import "image/color"
// Cap represents a stroke cap type.
type Cap int; const (
CapButt Cap = iota // Square cap that ends at the point
CapRound // Round cap that surrounds the point
CapSquare // square cap that surrounds the point
CapRound Cap = iota // Round cap that surrounds the point
CapSquare // Square cap that surrounds the point
CapButt // Square cap that ends at the point
)
// Joint represents a stroke joint type.
@@ -30,23 +31,38 @@ type StrokeAlign int; const (
// Pen represents a drawing context that is linked to a canvas. Each canvas can
// have multiple pens associated with it, each maintaining their own drawing
// context.
// state.
type Pen interface {
// Rectangle draws a rectangle
// Rectangle draws a rectangle.
Rectangle (image.Rectangle)
// Path draws a path
// Path draws a path, which is a series of connected points.
Path (points ...image.Point)
Closed (bool) // if the path is closed
Cap (Cap) // line cap stype
Joint (Joint) // line joint style
StrokeWeight (int) // how thick the stroke is
StrokeAlign (StrokeAlign) // where the stroke is drawn
// StrokeWeight sets how thick the stroke is. The default value is zero.
StrokeWeight (int)
// SetClosed sets whether the path is a closed shape, or has an open
// side. This only applies if the stroke weight is greater than zero.
Closed (bool)
// Cap sets how the ends of the stroke look. This only applies if the
// stroke weight is greater than zero, and if the path is not closed.
// The default value is CapRound.
Cap (Cap)
// Joint sets how bend points in the stroke look. This only applies if
// the stroke weight is greater than zero. The default value is
// JointRound.
Joint (Joint)
// StrokeAlign sets where the stroke is drawn in relation to the path.
// This only applies if the stroke weight is greater than zero. The
// default value is StrokeAlignCenter.
StrokeAlign (StrokeAlign)
Stroke (color.Color) // Sets the stroke to a solid color
Fill (color.Color) // Sets the fill to a solid color
Texture (Texture) // Overlaps a texture onto the fill color
// Stroke sets the stroke to a solid color.
Stroke (color.Color)
// Fill sets the fill to a solid color.
Fill (color.Color)
// Texture overlaps a texture onto the fill color.
Texture (Texture)
}
// Canvas is an image that supports drawing paths.
@@ -56,11 +72,20 @@ type Canvas interface {
// Pen returns a new pen for this canvas.
Pen () Pen
// Clip returns a new canvas that points to a specific area of this one.
Clip (image.Rectangle) Canvas
// SubCanvas returns a returns a Canvas representing the portion of this
// Canvas visible and drawable through a rectangle. The returned value
// shares pixels with the original Canvas.
SubCanvas (image.Rectangle) Canvas
}
// Drawer is an object that can draw to a canvas.
// CanvasCloser is a canvas that can be closed. Anything that receives a
// CanvasCloser must close it after use.
type CanvasCloser interface {
Canvas
io.Closer
}
// Drawer can draw to a canvas.
type Drawer interface {
// Draw draws to the given canvas.
Draw (Canvas)

View File

@@ -5,25 +5,17 @@ import "image"
// Texture is a handle that points to a 2D raster image managed by the backend.
type Texture interface {
io.Closer
image.Image
// Clip returns a smaller section of this texture, pointing to the same
// internal data. Becaue of this, closing a clipped section will close
// the original texture as well.
Clip (image.Rectangle) Texture
// SubTexture returns a returns a Texture representing the portion of
// this Texture visible through a rectangle. The returned value shares
// pixels with the original Texture.
SubTexture (image.Rectangle) Texture
}
type protectedTexture struct {
// TextureCloser is a texture that can be closed. Anything that receives a
// TextureCloser must close it after use.
type TextureCloser interface {
Texture
}
func (protectedTexture) Close () error {
return nil
}
// Protect makes the Close() method of a texture do nothing. This is useful if
// several of the same texture are given out to different objects, but only one
// has the responsibility of closing it.
func Protect (texture Texture) Texture {
return protectedTexture { Texture: texture }
io.Closer
}

View File

@@ -3,57 +3,127 @@ package data
import "io"
import "bytes"
import "strings"
// Data represents arbitrary polymorphic data that can be used for data transfer
// between applications.
type Data map[Mime] io.ReadSeekCloser
type Data interface {
// Convert converts the data to the specified MIME type and returns it.
// If the type is not supported, this behavior will return nil, and
// false for ok. Note that Convert may be called multiple times for the
// same MIME type, so it must not return the same reader.
Convert (Mime) (reader io.ReadSeekCloser, ok bool)
// Supported returns a slice of MIME types that Convert can accept.
Supported () []Mime
}
// Mime represents a MIME type.
type Mime struct {
// Type is the first half of the MIME type, and Subtype is the second
// half. The separating slash is not included in either. For example,
// text/html becomes:
// Mime { Type: "text", Subtype: "html" }
// Mime { Type: "text", Subtype: "html" }
// The subtype is stored here including the tree and the suffix.
Type, Subtype string
// Charset is an optional field applicable to text types that specifies
// the character encoding of the data. If empty, UTF-8 is conventionally
// assumed because it's the only text encoding worth using.
Charset string
}
// M is shorthand for creating a MIME type.
func M (ty, subtype string) Mime {
return Mime { ty, subtype }
return Mime {
Type: strings.ToLower(ty),
Subtype: strings.ToLower(subtype),
}
}
// String returns the string representation of the MIME type.
func (mime Mime) String () string {
return mime.Type + "/" + mime.Subtype
// ParseMime parses a MIME type from text.
func ParseMime (text string) Mime {
ty, subty, _ := strings.Cut(text, "/")
subty, parameters, _ := strings.Cut(subty, ";")
mime := M(ty, subty)
for _, parameter := range strings.Split(parameters, " ") {
if parameter == "" { continue }
key, val, _ := strings.Cut(parameter, "=")
// TODO handle things like quoted values
val = strings.TrimSpace(val)
switch strings.TrimSpace(strings.ToLower(key)) {
case "charset":
mime.Charset = val
}
}
return mime
}
// MimePlain returns the MIME type of plain text.
func MimePlain () Mime { return Mime { "text", "plain" } }
func MimePlain () Mime { return Mime { Type: "text", Subtype: "plain" } }
// MimeFile returns the MIME type of a file path/URI.
func MimeFile () Mime { return Mime { "text", "uri-list" } }
func MimeFile () Mime { return Mime { Type: "text", Subtype: "uri-list" } }
// String returns the string representation of the MIME type.
func (mime Mime) String () string {
out := mime.Type + "/" + mime.Subtype
if mime.Charset != "" {
out += "; charset=" + mime.Charset
}
return out
}
// FromText returns plain text Data given a string.
func FromText (text string) Data {
return FromBytes(MimePlain(), []byte(text))
}
type byteReadCloser struct { *bytes.Reader }
func (byteReadCloser) Close () error { return nil }
// Text returns plain text Data given a string.
func Text (text string) Data {
return Bytes(MimePlain(), []byte(text))
type bytesData struct {
mime Mime
buffer []byte
}
// Bytes constructs a Data given a buffer and a mime type.
func Bytes (mime Mime, buffer []byte) Data {
return Data {
mime: byteReadCloser { bytes.NewReader(buffer) },
// FromBytes constructs a Data given a buffer and a mime type.
func FromBytes (mime Mime, buffer []byte) Data {
return bytesData {
mime: mime,
buffer: buffer,
}
}
// Merge combines several Datas together. If multiple Datas provide a reader for
// the same mime type, the ones further on in the list will take precedence.
func Merge (individual ...Data) (combined Data) {
for _, data := range individual {
for mime, reader := range data {
combined[mime] = reader
}}
return
func (bytesDat bytesData) Convert (mime Mime) (io.ReadSeekCloser, bool) {
if mime != bytesDat.mime { return nil, false }
return byteReadCloser { bytes.NewReader(bytesDat.buffer) }, true
}
func (bytesDat bytesData) Supported () []Mime {
return []Mime { bytesDat.mime }
}
type mergedData []Data
func (merged mergedData) Convert (mime Mime) (io.ReadSeekCloser, bool) {
for _, individual := range merged {
if reader, ok := individual.Convert(mime); ok {
return reader, ok
}
}
return nil, false
}
func (merged mergedData) Supported () (supported []Mime) {
for _, individual := range merged {
supported = append(individual.Supported(), supported...)
}
return supported
}
// Merge combines several Datas together. If multiple Datas provide a reader for
// the same mime type, the ones first in the list will take precedence.
func Merge (individual ...Data) (combined Data) {
return mergedData(individual)
}

3
go.sum
View File

@@ -1,8 +1,6 @@
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.8.0 h1:agUcRXV/+w6L9ryntYYsF2x9fQTMd4T8fiiYXAVW6Jg=
golang.org/x/image v0.8.0/go.mod h1:PwLxp3opCYg4WR2WO9P0L6ESnsD6bLTWcw8zanLMVFM=
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=
@@ -27,7 +25,6 @@ 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.10.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
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=

415
icon.go Normal file
View File

@@ -0,0 +1,415 @@
package tomo
import "git.tebibyte.media/tomo/tomo/data"
import "git.tebibyte.media/tomo/tomo/canvas"
// IconSize represents the size of an icon.
type IconSize int; const (
IconSizeSmall IconSize = iota;
IconSizeMedium
IconSizeLarge
)
// Icon represents an icon ID.
type Icon string
// A list of standard icon IDs. This is roughly based off of the XDG Icon Naming
// Specification (https://specifications.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html).
const (
IconUnknown Icon = ""
// actions
IconAddressBookNew Icon = "AddressBookNew"
IconApplicationExit Icon = "ApplicationExit"
IconAppointmentNew Icon = "AppointmentNew"
IconCallStart Icon = "CallStart"
IconCallStop Icon = "CallStop"
IconContactNew Icon = "ContactNew"
// actions: dialog
IconDialogOkay Icon = "DialogOkay"
IconDialogCancel Icon = "DialogCancel"
// actions: edit
IconEditClear Icon = "EditClear"
IconEditCopy Icon = "EditCopy"
IconEditCut Icon = "EditCut"
IconEditDelete Icon = "EditDelete"
IconEditFind Icon = "EditFind"
IconEditFindReplace Icon = "EditFindReplace"
IconEditPaste Icon = "EditPaste"
IconEditRedo Icon = "EditRedo"
IconEditSelectAll Icon = "EditSelectAll"
IconEditUndo Icon = "EditUndo"
// actions: file
IconFileNew Icon = "FileNew"
IconDirectoryNew Icon = "DirectoryNew"
IconFileOpen Icon = "FileOpen"
IconFileOpenRecent Icon = "FileOpenRecent"
IconFilePageSetup Icon = "FilePageSetup"
IconFilePrint Icon = "FilePrint"
IconFilePrintPreview Icon = "FilePrintPreview"
IconFilePermissions Icon = "FilePermissions"
IconFileProperties Icon = "FileProperties"
IconFileRename Icon = "FileRename"
IconFileRevert Icon = "FileRevert"
IconFileSave Icon = "FileSave"
IconFileSaveAs Icon = "FileSaveAs"
IconFileSend Icon = "FileSend"
// actions: format
IconFormatIndentLess Icon = "FormatIndentLess"
IconFormatIndentMore Icon = "FormatIndentMore"
IconFormatAlignCenter Icon = "FormatAlignCenter"
IconFormatAlignEven Icon = "FormatAlignEven"
IconFormatAlignLeft Icon = "FormatAlignLeft"
IconFormatAlignRight Icon = "FormatAlignRight"
IconFormatTextDirectionLtr Icon = "FormatTextDirectionLtr"
IconFormatTextDirectionRtl Icon = "FormatTextDirectionRtl"
IconFormatTextBold Icon = "FormatTextBold"
IconFormatTextItalic Icon = "FormatTextItalic"
IconFormatTextUnderline Icon = "FormatTextUnderline"
IconFormatTextStrikethrough Icon = "FormatTextStrikethrough"
// actions: go
IconGoBottom Icon = "GoBottom"
IconGoDown Icon = "GoDown"
IconGoFirst Icon = "GoFirst"
IconGoHome Icon = "GoHome"
IconGoJump Icon = "GoJump"
IconGoLast Icon = "GoLast"
IconGoNext Icon = "GoNext"
IconGoPrevious Icon = "GoPrevious"
IconGoTop Icon = "GoTop"
IconGoUp Icon = "GoUp"
// actions: help
IconHelpAbout Icon = "HelpAbout"
IconHelpContents Icon = "HelpContents"
IconHelpFaq Icon = "HelpFaq"
// actions: insert
IconInsertImage Icon = "InsertImage"
IconInsertLink Icon = "InsertLink"
IconInsertObject Icon = "InsertObject"
IconInsertText Icon = "InsertText"
// actions: list
IconListAdd Icon = "ListAdd"
IconListRemove Icon = "ListRemove"
// actions: mail
IconMailForward Icon = "MailForward"
IconMailMarkImportant Icon = "MailMarkImportant"
IconMailMarkJunk Icon = "MailMarkJunk"
IconMailMarkNotJunk Icon = "MailMarkNotJunk"
IconMailMarkRead Icon = "MailMarkRead"
IconMailMarkUnread Icon = "MailMarkUnread"
IconMailMessageNew Icon = "MailMessageNew"
IconMailReplyAll Icon = "MailReplyAll"
IconMailReplySender Icon = "MailReplySender"
IconMailSend Icon = "MailSend"
IconMailReceive Icon = "MailReceive"
// actions: media
IconMediaEject Icon = "MediaEject"
IconMediaPlaybackPause Icon = "MediaPlaybackPause"
IconMediaPlaybackStart Icon = "MediaPlaybackStart"
IconMediaPlaybackStop Icon = "MediaPlaybackStop"
IconMediaRecord Icon = "MediaRecord"
IconMediaSeekBackward Icon = "MediaSeekBackward"
IconMediaSeekForward Icon = "MediaSeekForward"
IconMediaSkipBackward Icon = "MediaSkipBackward"
IconMediaSkipForward Icon = "MediaSkipForward"
// actions: object
IconObjectFlipHorizontal Icon = "ObjectFlipHorizontal"
IconObjectFlipVertical Icon = "ObjectFlipVertical"
IconObjectRotateLeft Icon = "ObjectRotateLeft"
IconObjectRotateRight Icon = "ObjectRotateRight"
// actions: process
IconProcessStop Icon = "ProcessStop"
// actions: system
IconSystemLockScreen Icon = "SystemLockScreen"
IconSystemLogOut Icon = "SystemLogOut"
IconSystemRun Icon = "SystemRun"
IconSystemSearch Icon = "SystemSearch"
IconSystemReboot Icon = "SystemReboot"
IconSystemShutdown Icon = "SystemShutdown"
// actions: tools
IconToolsCheckSpelling Icon = "ToolsCheckSpelling"
// actions: value
IconValueIncrement Icon = "ValueIncrement"
IconValueDecrement Icon = "ValueDecrement"
IconValueReset Icon = "ValueReset"
// actions: view
IconViewFullscreen Icon = "ViewFullscreen"
IconViewRefresh Icon = "ViewRefresh"
IconViewRestore Icon = "ViewRestore"
IconViewSortAscending Icon = "ViewSortAscending"
IconViewSortDescending Icon = "ViewSortDescending"
// actions: window
IconWindowClose Icon = "WindowClose"
IconWindowNew Icon = "WindowNew"
// actions: zoom
IconZoomFitBest Icon = "ZoomFitBest"
IconZoomIn Icon = "ZoomIn"
IconZoomOriginal Icon = "ZoomOriginal"
IconZoomOut Icon = "ZoomOut"
// applications
// Keep these in sync with nasin.ApplicationRole!
IconApplication Icon = "Application" // generic
IconApplicationWebBrowser Icon = "ApplicationWebBrowser"
IconApplicationMesssanger Icon = "ApplicationMesssanger"
IconApplicationPhone Icon = "ApplicationPhone"
IconApplicationMail Icon = "ApplicationMail"
IconApplicationTerminalEmulator Icon = "ApplicationTerminalEmulator"
IconApplicationFileBrowser Icon = "ApplicationFileBrowser"
IconApplicationTextEditor Icon = "ApplicationTextEditor"
IconApplicationDocumentViewer Icon = "ApplicationDocumentViewer"
IconApplicationWordProcessor Icon = "ApplicationWordProcessor"
IconApplicationSpreadsheet Icon = "ApplicationSpreadsheet"
IconApplicationSlideshow Icon = "ApplicationSlideshow"
IconApplicationCalculator Icon = "ApplicationCalculator"
IconApplicationPreferences Icon = "ApplicationPreferences"
IconApplicationProcessManager Icon = "ApplicationProcessManager"
IconApplicationSystemInformation Icon = "ApplicationSystemInformation"
IconApplicationManual Icon = "ApplicationManual"
IconApplicationCamera Icon = "ApplicationCamera"
IconApplicationImageViewer Icon = "ApplicationImageViewer"
IconApplicationMediaPlayer Icon = "ApplicationMediaPlayer"
IconApplicationImageEditor Icon = "ApplicationImageEditor"
IconApplicationAudioEditor Icon = "ApplicationAudioEditor"
IconApplicationVideoEditor Icon = "ApplicationVideoEditor"
IconApplicationClock Icon = "ApplicationClock"
IconApplicationCalendar Icon = "ApplicationCalendar"
IconApplicationChecklist Icon = "ApplicationChecklist"
// categories: applications
IconApplications Icon = "Applications"
IconApplicationsAccessories Icon = "ApplicationsAccessories"
IconApplicationsDevelopment Icon = "ApplicationsDevelopment"
IconApplicationsEngineering Icon = "ApplicationsEngineering"
IconApplicationsGames Icon = "ApplicationsGames"
IconApplicationsGraphics Icon = "ApplicationsGraphics"
IconApplicationsInternet Icon = "ApplicationsInternet"
IconApplicationsMultimedia Icon = "ApplicationsMultimedia"
IconApplicationsOffice Icon = "ApplicationsOffice"
IconApplicationsScience Icon = "ApplicationsScience"
IconApplicationsSystem Icon = "ApplicationsSystem"
IconApplicationsUtilities Icon = "ApplicationsUtilities"
// categories: preferences
IconPreferences Icon = "Preferences"
IconPreferencesDesktop Icon = "PreferencesDesktop"
IconPreferencesPeripherals Icon = "PreferencesPeripherals"
IconPreferencesPersonal Icon = "PreferencesPersonal"
IconPreferencesSystem Icon = "PreferencesSystem"
IconPreferencesNetwork Icon = "PreferencesNetwork"
// devices
IconDevice Icon = "Device"
IconDeviceCamera Icon = "DeviceCamera"
IconDeviceWebCamera Icon = "DeviceWebCamera"
IconDeviceComputer Icon = "DeviceComputer"
IconDevicePda Icon = "DevicePda"
IconDevicePhone Icon = "DevicePhone"
IconDevicePrinter Icon = "DevicePrinter"
IconDeviceScanner Icon = "DeviceScanner"
IconDeviceMultimediaPlayer Icon = "DeviceMultimediaPlayer"
IconDeviceVideoDisplay Icon = "DeviceVideoDisplay"
IconDeviceAudioInput Icon = "DeviceAudioInput"
IconDeviceAudioOutput Icon = "DeviceAudioOutput"
// devices: hardware
IconHardware Icon = "Hardware"
IconHardwareCPU Icon = "HardwareCPU"
IconHardwareGPU Icon = "HardwareGPU"
IconHardwareRAM Icon = "HardwareRAM"
IconHardwareSoundCard Icon = "HardwareSoundCard"
IconHardwareNetworkAdapter Icon = "HardwareNetworkAdapter"
// devices: power
IconPowerBattery Icon = "PowerBattery"
// devices: storage
IconStorageHardDisk Icon = "StorageHardDisk"
IconStorageFloppyDisk Icon = "StorageFloppyDisk"
IconStorageSolidState Icon = "StorageSolidState"
IconStorageOptical Icon = "StorageOptical"
IconStorageFlashStick Icon = "StorageFlashStick"
IconStorageFlashCard Icon = "StorageFlashCard"
IconStorageMagneticTape Icon = "StorageMagneticTape"
// devices: input
IconInputGaming Icon = "InputGaming"
IconInputKeyboard Icon = "InputKeyboard"
IconInputMouse Icon = "InputMouse"
IconInputTablet Icon = "InputTablet"
// devices: network
IconNetworkWired Icon = "NetworkWired"
IconNetworkWireless Icon = "NetworkWireless"
IconNetworkCellular Icon = "NetworkCellular"
IconNetworkLocal Icon = "NetworkLocal"
IconNetworkInternet Icon = "NetworkInternet"
IconNetworkVPN Icon = "NetworkVPN"
IconNetworkServer Icon = "NetworkServer"
IconNetworkWorkgroup Icon = "NetworkWorkgroup"
// emblems
IconEmblemDefault Icon = "EmblemDefault"
IconEmblemEncrypted Icon = "EmblemEncrypted"
IconEmblemFavorite Icon = "EmblemFavorite"
IconEmblemImportant Icon = "EmblemImportant"
IconEmblemReadOnly Icon = "EmblemReadOnly"
IconEmblemShared Icon = "EmblemShared"
IconEmblemSymbolicLink Icon = "EmblemSymbolicLink"
IconEmblemSynchronized Icon = "EmblemSynchronized"
IconEmblemSystem Icon = "EmblemSystem"
IconEmblemUnreadable Icon = "EmblemUnreadable"
// places
IconPlaceDirectory Icon = "PlaceDirectory"
IconPlaceRemote Icon = "PlaceRemote"
IconPlaceHome Icon = "PlaceHome"
IconPlaceDownloads Icon = "PlaceDownloads"
IconPlaceDesktop Icon = "PlaceDesktop"
IconPlacePhotos Icon = "PlacePhotos"
IconPlaceBooks Icon = "PlaceBooks"
IconPlaceBookmarks Icon = "PlaceBookmarks"
IconPlaceTrash Icon = "PlaceTrash"
IconPlaceDocuments Icon = "PlaceDocuments"
IconPlaceRepositories Icon = "PlaceRepositories"
IconPlaceMusic Icon = "PlaceMusic"
IconPlaceArchives Icon = "PlaceArchives"
IconPlaceFonts Icon = "PlaceFonts"
IconPlaceBinaries Icon = "PlaceBinaries"
IconPlaceVideos Icon = "PlaceVideos"
IconPlace3DObjects Icon = "Place3DObjects"
IconPlaceHistory Icon = "PlaceHistory"
IconPlacePreferences Icon = "PlacePreferences"
// status: checkbox
IconCheckboxChecked Icon = "CheckboxChecked"
IconCheckboxUnchecked Icon = "CheckboxUnchecked"
// status: appointments
IconAppointmentMissed Icon = "AppointmentMissed"
IconAppointmentSoon Icon = "AppointmentSoon"
// status: dialogs
IconDialogError Icon = "DialogError"
IconDialogInformation Icon = "DialogInformation"
IconDialogPassword Icon = "DialogPassword"
IconDialogQuestion Icon = "DialogQuestion"
IconDialogWarning Icon = "DialogWarning"
// status: directories
IconDirectoryDragAccept Icon = "DirectoryDragAccept"
IconDirectoryFull Icon = "DirectoryFull"
IconDirectoryOpen Icon = "DirectoryOpen"
IconDirectoryVisiting Icon = "DirectoryVisiting"
// status: trash
IconTrashFull Icon = "TrashFull"
// status: resource
IconResourceLoading Icon = "ResourceLoading"
IconResourceMissing Icon = "ResourceMissing"
// status: mail
IconMailAttachment Icon = "MailAttachment"
IconMailUnread Icon = "MailUnread"
IconMailReplied Icon = "MailReplied"
IconMailSigned Icon = "MailSigned"
IconMailSignedVerified Icon = "MailSignedVerified"
// status: network
IconCellularSignal0 Icon = "CellularSignal0"
IconCellularSignal1 Icon = "CellularSignal1"
IconCellularSignal2 Icon = "CellularSignal2"
IconCellularSignal3 Icon = "CellularSignal3"
IconWirelessSignal0 Icon = "WirelessSignal0"
IconWirelessSignal1 Icon = "WirelessSignal1"
IconWirelessSignal2 Icon = "WirelessSignal2"
IconWirelessSignal3 Icon = "WirelessSignal3"
IconNetworkError Icon = "NetworkError"
IconNetworkIdle Icon = "NetworkIdle"
IconNetworkOffline Icon = "NetworkOffline"
IconNetworkReceive Icon = "NetworkReceive"
IconNetworkTransmit Icon = "NetworkTransmit"
IconNetworkTransmitReceive Icon = "NetworkTransmitReceive"
// status: print
IconPrintError Icon = "PrintError"
IconPrintPrinting Icon = "PrintPrinting"
// status: security
IconSecurityHigh Icon = "SecurityHigh"
IconSecurityMedium Icon = "SecurityMedium"
IconSecurityLow Icon = "SecurityLow"
// status: software
IconSoftwareUpdateAvailable Icon = "SoftwareUpdateAvailable"
IconSoftwareUpdateUrgent Icon = "SoftwareUpdateUrgent"
IconSoftwareInstalling Icon = "SoftwareInstalling"
// status: sync
IconSyncError Icon = "SyncError"
IconSyncSynchronizing Icon = "SyncSynchronizing"
// status: tasks
IconTaskDue Icon = "TaskDue"
IconTaskPastDue Icon = "TaskPastDue"
// status: users
IconUserAvailable Icon = "UserAvailable"
IconUserAway Icon = "UserAway"
IconUserIdle Icon = "UserIdle"
IconUserOffline Icon = "UserOffline"
// status: power
IconBattery0 Icon = "Battery0"
IconBattery1 Icon = "Battery1"
IconBattery2 Icon = "Battery2"
IconBattery3 Icon = "Battery3"
IconBrightness0 Icon = "Brightness0"
IconBrightness1 Icon = "Brightness1"
IconBrightness2 Icon = "Brightness2"
IconBrightness3 Icon = "Brightness3"
// status: media
IconVolume0 Icon = "Volume0"
IconVolume1 Icon = "Volume1"
IconVolume2 Icon = "Volume2"
IconVolume3 Icon = "Volume3"
IconPlaylistRepeat Icon = "PlaylistRepeat"
IconPlaylistShuffle Icon = "PlaylistShuffle"
// status: weather
IconWeatherClear Icon = "WeatherClear"
IconWeatherClearNight Icon = "WeatherClearNight"
IconWeatherFewClouds Icon = "WeatherFewClouds"
IconWeatherFewCloudsNight Icon = "WeatherFewCloudsNight"
IconWeatherFog Icon = "WeatherFog"
IconWeatherOvercast Icon = "WeatherOvercast"
IconWeatherSevereAlert Icon = "WeatherSevereAlert"
IconWeatherShowers Icon = "WeatherShowers"
IconWeatherShowersScattered Icon = "WeatherShowersScattered"
IconWeatherSnow Icon = "WeatherSnow"
IconWeatherStorm Icon = "WeatherStorm"
)
// Texture returns a texture of the corresponding icon ID.
func (id Icon) Texture (size IconSize) canvas.Texture {
if iconSet == nil { return nil }
return iconSet.Icon(id, size)
}
// MimeIcon returns an icon corresponding to a MIME type.
func MimeIcon (mime data.Mime, size IconSize) canvas.Texture {
if iconSet == nil { return nil }
return iconSet.MimeIcon(mime, size)
}
// IconSet holds a set of icon textures.
type IconSet interface {
// A word on textures:
//
// Because textures can be linked to some resource that is outside of
// the control of Go's garbage collector, methods of IconSet must not
// allocate new copies of a texture each time they are called. It is
// fine to lazily load textures and save them for later use, but the
// same texture must never be allocated multiple times as this could
// cause a memory leak.
//
// As such, textures returned by these methods must be protected.
// Icon returns a texture of the corresponding icon ID. If there is no
// suitable option, it should return nil.
Icon (Icon, IconSize) canvas.Texture
// MimeIcon returns a texture of an icon corresponding to a MIME type.
// If there is no suitable specific option, it should return a more
// generic icon or a plain file icon.
MimeIcon (data.Mime, IconSize) canvas.Texture
}
var iconSet IconSet
// SetIconSet sets the icon set.
func SetIconSet (set IconSet) {
assertBackend()
iconSet = set
backend.SetIconSet(set)
}

452
object.go
View File

@@ -1,155 +1,73 @@
package tomo
import "image"
import "image/color"
import "golang.org/x/image/font"
import "git.tebibyte.media/tomo/tomo/text"
import "git.tebibyte.media/tomo/tomo/data"
import "git.tebibyte.media/tomo/tomo/event"
import "git.tebibyte.media/tomo/tomo/input"
import "git.tebibyte.media/tomo/tomo/canvas"
// Side represents one side of a rectangle.
type Side int; const (
SideTop Side = iota
SideRight
SideBottom
SideLeft
)
// Inset represents a rectangle inset that can have a different value for each
// side.
type Inset [4]int
// I allows you to create an inset in a CSS-ish way:
//
// - One argument: all sides are set to this value
// - Two arguments: the top and bottom sides are set to the first value, and
// the left and right sides are set to the second value.
// - Three arguments: the top side is set by the first value, the left and
// right sides are set by the second vaue, and the bottom side is set by the
// third value.
// - Four arguments: each value corresponds to a side.
//
// This function will panic if an argument count that isn't one of these is
// given.
func I (sides ...int) Inset {
switch len(sides) {
case 1: return Inset { sides[0], sides[0], sides[0], sides[0] }
case 2: return Inset { sides[0], sides[1], sides[0], sides[1] }
case 3: return Inset { sides[0], sides[1], sides[2], sides[1] }
case 4: return Inset { sides[0], sides[1], sides[2], sides[3] }
default: panic("I: illegal argument count.")
}
}
// Apply returns the given rectangle, shrunk on all four sides by the given
// inset. If a measurment of the inset is negative, that side will instead be
// expanded outward. If the rectangle's dimensions cannot be reduced any
// further, an empty rectangle near its center will be returned.
func (inset Inset) Apply (bigger image.Rectangle) (smaller image.Rectangle) {
smaller = bigger
if smaller.Dx() < inset[3] + inset[1] {
smaller.Min.X = (smaller.Min.X + smaller.Max.X) / 2
smaller.Max.X = smaller.Min.X
} else {
smaller.Min.X += inset[3]
smaller.Max.X -= inset[1]
}
if smaller.Dy() < inset[0] + inset[2] {
smaller.Min.Y = (smaller.Min.Y + smaller.Max.Y) / 2
smaller.Max.Y = smaller.Min.Y
} else {
smaller.Min.Y += inset[0]
smaller.Max.Y -= inset[2]
}
return
}
// Inverse returns a negated version of the inset.
func (inset Inset) Inverse () (prime Inset) {
return Inset {
inset[0] * -1,
inset[1] * -1,
inset[2] * -1,
inset[3] * -1,
}
}
// Horizontal returns the sum of SideRight and SideLeft.
func (inset Inset) Horizontal () int {
return inset[SideRight] + inset[SideLeft]
}
// Vertical returns the sum of SideTop and SideBottom.
func (inset Inset) Vertical () int {
return inset[SideTop] + inset[SideBottom]
}
// Border represents a single border of a box.
type Border struct {
Width Inset
Color [4]color.Color
}
// Align lists basic alignment types.
type Align int; const (
AlignStart Align = iota // similar to left-aligned text
AlignMiddle // similar to center-aligned text
AlignEnd // similar to right-aligned text
AlignEven // similar to justified text
)
// Object is any obscreen object. Each object must be linked to a box, even if
// it is that box.
// Object is any onscreen object that is linked to a box (or is that box).
// Unlike the Box interface and associated interfaces, Object implementations
// may originate from anywhere.
type Object interface {
GetBox () Box
}
// Box is a basic styled box.
// ContentObject is an object that has some kind of content.
type ContentObject interface {
Object
// ContentBounds returns the bounds of the inner content of the Box
// relative to the Box's InnerBounds.
ContentBounds () image.Rectangle
// ScrollTo shifts the origin of the Box's content to the origin of the
// Box's InnerBounds, offset by the given point.
ScrollTo (image.Point)
// OnContentBoundsChange specifies a function to be called when the
// Box's ContentBounds or InnerBounds changes.
OnContentBoundsChange (func ()) event.Cookie
}
// Box is a basic styled box. Implementations of Box, as well as any interface
// that embed Box, may only originate from a Backend.
type Box interface {
Object
// Window returns the Window this Box is a part of.
Window () Window
Window () Window
// Bounds returns the outer bounding rectangle of the Box relative to
// the Window.
Bounds () image.Rectangle
Bounds () image.Rectangle
// InnerBounds returns the inner bounding rectangle of the box. It is
// the value of Bounds inset by the Box's border and padding.
InnerBounds () image.Rectangle
// MinimumSize returns the minimum width and height this Box's bounds
// can be set to. This will return the value of whichever of these is
// greater:
// - The size as set by SetMinimumSize
// - The size taken up by the Box's border and padding. If there is
// internal content that does not overflow, the size of that is also
// taken into account here.
MinimumSize () image.Point
// SetBounds sets the bounding rectangle of this Box relative to the
// Window.
SetBounds (image.Rectangle)
// SetColor sets the background color of this Box.
SetColor (color.Color)
// SetTexture sets a repeating background texture. If the texture is
// transparent, it will be overlayed atop the color specified by
// SetColor().
SetTexture (canvas.Texture)
// SetBorder sets the Border(s) of the box. The first Border will be the
// most outset, and the last Border will be the most inset.
SetBorder (...Border)
// SetMinimumSize sets the minimum width and height of the box, as
// described in MinimumSize.
SetMinimumSize (image.Point)
// SetPadding sets the padding between the Box's innermost Border and
// its content.
SetPadding (Inset)
InnerBounds () image.Rectangle
// Role returns this Box's role as set by SetRole.
Role () Role
// SetRole sets what role this Box takes on. It is used to apply styling
// from a theme.
SetRole (Role)
// Tag returns whether or not a named tag exists. These are used for
// applying styling, among other things. There are some special tags
// that are only and always extant during certain user input states:
// - hovered: The mouse pointer is within the box
// - focused: The box has keyboard focus
// - pressed: The box is being pressed by the left mouse button
Tag (string) bool
// SetTag adds or removes a named tag.
SetTag (string, bool)
// SetAttr sets a style attribute, overriding the currently applied
// style.
SetAttr (Attr)
// UnsetAttr reverts a style attribute to whatever is specified by the
// currently applied style.
UnsetAttr (AttrKind)
// SetDNDData sets the data that will be picked up if this Box is
// dragged. If this is nil (which is the default), this Box will not be
// picked up.
SetDNDData (data.Data)
SetDNDData (data.Data)
// SetDNDAccept sets the type of data that can be dropped onto this Box.
// If this is nil (which is the default), this Box will reject all
// drops.
@@ -157,37 +75,37 @@ type Box interface {
// SetFocused sets whether or not this Box has keyboard focus. If set to
// true, this method will steal focus away from whichever Object
// currently has focus.
SetFocused (bool)
SetFocused (bool)
// SetFocusable sets whether or not this Box can receive keyboard focus.
// If set to false and the Box is already focused. the focus is removed.
SetFocusable (bool)
// Focused returns whether or not this Box has keyboard focus.
Focused () bool
// Modifiers returns which modifier keys on the keyboard are currently
// being held down.
Modifiers () input.Modifiers
// MousePosition returns the position of the mouse pointer relative to
// the Window.
MousePosition () image.Point
// These are event subscription functions that allow callbacks to be
// These are event subscription behaviors that allow callbacks to be
// connected to particular events. Multiple callbacks may be connected
// to the same event at once. Callbacks can be removed by closing the
// returned cookie.
OnFocusEnter (func ()) event.Cookie
OnFocusLeave (func ()) event.Cookie
OnDNDEnter (func ()) event.Cookie
OnDNDLeave (func ()) event.Cookie
OnDNDDrop (func (data.Data)) event.Cookie
OnMouseEnter (func ()) event.Cookie
OnMouseLeave (func ()) event.Cookie
OnMouseMove (func ()) event.Cookie
OnMouseDown (func (input.Button)) event.Cookie
OnMouseUp (func (input.Button)) event.Cookie
OnScroll (func (deltaX, deltaY float64)) event.Cookie
OnKeyDown (func (key input.Key, numberPad bool)) event.Cookie
OnKeyUp (func (key input.Key, numberPad bool)) event.Cookie
OnFocusEnter (func () ) event.Cookie
OnFocusLeave (func () ) event.Cookie
OnStyleChange (func () ) event.Cookie
OnIconSetChange (func () ) event.Cookie
OnDNDEnter (func () ) event.Cookie
OnDNDLeave (func () ) event.Cookie
OnDNDDrop (func (data.Data)) event.Cookie
OnMouseEnter (func () ) event.Cookie
OnMouseLeave (func () ) event.Cookie
// These event subscription behaviors require their callbacks to return
// a bool value. Under normal circumstances, these events are propagated
// to the Box which is most directly affected by them, and then to all
// of its parents from the bottom-up. Returning true from the callback
// will cause the propagation to stop immediately, thereby "catching"
// the event. Generally, if the event was successfully handled, the
// callbacks ought to return true.
OnMouseMove (func () bool) event.Cookie
OnButtonDown (func (button input.Button) bool) event.Cookie
OnButtonUp (func (button input.Button) bool) event.Cookie
OnScroll (func (deltaX, deltaY float64) bool) event.Cookie
OnKeyDown (func (key input.Key, numberPad bool) bool) event.Cookie
OnKeyUp (func (key input.Key, numberPad bool) bool) event.Cookie
}
// CanvasBox is a box that can be drawn to.
@@ -195,32 +113,55 @@ type CanvasBox interface {
Box
// SetDrawer sets the Drawer that will be called upon to draw the Box's
// content when it is invalidated.
SetDrawer (canvas.Drawer)
// content when it is invalidated. The Canvas passed to the drawer will
// have these properties:
// - It will have the same origin (0, 0) as the window which contains
// the CanvasBox
// - The Canvas bounds will describe the portion of the CanvasBox
// visible on screen
SetDrawer (canvas.Drawer)
// Invalidate causes the Box's area to be redrawn at the end of the
// event cycle, even if it wouldn't be otherwise.
Invalidate ()
}
// ContentBox is an abstract box that has some kind of content. Its only purpose
// is to be embedded into TextBox and ContainerBox.
type ContentBox interface {
// SurfaceBox is a box that can be drawn to via a hardware accelerated (or
// platform-specific) graphics context.
type SurfaceBox interface {
Box
// SetOverflow sets whether or not the Box's content overflows
// horizontally and vertically. Overflowing content is clipped to the
// bounds of the Box inset by all Borders (but not padding).
SetOverflow (horizontal, vertical bool)
// SetAlign sets how the Box's content is distributed horizontally and
// vertically.
SetAlign (x, y Align)
// Surface returns the underlying graphics context. The result must be
// asserted to the expected type or passed through a type switch before
// use. The exact type returned here depends on the backend being used,
// and it is up to the application author to ensure that the application
// and backend agree on it. Applications should fail gracefully if the
// expected type was not found.
Surface () any
// Invalidate causes the data within the surface to be pushed to the
// screen at the end of the event cycle, even if it wouldn't be
// otherwise.
Invalidate ()
// OnSizeChange specifies a function to be called when the size of the
// Box is changed, or the surface is re-allocated. The application must
// call Surface() each time this event fires in order to not draw to a
// closed surface.
OnSizeChange (func ())
}
// ContentBox is a box that has some kind of content.
type ContentBox interface {
Box
// ContentBounds returns the bounds of the inner content of the Box
// relative to the window.
ContentBounds () image.Rectangle
// relative to the Box's InnerBounds.
ContentBounds () image.Rectangle
// ScrollTo shifts the origin of the Box's content to the origin of the
// Box's InnerBounds, offset by the given point.
ScrollTo (image.Point)
ScrollTo (image.Point)
// OnContentBoundsChange specifies a function to be called when the
// Box's ContentBounds or InnerBounds changes.
OnContentBoundsChange (func ()) event.Cookie
@@ -231,26 +172,18 @@ type TextBox interface {
ContentBox
// SetText sets the text content of the Box.
SetText (string)
// SetTextColor sets the text color.
SetTextColor (color.Color)
// SetFace sets the font face text is rendered in.
SetFace (font.Face)
// SetWrap sets whether or not the text wraps.
SetWrap (bool)
SetText (string)
// SetSelectable sets whether or not the text content can be
// highlighted/selected.
SetSelectable (bool)
// SetDotColor sets the highlight color of selected text.
SetDotColor (color.Color)
// Select sets the text cursor or selection.
Select (text.Dot)
Select (text.Dot)
// Dot returns the text cursor or selection.
Dot () text.Dot
Dot () text.Dot
// OnDotChange specifies a function to be called when the text cursor or
// selection changes.
OnDotChange (func ()) event.Cookie
OnDotChange (func ()) event.Cookie
}
// ContentBox is a box that can contain child Objects. It arranges them
@@ -258,30 +191,32 @@ type TextBox interface {
type ContainerBox interface {
ContentBox
// SetPropagateEvents specifies whether or not child Objects will
// receive user input events. It is true by default. If it is false, all
// user input that would otherwise be directed to a child Box is
// directed to this Box.
SetPropagateEvents (bool)
// SetGap sets the gap between child Objects.
SetGap (image.Point)
// Add appends a child Object.
Add (Object)
// Delete removes a child Object, if it is a child of this Box.
Delete (Object)
// Add appends a child Object. If the object is already a child of
// another object, it will be removed from that object first.
Add (Object)
// Remove removes a child Object, if it is a child of this Box.
Remove (Object)
// Insert inserts a child Object before a specified Object. If the
// before Object is nil or is not contained within this Box, the
// inserted Object is appended.
Insert (child Object, before Object)
Insert (child Object, before Object)
// Clear removes all child Objects.
Clear ()
// Length returns the amount of child objects.
Length () int
Clear ()
// Len returns the amount of child Objects.
Len () int
// At returns the child Object at the specified index.
At (int) Object
// SetLayout sets the layout of this Box. Child Objects will be
// positioned according to it.
SetLayout (Layout)
At (int) Object
// SetInputMask sets whether or not user input events will be sent to
// this Box's children. If false, which is the default, input events
// will be sent to this Box as well as all of its children. If true,
// any input events that would otherwise go to this Box's children are
// sent to it instead. This prevents children from performing event
// catching as described in the documentation for Box.
SetInputMask (bool)
// TODO: if it turns out selecting specific kinds of events to mask off
// is a good idea, have SetInputMask take in a vararg list of event
// types.
}
// LayoutHints are passed to a layout to tell it how to arrange child boxes.
@@ -289,14 +224,14 @@ type LayoutHints struct {
// Bounds is the bounding rectangle that children should be placed
// within. Any padding values are already applied.
Bounds image.Rectangle
// OverflowX and OverflowY control wether child Boxes may be positioned
// OverflowX and OverflowY control whether child Boxes may be positioned
// outside of Bounds.
OverflowX bool
OverflowY bool
// AlignX and AlignY control how child Boxes are aligned horizontally
// and vertically. The effect of this may vary depending on the Layout.
AlignX Align
AlignY Align
AlignX Align
AlignY Align
// Gap controls the amount of horizontal and vertical spacing in-between
// child Boxes.
Gap image.Point
@@ -306,54 +241,95 @@ type LayoutHints struct {
type Layout interface {
// MinimumSize returns the minimum width and height of
// LayoutHints.Bounds needed to properly lay out all child Boxes.
MinimumSize (LayoutHints, []Box) image.Point
MinimumSize (LayoutHints, BoxQuerier) image.Point
// Arrange arranges child boxes according to the given LayoutHints.
Arrange (LayoutHints, []Box)
Arrange (LayoutHints, BoxArranger)
// RecommendedHeight returns the recommended height for a given width,
// if supported. Otherwise, it should just return the minimum height.
// The result of this behavior may or may not be respected, depending on
// the situation.
RecommendedHeight (LayoutHints, BoxQuerier, int) int
// RecommendedWidth returns the recommended width for a given height, if
// supported. Otherwise, it should just return the minimum width. The
// result of this behavior may or may not be respected, depending on the
// situation.
RecommendedWidth (LayoutHints, BoxQuerier, int) int
}
// Window is an operating system window. It can contain one object.
// BoxQuerier allows the attributes of a ContainerBox's children to be queried.
type BoxQuerier interface {
// Len returns the amount of boxes.
Len () int
// MinimumSize returns the minimum size of a box.
MinimumSize (index int) image.Point
// RecommendedWidth returns the recommended width for a given height for
// a box, if supported. Otherwise, it should just return the minimum
// width of that box. The result of this behavior may or may not be
// respected, depending on the situation.
RecommendedWidth (index int, height int) int
// RecommendedHeight returns the recommended height for a given width
// for a box, if supported. Otherwise, it should just return the minimum
// width of that box. The result of this behavireor may or may not be
// respected, depending on the situation.
RecommendedHeight (index int, width int) int
}
// BoxArranger is a BoxQuerier that allows arranging child boxes according to a
// layout.
type BoxArranger interface {
BoxQuerier
// SetBounds sets the bounds of a box.
SetBounds (index int, bounds image.Rectangle)
}
// Window is an operating system window. It can contain one object. Windows
// themselves are completely transparent, and become opaque once an opaque
// object is added as their root.
type Window interface {
// SetRoot sets the root child of the window. There can only be one at
// a time, and setting it will remove the current child if there is one.
SetRoot (Object)
SetRoot (Object)
// SetTitle sets the title of the window.
SetTitle (string)
// SetIcon sets the icon of the window. When multiple icon sizes are
// provided, the best fitting one is chosen for display.
SetIcon (... image.Image)
// Widget returns a window representing a smaller iconified form of this
// window. How exactly this window is used depends on the platform.
// Subsequent calls to this method on the same window will return the
// same window object.
Widget () (Window, error)
// NewMenu creates a new menu window. This window is undecorated and
// will close once the user clicks outside of it.
NewMenu (image.Rectangle) (Window, error)
// NewModal creates a new modal window that blocks all input to this
// window until it is closed.
NewModal (image.Rectangle) (Window, error)
// Copy copies data to the clipboard.
Copy (data.Data)
// Paste reads data from the clipboard. When the data is available or an
// error has occurred, the provided function will be called.
Paste (callback func (data.Data, error), accept ...data.Mime)
// Show shows the window.
Show ()
// Hide hides the window.
Hide ()
// Close closes the window.
Close ()
// OnClose specifies a function to be called when the window is closed.
OnClose (func ()) event.Cookie
}
// MainWindow is a top-level operating system window.
type MainWindow interface {
Window
// SetIcon sets the icon of the window.
SetIcon (Icon)
// SetResizable sets whether the window can be resized by the user in
// the X and Y directions. If one or both axes are false, the ones that
// are will be shrunk to the window's minimum size.
SetResizable (x, y bool)
// SetBounds sets this window's bounds. This may or may not have any
// effect on the window's position on screen depending on the platform.
SetBounds (image.Rectangle)
// NewChild creates a new window that is semantically a child of this
// window. It does not actually reside within this window, but it may be
// linked to it via some other means. This is intended for things like
// toolboxes and tear-off menus.
NewChild (image.Rectangle) (Window, error)
// NewMenu creates a new menu window. This window is undecorated and
// will close once the user clicks outside of it.
NewMenu (image.Rectangle) (Window, error)
// NewModal creates a new modal window that blocks all input to this
// window until it is closed.
NewModal (image.Rectangle) (Window, error)
// Modifiers returns which modifier keys on the keyboard are currently
// being held down.
Modifiers () input.Modifiers
// MousePosition returns the position of the mouse pointer relative to
// the Window.
MousePosition () image.Point
// Copy copies data to the clipboard.
Copy (data.Data)
// Paste reads data from the clipboard. When the data is available or an
// error has occurred, the provided function will be called.
Paste (callback func (data.Data, error), accept ...data.Mime)
// SetVisible sets whether or not this window is visible. Windows are
// invisible by default.
SetVisible (bool)
// Visible returns whether or not this window is visible.
Visible () bool
// Close closes the window.
Close ()
// OnClose specifies a function to be called when the window is closed.
OnClose (func ()) event.Cookie
}

View File

@@ -1,55 +0,0 @@
package tomo
import "os"
import "plugin"
import "path/filepath"
var pluginPaths []string
func loadPlugins () {
for _, dir := range pluginPaths {
if dir != "" {
loadPluginsFrom(dir)
}
}
}
func loadPluginsFrom (dir string) {
entries, err := os.ReadDir(dir)
// its no big deal if one of the dirs doesn't exist
if err != nil { return }
for _, entry := range entries {
if entry.IsDir() { continue }
if filepath.Ext(entry.Name()) != ".so" { continue }
pluginPath := filepath.Join(dir, entry.Name())
loadPlugin(pluginPath)
}
}
func loadPlugin (path string) {
die := func (reason string) {
println("tomo: could not load plugin at", path + ":", reason)
}
plugin, err := plugin.Open(path)
if err != nil {
die(err.Error())
return
}
// check for and obtain basic plugin functions
name, ok := extract[func () string](plugin, "Name")
if !ok { die("does not implement Name() string"); return }
_, ok = extract[func () string](plugin, "Description")
if !ok { die("does not implement Description() string"); return }
println("tomo: loaded plugin", name())
}
func extract[T any] (plugin *plugin.Plugin, name string) (value T, ok bool) {
symbol, err := plugin.Lookup(name)
if err != nil { return }
value, ok = symbol.(T)
return
}

80
style.go Normal file
View File

@@ -0,0 +1,80 @@
package tomo
import "fmt"
import "image/color"
// Role describes the role of an object.
type Role struct {
// Package is an optional namespace field. If specified, it should be
// the package name or module name the object is from.
Package string
// Object specifies what type of object it is. For example:
// - TextInput
// - Table
// - Label
// - Dial
// This should correspond directly to the type name of the object.
Object string
}
// String satisfies the fmt.Stringer interface. It follows the format of:
// Package.Object
func (r Role) String () string {
return fmt.Sprintf("%s.%s", r.Package, r.Object)
}
// R is shorthand for creating a role structure.
func R (pack, object string) Role {
return Role { Package: pack, Object: object }
}
// Color represents a color ID.
type Color int; const (
ColorBackground Color = iota
ColorForeground
ColorRaised
ColorSunken
ColorAccent
)
// RGBA satisfies the color.Color interface.
func (id Color) RGBA () (r, g, b, a uint32) {
if style == nil { return }
return style.Colors[id].RGBA()
}
var style *Style
// SetStyle sets the style.
func SetStyle (sty *Style) {
assertBackend()
style = sty
backend.SetStyle(sty)
}
// Style can apply a visual style to different objects.
type Style struct {
// Rules determines which styles get applied to which Objects.
Rules []Rule
// Colors maps tomo.Color values to color.RGBA values.
Colors map[Color] color.Color
}
// Rule describes under what circumstances should certain style attributes be
// active.
type Rule struct {
Role Role
Tags []string
Set AttrSet
}
// Ru is shorthand for creating a rule structure
func Ru (set AttrSet, role Role, tags ...string) Rule {
return Rule {
Role: role,
Tags: tags,
Set: set,
}
}

View File

@@ -1,293 +0,0 @@
package theme
import "git.tebibyte.media/tomo/tomo/data"
import "git.tebibyte.media/tomo/tomo/canvas"
// IconSize represents the size of an icon.
type IconSize int; const (
IconSizeSmall IconSize = iota;
IconSizeMedium
IconSizeLarge
)
// Icon represents an icon ID.
type Icon int; const (
// --- Objects --- //
// files
IconFile Icon = iota
IconDirectory
IconDirectoryFull
// places
IconDownloads
IconPhotos
IconBooks
IconDocuments
IconRepositories
IconMusic
IconArchives
IconFonts
IconBinaries
IconVideos
Icon3DObjects
IconHistory
IconPreferences
// storage
IconStorage // generic
IconMagneticTape
IconFloppyDisk
IconHardDisk
IconSolidStateDrive
IconFlashDrive
IconMemoryCard
IconROMDisk
IconRAMDisk
IconCD
IconDVD
// network
IconNetwork // generic
IconLocalNetwork
IconInternet
IconEthernet
IconWireless
IconCell
IconBluetooth
IconRadio
// devices
IconDevice // generic
IconRouter
IconServer
IconDesktop
IconLaptop
IconTablet
IconPhone
IconWatch
IconCamera
// peripherals
IconPeripheral // generic
IconKeyboard
IconMouse
IconMonitor
IconWebcam
IconMicrophone
IconSpeaker
IconPenTablet
IconTrackpad
IconController
// i/o
IconPort // generic
IconEthernetPort
IconUSBPort
IconParallelPort
IconSerialPort
IconPS2Port
IconDisplayConnector
IconCGAPort
IconVGAPort
IconHDMIPort
IconDisplayPort
IconInfrared
// --- Actions --- //
// files
IconOpen
IconOpenIn
IconSave
IconSaveAs
IconPrints
IconNew
IconNewDirectory
IconDelete
IconRename
IconGetInformation
IconChangePermissions
IconRevert
// list management
IconAdd
IconRemove
IconAddBookmark
IconRemoveBookmark
IconAddFavorite
IconRemoveFavorite
// media
IconPlay
IconPause
IconStop
IconFastForward
IconRewind
IconToBeginning
IconToEnd
IconRecord
IconVolumeUp
IconVolumeDown
IconMute
// editing
IconUndo
IconRedo
IconCut
IconCopy
IconPaste
IconFind
IconReplace
IconSelectAll
IconSelectNone
IconIncrement
IconDecrement
// window management
IconClose
IconQuit
IconIconify
IconShade
IconMaximize
IconFullScreen
IconRestore
// view controls
IconExpand
IconContract
IconBack
IconForward
IconUp
IconDown
IconReload
IconZoomIn
IconZoomOut
IconZoomReset
IconMove
IconResize
IconGoTo
// tools
IconTransform
IconTranslate
IconRotate
IconScale
IconWarp
IconCornerPin
IconSelectRectangle
IconSelectEllipse
IconSelectLasso
IconSelectGeometric
IconSelectAuto
IconCrop
IconFill
IconGradient
IconPencil
IconBrush
IconEraser
IconText
IconEyedropper
// --- Status --- //
// dialogs
IconInformation
IconQuestion
IconWarning
IconError
IconCancel
IconOkay
// network
IconCellSignal0
IconCellSignal1
IconCellSignal2
IconCellSignal3
IconWirelessSignal0
IconWirelessSignal1
IconWirelessSignal2
IconWirelessSignal3
// power
IconBattery0
IconBattery1
IconBattery2
IconBattery3
IconBrightness0
IconBrightness1
IconBrightness2
IconBrightness3
// media
IconVolume0
IconVolume1
IconVolume2
IconVolume3
)
// Texture returns a texture of the corresponding icon ID.
func (id Icon) Texture (size IconSize) canvas.Texture {
if current == nil { return nil }
return current.Icon(id, size)
}
// MimeIcon returns an icon corresponding to a MIME type.
func MimeIcon (mime data.Mime, size IconSize) canvas.Texture {
if current == nil { return nil }
return current.MimeIcon(mime, size)
}
// ApplicationIcon describes the icon of the application.
type ApplicationIcon struct {
// The name or ID of the application. If applicable, this should
// correspond to the file name (without the path or extension) of the
// icon on the system. This field is optional.
Name string
// Role describes what the application does. If a specific icon file
// cannot be found, a generic one is picked using this field.
Role ApplicationRole
}
// Texture returns a texture of the corresponding icon ID.
func (icon ApplicationIcon) Texture (size IconSize) canvas.Texture {
if current == nil { return nil }
return current.ApplicationIcon(icon, size)
}
// ApplicationRole describes what an application does.
type ApplicationRole int; const (
RoleUnknown ApplicationRole = iota
RoleWebBrowser
RoleMesssanger
RolePhone
RoleMail
RoleTerminalEmulator
RoleFileBrowser
RoleTextEditor
RoleDocumentViewer
RoleWordProcessor
RoleSpreadsheet
RoleSlideshow
RoleCalculator
RolePreferences
RoleProcessManager
RoleSystemInformation
RoleManual
RoleCamera
RoleImageViewer
RoleMediaPlayer
RoleImageEditor
RoleAudioEditor
RoleVideoEditor
RoleClock
RoleCalendar
RoleChecklist
)

View File

@@ -1,88 +0,0 @@
package theme
import "git.tebibyte.media/tomo/tomo"
import "git.tebibyte.media/tomo/tomo/data"
import "git.tebibyte.media/tomo/tomo/event"
import "git.tebibyte.media/tomo/tomo/canvas"
// Role describes the role of an object.
type Role struct {
// Package is an optional namespace field. If specified, it should be
// the package name or module name the object is from.
Package string
// Object specifies what type of object it is. For example:
// - TextInput
// - Table
// - Label
// - Dial
// This should correspond directly to the type name of the object.
Object string
// Variant is an optional field to be used when an object has one or
// more soft variants under one type. For example, an object "Slider"
// may have variations "horizontal" and "vertical".
Variant string
}
// R is shorthand for creating a Role structure.
func R (pack, object, variant string) Role {
return Role { Package: pack, Object: object, Variant: variant }
}
// Color represents a color ID.
type Color int; const (
ColorBackground Color = iota
ColorForeground
ColorRaised
ColorSunken
ColorAccent
)
// RGBA satisfies the color.Color interface.
func (id Color) RGBA () (r, g, b, a uint32) {
if current == nil { return }
return current.RGBA(id)
}
// Theme is an object that can apply a visual style to different objects.
type Theme interface {
// Apply applies the theme to the given object, according to the given
// role. This may register event listeners with the given object;
// closing the returned cookie will remove them.
Apply (tomo.Object, Role) event.Cookie
// RGBA returns the RGBA values of the corresponding color ID.
RGBA (Color) (r, g, b, a uint32)
// Icon returns a texture of the corresponding icon ID. This texture
// should be protected, unless a new copy of it is returned with each
// subsequent call.
Icon (Icon, IconSize) canvas.Texture
// MimeIcon returns an icon corresponding to a MIME type. This texture
// should be protected, unless a new copy of it is returned with each
// subsequent call.
MimeIcon (data.Mime, IconSize) canvas.Texture
// ApplicationIcon returns an icon corresponding to an application. This
// texture should be protected, unless a new copy of it is returned with
// each subsequent call.
ApplicationIcon (ApplicationIcon, IconSize) canvas.Texture
}
var current Theme
// SetTheme sets the theme.
func SetTheme (theme Theme) {
current = theme
}
// Apply applies the current theme to the given object, according to the given
// role. This may register event listeners with the given object; closing the
// returned cookie will remove them.
func Apply (object tomo.Object, role Role) event.Cookie {
if current == nil { return event.NoCookie { } }
return current.Apply(object, role)
}

25
tomo.go
View File

@@ -12,13 +12,11 @@ var backend Backend
// event loop in that order. This function blocks until Stop is called, or the
// backend experiences a fatal error.
func Run (callback func ()) error {
loadPlugins()
if backend != nil {
return errors.New("there is already a backend running")
}
back, err := Initialize()
back, err := initialize()
if err != nil { return err }
backendLock.Lock()
@@ -26,6 +24,8 @@ func Run (callback func ()) error {
backendLock.Unlock()
callback()
// callback may have called tomo.Stop
if backend == nil { return nil }
return backend.Run()
}
@@ -52,11 +52,19 @@ func Do (callback func ()) {
}
// NewWindow creates and returns a window within the specified bounds on screen.
func NewWindow (bounds image.Rectangle) (MainWindow, error) {
func NewWindow (bounds image.Rectangle) (Window, error) {
assertBackend()
return backend.NewWindow(bounds)
}
// NewPlainWindow is like NewWindow, but it creates an undecorated window that
// does not appear in window lists. It is intended for creating things like
// docks, panels, etc.
func NewPlainWindow (bounds image.Rectangle) (Window, error) {
assertBackend()
return backend.NewPlainWindow(bounds)
}
// NewBox creates and returns a basic Box.
func NewBox () Box {
assertBackend()
@@ -83,7 +91,14 @@ func NewContainerBox () ContainerBox {
// NewTexture creates a new texture from an image. When no longer in use, it
// must be freed using Close().
func NewTexture (source image.Image) canvas.Texture {
func NewTexture (source image.Image) canvas.TextureCloser {
assertBackend()
return backend.NewTexture(source)
}
// NewCanvas creates a new canvas with the specified bounds. When no longer in
// use, it must be freed using Close().
func NewCanvas (bounds image.Rectangle) canvas.CanvasCloser {
assertBackend()
return backend.NewCanvas(bounds)
}

105
unit.go Normal file
View File

@@ -0,0 +1,105 @@
package tomo
import "image"
import "image/color"
// Side represents one side of a rectangle.
type Side int; const (
SideTop Side = iota
SideRight
SideBottom
SideLeft
)
// Inset represents a rectangle inset that can have a different value for each
// side.
type Inset [4]int
// I allows you to create an inset in a CSS-ish way:
//
// - One argument: all sides are set to this value
// - Two arguments: the top and bottom sides are set to the first value, and
// the left and right sides are set to the second value.
// - Three arguments: the top side is set by the first value, the left and
// right sides are set by the second vaue, and the bottom side is set by the
// third value.
// - Four arguments: each value corresponds to a side.
//
// This function will panic if an argument count that isn't one of these is
// given.
func I (sides ...int) Inset {
switch len(sides) {
case 1: return Inset { sides[0], sides[0], sides[0], sides[0] }
case 2: return Inset { sides[0], sides[1], sides[0], sides[1] }
case 3: return Inset { sides[0], sides[1], sides[2], sides[1] }
case 4: return Inset { sides[0], sides[1], sides[2], sides[3] }
default: panic("I: illegal argument count.")
}
}
// Apply returns the given rectangle, shrunk on all four sides by the given
// inset. If a measurment of the inset is negative, that side will instead be
// expanded outward. If the rectangle's dimensions cannot be reduced any
// further, an empty rectangle near its center will be returned.
func (inset Inset) Apply (bigger image.Rectangle) (smaller image.Rectangle) {
smaller = bigger
if smaller.Dx() < inset[3] + inset[1] {
smaller.Min.X = (smaller.Min.X + smaller.Max.X) / 2
smaller.Max.X = smaller.Min.X
} else {
smaller.Min.X += inset[3]
smaller.Max.X -= inset[1]
}
if smaller.Dy() < inset[0] + inset[2] {
smaller.Min.Y = (smaller.Min.Y + smaller.Max.Y) / 2
smaller.Max.Y = smaller.Min.Y
} else {
smaller.Min.Y += inset[0]
smaller.Max.Y -= inset[2]
}
return
}
// Inverse returns a negated version of the inset.
func (inset Inset) Inverse () (prime Inset) {
return Inset {
inset[0] * -1,
inset[1] * -1,
inset[2] * -1,
inset[3] * -1,
}
}
// Horizontal returns the sum of SideRight and SideLeft.
func (inset Inset) Horizontal () int {
return inset[SideRight] + inset[SideLeft]
}
// Vertical returns the sum of SideTop and SideBottom.
func (inset Inset) Vertical () int {
return inset[SideTop] + inset[SideBottom]
}
// Border represents a single border of a box.
type Border struct {
Width Inset
Color [4]color.Color
}
// Align lists basic alignment types.
type Align int; const (
AlignStart Align = iota // similar to left-aligned text
AlignMiddle // similar to center-aligned text
AlignEnd // similar to right-aligned text
AlignEven // similar to justified text
)
// TextureMode lists texture rendering modes.
type TextureMode int; const (
TextureModeTile TextureMode = iota
TextureModeCenter
// TODO more modes: fit, fill, and stretch
// Of course canvas will need to have a concept of this.
)

22
unix.go
View File

@@ -1,22 +0,0 @@
//go:build linux || darwin || freebsd
package tomo
import "os"
import "strings"
import "path/filepath"
func init () {
pathVariable := os.Getenv("TOMO_PLUGIN_PATH")
pluginPaths = strings.Split(pathVariable, ":")
pluginPaths = append (
pluginPaths,
"/usr/lib/tomo/plugins",
"/usr/local/lib/tomo/plugins")
homeDir, err := os.UserHomeDir()
if err == nil {
pluginPaths = append (
pluginPaths,
filepath.Join(homeDir, ".local/lib/tomo/plugins"))
}
}