feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
+495
@@ -0,0 +1,495 @@
|
||||
package platform
|
||||
|
||||
// AccessTree is the content of a surface for assistive technology, such as
|
||||
// screen readers: the elements a user can perceive and act on.
|
||||
type AccessTree struct {
|
||||
// Nodes are the elements in tree order: a parent before its children.
|
||||
Nodes []AccessNode
|
||||
// Focus is the ID of the element with the keyboard focus, 0 for none.
|
||||
Focus uint64
|
||||
// Announcements are texts for assistive technology to read out once,
|
||||
// after what it is reading, as the title of a page shown or a toast:
|
||||
// news the focus does not bring.
|
||||
Announcements []string
|
||||
// Alerts are texts to read out at once, interrupting what is being
|
||||
// read: what an alert (RoleAlert) shows as it appears or changes, as
|
||||
// ARIA's assertive live regions.
|
||||
Alerts []string
|
||||
// Selected is the word for a chosen cell of a grid in the window's
|
||||
// language ("selected"), given while a cell says whether it is
|
||||
// chosen, for a bridge whose screen reader reads no chosen state of
|
||||
// cells to say with its name.
|
||||
Selected string
|
||||
}
|
||||
|
||||
// AccessNode is an element of an AccessTree.
|
||||
type AccessNode struct {
|
||||
// ID identifies the element from frame to frame.
|
||||
ID uint64
|
||||
// Parent is the index of the parent node in AccessTree.Nodes, -1 for
|
||||
// the elements at the top.
|
||||
Parent int
|
||||
Role AccessRole
|
||||
// Label names the element; Value is its value, as the text of a text
|
||||
// field, for elements that have one.
|
||||
Label, Value string
|
||||
// Bounds is the element's visible box, in DIPs relative to the
|
||||
// surface.
|
||||
Bounds RectF
|
||||
States AccessStates
|
||||
// Min, Max and Now are the range and the value of a slider or a
|
||||
// progress bar; Now is below Min for progress of unknown length. Step
|
||||
// is how far an increment moves the value, 0 for none.
|
||||
Min, Max, Now, Step float64
|
||||
// SelStart and SelEnd are the selection of a text field, in runes,
|
||||
// and Placeholder what it shows while empty.
|
||||
SelStart, SelEnd int
|
||||
Placeholder string
|
||||
// Description tells more about the element than its name, as help
|
||||
// text read after it: a field's description and its error, or a
|
||||
// tooltip.
|
||||
Description string
|
||||
// KeyShortcuts are the keys that press or focus the element, as
|
||||
// ARIA's aria-keyshortcuts, written as the platform's menus write
|
||||
// them ("⌘K" on macOS, "Ctrl+K" elsewhere), separated by spaces.
|
||||
KeyShortcuts string
|
||||
// Level is how deep an item of a tree is, or the rank of a heading,
|
||||
// from 1; 0 for other nodes.
|
||||
Level int
|
||||
// Current says which item the element is the current one of, as the
|
||||
// page the user is on.
|
||||
Current AccessCurrent
|
||||
// AutoComplete says what the suggestions of a text field or a combo
|
||||
// box complete as the user types, as ARIA's aria-autocomplete.
|
||||
AutoComplete AccessAutoComplete
|
||||
// PosInSet is the place of an item in its set, from 1, and SetSize
|
||||
// the size of the set, 0 when not given: a list's rows say which of
|
||||
// all they are, whether or not the others are built, and the list how
|
||||
// many rows it has.
|
||||
PosInSet, SetSize int
|
||||
// RowCount and ColCount are how many rows and columns a table, a grid
|
||||
// or a tree grid has, built or not, as ARIA's aria-rowcount and
|
||||
// aria-colcount; RowIndex and ColIndex are the place of a row or a
|
||||
// cell among them, from 1, header rows counted (aria-rowindex,
|
||||
// aria-colindex). 0 when the app gives none: a row's PosInSet and its
|
||||
// table's SetSize then tell its place, and the rows and cells built
|
||||
// the rest.
|
||||
RowCount, ColCount, RowIndex, ColIndex int
|
||||
// RowSpan and ColSpan are how many rows and columns of its table a
|
||||
// cell covers, as ARIA's aria-rowspan and aria-colspan: 0 for one.
|
||||
// The cell after one spanning columns in its row is in the column
|
||||
// after those it covers.
|
||||
RowSpan, ColSpan int
|
||||
// Actions are the actions the element takes in AccessAction events.
|
||||
Actions AccessActions
|
||||
// RoleDescription is what screen readers read for the element's role
|
||||
// in place of its own, as "carousel" for a group or "slide" for a tab
|
||||
// panel: ARIA's aria-roledescription. "" reads the role.
|
||||
RoleDescription string
|
||||
// Controls are the IDs of the nodes whose content or presence the
|
||||
// element controls, as the region a disclosure button opens: ARIA's
|
||||
// aria-controls.
|
||||
Controls []uint64
|
||||
// DescribedBy are the IDs of the nodes whose text describes the
|
||||
// element, as a hint below a field, which Description holds: ARIA's
|
||||
// aria-describedby. ErrorMessage are those of the nodes holding the
|
||||
// message of an element that is AccessInvalid, whose text Description
|
||||
// starts with: ARIA's aria-errormessage, given only while invalid.
|
||||
DescribedBy, ErrorMessage []uint64
|
||||
// HasPopup is the kind of popup the element opens, as ARIA's
|
||||
// aria-haspopup.
|
||||
HasPopup AccessPopup
|
||||
// WebView is the web view whose page the node stands for, if any
|
||||
// (Surface.NewWebView): assistive technology finds the page's elements
|
||||
// inside it, and it has no children of its own.
|
||||
WebView WebView
|
||||
// TextRuns are the formats of the runes of a text field's Value, as a
|
||||
// rich text editor's: runs in order, from rune Start to End, that
|
||||
// screen readers read as bold, italic, links and headings. Runes no
|
||||
// run holds take the text's default font. Empty for plain text.
|
||||
TextRuns []AccessTextRun
|
||||
// LineBoxes are where the lines of a text field's Value in view
|
||||
// show, as a code editor lays them out, in the order of the lines:
|
||||
// assistive technology finds where a range of the text is by them
|
||||
// (RangeBounds). Empty for a field that gives none, whose
|
||||
// Bounds then stand for any range.
|
||||
LineBoxes []AccessLineBox
|
||||
}
|
||||
|
||||
// AccessLineBox is where a line of the Value of a text field shows
|
||||
// (AccessNode.LineBoxes).
|
||||
type AccessLineBox struct {
|
||||
// Line is the line's index in Value, from 0: how many line feeds come
|
||||
// before it.
|
||||
Line int
|
||||
// Count is how many lines from Line the box holds, 0 for one: a run
|
||||
// of lines collapsed under one row, as the unchanged lines a diff's
|
||||
// separator stands for, or those of a fold.
|
||||
Count int
|
||||
// Bounds is its box, all of its rows when it wraps, in DIPs relative
|
||||
// to the surface, as the node's Bounds.
|
||||
Bounds RectF
|
||||
}
|
||||
|
||||
// AccessTextRun is a run of the Value of a text field with formats of its
|
||||
// own (AccessNode.TextRuns).
|
||||
type AccessTextRun struct {
|
||||
// Start and End are the run's runes of Value.
|
||||
Start, End int
|
||||
// Family is its font's family, "" for the system's; Size its size in
|
||||
// DIPs, 0 for the text's; Weight from 100 to 900, 0 for 400.
|
||||
Family string
|
||||
Size float32
|
||||
Weight int
|
||||
Italic, Underline, Strikethrough bool
|
||||
// Color and Background are RGBA, transparent where unset.
|
||||
Color, Background [4]uint8
|
||||
// Link is the URL the run links to.
|
||||
Link string
|
||||
// Heading is the level of the heading the run is in, from 1, 0 in a
|
||||
// body paragraph.
|
||||
Heading int
|
||||
}
|
||||
|
||||
// AccessRole is the kind of an element of an AccessTree.
|
||||
type AccessRole uint8
|
||||
|
||||
const (
|
||||
RoleGroup AccessRole = iota
|
||||
RoleText
|
||||
RoleButton
|
||||
RoleLink
|
||||
RoleCheckBox
|
||||
RoleRadio
|
||||
RoleSwitch
|
||||
RoleSlider
|
||||
RoleProgress
|
||||
RoleTextField
|
||||
RoleImage
|
||||
RoleList
|
||||
RoleScroll
|
||||
RoleDialog
|
||||
RolePopup
|
||||
RoleTooltip
|
||||
RolePopUpButton
|
||||
RoleTabList
|
||||
RoleTab
|
||||
RoleSplitter
|
||||
RoleStatus
|
||||
RoleTable
|
||||
RoleRow
|
||||
RoleCell
|
||||
RoleColumnHeader
|
||||
RoleTree
|
||||
RoleTreeItem
|
||||
RoleListItem
|
||||
RoleMenuButton
|
||||
RoleToolbar
|
||||
RoleRadioGroup
|
||||
// RoleToggleButton is pressed while AccessChecked.
|
||||
RoleToggleButton
|
||||
// RoleComboBox is a text field with a popup of options, which is
|
||||
// AccessExpanded while it shows.
|
||||
RoleComboBox
|
||||
// RoleDisclosure is a button showing or hiding content below it, which
|
||||
// is AccessExpanded while it shows: the trigger of a collapsible, or
|
||||
// the header of an accordion's section.
|
||||
RoleDisclosure
|
||||
// RoleMeter shows a value in a range, as a level indicator, and
|
||||
// RoleStepper steps one, as a spin button: both have Min, Max and Now.
|
||||
RoleMeter
|
||||
RoleStepper
|
||||
// RoleColorWell is a button showing a color, its Value, which opens a
|
||||
// picker of it, as AppKit's color well.
|
||||
RoleColorWell
|
||||
// RoleAlertDialog is a dialog asking about something important, its
|
||||
// Description the message.
|
||||
RoleAlertDialog
|
||||
// RoleMenu holds the items of a menu, RoleMenuBar the menus' titles
|
||||
// along a window, and RoleMenuItem is an item of either, which
|
||||
// RoleMenuItemCheckBox and RoleMenuItemRadio are when they show a
|
||||
// choice, AccessChecked (AccessMixed) while chosen.
|
||||
RoleMenu
|
||||
RoleMenuBar
|
||||
RoleMenuItem
|
||||
RoleMenuItemCheckBox
|
||||
RoleMenuItemRadio
|
||||
// RoleHeading is the title of a section, Level its rank: 1 for the
|
||||
// highest.
|
||||
RoleHeading
|
||||
// RoleRegion is a landmark with a name, as a panel screen readers list
|
||||
// among the window's landmarks: ARIA's region.
|
||||
RoleRegion
|
||||
// RoleLog, RoleTimer and RoleAlert are ARIA's live regions of those
|
||||
// roles: content added to a log is read out as it is added
|
||||
// (AccessTree.Announcements), a timer's changes only when the user
|
||||
// goes to it, and an alert's content at once, as it appears or
|
||||
// changes (AccessTree.Alerts).
|
||||
RoleLog
|
||||
RoleTimer
|
||||
RoleAlert
|
||||
// RoleSeparator divides groups of content or controls, as a rule
|
||||
// between a toolbar's groups of buttons, AccessVertical when it runs
|
||||
// up and down.
|
||||
RoleSeparator
|
||||
// RoleRowHeader is the cell of a table's row naming the row, as
|
||||
// RoleColumnHeader names a column.
|
||||
RoleRowHeader
|
||||
// RoleSearch is a landmark holding what searches the app or a
|
||||
// document, as a search field and its button: ARIA's search.
|
||||
RoleSearch
|
||||
// RoleArticle is a self-contained piece of content, as a post of a
|
||||
// feed or a comment of a thread: ARIA's article, no landmark.
|
||||
RoleArticle
|
||||
// RoleNavigation is a landmark holding links that move around the app
|
||||
// or a document, as a breadcrumb trail or a navigation bar: ARIA's
|
||||
// navigation.
|
||||
RoleNavigation
|
||||
// RoleGrid is a table whose cells take the focus and the arrow keys,
|
||||
// as a spreadsheet's, and RoleTreeGrid one whose rows open and close
|
||||
// as a tree's items do: ARIA's grid and treegrid. Their rows and
|
||||
// cells are RoleRow, RoleCell and RoleColumnHeader, as a table's.
|
||||
RoleGrid
|
||||
RoleTreeGrid
|
||||
// RoleDeletion and RoleInsertion hold content removed from or added
|
||||
// to a document, as the lines of a diff or a price struck out:
|
||||
// ARIA's deletion and insertion, HTML's del and ins.
|
||||
RoleDeletion
|
||||
RoleInsertion
|
||||
// RoleTabPanel holds the content of a tab, which labels it and
|
||||
// points to it (Controls): ARIA's tabpanel.
|
||||
RoleTabPanel
|
||||
// RoleMain, RoleBanner, RoleContentInfo and RoleComplementary are
|
||||
// landmarks: ARIA's main, banner, contentinfo and complementary,
|
||||
// HTML's main, a page's header, a page's footer and aside.
|
||||
RoleMain
|
||||
RoleBanner
|
||||
RoleContentInfo
|
||||
RoleComplementary
|
||||
)
|
||||
|
||||
// Tabular reports whether nodes of a role hold rows of cells: tables,
|
||||
// grids and tree grids.
|
||||
func (r AccessRole) Tabular() bool {
|
||||
return r == RoleTable || r == RoleGrid || r == RoleTreeGrid
|
||||
}
|
||||
|
||||
// Ranged reports whether nodes of a role have a value in a range (Min,
|
||||
// Max and Now).
|
||||
func (r AccessRole) Ranged() bool {
|
||||
return r == RoleSlider || r == RoleProgress || r == RoleMeter || r == RoleStepper
|
||||
}
|
||||
|
||||
// Live returns how content changing in a live region of a role is read,
|
||||
// as ARIA's aria-live, "polite" or "assertive", and whether the region is
|
||||
// read whole (aria-atomic): "" for roles that are no live region.
|
||||
// Statuses and logs are read after what is being read, an alert at once;
|
||||
// a timer is read only when the user goes to it.
|
||||
func (r AccessRole) Live() (live string, atomic bool) {
|
||||
switch r {
|
||||
case RoleStatus:
|
||||
return "polite", true
|
||||
case RoleLog:
|
||||
return "polite", false
|
||||
case RoleAlert:
|
||||
return "assertive", true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// AccessStates are the states of an element of an AccessTree.
|
||||
// AccessChecked is the choice among a tab list's tabs, a tree's items, and
|
||||
// the rows of a list or a table that are AccessSelectable.
|
||||
type AccessStates uint32
|
||||
|
||||
const (
|
||||
AccessFocusable AccessStates = 1 << iota
|
||||
AccessDisabled
|
||||
AccessChecked
|
||||
AccessMixed
|
||||
AccessSelected
|
||||
AccessExpanded
|
||||
AccessMultiline
|
||||
AccessPassword
|
||||
AccessReadOnly
|
||||
AccessSelectable
|
||||
// AccessOffscreen is set on elements built but out of view, as the
|
||||
// rows a list builds beyond its edges.
|
||||
AccessOffscreen
|
||||
// AccessMultiselectable is set on a list, a table, a grid or a tree
|
||||
// whose user chooses several rows (aria-multiselectable).
|
||||
AccessMultiselectable
|
||||
// AccessSegment is set on the segments of a segmented control or a
|
||||
// group of toggles, as AppKit's subrole AXSegment says.
|
||||
AccessSegment
|
||||
// AccessSearch is set on a text field for searching.
|
||||
AccessSearch
|
||||
// AccessInvalid is set on a control whose value is not valid, as a
|
||||
// field with an error.
|
||||
AccessInvalid
|
||||
// AccessSortAscending and AccessSortDescending are set on the header
|
||||
// of the column a table's rows are sorted by.
|
||||
AccessSortAscending
|
||||
AccessSortDescending
|
||||
// AccessExpandable is set on an item of a tree with children, which
|
||||
// AccessExpanded shows.
|
||||
AccessExpandable
|
||||
// AccessVertical is set on a slider going up, a separator running up
|
||||
// and down, and an element the app says runs up and down, as ARIA's
|
||||
// aria-orientation="vertical".
|
||||
AccessVertical
|
||||
// AccessBusy is set on an element whose content is about to change,
|
||||
// as a region loading, which assistive technology waits for before
|
||||
// reading it: ARIA's aria-busy.
|
||||
AccessBusy
|
||||
// AccessSortOther is set on the header of the column a table's rows
|
||||
// are sorted by in an order neither ascending nor descending.
|
||||
AccessSortOther
|
||||
// AccessHorizontal is set on an element the app says runs across, as
|
||||
// ARIA's aria-orientation="horizontal". A slider or a separator that
|
||||
// is neither AccessVertical nor AccessHorizontal runs across; other
|
||||
// elements then have no orientation.
|
||||
AccessHorizontal
|
||||
)
|
||||
|
||||
// AccessPopup is the kind of popup an element opens, as ARIA's
|
||||
// aria-haspopup says.
|
||||
type AccessPopup uint8
|
||||
|
||||
const (
|
||||
// PopupNone opens no popup.
|
||||
PopupNone AccessPopup = iota
|
||||
// PopupMenu opens a menu, aria-haspopup="menu" (or "true").
|
||||
PopupMenu
|
||||
// PopupListBox opens a list of options, PopupTree a tree, PopupGrid
|
||||
// a grid, as a calendar's, and PopupDialog a dialog.
|
||||
PopupListBox
|
||||
PopupTree
|
||||
PopupGrid
|
||||
PopupDialog
|
||||
)
|
||||
|
||||
// String returns the value of aria-haspopup that p is, "" for PopupNone.
|
||||
func (p AccessPopup) String() string {
|
||||
switch p {
|
||||
case PopupMenu:
|
||||
return "menu"
|
||||
case PopupListBox:
|
||||
return "listbox"
|
||||
case PopupTree:
|
||||
return "tree"
|
||||
case PopupGrid:
|
||||
return "grid"
|
||||
case PopupDialog:
|
||||
return "dialog"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// AccessCurrent is the item an element is the current one of among those
|
||||
// around it, as ARIA's aria-current says.
|
||||
type AccessCurrent uint8
|
||||
|
||||
const (
|
||||
// CurrentNone is not current.
|
||||
CurrentNone AccessCurrent = iota
|
||||
// CurrentItem is the current item of a set, aria-current="true".
|
||||
CurrentItem
|
||||
// CurrentPage is the page the user is on, as the last crumb of a
|
||||
// breadcrumb trail or the link of a navigation bar to it.
|
||||
CurrentPage
|
||||
// CurrentStep is the step of a process the user is at.
|
||||
CurrentStep
|
||||
// CurrentLocation is the place shown, as in a flow chart.
|
||||
CurrentLocation
|
||||
// CurrentDate is today in a calendar, and CurrentTime now in a
|
||||
// timetable.
|
||||
CurrentDate
|
||||
CurrentTime
|
||||
)
|
||||
|
||||
// String returns the value of aria-current that c is, "" for CurrentNone.
|
||||
func (c AccessCurrent) String() string {
|
||||
switch c {
|
||||
case CurrentItem:
|
||||
return "true"
|
||||
case CurrentPage:
|
||||
return "page"
|
||||
case CurrentStep:
|
||||
return "step"
|
||||
case CurrentLocation:
|
||||
return "location"
|
||||
case CurrentDate:
|
||||
return "date"
|
||||
case CurrentTime:
|
||||
return "time"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// AccessAutoComplete is what the suggestions of a text field complete as
|
||||
// the user types, as ARIA's aria-autocomplete says.
|
||||
type AccessAutoComplete uint8
|
||||
|
||||
const (
|
||||
// AutoCompleteNone suggests nothing as the user types.
|
||||
AutoCompleteNone AccessAutoComplete = iota
|
||||
// AutoCompleteInline completes the text in place, the rest of the
|
||||
// value inserted after the caret and selected.
|
||||
AutoCompleteInline
|
||||
// AutoCompleteList shows a popup of the values that complete it.
|
||||
AutoCompleteList
|
||||
// AutoCompleteBoth shows the popup and completes the text in place
|
||||
// with the option the arrows are on.
|
||||
AutoCompleteBoth
|
||||
)
|
||||
|
||||
// String returns the value of aria-autocomplete that a is, "" for
|
||||
// AutoCompleteNone.
|
||||
func (a AccessAutoComplete) String() string {
|
||||
switch a {
|
||||
case AutoCompleteInline:
|
||||
return "inline"
|
||||
case AutoCompleteList:
|
||||
return "list"
|
||||
case AutoCompleteBoth:
|
||||
return "both"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// AccessActions are the actions an element of an AccessTree takes.
|
||||
type AccessActions uint8
|
||||
|
||||
const (
|
||||
ActionPress AccessActions = 1 << iota
|
||||
ActionFocus
|
||||
ActionIncrement
|
||||
ActionDecrement
|
||||
ActionSetValue
|
||||
// ActionScrollIntoView scrolls the containers around the element to
|
||||
// show it, as assistive technology moving to it out of view asks.
|
||||
ActionScrollIntoView
|
||||
// ActionExpand opens and closes an item of a tree with children
|
||||
// (AccessExpand, AccessCollapse), which pressing chooses.
|
||||
ActionExpand
|
||||
)
|
||||
|
||||
// AccessActionKind is the action of an AccessAction event.
|
||||
type AccessActionKind uint8
|
||||
|
||||
const (
|
||||
AccessPress AccessActionKind = iota
|
||||
AccessFocus
|
||||
AccessIncrement
|
||||
AccessDecrement
|
||||
AccessSetValue
|
||||
AccessScrollIntoView
|
||||
AccessExpand
|
||||
AccessCollapse
|
||||
// AccessSelectText selects runes From to To of a text field's Value.
|
||||
AccessSelectText
|
||||
// AccessInsertText replaces the selection of a text field with Text,
|
||||
// as typing it does: at the caret when nothing is selected.
|
||||
AccessInsertText
|
||||
)
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"unicode/utf16"
|
||||
)
|
||||
|
||||
// The lines of a text field's Value, for the bridges that count its text
|
||||
// in UTF-16 units, as AppKit does: a line ends after its line feed, as
|
||||
// the Windows and Linux bridges take lines (isBoundary, segment), so that
|
||||
// every unit is on a line and the text after the last line feed, empty or
|
||||
// not, is the last line.
|
||||
|
||||
// LineOfUnit returns the line of value that UTF-16 unit u is on, from 0:
|
||||
// how many line feeds come before it. A unit past the end is on the last
|
||||
// line.
|
||||
func LineOfUnit(value string, u int) int {
|
||||
line, at := 0, 0
|
||||
for _, r := range value {
|
||||
if at >= u {
|
||||
break
|
||||
}
|
||||
at += utf16.RuneLen(r)
|
||||
if r == '\n' {
|
||||
line++
|
||||
}
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
// LineUnits returns the UTF-16 units of line of value, from start, n of
|
||||
// them, its line feed included, and false for a line value does not have:
|
||||
// one below 0 or past the last.
|
||||
func LineUnits(value string, line int) (start, n int, ok bool) {
|
||||
if line < 0 {
|
||||
return 0, 0, false
|
||||
}
|
||||
cur := 0
|
||||
for _, r := range value {
|
||||
units := utf16.RuneLen(r)
|
||||
if cur < line {
|
||||
start += units
|
||||
} else {
|
||||
n += units
|
||||
}
|
||||
if r == '\n' {
|
||||
if cur == line {
|
||||
return start, n, true
|
||||
}
|
||||
cur++
|
||||
}
|
||||
}
|
||||
return start, n, cur == line
|
||||
}
|
||||
|
||||
// RangeBounds returns where UTF-16 units from u, count of them, of n's
|
||||
// Value show: the union of the boxes of the lines they are on
|
||||
// (LineBoxes), a run of lines collapsed sharing one, or the node's Bounds
|
||||
// where it gives none of them, as for lines out of view.
|
||||
func RangeBounds(n *AccessNode, u, count int) RectF {
|
||||
if len(n.LineBoxes) == 0 {
|
||||
return n.Bounds
|
||||
}
|
||||
first := LineOfUnit(n.Value, u)
|
||||
last := first
|
||||
if count > 0 {
|
||||
last = LineOfUnit(n.Value, u+count-1)
|
||||
}
|
||||
boxes := n.LineBoxes
|
||||
i := sort.Search(len(boxes), func(i int) bool { return boxes[i].Line+max(boxes[i].Count, 1)-1 >= first })
|
||||
var out RectF
|
||||
found := false
|
||||
for ; i < len(boxes) && boxes[i].Line <= last; i++ {
|
||||
b := boxes[i].Bounds
|
||||
if !found {
|
||||
out, found = b, true
|
||||
continue
|
||||
}
|
||||
x0, y0 := min(out.X, b.X), min(out.Y, b.Y)
|
||||
x1, y1 := max(out.X+out.W, b.X+b.W), max(out.Y+out.H, b.Y+b.H)
|
||||
out = RectF{X: x0, Y: y0, W: x1 - x0, H: y1 - y0}
|
||||
}
|
||||
if !found {
|
||||
return n.Bounds
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// TextSelectionChange is how the selection of a text field moved, as
|
||||
// WebKit tells VoiceOver in the userInfo of AXSelectedTextChanged
|
||||
// (AXTextStateChangeType, AXTextSelectionDirection and
|
||||
// AXTextSelectionGranularity), which it reads out by: the new line for a
|
||||
// move by line, the character passed for a move by character.
|
||||
type TextSelectionChange struct {
|
||||
Type, Direction, Granularity int
|
||||
}
|
||||
|
||||
// The values of WebKit's AXTextStateChangeType, AXTextSelectionDirection
|
||||
// and AXTextSelectionGranularity.
|
||||
const (
|
||||
TextChangeMove = 2 // AXTextStateChangeTypeSelectionMove
|
||||
TextChangeExtend = 3 // AXTextStateChangeTypeSelectionExtend
|
||||
|
||||
TextDirectionUnknown = 0
|
||||
TextDirectionBeginning = 1
|
||||
TextDirectionEnd = 2
|
||||
TextDirectionPrevious = 3
|
||||
TextDirectionNext = 4
|
||||
TextDirectionDiscontiguous = 5
|
||||
|
||||
TextGranularityUnknown = 0
|
||||
TextGranularityCharacter = 1
|
||||
TextGranularityWord = 2
|
||||
TextGranularityLine = 3
|
||||
TextGranularityDocument = 7
|
||||
)
|
||||
|
||||
// SelectionChange returns how the selection of value moved from the runes
|
||||
// oldStart to oldEnd to those from start to end, as the keys move it: by
|
||||
// a character, a word or a line, to the beginning or the end of a line or
|
||||
// of the text, or elsewhere (discontiguous), judged from where its moving
|
||||
// end went. A selection that holds runes extends, an empty one moves.
|
||||
func SelectionChange(value string, oldStart, oldEnd, start, end int) TextSelectionChange {
|
||||
c := TextSelectionChange{Type: TextChangeMove}
|
||||
if end > start {
|
||||
c.Type = TextChangeExtend
|
||||
}
|
||||
// The end that moved: the caret of an empty selection, else the one
|
||||
// that is not the anchor.
|
||||
from, to := oldEnd, end
|
||||
if start != oldStart && (end == oldEnd || start == end) {
|
||||
from, to = oldStart, start
|
||||
}
|
||||
if from == to {
|
||||
c.Direction = TextDirectionDiscontiguous
|
||||
return c
|
||||
}
|
||||
// The lines of both places, and where the new one's starts and ends.
|
||||
runes := []rune(value)
|
||||
from, to = max(0, min(from, len(runes))), max(0, min(to, len(runes)))
|
||||
lines := func(rs []rune) int {
|
||||
n := 0
|
||||
for _, r := range rs {
|
||||
if r == '\n' {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
lineFrom, lineTo := lines(runes[:from]), lines(runes[:to])
|
||||
startTo, endTo := to, to
|
||||
for startTo > 0 && runes[startTo-1] != '\n' {
|
||||
startTo--
|
||||
}
|
||||
for endTo < len(runes) && runes[endTo] != '\n' {
|
||||
endTo++
|
||||
}
|
||||
next := to > from
|
||||
dir := func(forward bool) int {
|
||||
if forward {
|
||||
return TextDirectionNext
|
||||
}
|
||||
return TextDirectionPrevious
|
||||
}
|
||||
switch d := lineTo - lineFrom; {
|
||||
case d == 1 || d == -1:
|
||||
c.Direction, c.Granularity = dir(next), TextGranularityLine
|
||||
case d != 0 && to == 0:
|
||||
c.Direction, c.Granularity = TextDirectionBeginning, TextGranularityDocument
|
||||
case d != 0 && to == len(runes):
|
||||
c.Direction, c.Granularity = TextDirectionEnd, TextGranularityDocument
|
||||
case d != 0:
|
||||
c.Direction = TextDirectionDiscontiguous
|
||||
case to-from == 1 || from-to == 1:
|
||||
c.Direction, c.Granularity = dir(next), TextGranularityCharacter
|
||||
case to == startTo:
|
||||
c.Direction, c.Granularity = TextDirectionBeginning, TextGranularityLine
|
||||
case to == endTo:
|
||||
c.Direction, c.Granularity = TextDirectionEnd, TextGranularityLine
|
||||
default:
|
||||
c.Direction, c.Granularity = dir(next), TextGranularityWord
|
||||
}
|
||||
return c
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package platform
|
||||
|
||||
import "testing"
|
||||
|
||||
// Lines end after their line feeds, in UTF-16 units: a character outside
|
||||
// the Basic Multilingual Plane takes two.
|
||||
func TestAccessLines(t *testing.T) {
|
||||
const value = "ab\n😀c\n\nlast" // lines at units 0, 3, 7 and 8
|
||||
for _, c := range []struct{ u, line int }{
|
||||
{0, 0}, {2, 0}, {3, 1}, {4, 1}, {6, 1}, {7, 2}, {8, 3}, {11, 3}, {12, 3}, {99, 3},
|
||||
} {
|
||||
if got := LineOfUnit(value, c.u); got != c.line {
|
||||
t.Errorf("LineOfUnit(%d) = %d, want %d", c.u, got, c.line)
|
||||
}
|
||||
}
|
||||
for _, c := range []struct {
|
||||
line, start, n int
|
||||
ok bool
|
||||
}{
|
||||
{0, 0, 3, true}, {1, 3, 4, true}, {2, 7, 1, true}, {3, 8, 4, true}, {4, 0, 0, false}, {-1, 0, 0, false},
|
||||
} {
|
||||
start, n, ok := LineUnits(value, c.line)
|
||||
if ok != c.ok || ok && (start != c.start || n != c.n) {
|
||||
t.Errorf("LineUnits(%d) = %d, %d, %v, want %d, %d, %v", c.line, start, n, ok, c.start, c.n, c.ok)
|
||||
}
|
||||
}
|
||||
// Every unit is on the line whose range holds it.
|
||||
for u := range 12 {
|
||||
start, n, _ := LineUnits(value, LineOfUnit(value, u))
|
||||
if u < start || u >= start+n {
|
||||
t.Errorf("unit %d is outside its line's %d+%d", u, start, n)
|
||||
}
|
||||
}
|
||||
// A text ending with a line feed has an empty last line, and an
|
||||
// empty text one line.
|
||||
if start, n, ok := LineUnits("a\n", 1); !ok || start != 2 || n != 0 {
|
||||
t.Errorf("the line after a final line feed is %d+%d, %v", start, n, ok)
|
||||
}
|
||||
if start, n, ok := LineUnits("", 0); !ok || start != 0 || n != 0 {
|
||||
t.Errorf("an empty text's line is %d+%d, %v", start, n, ok)
|
||||
}
|
||||
if LineOfUnit("a\n", 2) != 1 {
|
||||
t.Error("the end of a text ending with a line feed is not on its last line")
|
||||
}
|
||||
}
|
||||
|
||||
// A range is where the boxes of its lines are, and the node's bounds where
|
||||
// no line of it shows.
|
||||
func TestAccessRangeBounds(t *testing.T) {
|
||||
n := AccessNode{
|
||||
Value: "a\nb\nc\nd",
|
||||
Bounds: RectF{0, 0, 100, 400},
|
||||
LineBoxes: []AccessLineBox{
|
||||
{Line: 1, Bounds: RectF{10, 20, 80, 20}},
|
||||
{Line: 2, Bounds: RectF{10, 40, 80, 40}}, // wrapped in two rows
|
||||
},
|
||||
}
|
||||
for _, c := range []struct {
|
||||
u, n int
|
||||
want RectF
|
||||
}{
|
||||
{2, 1, RectF{10, 20, 80, 20}}, // b
|
||||
{2, 2, RectF{10, 20, 80, 20}}, // b and its line feed
|
||||
{2, 3, RectF{10, 20, 80, 60}}, // into c
|
||||
{4, 0, RectF{10, 40, 80, 40}}, // the caret before c
|
||||
{0, 3, RectF{10, 20, 80, 20}}, // a, out of view, and b
|
||||
{0, 1, n.Bounds}, // a alone
|
||||
{6, 1, n.Bounds}, // d
|
||||
} {
|
||||
if got := RangeBounds(&n, c.u, c.n); got != c.want {
|
||||
t.Errorf("RangeBounds(%d, %d) = %v, want %v", c.u, c.n, got, c.want)
|
||||
}
|
||||
}
|
||||
none := AccessNode{Value: "a\nb", Bounds: RectF{1, 2, 3, 4}}
|
||||
if got := RangeBounds(&none, 2, 1); got != none.Bounds {
|
||||
t.Errorf("a field without line boxes gives %v for a range, want its bounds", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A run of lines collapsed under one box is found by any of its lines.
|
||||
func TestAccessRangeBoundsCollapsed(t *testing.T) {
|
||||
n := AccessNode{
|
||||
Value: "a\nb\nc\nd\ne",
|
||||
Bounds: RectF{0, 0, 100, 400},
|
||||
LineBoxes: []AccessLineBox{
|
||||
{Line: 0, Bounds: RectF{10, 0, 80, 20}},
|
||||
{Line: 1, Count: 3, Bounds: RectF{0, 20, 100, 32}}, // b to d, under a separator
|
||||
{Line: 4, Bounds: RectF{10, 52, 80, 20}},
|
||||
},
|
||||
}
|
||||
for _, c := range []struct {
|
||||
u, n int
|
||||
want RectF
|
||||
}{
|
||||
{2, 1, RectF{0, 20, 100, 32}}, // b
|
||||
{6, 1, RectF{0, 20, 100, 32}}, // d
|
||||
{8, 1, RectF{10, 52, 80, 20}}, // e
|
||||
{0, 3, RectF{0, 0, 100, 52}}, // a and b
|
||||
} {
|
||||
if got := RangeBounds(&n, c.u, c.n); got != c.want {
|
||||
t.Errorf("RangeBounds(%d, %d) = %v, want %v", c.u, c.n, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A selection moving as the keys move it says how, as VoiceOver reads it:
|
||||
// a line for Up and Down, a character for Left and Right.
|
||||
func TestSelectionChange(t *testing.T) {
|
||||
const value = "one two\nthree\nfour\nfive" // lines at 0, 8, 14 and 19
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
oldStart, oldEnd int
|
||||
start, end int
|
||||
typ, dir, granularity int
|
||||
}{
|
||||
{"down", 2, 2, 10, 10, TextChangeMove, TextDirectionNext, TextGranularityLine},
|
||||
{"up", 10, 10, 2, 2, TextChangeMove, TextDirectionPrevious, TextGranularityLine},
|
||||
{"down to an empty end", 15, 15, 19, 19, TextChangeMove, TextDirectionNext, TextGranularityLine},
|
||||
{"right", 2, 2, 3, 3, TextChangeMove, TextDirectionNext, TextGranularityCharacter},
|
||||
{"left over a line feed", 8, 8, 7, 7, TextChangeMove, TextDirectionPrevious, TextGranularityLine},
|
||||
{"a word", 0, 0, 3, 3, TextChangeMove, TextDirectionNext, TextGranularityWord},
|
||||
{"home", 12, 12, 8, 8, TextChangeMove, TextDirectionBeginning, TextGranularityLine},
|
||||
{"end", 9, 9, 13, 13, TextChangeMove, TextDirectionEnd, TextGranularityLine},
|
||||
{"the beginning", 16, 16, 0, 0, TextChangeMove, TextDirectionBeginning, TextGranularityDocument},
|
||||
{"the end", 2, 2, 23, 23, TextChangeMove, TextDirectionEnd, TextGranularityDocument},
|
||||
{"a click", 2, 2, 16, 16, TextChangeMove, TextDirectionDiscontiguous, TextGranularityUnknown},
|
||||
{"shift down", 2, 2, 2, 10, TextChangeExtend, TextDirectionNext, TextGranularityLine},
|
||||
{"shift left", 5, 5, 4, 5, TextChangeExtend, TextDirectionPrevious, TextGranularityCharacter},
|
||||
{"shift right, back", 4, 5, 5, 5, TextChangeMove, TextDirectionNext, TextGranularityCharacter},
|
||||
} {
|
||||
got := SelectionChange(value, c.oldStart, c.oldEnd, c.start, c.end)
|
||||
if want := (TextSelectionChange{c.typ, c.dir, c.granularity}); got != want {
|
||||
t.Errorf("%s: %+v, want %+v", c.name, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package platform
|
||||
|
||||
import "strings"
|
||||
|
||||
// AuthRequest is an HTTP authentication challenge of a page, or of what
|
||||
// it loads (WindowHandler.AuthRequested).
|
||||
type AuthRequest struct {
|
||||
// Host and Port of the server asking, or of the proxy.
|
||||
Host string
|
||||
Port int
|
||||
// Realm is the protection space the server named, "" for none.
|
||||
Realm string
|
||||
// Scheme is the authentication scheme, lowercase: "basic", "digest",
|
||||
// "ntlm" or "negotiate".
|
||||
Scheme string
|
||||
IsProxy bool
|
||||
}
|
||||
|
||||
// AuthResponse answers an AuthRequest. Default leaves the challenge to
|
||||
// the web view, as if nobody had been asked; otherwise the request goes on
|
||||
// with Username and Password, or, when both are empty, without
|
||||
// credentials: the page gets the server's refusal (401 or 407).
|
||||
type AuthResponse struct {
|
||||
Default bool
|
||||
Username, Password string
|
||||
}
|
||||
|
||||
// ClientCertificate is one of the certificates a platform can offer a
|
||||
// server that asks for one (ClientCertificateRequest.Certificates).
|
||||
type ClientCertificate struct {
|
||||
// DER is the certificate, DER-encoded; x509.ParseCertificate reads
|
||||
// it. It is nil where the platform names its certificates without
|
||||
// their bytes.
|
||||
DER []byte
|
||||
// Subject and Issuer name it as the platform does, and ValidFrom and
|
||||
// ValidTo are the unix seconds it is valid from and to.
|
||||
Subject, Issuer string
|
||||
ValidFrom, ValidTo int64
|
||||
// Native is the platform's own certificate, which a backend fills in
|
||||
// and an answer carries back: an ICoreWebView2ClientCertificate on
|
||||
// Windows, a SecIdentityRef on macOS. Zero where the platform offers
|
||||
// none.
|
||||
Native uintptr
|
||||
}
|
||||
|
||||
// ClientCertificateRequest is a server, or a proxy, asking for the
|
||||
// certificate of a TLS connection of the page, or of what it loads
|
||||
// (WindowHandler.ClientCertificateRequested).
|
||||
type ClientCertificateRequest struct {
|
||||
// Host and Port of the server asking, or of the proxy.
|
||||
Host string
|
||||
Port int
|
||||
IsProxy bool
|
||||
// Certificates are those the platform can offer, which an answer may
|
||||
// return. Linux lists none: WebKitGTK has no way to, and an answer
|
||||
// can only take the default or cancel there.
|
||||
Certificates []ClientCertificate
|
||||
}
|
||||
|
||||
// ClientCertificateResponse answers a ClientCertificateRequest. Default
|
||||
// leaves the challenge to the platform, the choice of the web view. An
|
||||
// answer with no certificate and not Default refuses the challenge where
|
||||
// the platform can: the load fails, as a user dismissing a browser's
|
||||
// prompt does.
|
||||
type ClientCertificateResponse struct {
|
||||
Default bool
|
||||
Cancel bool
|
||||
Certificate *ClientCertificate
|
||||
}
|
||||
|
||||
// CertificateError is a server certificate that does not verify
|
||||
// (WindowHandler.CertificateError).
|
||||
type CertificateError struct {
|
||||
// URL is what was loading; Host the server's host in it.
|
||||
URL, Host string
|
||||
// Error tells what is wrong, in the platform's words.
|
||||
Error string
|
||||
// Certificate is the server's certificate, DER-encoded.
|
||||
Certificate []byte
|
||||
}
|
||||
|
||||
// ParseAuthChallenge returns the scheme, lowercase, and the realm of an
|
||||
// HTTP authentication challenge, as a WWW-Authenticate header gives it:
|
||||
// `Basic realm="intranet", charset="UTF-8"` is "basic" and "intranet".
|
||||
func ParseAuthChallenge(challenge string) (scheme, realm string) {
|
||||
s := strings.TrimSpace(challenge)
|
||||
end := strings.IndexAny(s, " \t,")
|
||||
if end < 0 {
|
||||
return strings.ToLower(s), ""
|
||||
}
|
||||
scheme, s = strings.ToLower(s[:end]), s[end:]
|
||||
for s != "" {
|
||||
s = strings.TrimLeft(s, " \t,")
|
||||
eq := strings.IndexByte(s, '=')
|
||||
if eq < 0 {
|
||||
break
|
||||
}
|
||||
name := strings.TrimSpace(s[:eq])
|
||||
s = strings.TrimLeft(s[eq+1:], " \t")
|
||||
var value string
|
||||
if strings.HasPrefix(s, `"`) {
|
||||
// A quoted string, with backslash escapes.
|
||||
var b strings.Builder
|
||||
i := 1
|
||||
for ; i < len(s) && s[i] != '"'; i++ {
|
||||
if s[i] == '\\' && i+1 < len(s) {
|
||||
i++
|
||||
}
|
||||
b.WriteByte(s[i])
|
||||
}
|
||||
value, s = b.String(), s[min(i+1, len(s)):]
|
||||
} else {
|
||||
end := strings.IndexAny(s, ", \t")
|
||||
if end < 0 {
|
||||
end = len(s)
|
||||
}
|
||||
value, s = s[:end], s[end:]
|
||||
}
|
||||
if strings.EqualFold(name, "realm") {
|
||||
return scheme, value
|
||||
}
|
||||
}
|
||||
return scheme, ""
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package platform
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestParseAuthChallenge(t *testing.T) {
|
||||
for _, c := range []struct{ challenge, scheme, realm string }{
|
||||
{`Basic realm="intranet"`, "basic", "intranet"},
|
||||
{`Basic realm="Access to the staging site", charset="UTF-8"`, "basic", "Access to the staging site"},
|
||||
{`basic charset="UTF-8", REALM="later"`, "basic", "later"},
|
||||
{`Digest realm="http-auth@example.org", qop="auth, auth-int", algorithm=SHA-256, nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v"`, "digest", "http-auth@example.org"},
|
||||
{`Digest qop="auth", realm=bare, nonce="x"`, "digest", "bare"},
|
||||
{`Basic realm="say \"hi\" \\ bye"`, "basic", `say "hi" \ bye`},
|
||||
{`Basic realm="unterminated`, "basic", "unterminated"},
|
||||
{`NTLM`, "ntlm", ""},
|
||||
{`Negotiate YIIBhwYGKwYBBQUC`, "negotiate", ""},
|
||||
{` Basic `, "basic", ""},
|
||||
{``, "", ""},
|
||||
} {
|
||||
scheme, realm := ParseAuthChallenge(c.challenge)
|
||||
if scheme != c.scheme || realm != c.realm {
|
||||
t.Errorf("ParseAuthChallenge(%q) = %q, %q; want %q, %q", c.challenge, scheme, realm, c.scheme, c.realm)
|
||||
}
|
||||
}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
"unicode/utf16"
|
||||
)
|
||||
|
||||
// CertificateIssuer reads the issuer's name and the validity of a
|
||||
// DER-encoded certificate, for a backend whose platform does not name
|
||||
// them: the issuer's common name (its organization when it has none),
|
||||
// and the unix seconds it is valid from and to. ok is false when der is
|
||||
// not a certificate.
|
||||
//
|
||||
// It walks the few fields it needs instead of using crypto/x509, which
|
||||
// would grow every app, whether it handles client certificates or not.
|
||||
func CertificateIssuer(der []byte) (issuer string, from, to int64, ok bool) {
|
||||
cert, ok := derField(der, 0x30)
|
||||
if !ok {
|
||||
return "", 0, 0, false
|
||||
}
|
||||
tbs, ok := derField(cert, 0x30)
|
||||
if !ok {
|
||||
return "", 0, 0, false
|
||||
}
|
||||
if len(tbs) > 0 && tbs[0] == 0xa0 { // [0] version, absent in v1
|
||||
if _, tbs, ok = derNext(tbs); !ok {
|
||||
return "", 0, 0, false
|
||||
}
|
||||
}
|
||||
// The serial number, the signature's algorithm, the issuer and the
|
||||
// validity, in that order.
|
||||
var fields [4][]byte
|
||||
for i, tag := range []byte{0x02, 0x30, 0x30, 0x30} {
|
||||
var t byte
|
||||
if t, fields[i], tbs, ok = derRead(tbs); !ok || t != tag {
|
||||
return "", 0, 0, false
|
||||
}
|
||||
}
|
||||
name, validity := fields[2], fields[3]
|
||||
if from, ok = derTime(&validity); !ok {
|
||||
return "", 0, 0, false
|
||||
}
|
||||
if to, ok = derTime(&validity); !ok {
|
||||
return "", 0, 0, false
|
||||
}
|
||||
return nameIssuer(name), from, to, true
|
||||
}
|
||||
|
||||
// nameIssuer returns the common name of an X.501 name's content, or its
|
||||
// organization when it has none.
|
||||
func nameIssuer(name []byte) string {
|
||||
var cn, org string
|
||||
for len(name) > 0 {
|
||||
t, set, rest, ok := derRead(name)
|
||||
if !ok || t != 0x31 {
|
||||
break
|
||||
}
|
||||
name = rest
|
||||
for len(set) > 0 {
|
||||
t, atv, rest, ok := derRead(set)
|
||||
if !ok || t != 0x30 {
|
||||
break
|
||||
}
|
||||
set = rest
|
||||
t, oid, value, ok := derRead(atv)
|
||||
if !ok || t != 0x06 || len(oid) != 3 || oid[0] != 0x55 || oid[1] != 0x04 {
|
||||
continue
|
||||
}
|
||||
s, ok := derString(value)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
switch oid[2] {
|
||||
case 0x03: // 2.5.4.3, commonName
|
||||
if cn == "" {
|
||||
cn = s
|
||||
}
|
||||
case 0x0a: // 2.5.4.10, organizationName
|
||||
if org == "" {
|
||||
org = s
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if cn != "" {
|
||||
return cn
|
||||
}
|
||||
return org
|
||||
}
|
||||
|
||||
// derString reads a directory string, the value of a name's attribute.
|
||||
func derString(b []byte) (string, bool) {
|
||||
t, content, _, ok := derRead(b)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
switch t {
|
||||
case 0x0c, 0x13, 0x14, 0x16: // UTF8String, PrintableString, T61String, IA5String
|
||||
return string(content), true
|
||||
case 0x1e: // BMPString, UTF-16BE
|
||||
if len(content)%2 != 0 {
|
||||
return "", false
|
||||
}
|
||||
u := make([]uint16, len(content)/2)
|
||||
for i := range u {
|
||||
u[i] = uint16(content[2*i])<<8 | uint16(content[2*i+1])
|
||||
}
|
||||
return string(utf16.Decode(u)), true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// derTime reads the UTCTime or GeneralizedTime at the start of *b, in
|
||||
// unix seconds, and moves *b past it.
|
||||
func derTime(b *[]byte) (int64, bool) {
|
||||
t, content, rest, ok := derRead(*b)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
*b = rest
|
||||
s := string(content)
|
||||
switch t {
|
||||
case 0x17: // UTCTime, YYMMDDHHMMSSZ: years from 50 are the 1900s
|
||||
if len(s) < 2 {
|
||||
return 0, false
|
||||
}
|
||||
yy, err := strconv.Atoi(s[:2])
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
if yy >= 50 {
|
||||
s = "19" + s
|
||||
} else {
|
||||
s = "20" + s
|
||||
}
|
||||
case 0x18: // GeneralizedTime, YYYYMMDDHHMMSSZ
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
v, err := time.Parse("20060102150405Z0700", s)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
return v.Unix(), true
|
||||
}
|
||||
|
||||
// derField returns the content of the element at the start of b, which
|
||||
// must have the tag.
|
||||
func derField(b []byte, tag byte) ([]byte, bool) {
|
||||
t, content, _, ok := derRead(b)
|
||||
return content, ok && t == tag
|
||||
}
|
||||
|
||||
// derNext skips the element at the start of b.
|
||||
func derNext(b []byte) (byte, []byte, bool) {
|
||||
t, _, rest, ok := derRead(b)
|
||||
return t, rest, ok
|
||||
}
|
||||
|
||||
// derRead splits the DER element at the start of b into its tag, its
|
||||
// content and what follows it.
|
||||
func derRead(b []byte) (tag byte, content, rest []byte, ok bool) {
|
||||
if len(b) < 2 || b[0]&0x1f == 0x1f { // no high tag numbers in a certificate's fields
|
||||
return 0, nil, nil, false
|
||||
}
|
||||
tag, n, b := b[0], int(b[1]), b[2:]
|
||||
if n&0x80 != 0 {
|
||||
size := n & 0x7f
|
||||
if size == 0 || size > 4 || len(b) < size {
|
||||
return 0, nil, nil, false
|
||||
}
|
||||
n = 0
|
||||
for _, c := range b[:size] {
|
||||
n = n<<8 | int(c)
|
||||
}
|
||||
b = b[size:]
|
||||
}
|
||||
if n < 0 || n > len(b) {
|
||||
return 0, nil, nil, false
|
||||
}
|
||||
return tag, b[:n], b[n:], true
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"math/big"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCertificateIssuer(t *testing.T) {
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
issuer pkix.Name
|
||||
from, to time.Time
|
||||
want string
|
||||
}{
|
||||
{"common name", pkix.Name{CommonName: "mygo test client CA", Organization: []string{"MyGo"}}, time.Date(2026, 11, 10, 8, 0, 0, 0, time.UTC), time.Date(2027, 11, 10, 8, 0, 0, 0, time.UTC), "mygo test client CA"},
|
||||
{"organization", pkix.Name{Organization: []string{"MyGo"}, Country: []string{"US"}}, time.Date(1999, 1, 2, 3, 4, 5, 0, time.UTC), time.Date(2049, 12, 31, 23, 59, 59, 0, time.UTC), "MyGo"},
|
||||
// Years from 2050 are GeneralizedTime.
|
||||
{"generalized time", pkix.Name{CommonName: "长期 CA"}, time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), time.Date(2100, 1, 1, 0, 0, 0, 0, time.UTC), "长期 CA"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1234567),
|
||||
Subject: pkix.Name{CommonName: "mygo test client"},
|
||||
Issuer: tc.issuer,
|
||||
NotBefore: tc.from,
|
||||
NotAfter: tc.to,
|
||||
}
|
||||
parent := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: tc.issuer, NotBefore: tc.from, NotAfter: tc.to}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, parent, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
issuer, from, to, ok := CertificateIssuer(der)
|
||||
if !ok || issuer != tc.want || from != tc.from.Unix() || to != tc.to.Unix() {
|
||||
t.Errorf("CertificateIssuer = %q, %d, %d, %v; want %q, %d, %d, true", issuer, from, to, ok, tc.want, tc.from.Unix(), tc.to.Unix())
|
||||
}
|
||||
for n := range der {
|
||||
if _, _, _, ok := CertificateIssuer(der[:n]); ok {
|
||||
t.Fatalf("CertificateIssuer of %d of %d bytes is ok", n, len(der))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
if _, _, _, ok := CertificateIssuer(nil); ok {
|
||||
t.Error("CertificateIssuer(nil) is ok")
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"math"
|
||||
"time"
|
||||
)
|
||||
|
||||
// DoubleClick is how far apart in time and on each axis two presses make
|
||||
// a double click.
|
||||
type DoubleClick struct {
|
||||
Time time.Duration
|
||||
DX, DY float64
|
||||
}
|
||||
|
||||
// DefaultDoubleClick is the double click where the system tells none.
|
||||
var DefaultDoubleClick = DoubleClick{Time: 500 * time.Millisecond, DX: 5, DY: 5}
|
||||
|
||||
// ClickCounter counts quick successive presses for a backend whose system
|
||||
// reports no count with a press, by the system's double-click time and
|
||||
// distance where it has them.
|
||||
type ClickCounter struct {
|
||||
ms uint32
|
||||
x, y float64
|
||||
button int
|
||||
count int
|
||||
}
|
||||
|
||||
// Press counts a press of button at x, y at ms, the event's time in
|
||||
// milliseconds, which may wrap around as the system's does: one more than
|
||||
// the last press's count when that press was of the same button and
|
||||
// within d of it; else 1. The event's time rather than now's keeps presses
|
||||
// waiting for a busy main thread as far apart as they were made.
|
||||
func (c *ClickCounter) Press(button int, x, y float64, ms uint32, d DoubleClick) int {
|
||||
if c.count > 0 && button == c.button && ms-c.ms <= uint32(d.Time.Milliseconds()) && math.Abs(x-c.x) <= d.DX && math.Abs(y-c.y) <= d.DY {
|
||||
c.count++
|
||||
} else {
|
||||
c.count = 1
|
||||
}
|
||||
c.ms, c.x, c.y, c.button = ms, x, y, button
|
||||
return c.count
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestClickCounter(t *testing.T) {
|
||||
var c ClickCounter
|
||||
ms := uint32(math.MaxUint32 - 200) // the system's time wraps around between presses
|
||||
for i, step := range []struct {
|
||||
button int
|
||||
x, y float64
|
||||
after uint32
|
||||
want int
|
||||
}{
|
||||
{0, 10, 10, 0, 1},
|
||||
{0, 12, 13, 500, 2}, // at the edges of time and distance, past the wrap
|
||||
{0, 12, 13, 100, 3},
|
||||
{0, 12, 13, 501, 1}, // too late
|
||||
{0, 14.5, 13, 100, 1}, // too far across
|
||||
{0, 14.5, 17, 100, 1}, // too far down
|
||||
{1, 14.5, 17, 100, 1}, // another button
|
||||
{1, 14.5, 17, 100, 2},
|
||||
} {
|
||||
ms += step.after
|
||||
if got := c.Press(step.button, step.x, step.y, ms, DoubleClick{Time: 500 * time.Millisecond, DX: 2, DY: 3}); got != step.want {
|
||||
t.Fatalf("press %d: count %d, want %d", i, got, step.want)
|
||||
}
|
||||
}
|
||||
// A press timed before the last, as from another clock, starts over.
|
||||
if got := c.Press(1, 14.5, 17, ms-10, DoubleClick{Time: 500 * time.Millisecond, DX: 2, DY: 3}); got != 1 {
|
||||
t.Fatalf("a press before the last: count %d, want 1", got)
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package platform
|
||||
|
||||
import "errors"
|
||||
|
||||
// ErrClipboardChanged prevents a read from mixing representations from
|
||||
// different native clipboard owners while a toolkit pumps its event loop.
|
||||
var ErrClipboardChanged = errors.New("mygo: clipboard contents changed while reading")
|
||||
|
||||
// ErrClipboardPersistence means the desktop has no storage for clipboard
|
||||
// data after the owner exits (for example, X11 without a clipboard manager).
|
||||
var ErrClipboardPersistence = errors.New("mygo: desktop cannot persist clipboard contents")
|
||||
@@ -0,0 +1,34 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// contentRulesHash is the length of the hash ContentRulesIdentifier puts
|
||||
// after the id, in hexadecimal digits.
|
||||
const contentRulesHash = 16
|
||||
|
||||
// ContentRulesIdentifier names the list compiled from rules for id: the id
|
||||
// and a hash of the rules, so that a later launch with the same rules
|
||||
// loads what it compiled before, and changed rules compile again.
|
||||
func ContentRulesIdentifier(id, rules string) string {
|
||||
sum := sha256.Sum256([]byte(rules))
|
||||
return id + "-" + hex.EncodeToString(sum[:])[:contentRulesHash]
|
||||
}
|
||||
|
||||
// StaleContentRules reports whether identifier names a list compiled for
|
||||
// id from other rules than current, which is ContentRulesIdentifier's.
|
||||
func StaleContentRules(id, current, identifier string) bool {
|
||||
hash, ok := strings.CutPrefix(identifier, id+"-")
|
||||
if !ok || identifier == current || len(hash) != contentRulesHash {
|
||||
return false
|
||||
}
|
||||
for _, c := range []byte(hash) {
|
||||
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package platform
|
||||
|
||||
// ContextMenu is a page's context menu about to open
|
||||
// (WindowHandler.ContextMenu): what was clicked, as far as the backend
|
||||
// tells, and the web view's own items.
|
||||
type ContextMenu struct {
|
||||
// Pointer is set for a menu the pointer opened, at X, Y in DIPs from
|
||||
// the top-left corner of the web view; a menu the keyboard opened has
|
||||
// none.
|
||||
Pointer bool
|
||||
X, Y float64
|
||||
// Target is what the backend tells of what was clicked. The core takes
|
||||
// what it leaves empty from the page's own contextmenu event, which
|
||||
// the bridge records just before, unless Complete says it told all:
|
||||
// the event of another frame than the page's own never reaches it.
|
||||
Target ContextMenuTarget
|
||||
Complete bool
|
||||
// Items are the web view's items, each with its Native number.
|
||||
Items []*MenuItem
|
||||
}
|
||||
|
||||
// ContextMenuTarget is what a context menu was opened on.
|
||||
type ContextMenuTarget struct {
|
||||
// LinkURL and LinkText are those of the link clicked; ImageURL of
|
||||
// the image, MediaURL of the video or audio.
|
||||
LinkURL, LinkText string
|
||||
ImageURL string
|
||||
MediaURL string
|
||||
// SelectionText is the text selected where the menu opened.
|
||||
SelectionText string
|
||||
// Editable is set over a text field or editable content.
|
||||
Editable bool
|
||||
// FrameURL is the URL of the frame clicked, when it is not the
|
||||
// page's own document but a frame in it.
|
||||
FrameURL string
|
||||
}
|
||||
|
||||
// ContextMenuResponse answers a ContextMenu. Default shows the web view's
|
||||
// menu as it is, as if nobody had been asked; otherwise Menu is the menu
|
||||
// to show, of the web view's items (by Native, each once) and the app's,
|
||||
// or nil to show none.
|
||||
type ContextMenuResponse struct {
|
||||
Default bool
|
||||
Menu *Menu
|
||||
}
|
||||
|
||||
// TidySeparators drops the separators of a menu shown that would start or
|
||||
// end it, or follow another, as the items removed between them leave:
|
||||
// Remove(ContextMenuBack, ContextMenuForward, ContextMenuReload) leaves the
|
||||
// one after them first.
|
||||
func (m *Menu) TidySeparators() {
|
||||
kept := m.Items[:0]
|
||||
afterItem := false // a visible item other than a separator came last
|
||||
for _, it := range m.Items {
|
||||
if it.Submenu != nil {
|
||||
it.Submenu.TidySeparators()
|
||||
}
|
||||
if it.Visible {
|
||||
sep := it.Type == MenuItemSeparator
|
||||
if sep && !afterItem {
|
||||
continue
|
||||
}
|
||||
afterItem = !sep
|
||||
}
|
||||
kept = append(kept, it)
|
||||
}
|
||||
if !afterItem { // a separator came last
|
||||
for i := len(kept) - 1; i >= 0; i-- {
|
||||
if kept[i].Visible {
|
||||
kept = append(kept[:i], kept[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
m.Items = kept
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Cookie is a normalized snapshot of a cookie in a page store.
|
||||
// SameSite is lax, strict, none, or empty (unknown on output only).
|
||||
// A zero Expires denotes a session cookie.
|
||||
type Cookie struct {
|
||||
Name, Value, Domain, Path string
|
||||
Expires time.Time
|
||||
Secure, HTTPOnly bool
|
||||
SameSite string
|
||||
}
|
||||
|
||||
// CookieKey identifies a cookie without request URL matching.
|
||||
type CookieKey struct{ Name, Domain, Path string }
|
||||
|
||||
// CookieMatchesURL reports whether a request to u sends c, by the rules
|
||||
// of RFC 6265 section 5.4: its domain, path and Secure attribute.
|
||||
func CookieMatchesURL(c Cookie, u *url.URL) bool {
|
||||
host := strings.ToLower(u.Hostname())
|
||||
domain := strings.ToLower(c.Domain)
|
||||
if d, ok := strings.CutPrefix(domain, "."); ok {
|
||||
if host != d && (!strings.HasSuffix(host, "."+d) || net.ParseIP(host) != nil) {
|
||||
return false
|
||||
}
|
||||
} else if host != domain {
|
||||
return false
|
||||
}
|
||||
path := u.EscapedPath()
|
||||
if !strings.HasPrefix(path, "/") {
|
||||
path = "/"
|
||||
}
|
||||
p := c.Path
|
||||
if p == "" {
|
||||
p = "/"
|
||||
}
|
||||
if path != p && (!strings.HasPrefix(path, p) || !strings.HasSuffix(p, "/") && path[len(p)] != '/') {
|
||||
return false
|
||||
}
|
||||
return !c.Secure || strings.EqualFold(u.Scheme, "https")
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package platform
|
||||
|
||||
import "github.com/egoist/mygo/transfer"
|
||||
|
||||
// DragSessionFormat carries an unguessable, process-local registry key.
|
||||
// It never contains a pointer. Only the core resolves it while a drag lives.
|
||||
const DragSessionFormat transfer.Format = "application/x-mygo-drag-session"
|
||||
|
||||
// DragRequest starts a native drag on the main thread during a pointer
|
||||
// gesture. Done must be called exactly once on the main thread. Windows
|
||||
// may run a native nested event loop; other backends return immediately.
|
||||
type DragRequest struct {
|
||||
Data transfer.Data
|
||||
Operations transfer.Operation
|
||||
Session string
|
||||
X, Y float64
|
||||
Preview []byte // premultiplied BGRA, one pixel per DIP
|
||||
Width, Height, HotX, HotY int
|
||||
Done func(transfer.Result)
|
||||
}
|
||||
|
||||
// DataDragEvent is a synchronous destination query. The core resolves
|
||||
// Session to Local and the original Data only for a live local source.
|
||||
// Content sets Operation and Formats to accept. Backends read those
|
||||
// formats on drop, never while hovering, and copy the bytes into Data.
|
||||
type DataDragEvent struct {
|
||||
Offer transfer.Offer
|
||||
Session string
|
||||
Local any
|
||||
Data transfer.Data
|
||||
Operation transfer.Operation
|
||||
Formats []transfer.Format
|
||||
HasFiles bool
|
||||
Resolved bool // the core substituted its process-local data
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
package platform
|
||||
|
||||
// Flyout makes a window a flyout (WindowOptions.Flyout): a borderless
|
||||
// window owned by its parent and placed next to a rectangle of it, which
|
||||
// may extend beyond the parent but stays in the work area of a display.
|
||||
type Flyout struct {
|
||||
// Anchor is the rectangle the flyout is placed against, in DIPs
|
||||
// relative to the parent's content area.
|
||||
Anchor Rect
|
||||
// Tray anchors the flyout to a tray icon, where it shows without a
|
||||
// parent, above the windows of other apps: the icon's Bounds are the
|
||||
// anchor, on the screen. Where they are empty, it goes in the middle
|
||||
// of the primary display's work area.
|
||||
Tray Tray
|
||||
// Side is where the flyout goes from Anchor, and Align how it lines
|
||||
// up with it along that side.
|
||||
Side Side
|
||||
Align Align
|
||||
// Gap is the distance between Anchor and the flyout, in DIPs.
|
||||
Gap int
|
||||
// Focusable makes the flyout take the keyboard as it shows, and close
|
||||
// (WindowHandler.ShouldClose) when the user presses outside it or
|
||||
// another window takes the keyboard. Others never take the keyboard
|
||||
// and stay until closed.
|
||||
Focusable bool
|
||||
// Popover shows the flyout in a popover of the system, which draws its
|
||||
// background and an arrow pointing at the middle of Anchor, and places
|
||||
// it (macOS); Align and Gap do not apply. Elsewhere it is ignored.
|
||||
Popover bool
|
||||
// Radius rounds the flyout's corners, in DIPs, its content, material
|
||||
// and shadow with them (macOS).
|
||||
Radius int
|
||||
}
|
||||
|
||||
// Side is the side of the anchor a flyout goes to.
|
||||
type Side uint8
|
||||
|
||||
// Sides.
|
||||
const (
|
||||
SideBottom Side = iota
|
||||
SideTop
|
||||
SideRight
|
||||
SideLeft
|
||||
)
|
||||
|
||||
// Align lines a flyout up with its anchor along the side it goes to: its
|
||||
// left or top edges (start), centers, or right or bottom edges (end).
|
||||
type Align uint8
|
||||
|
||||
// Alignments.
|
||||
const (
|
||||
AlignStart Align = iota
|
||||
AlignCenter
|
||||
AlignEnd
|
||||
)
|
||||
|
||||
// Gravity is one of the nine points of a rectangle: its corners, the
|
||||
// middles of its edges and its center, as GdkGravity and Wayland's
|
||||
// xdg_positioner anchors and gravities name them.
|
||||
// X and Y are -1 for the left or top, 0 for the middle, 1 for the right or
|
||||
// bottom.
|
||||
type Gravity struct{ X, Y int }
|
||||
|
||||
// Gravities returns the point of the anchor the flyout is placed at, the
|
||||
// point of the flyout that goes there, and the offset between them.
|
||||
func (f *Flyout) Gravities() (anchor, window Gravity, dx, dy int) {
|
||||
cross := int(f.Align) - 1 // AlignStart, AlignCenter, AlignEnd: -1, 0, 1
|
||||
switch f.Side {
|
||||
case SideTop:
|
||||
return Gravity{cross, -1}, Gravity{cross, 1}, 0, -f.Gap
|
||||
case SideRight:
|
||||
return Gravity{1, cross}, Gravity{-1, cross}, f.Gap, 0
|
||||
case SideLeft:
|
||||
return Gravity{-1, cross}, Gravity{1, cross}, -f.Gap, 0
|
||||
default:
|
||||
return Gravity{cross, 1}, Gravity{cross, -1}, 0, f.Gap
|
||||
}
|
||||
}
|
||||
|
||||
// Place returns where a flyout of the given size goes, its anchor being at
|
||||
// anchor on the screen, in the work area of the display that work
|
||||
// returns for anchor. It resolves the placement as GTK places popups on
|
||||
// X11 (gdk_window_move_to_rect, with GDK_ANCHOR_FLIP, GDK_ANCHOR_SLIDE
|
||||
// and GDK_ANCHOR_RESIZE) and Wayland compositors do (xdg_positioner): on
|
||||
// each axis the flyout flips to the other side of the anchor, or to the
|
||||
// other end of it, where it would not fit and the flipped one would;
|
||||
// then it slides along the edge it would cross, back into the work area;
|
||||
// then it shrinks to it. flippedX and flippedY tell whether it flipped.
|
||||
func (f *Flyout) Place(anchor Rect, size Size, work Rect) (r Rect, flippedX, flippedY bool) {
|
||||
ra, wa, dx, dy := f.Gravities()
|
||||
r.Width, r.Height = size.Width, size.Height
|
||||
r.X, flippedX = flipPosition(work.X, work.Width, anchor.X, anchor.Width, r.Width, ra.X, wa.X, dx)
|
||||
r.Y, flippedY = flipPosition(work.Y, work.Height, anchor.Y, anchor.Height, r.Height, ra.Y, wa.Y, dy)
|
||||
r.X, r.Width = slideAndResize(work.X, work.Width, r.X, r.Width)
|
||||
r.Y, r.Height = slideAndResize(work.Y, work.Height, r.Y, r.Height)
|
||||
return r, flippedX, flippedY
|
||||
}
|
||||
|
||||
// flipPosition is GDK's maybe_flip_position on one axis.
|
||||
func flipPosition(boundsPos, boundsSize, rectPos, rectSize, size, rectSign, windowSign, offset int) (int, bool) {
|
||||
primary := rectPos + (1+rectSign)*rectSize/2 + offset - (1+windowSign)*size/2
|
||||
fits := func(p int) bool { return p >= boundsPos && p+size <= boundsPos+boundsSize }
|
||||
if fits(primary) {
|
||||
return primary, false
|
||||
}
|
||||
secondary := rectPos + (1-rectSign)*rectSize/2 - offset - (1-windowSign)*size/2
|
||||
if fits(secondary) {
|
||||
return secondary, true
|
||||
}
|
||||
return primary, false
|
||||
}
|
||||
|
||||
// slideAndResize moves a span back into bounds, its start first when it
|
||||
// is longer, then cuts what still sticks out.
|
||||
func slideAndResize(boundsPos, boundsSize, pos, size int) (int, int) {
|
||||
if pos+size > boundsPos+boundsSize {
|
||||
pos = boundsPos + boundsSize - size
|
||||
}
|
||||
if pos < boundsPos {
|
||||
pos = boundsPos
|
||||
}
|
||||
if pos+size > boundsPos+boundsSize {
|
||||
size = boundsPos + boundsSize - pos
|
||||
}
|
||||
return pos, max(size, 1)
|
||||
}
|
||||
|
||||
// WorkAreaFor returns the work area of the display a flyout anchored at r
|
||||
// goes to, as GDK picks it: the one whose work area overlaps r the most,
|
||||
// else the one nearest to r's center.
|
||||
func WorkAreaFor(r Rect, displays []Display) Rect {
|
||||
best, bestArea := -1, 0
|
||||
for i, d := range displays {
|
||||
if a := overlap(d.WorkArea, r); a > bestArea {
|
||||
best, bestArea = i, a
|
||||
}
|
||||
}
|
||||
if best < 0 {
|
||||
cx, cy := r.X+r.Width/2, r.Y+r.Height/2
|
||||
bestDist := -1
|
||||
for i, d := range displays {
|
||||
b := d.Bounds
|
||||
dx := max(b.X-cx, 0, cx-(b.X+b.Width-1))
|
||||
dy := max(b.Y-cy, 0, cy-(b.Y+b.Height-1))
|
||||
if dist := dx*dx + dy*dy; bestDist < 0 || dist < bestDist {
|
||||
best, bestDist = i, dist
|
||||
}
|
||||
}
|
||||
}
|
||||
if best < 0 {
|
||||
return Rect{}
|
||||
}
|
||||
return displays[best].WorkArea
|
||||
}
|
||||
|
||||
func overlap(a, b Rect) int {
|
||||
w := min(a.X+a.Width, b.X+b.Width) - max(a.X, b.X)
|
||||
h := min(a.Y+a.Height, b.Y+b.Height) - max(a.Y, b.Y)
|
||||
if w <= 0 || h <= 0 {
|
||||
return 0
|
||||
}
|
||||
return w * h
|
||||
}
|
||||
|
||||
// Centered returns where a flyout of the given size goes without an
|
||||
// anchor: in the middle of the work area, as large as it fits.
|
||||
func Centered(size Size, work Rect) Rect {
|
||||
r := Rect{Width: min(size.Width, work.Width), Height: min(size.Height, work.Height)}
|
||||
r.X = work.X + (work.Width-r.Width)/2
|
||||
r.Y = work.Y + (work.Height-r.Height)/2
|
||||
return r
|
||||
}
|
||||
|
||||
// PrimaryWorkArea returns the work area of the primary display.
|
||||
func PrimaryWorkArea(displays []Display) Rect {
|
||||
for _, d := range displays {
|
||||
if d.Primary {
|
||||
return d.WorkArea
|
||||
}
|
||||
}
|
||||
if len(displays) > 0 {
|
||||
return displays[0].WorkArea
|
||||
}
|
||||
return Rect{}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package platform
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestFlyoutPlace(t *testing.T) {
|
||||
work := Rect{0, 25, 1000, 700} // under a menu bar
|
||||
button := Rect{100, 100, 80, 20}
|
||||
size := Size{200, 150}
|
||||
tests := []struct {
|
||||
name string
|
||||
f Flyout
|
||||
anchor Rect
|
||||
size Size
|
||||
want Rect
|
||||
fx, fy bool
|
||||
}{
|
||||
{"below, start", Flyout{Gap: 4}, button, size, Rect{100, 124, 200, 150}, false, false},
|
||||
{"below, centered", Flyout{Align: AlignCenter}, button, size, Rect{40, 120, 200, 150}, false, false},
|
||||
{"below, end", Flyout{Align: AlignEnd}, Rect{400, 100, 80, 20}, size, Rect{280, 120, 200, 150}, false, false},
|
||||
{"flips to the start", Flyout{Align: AlignEnd}, button, size, Rect{100, 120, 200, 150}, true, false},
|
||||
{"above", Flyout{Side: SideTop, Gap: 4}, Rect{100, 400, 80, 20}, size, Rect{100, 246, 200, 150}, false, false},
|
||||
{"right", Flyout{Side: SideRight, Gap: 2}, button, size, Rect{182, 100, 200, 150}, false, false},
|
||||
{"left, end", Flyout{Side: SideLeft, Align: AlignEnd}, Rect{500, 300, 80, 20}, size, Rect{300, 170, 200, 150}, false, false},
|
||||
// Not enough room below: above instead, the gap on that side.
|
||||
{"flips up", Flyout{Gap: 4}, Rect{100, 600, 80, 20}, size, Rect{100, 446, 200, 150}, false, true},
|
||||
// Not enough room right of the start: lines up with the end.
|
||||
{"flips to the end", Flyout{}, Rect{900, 100, 80, 20}, size, Rect{780, 120, 200, 150}, true, false},
|
||||
// Not enough room on either side: stays, slides back in.
|
||||
{"slides", Flyout{}, Rect{100, 300, 80, 20}, Size{200, 600}, Rect{100, 125, 200, 600}, false, false},
|
||||
{"slides from the left", Flyout{Side: SideLeft}, Rect{50, 300, 80, 20}, Size{200, 100}, Rect{130, 300, 200, 100}, true, false},
|
||||
// Larger than the work area: its start shows, the rest is cut.
|
||||
{"shrinks", Flyout{}, button, Size{1200, 900}, Rect{0, 25, 1000, 700}, false, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, fx, fy := tt.f.Place(tt.anchor, tt.size, work)
|
||||
if got != tt.want || fx != tt.fx || fy != tt.fy {
|
||||
t.Errorf("Place = %+v, flipped %v %v; want %+v, %v %v", got, fx, fy, tt.want, tt.fx, tt.fy)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkAreaFor(t *testing.T) {
|
||||
displays := []Display{
|
||||
{Bounds: Rect{0, 0, 1920, 1080}, WorkArea: Rect{0, 25, 1920, 1055}},
|
||||
{Bounds: Rect{1920, -77, 1470, 956}, WorkArea: Rect{1920, -77, 1470, 900}},
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
r Rect
|
||||
want int
|
||||
}{
|
||||
{Rect{100, 100, 50, 20}, 0},
|
||||
{Rect{1900, 100, 50, 20}, 1}, // more of it on the second
|
||||
{Rect{1880, 100, 50, 20}, 0},
|
||||
{Rect{2000, 100, 0, 0}, 1}, // a point: the nearest display
|
||||
{Rect{5000, 100, 10, 10}, 1}, // off every display
|
||||
{Rect{-300, 5, 10, 10}, 0},
|
||||
} {
|
||||
if got := WorkAreaFor(tt.r, displays); got != displays[tt.want].WorkArea {
|
||||
t.Errorf("WorkAreaFor(%+v) = %+v, want display %d", tt.r, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package platform
|
||||
|
||||
// HeldKeys keeps the keys whose presses a backend sent the content and
|
||||
// whose releases it has not, for a backend whose system keeps some
|
||||
// releases from the window: those an input method takes, those a menu's
|
||||
// loop takes, and, in a Mac's browsers, those let go of while Command is
|
||||
// held. The backend lets go of them itself (Lift, LiftAll), so that the
|
||||
// content never holds a key the user let go of (KeyReleased).
|
||||
type HeldKeys struct {
|
||||
held []heldKey
|
||||
// gone are the keys Lift and LiftAll let go of, whose own releases may
|
||||
// still come, which Track then keeps from the content.
|
||||
gone []heldKey
|
||||
}
|
||||
|
||||
type heldKey struct {
|
||||
key, physical Key
|
||||
code KeyCode
|
||||
}
|
||||
|
||||
// same reports whether k is the key at physical, or key where either
|
||||
// position is unknown.
|
||||
func (k heldKey) same(key, physical Key) bool {
|
||||
if k.physical != KeyUnknown && physical != KeyUnknown {
|
||||
return k.physical == physical
|
||||
}
|
||||
return key != KeyUnknown && k.key == key
|
||||
}
|
||||
|
||||
func indexKey(keys []heldKey, key, physical Key) int {
|
||||
for i, k := range keys {
|
||||
if k.same(key, physical) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// Track notes ev, an event the backend is about to send the content, and
|
||||
// reports whether to send it: false for the release of a key Lift or
|
||||
// LiftAll let go of already.
|
||||
func (h *HeldKeys) Track(ev SurfaceEvent) bool {
|
||||
switch ev.Kind {
|
||||
case KeyPressed:
|
||||
if i := indexKey(h.gone, ev.Key, ev.PhysicalKey); i >= 0 {
|
||||
h.gone = append(h.gone[:i], h.gone[i+1:]...)
|
||||
}
|
||||
if indexKey(h.held, ev.Key, ev.PhysicalKey) < 0 && (ev.Key != KeyUnknown || ev.PhysicalKey != KeyUnknown) {
|
||||
h.held = append(h.held, heldKey{ev.Key, ev.PhysicalKey, ev.Code})
|
||||
}
|
||||
case KeyReleased:
|
||||
if i := indexKey(h.held, ev.Key, ev.PhysicalKey); i >= 0 {
|
||||
h.held = append(h.held[:i], h.held[i+1:]...)
|
||||
return true
|
||||
}
|
||||
if i := indexKey(h.gone, ev.Key, ev.PhysicalKey); i >= 0 {
|
||||
h.gone = append(h.gone[:i], h.gone[i+1:]...)
|
||||
return false
|
||||
}
|
||||
case SurfaceBlur:
|
||||
// The content lets go of every key itself.
|
||||
h.held, h.gone = h.held[:0], h.gone[:0]
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Lift sends the release of the key held at physical (or key, where its
|
||||
// position is unknown), whose own release the system keeps from the
|
||||
// window, as an input method takes it, through send, which tracks it. It
|
||||
// does nothing when no such key is held.
|
||||
func (h *HeldKeys) Lift(key, physical Key, mods Modifiers, send func(SurfaceEvent) bool) {
|
||||
i := indexKey(h.held, key, physical)
|
||||
if i < 0 {
|
||||
return
|
||||
}
|
||||
k := h.held[i]
|
||||
send(SurfaceEvent{Kind: KeyReleased, Key: k.key, PhysicalKey: k.physical, Code: k.code, Mods: mods})
|
||||
// send tracked the release, unless the window closed.
|
||||
if i := indexKey(h.held, k.key, k.physical); i >= 0 {
|
||||
h.held = append(h.held[:i], h.held[i+1:]...)
|
||||
}
|
||||
h.gone = append(h.gone, k)
|
||||
}
|
||||
|
||||
// LiftAll sends the releases of every key held through send, as a menu's
|
||||
// loop takes the keyboard.
|
||||
func (h *HeldKeys) LiftAll(mods Modifiers, send func(SurfaceEvent) bool) {
|
||||
for len(h.held) > 0 {
|
||||
k := h.held[0]
|
||||
h.Lift(k.key, k.physical, mods, send)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// heldBackend sends what a backend would, through HeldKeys, and keeps what
|
||||
// reached the content.
|
||||
type heldBackend struct {
|
||||
held HeldKeys
|
||||
sent []SurfaceEvent
|
||||
}
|
||||
|
||||
func (b *heldBackend) send(ev SurfaceEvent) bool {
|
||||
if !b.held.Track(ev) {
|
||||
return false
|
||||
}
|
||||
b.sent = append(b.sent, ev)
|
||||
return true
|
||||
}
|
||||
|
||||
func (b *heldBackend) releases() []Key {
|
||||
var keys []Key
|
||||
for _, ev := range b.sent {
|
||||
if ev.Kind == KeyReleased {
|
||||
keys = append(keys, ev.Key)
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// An input method taking a key's release lets go of the key by its
|
||||
// position; when it hands the release back after all, as IBus does, the
|
||||
// content gets it once.
|
||||
func TestHeldKeysLift(t *testing.T) {
|
||||
var b heldBackend
|
||||
b.send(SurfaceEvent{Kind: KeyPressed, Key: KeyA, PhysicalKey: KeyQ}) // A on AZERTY
|
||||
b.held.Lift(KeyUnknown, KeyQ, ModShift, b.send)
|
||||
if got := b.releases(); !slices.Equal(got, []Key{KeyA}) {
|
||||
t.Fatalf("released %v, want A", got)
|
||||
}
|
||||
if ev := b.sent[len(b.sent)-1]; ev.PhysicalKey != KeyQ || ev.Mods != ModShift {
|
||||
t.Errorf("the release: %+v", ev)
|
||||
}
|
||||
b.send(SurfaceEvent{Kind: KeyReleased, Key: KeyA, PhysicalKey: KeyQ})
|
||||
if got := b.releases(); len(got) != 1 {
|
||||
t.Errorf("the release handed back reached the content: %v", got)
|
||||
}
|
||||
// Pressed again, its release comes as usual.
|
||||
b.send(SurfaceEvent{Kind: KeyPressed, Key: KeyA, PhysicalKey: KeyQ})
|
||||
b.send(SurfaceEvent{Kind: KeyReleased, Key: KeyA, PhysicalKey: KeyQ})
|
||||
if got := b.releases(); len(got) != 2 {
|
||||
t.Errorf("a later release: %v", got)
|
||||
}
|
||||
// Nothing held there: nothing to let go of.
|
||||
b.held.Lift(KeyUnknown, KeyW, 0, b.send)
|
||||
if got := b.releases(); len(got) != 2 {
|
||||
t.Errorf("lifted a key not held: %v", got)
|
||||
}
|
||||
// A release of a key never held goes on, as before.
|
||||
b.send(SurfaceEvent{Kind: KeyReleased, Key: KeyZ})
|
||||
if got := b.releases(); len(got) != 3 {
|
||||
t.Errorf("a release with nothing held: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A menu's loop taking the keyboard lets go of every key held, once; a
|
||||
// repeat holds a key once; the window losing the keyboard forgets them.
|
||||
func TestHeldKeysLiftAll(t *testing.T) {
|
||||
var b heldBackend
|
||||
b.send(SurfaceEvent{Kind: KeyPressed, Key: KeyF, PhysicalKey: KeyF, Mods: ModAlt})
|
||||
b.send(SurfaceEvent{Kind: KeyPressed, Key: KeyF, PhysicalKey: KeyF, Mods: ModAlt, Repeat: true})
|
||||
b.send(SurfaceEvent{Kind: KeyPressed, Key: KeyEnter})
|
||||
b.held.LiftAll(0, b.send)
|
||||
if got := b.releases(); !slices.Equal(got, []Key{KeyF, KeyEnter}) {
|
||||
t.Fatalf("released %v, want F and Enter", got)
|
||||
}
|
||||
b.held.LiftAll(0, b.send)
|
||||
b.send(SurfaceEvent{Kind: KeyReleased, Key: KeyEnter})
|
||||
if got := b.releases(); len(got) != 2 {
|
||||
t.Errorf("released again: %v", got)
|
||||
}
|
||||
b.send(SurfaceEvent{Kind: KeyPressed, Key: KeyG, PhysicalKey: KeyG})
|
||||
b.send(SurfaceEvent{Kind: SurfaceBlur})
|
||||
b.held.LiftAll(0, b.send)
|
||||
if got := b.releases(); len(got) != 2 {
|
||||
t.Errorf("released after the window lost the keyboard: %v", got)
|
||||
}
|
||||
// A closed window takes nothing; the keys are let go of all the same.
|
||||
b.send(SurfaceEvent{Kind: KeyPressed, Key: KeyH})
|
||||
b.held.LiftAll(0, func(SurfaceEvent) bool { return false })
|
||||
if len(b.held.held) != 0 {
|
||||
t.Errorf("held after LiftAll: %v", b.held.held)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package platform
|
||||
|
||||
// InRegion reports whether x, y is in one of the rectangles of region,
|
||||
// their far edges excluded: the input region of a window
|
||||
// (Window.SetInputRegion), in DIPs from the top-left corner of its
|
||||
// content.
|
||||
func InRegion(region []Rect, x, y float64) bool {
|
||||
for _, r := range region {
|
||||
if x >= float64(r.X) && y >= float64(r.Y) && x < float64(r.X+r.Width) && y < float64(r.Y+r.Height) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// LetsMouseThrough tells whether a window with an input region lets the
|
||||
// mouse through to what is behind it, the pointer at x, y in DIPs from
|
||||
// the top-left corner of its content, for a backend whose system shapes
|
||||
// no window's input and lets the mouse through all of a window or none of
|
||||
// it (macOS, Windows), switching as the pointer moves: through outside
|
||||
// the rectangles, and as it was, through, while a button is held, held.
|
||||
// A press that started on the window, as one dragging it by its character,
|
||||
// keeps the window until it ends, as one that started behind it keeps
|
||||
// what is behind; the release settles it.
|
||||
func LetsMouseThrough(region []Rect, x, y float64, held, through bool) bool {
|
||||
if held {
|
||||
return through
|
||||
}
|
||||
return !InRegion(region, x, y)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package platform
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestInRegion(t *testing.T) {
|
||||
region := []Rect{{X: 10, Y: 20, Width: 30, Height: 40}, {X: 100, Y: 0, Width: 5, Height: 5}}
|
||||
for _, c := range []struct {
|
||||
x, y float64
|
||||
want bool
|
||||
}{
|
||||
{10, 20, true}, // the near corner
|
||||
{39.9, 59.9, true}, // just inside the far one
|
||||
{40, 30, false}, // the far edges are out
|
||||
{20, 60, false},
|
||||
{9.9, 30, false},
|
||||
{102, 2, true}, // the second rectangle
|
||||
{-1, -1, false},
|
||||
} {
|
||||
if got := InRegion(region, c.x, c.y); got != c.want {
|
||||
t.Errorf("InRegion(%v, %v) = %v, want %v", c.x, c.y, got, c.want)
|
||||
}
|
||||
}
|
||||
if InRegion(nil, 0, 0) || InRegion([]Rect{}, 0, 0) {
|
||||
t.Error("an empty region holds a point")
|
||||
}
|
||||
if InRegion([]Rect{{X: 5, Y: 5}}, 5, 5) {
|
||||
t.Error("a rectangle without area holds a point")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLetsMouseThrough(t *testing.T) {
|
||||
region := []Rect{{X: 0, Y: 0, Width: 10, Height: 10}}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
x, y float64
|
||||
held, through bool
|
||||
want bool
|
||||
}{
|
||||
{"on the region", 5, 5, false, true, false},
|
||||
{"off the region", 50, 5, false, false, true},
|
||||
{"a press on the window dragged off it", 50, 5, true, false, false},
|
||||
{"a press behind dragged onto the region", 5, 5, true, true, true},
|
||||
} {
|
||||
if got := LetsMouseThrough(region, c.x, c.y, c.held, c.through); got != c.want {
|
||||
t.Errorf("%s: %v, want %v", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
if !LetsMouseThrough([]Rect{}, 5, 5, false, false) {
|
||||
t.Error("an empty region takes the mouse")
|
||||
}
|
||||
}
|
||||
+500
@@ -0,0 +1,500 @@
|
||||
package platform
|
||||
|
||||
// KeyCode is a key by its position on the keyboard, whatever the layout
|
||||
// types and whichever system reports it: a USB HID usage ID of the keyboard
|
||||
// page (0x07), named after the code of UI Events' KeyboardEvent. Unlike Key
|
||||
// it tells the sides of the modifiers and every key of a full keyboard.
|
||||
type KeyCode uint16
|
||||
|
||||
// The keys by position.
|
||||
const (
|
||||
CodeUnknown KeyCode = 0
|
||||
|
||||
CodeKeyA KeyCode = iota + 3
|
||||
CodeKeyB
|
||||
CodeKeyC
|
||||
CodeKeyD
|
||||
CodeKeyE
|
||||
CodeKeyF
|
||||
CodeKeyG
|
||||
CodeKeyH
|
||||
CodeKeyI
|
||||
CodeKeyJ
|
||||
CodeKeyK
|
||||
CodeKeyL
|
||||
CodeKeyM
|
||||
CodeKeyN
|
||||
CodeKeyO
|
||||
CodeKeyP
|
||||
CodeKeyQ
|
||||
CodeKeyR
|
||||
CodeKeyS
|
||||
CodeKeyT
|
||||
CodeKeyU
|
||||
CodeKeyV
|
||||
CodeKeyW
|
||||
CodeKeyX
|
||||
CodeKeyY
|
||||
CodeKeyZ
|
||||
CodeDigit1
|
||||
CodeDigit2
|
||||
CodeDigit3
|
||||
CodeDigit4
|
||||
CodeDigit5
|
||||
CodeDigit6
|
||||
CodeDigit7
|
||||
CodeDigit8
|
||||
CodeDigit9
|
||||
CodeDigit0
|
||||
CodeEnter
|
||||
CodeEscape
|
||||
CodeBackspace
|
||||
CodeTab
|
||||
CodeSpace
|
||||
CodeMinus
|
||||
CodeEqual
|
||||
CodeBracketLeft
|
||||
CodeBracketRight
|
||||
CodeBackslash
|
||||
)
|
||||
|
||||
const (
|
||||
CodeSemicolon KeyCode = iota + 0x33
|
||||
CodeQuote
|
||||
CodeBackquote
|
||||
CodeComma
|
||||
CodePeriod
|
||||
CodeSlash
|
||||
CodeCapsLock
|
||||
CodeF1
|
||||
CodeF2
|
||||
CodeF3
|
||||
CodeF4
|
||||
CodeF5
|
||||
CodeF6
|
||||
CodeF7
|
||||
CodeF8
|
||||
CodeF9
|
||||
CodeF10
|
||||
CodeF11
|
||||
CodeF12
|
||||
CodePrintScreen
|
||||
CodeScrollLock
|
||||
CodePause
|
||||
CodeInsert
|
||||
CodeHome
|
||||
CodePageUp
|
||||
CodeDelete
|
||||
CodeEnd
|
||||
CodePageDown
|
||||
CodeArrowRight
|
||||
CodeArrowLeft
|
||||
CodeArrowDown
|
||||
CodeArrowUp
|
||||
CodeNumLock
|
||||
CodeNumpadDivide
|
||||
CodeNumpadMultiply
|
||||
CodeNumpadSubtract
|
||||
CodeNumpadAdd
|
||||
CodeNumpadEnter
|
||||
CodeNumpad1
|
||||
CodeNumpad2
|
||||
CodeNumpad3
|
||||
CodeNumpad4
|
||||
CodeNumpad5
|
||||
CodeNumpad6
|
||||
CodeNumpad7
|
||||
CodeNumpad8
|
||||
CodeNumpad9
|
||||
CodeNumpad0
|
||||
CodeNumpadDecimal
|
||||
CodeIntlBackslash
|
||||
CodeContextMenu
|
||||
CodePower
|
||||
CodeNumpadEqual
|
||||
CodeF13
|
||||
CodeF14
|
||||
CodeF15
|
||||
CodeF16
|
||||
CodeF17
|
||||
CodeF18
|
||||
CodeF19
|
||||
CodeF20
|
||||
CodeF21
|
||||
CodeF22
|
||||
CodeF23
|
||||
CodeF24
|
||||
)
|
||||
|
||||
const (
|
||||
CodeAudioVolumeMute KeyCode = iota + 0x7F
|
||||
CodeAudioVolumeUp
|
||||
CodeAudioVolumeDown
|
||||
)
|
||||
|
||||
const (
|
||||
CodeNumpadComma KeyCode = 0x85
|
||||
CodeIntlRo KeyCode = 0x87
|
||||
CodeKanaMode KeyCode = 0x88
|
||||
CodeIntlYen KeyCode = 0x89
|
||||
CodeConvert KeyCode = 0x8A
|
||||
CodeNonConvert KeyCode = 0x8B
|
||||
CodeLang1 KeyCode = 0x90
|
||||
CodeLang2 KeyCode = 0x91
|
||||
CodeLang3 KeyCode = 0x92
|
||||
CodeLang4 KeyCode = 0x93
|
||||
)
|
||||
|
||||
const (
|
||||
CodeControlLeft KeyCode = iota + 0xE0
|
||||
CodeShiftLeft
|
||||
CodeAltLeft
|
||||
CodeSuperLeft
|
||||
CodeControlRight
|
||||
CodeShiftRight
|
||||
CodeAltRight
|
||||
CodeSuperRight
|
||||
)
|
||||
|
||||
// xtCodes maps the scancodes shared by XT set 1, which Windows reports, and
|
||||
// Linux's evdev: those of an AT keyboard's main block, its function keys and
|
||||
// its keypad, up to F12.
|
||||
var xtCodes = [...]KeyCode{
|
||||
0x01: CodeEscape, 0x02: CodeDigit1, 0x03: CodeDigit2, 0x04: CodeDigit3, 0x05: CodeDigit4,
|
||||
0x06: CodeDigit5, 0x07: CodeDigit6, 0x08: CodeDigit7, 0x09: CodeDigit8, 0x0A: CodeDigit9,
|
||||
0x0B: CodeDigit0, 0x0C: CodeMinus, 0x0D: CodeEqual, 0x0E: CodeBackspace, 0x0F: CodeTab,
|
||||
0x10: CodeKeyQ, 0x11: CodeKeyW, 0x12: CodeKeyE, 0x13: CodeKeyR, 0x14: CodeKeyT,
|
||||
0x15: CodeKeyY, 0x16: CodeKeyU, 0x17: CodeKeyI, 0x18: CodeKeyO, 0x19: CodeKeyP,
|
||||
0x1A: CodeBracketLeft, 0x1B: CodeBracketRight, 0x1C: CodeEnter, 0x1D: CodeControlLeft,
|
||||
0x1E: CodeKeyA, 0x1F: CodeKeyS, 0x20: CodeKeyD, 0x21: CodeKeyF, 0x22: CodeKeyG,
|
||||
0x23: CodeKeyH, 0x24: CodeKeyJ, 0x25: CodeKeyK, 0x26: CodeKeyL, 0x27: CodeSemicolon,
|
||||
0x28: CodeQuote, 0x29: CodeBackquote, 0x2A: CodeShiftLeft, 0x2B: CodeBackslash,
|
||||
0x2C: CodeKeyZ, 0x2D: CodeKeyX, 0x2E: CodeKeyC, 0x2F: CodeKeyV, 0x30: CodeKeyB,
|
||||
0x31: CodeKeyN, 0x32: CodeKeyM, 0x33: CodeComma, 0x34: CodePeriod, 0x35: CodeSlash,
|
||||
0x36: CodeShiftRight, 0x37: CodeNumpadMultiply, 0x38: CodeAltLeft, 0x39: CodeSpace,
|
||||
0x3A: CodeCapsLock, 0x3B: CodeF1, 0x3C: CodeF2, 0x3D: CodeF3, 0x3E: CodeF4, 0x3F: CodeF5,
|
||||
0x40: CodeF6, 0x41: CodeF7, 0x42: CodeF8, 0x43: CodeF9, 0x44: CodeF10, 0x45: CodeNumLock,
|
||||
0x46: CodeScrollLock, 0x47: CodeNumpad7, 0x48: CodeNumpad8, 0x49: CodeNumpad9,
|
||||
0x4A: CodeNumpadSubtract, 0x4B: CodeNumpad4, 0x4C: CodeNumpad5, 0x4D: CodeNumpad6,
|
||||
0x4E: CodeNumpadAdd, 0x4F: CodeNumpad1, 0x50: CodeNumpad2, 0x51: CodeNumpad3,
|
||||
0x52: CodeNumpad0, 0x53: CodeNumpadDecimal, 0x56: CodeIntlBackslash, 0x57: CodeF11, 0x58: CodeF12,
|
||||
}
|
||||
|
||||
// KeyCodeForEvdev returns the key of a Linux evdev code (KEY_*; an X or
|
||||
// GDK hardware keycode less 8), CodeUnknown for one it does not map.
|
||||
func KeyCodeForEvdev(code uint16) KeyCode {
|
||||
if int(code) < len(xtCodes) {
|
||||
return xtCodes[code]
|
||||
}
|
||||
if code >= 183 && code <= 194 {
|
||||
return CodeF13 + KeyCode(code-183)
|
||||
}
|
||||
switch code {
|
||||
case 89:
|
||||
return CodeIntlRo
|
||||
case 90:
|
||||
return CodeLang3 // Katakana
|
||||
case 91:
|
||||
return CodeLang4 // Hiragana
|
||||
case 92:
|
||||
return CodeConvert
|
||||
case 93:
|
||||
return CodeKanaMode
|
||||
case 94:
|
||||
return CodeNonConvert
|
||||
case 95, 121:
|
||||
return CodeNumpadComma
|
||||
case 96:
|
||||
return CodeNumpadEnter
|
||||
case 97:
|
||||
return CodeControlRight
|
||||
case 98:
|
||||
return CodeNumpadDivide
|
||||
case 99:
|
||||
return CodePrintScreen
|
||||
case 100:
|
||||
return CodeAltRight
|
||||
case 102:
|
||||
return CodeHome
|
||||
case 103:
|
||||
return CodeArrowUp
|
||||
case 104:
|
||||
return CodePageUp
|
||||
case 105:
|
||||
return CodeArrowLeft
|
||||
case 106:
|
||||
return CodeArrowRight
|
||||
case 107:
|
||||
return CodeEnd
|
||||
case 108:
|
||||
return CodeArrowDown
|
||||
case 109:
|
||||
return CodePageDown
|
||||
case 110:
|
||||
return CodeInsert
|
||||
case 111:
|
||||
return CodeDelete
|
||||
case 113:
|
||||
return CodeAudioVolumeMute
|
||||
case 114:
|
||||
return CodeAudioVolumeDown
|
||||
case 115:
|
||||
return CodeAudioVolumeUp
|
||||
case 116:
|
||||
return CodePower
|
||||
case 117:
|
||||
return CodeNumpadEqual
|
||||
case 119:
|
||||
return CodePause
|
||||
case 122:
|
||||
return CodeLang1 // Hangul
|
||||
case 123:
|
||||
return CodeLang2 // Hanja
|
||||
case 124:
|
||||
return CodeIntlYen
|
||||
case 125:
|
||||
return CodeSuperLeft
|
||||
case 126:
|
||||
return CodeSuperRight
|
||||
case 127:
|
||||
return CodeContextMenu
|
||||
}
|
||||
return CodeUnknown
|
||||
}
|
||||
|
||||
// KeyCodeForXT returns the key of an XT set 1 scancode as Windows reports it
|
||||
// in a key message's lParam, extended being its bit 24, CodeUnknown for one
|
||||
// it does not map. Windows's own quirks are in it: NumLock is the extended
|
||||
// 0x45 and Pause the plain one, Alt+Print Screen and Ctrl+Pause have codes of
|
||||
// their own, and CJK input methods set the extended bit of the right Shift.
|
||||
func KeyCodeForXT(scan uint8, extended bool) KeyCode {
|
||||
if extended {
|
||||
switch scan {
|
||||
case 0x1C:
|
||||
return CodeNumpadEnter
|
||||
case 0x1D:
|
||||
return CodeControlRight
|
||||
case 0x35:
|
||||
return CodeNumpadDivide
|
||||
case 0x36:
|
||||
return CodeShiftRight
|
||||
case 0x37:
|
||||
return CodePrintScreen
|
||||
case 0x38:
|
||||
return CodeAltRight
|
||||
case 0x45:
|
||||
return CodeNumLock
|
||||
case 0x46:
|
||||
return CodePause
|
||||
case 0x47:
|
||||
return CodeHome
|
||||
case 0x48:
|
||||
return CodeArrowUp
|
||||
case 0x49:
|
||||
return CodePageUp
|
||||
case 0x4B:
|
||||
return CodeArrowLeft
|
||||
case 0x4D:
|
||||
return CodeArrowRight
|
||||
case 0x4F:
|
||||
return CodeEnd
|
||||
case 0x50:
|
||||
return CodeArrowDown
|
||||
case 0x51:
|
||||
return CodePageDown
|
||||
case 0x52:
|
||||
return CodeInsert
|
||||
case 0x53:
|
||||
return CodeDelete
|
||||
case 0x5B:
|
||||
return CodeSuperLeft
|
||||
case 0x5C:
|
||||
return CodeSuperRight
|
||||
case 0x5D:
|
||||
return CodeContextMenu
|
||||
case 0x5E:
|
||||
return CodePower
|
||||
}
|
||||
return CodeUnknown
|
||||
}
|
||||
switch scan {
|
||||
case 0x45:
|
||||
return CodePause
|
||||
case 0x54:
|
||||
return CodePrintScreen
|
||||
case 0x59:
|
||||
return CodeNumpadEqual
|
||||
case 0x70:
|
||||
return CodeKanaMode
|
||||
case 0x73:
|
||||
return CodeIntlRo
|
||||
case 0x76:
|
||||
return CodeF24
|
||||
case 0x79:
|
||||
return CodeConvert
|
||||
case 0x7B:
|
||||
return CodeNonConvert
|
||||
case 0x7D:
|
||||
return CodeIntlYen
|
||||
case 0x7E:
|
||||
return CodeNumpadComma
|
||||
case 0x71:
|
||||
return CodeLang2 // Hanja
|
||||
case 0x72:
|
||||
return CodeLang1 // Hangul
|
||||
case 0x77:
|
||||
return CodeLang4 // Hiragana
|
||||
case 0x78:
|
||||
return CodeLang3 // Katakana
|
||||
}
|
||||
if scan >= 0x64 && scan <= 0x6E {
|
||||
return CodeF13 + KeyCode(scan-0x64)
|
||||
}
|
||||
if int(scan) < len(xtCodes) {
|
||||
return xtCodes[scan]
|
||||
}
|
||||
return CodeUnknown
|
||||
}
|
||||
|
||||
// macCodes maps macOS's virtual key codes (Carbon's kVK_*). A keyboard of
|
||||
// ISO's layout swaps the codes of its section and grave keys, which the
|
||||
// backend, knowing the keyboard, undoes.
|
||||
var macCodes = [...]KeyCode{
|
||||
0x00: CodeKeyA, 0x01: CodeKeyS, 0x02: CodeKeyD, 0x03: CodeKeyF, 0x04: CodeKeyH, 0x05: CodeKeyG,
|
||||
0x06: CodeKeyZ, 0x07: CodeKeyX, 0x08: CodeKeyC, 0x09: CodeKeyV, 0x0A: CodeIntlBackslash, 0x0B: CodeKeyB,
|
||||
0x0C: CodeKeyQ, 0x0D: CodeKeyW, 0x0E: CodeKeyE, 0x0F: CodeKeyR, 0x10: CodeKeyY, 0x11: CodeKeyT,
|
||||
0x12: CodeDigit1, 0x13: CodeDigit2, 0x14: CodeDigit3, 0x15: CodeDigit4, 0x16: CodeDigit6, 0x17: CodeDigit5,
|
||||
0x18: CodeEqual, 0x19: CodeDigit9, 0x1A: CodeDigit7, 0x1B: CodeMinus, 0x1C: CodeDigit8, 0x1D: CodeDigit0,
|
||||
0x1E: CodeBracketRight, 0x1F: CodeKeyO, 0x20: CodeKeyU, 0x21: CodeBracketLeft, 0x22: CodeKeyI, 0x23: CodeKeyP,
|
||||
0x24: CodeEnter, 0x25: CodeKeyL, 0x26: CodeKeyJ, 0x27: CodeQuote, 0x28: CodeKeyK, 0x29: CodeSemicolon,
|
||||
0x2A: CodeBackslash, 0x2B: CodeComma, 0x2C: CodeSlash, 0x2D: CodeKeyN, 0x2E: CodeKeyM, 0x2F: CodePeriod,
|
||||
0x30: CodeTab, 0x31: CodeSpace, 0x32: CodeBackquote, 0x33: CodeBackspace, 0x35: CodeEscape,
|
||||
0x36: CodeSuperRight, 0x37: CodeSuperLeft, 0x38: CodeShiftLeft, 0x39: CodeCapsLock, 0x3A: CodeAltLeft,
|
||||
0x3B: CodeControlLeft, 0x3C: CodeShiftRight, 0x3D: CodeAltRight, 0x3E: CodeControlRight,
|
||||
0x40: CodeF17, 0x41: CodeNumpadDecimal, 0x43: CodeNumpadMultiply, 0x45: CodeNumpadAdd, 0x47: CodeNumLock,
|
||||
0x48: CodeAudioVolumeUp, 0x49: CodeAudioVolumeDown, 0x4A: CodeAudioVolumeMute, 0x4B: CodeNumpadDivide,
|
||||
0x4C: CodeNumpadEnter, 0x4E: CodeNumpadSubtract, 0x4F: CodeF18, 0x50: CodeF19, 0x51: CodeNumpadEqual,
|
||||
0x52: CodeNumpad0, 0x53: CodeNumpad1, 0x54: CodeNumpad2, 0x55: CodeNumpad3, 0x56: CodeNumpad4,
|
||||
0x57: CodeNumpad5, 0x58: CodeNumpad6, 0x59: CodeNumpad7, 0x5A: CodeF20, 0x5B: CodeNumpad8, 0x5C: CodeNumpad9,
|
||||
0x5D: CodeIntlYen, 0x5E: CodeIntlRo, 0x5F: CodeNumpadComma, 0x60: CodeF5, 0x61: CodeF6, 0x62: CodeF7,
|
||||
0x63: CodeF3, 0x64: CodeF8, 0x65: CodeF9, 0x66: CodeLang2, 0x67: CodeF11, 0x68: CodeLang1, 0x69: CodeF13,
|
||||
0x6A: CodeF16, 0x6B: CodeF14, 0x6D: CodeF10, 0x6E: CodeContextMenu, 0x6F: CodeF12, 0x71: CodeF15,
|
||||
0x72: CodeInsert, 0x73: CodeHome, 0x74: CodePageUp, 0x75: CodeDelete, 0x76: CodeF4, 0x77: CodeEnd,
|
||||
0x78: CodeF2, 0x79: CodePageDown, 0x7A: CodeF1, 0x7B: CodeArrowLeft, 0x7C: CodeArrowRight,
|
||||
0x7D: CodeArrowDown, 0x7E: CodeArrowUp,
|
||||
}
|
||||
|
||||
// KeyCodeForMac returns the key of a macOS virtual key code, CodeUnknown for
|
||||
// one it does not map, as Fn.
|
||||
func KeyCodeForMac(code uint16) KeyCode {
|
||||
if int(code) < len(macCodes) {
|
||||
return macCodes[code]
|
||||
}
|
||||
return CodeUnknown
|
||||
}
|
||||
|
||||
// MacFlagsChanged returns the key of a flagsChanged: event, of virtual key
|
||||
// code keyCode and NSEvent modifierFlags flags, and whether it pressed that
|
||||
// key rather than let go of it; CodeUnknown for one of no modifier (AppKit
|
||||
// sends some with other codes) and for Fn, which has no code. The flags'
|
||||
// device-dependent bits tell the sides; where the left and right bits are
|
||||
// both clear while the side-independent bit is set, as in events another
|
||||
// program made, it counts as pressed. Caps Lock counts as pressed: macOS
|
||||
// tells of it once for each change of the lock, the backend gives it a
|
||||
// release at once.
|
||||
func MacFlagsChanged(keyCode uint16, flags uint) (code KeyCode, down bool) {
|
||||
const (
|
||||
shift = 1 << 17
|
||||
control = 1 << 18
|
||||
option = 1 << 19
|
||||
command = 1 << 20
|
||||
)
|
||||
var own, other, class uint
|
||||
code = KeyCodeForMac(keyCode)
|
||||
switch code {
|
||||
case CodeCapsLock:
|
||||
return code, true
|
||||
case CodeControlLeft:
|
||||
own, other, class = 0x0001, 0x2000, control
|
||||
case CodeControlRight:
|
||||
own, other, class = 0x2000, 0x0001, control
|
||||
case CodeShiftLeft:
|
||||
own, other, class = 0x0002, 0x0004, shift
|
||||
case CodeShiftRight:
|
||||
own, other, class = 0x0004, 0x0002, shift
|
||||
case CodeSuperLeft:
|
||||
own, other, class = 0x0008, 0x0010, command
|
||||
case CodeSuperRight:
|
||||
own, other, class = 0x0010, 0x0008, command
|
||||
case CodeAltLeft:
|
||||
own, other, class = 0x0020, 0x0040, option
|
||||
case CodeAltRight:
|
||||
own, other, class = 0x0040, 0x0020, option
|
||||
default:
|
||||
return CodeUnknown, false
|
||||
}
|
||||
return code, flags&own != 0 || flags&other == 0 && flags&class != 0
|
||||
}
|
||||
|
||||
// domCodes maps the named codes of UI Events' KeyboardEvent that are not a
|
||||
// letter or a digit.
|
||||
var domCodes = map[string]KeyCode{
|
||||
"Enter": CodeEnter, "Escape": CodeEscape, "Backspace": CodeBackspace, "Tab": CodeTab, "Space": CodeSpace,
|
||||
"Minus": CodeMinus, "Equal": CodeEqual, "BracketLeft": CodeBracketLeft, "BracketRight": CodeBracketRight,
|
||||
"Backslash": CodeBackslash, "Semicolon": CodeSemicolon, "Quote": CodeQuote, "Backquote": CodeBackquote,
|
||||
"Comma": CodeComma, "Period": CodePeriod, "Slash": CodeSlash, "CapsLock": CodeCapsLock,
|
||||
"PrintScreen": CodePrintScreen, "ScrollLock": CodeScrollLock, "Pause": CodePause, "Insert": CodeInsert,
|
||||
"Home": CodeHome, "PageUp": CodePageUp, "Delete": CodeDelete, "End": CodeEnd, "PageDown": CodePageDown,
|
||||
"ArrowRight": CodeArrowRight, "ArrowLeft": CodeArrowLeft, "ArrowDown": CodeArrowDown, "ArrowUp": CodeArrowUp,
|
||||
"NumLock": CodeNumLock, "NumpadDivide": CodeNumpadDivide, "NumpadMultiply": CodeNumpadMultiply,
|
||||
"NumpadSubtract": CodeNumpadSubtract, "NumpadAdd": CodeNumpadAdd, "NumpadEnter": CodeNumpadEnter,
|
||||
"NumpadDecimal": CodeNumpadDecimal, "NumpadEqual": CodeNumpadEqual, "NumpadComma": CodeNumpadComma,
|
||||
"IntlBackslash": CodeIntlBackslash, "IntlRo": CodeIntlRo, "IntlYen": CodeIntlYen, "KanaMode": CodeKanaMode,
|
||||
"Convert": CodeConvert, "NonConvert": CodeNonConvert, "Lang1": CodeLang1, "Lang2": CodeLang2,
|
||||
"Lang3": CodeLang3, "Lang4": CodeLang4, "ContextMenu": CodeContextMenu, "Power": CodePower,
|
||||
"AudioVolumeMute": CodeAudioVolumeMute, "AudioVolumeUp": CodeAudioVolumeUp, "AudioVolumeDown": CodeAudioVolumeDown,
|
||||
"ControlLeft": CodeControlLeft, "ShiftLeft": CodeShiftLeft, "AltLeft": CodeAltLeft, "MetaLeft": CodeSuperLeft,
|
||||
"ControlRight": CodeControlRight, "ShiftRight": CodeShiftRight, "AltRight": CodeAltRight, "MetaRight": CodeSuperRight,
|
||||
// Older names of the same keys, which some browsers still give.
|
||||
"OSLeft": CodeSuperLeft, "OSRight": CodeSuperRight,
|
||||
}
|
||||
|
||||
// KeyCodeForDOM returns the key of a KeyboardEvent's code, CodeUnknown for
|
||||
// one it does not map.
|
||||
func KeyCodeForDOM(code string) KeyCode {
|
||||
switch {
|
||||
case len(code) == 4 && code[:3] == "Key" && code[3] >= 'A' && code[3] <= 'Z':
|
||||
return CodeKeyA + KeyCode(code[3]-'A')
|
||||
case len(code) == 6 && code[:5] == "Digit" && code[5] >= '1' && code[5] <= '9':
|
||||
return CodeDigit1 + KeyCode(code[5]-'1')
|
||||
case code == "Digit0":
|
||||
return CodeDigit0
|
||||
case len(code) == 7 && code[:6] == "Numpad" && code[6] >= '1' && code[6] <= '9':
|
||||
return CodeNumpad1 + KeyCode(code[6]-'1')
|
||||
case code == "Numpad0":
|
||||
return CodeNumpad0
|
||||
case len(code) >= 2 && code[0] == 'F':
|
||||
if n := functionNumber(code[1:]); n >= 1 && n <= 12 {
|
||||
return CodeF1 + KeyCode(n-1)
|
||||
} else if n >= 13 && n <= 24 {
|
||||
return CodeF13 + KeyCode(n-13)
|
||||
}
|
||||
}
|
||||
return domCodes[code]
|
||||
}
|
||||
|
||||
// functionNumber reads the one or two digits of F1 to F24, 0 for anything
|
||||
// else.
|
||||
func functionNumber(s string) int {
|
||||
if len(s) == 0 || len(s) > 2 {
|
||||
return 0
|
||||
}
|
||||
n := 0
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] < '0' || s[i] > '9' {
|
||||
return 0
|
||||
}
|
||||
n = n*10 + int(s[i]-'0')
|
||||
}
|
||||
return n
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
package platform
|
||||
|
||||
import "testing"
|
||||
|
||||
// The constants are USB HID usage IDs, which apps may rely on.
|
||||
func TestKeyCodeUsages(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
code KeyCode
|
||||
usage uint16
|
||||
}{
|
||||
{CodeKeyA, 0x04}, {CodeKeyZ, 0x1D}, {CodeDigit1, 0x1E}, {CodeDigit0, 0x27}, {CodeEnter, 0x28},
|
||||
{CodeBackslash, 0x31}, {CodeSemicolon, 0x33}, {CodeCapsLock, 0x39}, {CodeF1, 0x3A}, {CodeF12, 0x45},
|
||||
{CodePrintScreen, 0x46}, {CodeScrollLock, 0x47}, {CodePause, 0x48}, {CodeArrowUp, 0x52},
|
||||
{CodeNumLock, 0x53}, {CodeNumpadEnter, 0x58}, {CodeNumpad1, 0x59}, {CodeNumpad0, 0x62},
|
||||
{CodeIntlBackslash, 0x64}, {CodeContextMenu, 0x65}, {CodeNumpadEqual, 0x67}, {CodeF13, 0x68},
|
||||
{CodeF24, 0x73}, {CodeAudioVolumeMute, 0x7F}, {CodeAudioVolumeDown, 0x81}, {CodeNumpadComma, 0x85},
|
||||
{CodeControlLeft, 0xE0}, {CodeShiftLeft, 0xE1}, {CodeAltLeft, 0xE2}, {CodeSuperLeft, 0xE3},
|
||||
{CodeControlRight, 0xE4}, {CodeShiftRight, 0xE5}, {CodeAltRight, 0xE6}, {CodeSuperRight, 0xE7},
|
||||
} {
|
||||
if uint16(c.code) != c.usage {
|
||||
t.Errorf("code %#x, want usage %#x", uint16(c.code), c.usage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Each system's code of the same key gives the same KeyCode.
|
||||
func TestKeyCodeTables(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
want KeyCode
|
||||
evdev uint16
|
||||
xt uint8
|
||||
xtExt bool
|
||||
mac uint16
|
||||
dom string
|
||||
noMac bool // a Mac's keyboard has no such key
|
||||
}{
|
||||
{name: "A", want: CodeKeyA, evdev: 30, xt: 0x1E, mac: 0x00, dom: "KeyA"},
|
||||
{name: "5", want: CodeDigit5, evdev: 6, xt: 0x06, mac: 0x17, dom: "Digit5"},
|
||||
{name: "0", want: CodeDigit0, evdev: 11, xt: 0x0B, mac: 0x1D, dom: "Digit0"},
|
||||
{name: "Caps Lock", want: CodeCapsLock, evdev: 58, xt: 0x3A, mac: 0x39, dom: "CapsLock"},
|
||||
{name: "left Shift", want: CodeShiftLeft, evdev: 42, xt: 0x2A, mac: 0x38, dom: "ShiftLeft"},
|
||||
{name: "right Shift", want: CodeShiftRight, evdev: 54, xt: 0x36, mac: 0x3C, dom: "ShiftRight"},
|
||||
{name: "left Control", want: CodeControlLeft, evdev: 29, xt: 0x1D, mac: 0x3B, dom: "ControlLeft"},
|
||||
{name: "right Control", want: CodeControlRight, evdev: 97, xt: 0x1D, xtExt: true, mac: 0x3E, dom: "ControlRight"},
|
||||
{name: "left Alt", want: CodeAltLeft, evdev: 56, xt: 0x38, mac: 0x3A, dom: "AltLeft"},
|
||||
{name: "right Alt", want: CodeAltRight, evdev: 100, xt: 0x38, xtExt: true, mac: 0x3D, dom: "AltRight"},
|
||||
{name: "left Super", want: CodeSuperLeft, evdev: 125, xt: 0x5B, xtExt: true, mac: 0x37, dom: "MetaLeft"},
|
||||
{name: "right Super", want: CodeSuperRight, evdev: 126, xt: 0x5C, xtExt: true, mac: 0x36, dom: "MetaRight"},
|
||||
{name: "keypad 0", want: CodeNumpad0, evdev: 82, xt: 0x52, mac: 0x52, dom: "Numpad0"},
|
||||
{name: "keypad 7", want: CodeNumpad7, evdev: 71, xt: 0x47, mac: 0x59, dom: "Numpad7"},
|
||||
{name: "keypad /", want: CodeNumpadDivide, evdev: 98, xt: 0x35, xtExt: true, mac: 0x4B, dom: "NumpadDivide"},
|
||||
{name: "keypad *", want: CodeNumpadMultiply, evdev: 55, xt: 0x37, mac: 0x43, dom: "NumpadMultiply"},
|
||||
{name: "keypad Enter", want: CodeNumpadEnter, evdev: 96, xt: 0x1C, xtExt: true, mac: 0x4C, dom: "NumpadEnter"},
|
||||
{name: "Num Lock", want: CodeNumLock, evdev: 69, xt: 0x45, xtExt: true, mac: 0x47, dom: "NumLock"},
|
||||
{name: "Pause", want: CodePause, evdev: 119, xt: 0x45, noMac: true, dom: "Pause"},
|
||||
{name: "Print Screen", want: CodePrintScreen, evdev: 99, xt: 0x37, xtExt: true, noMac: true, dom: "PrintScreen"},
|
||||
{name: "Scroll Lock", want: CodeScrollLock, evdev: 70, xt: 0x46, noMac: true, dom: "ScrollLock"},
|
||||
{name: "102nd key", want: CodeIntlBackslash, evdev: 86, xt: 0x56, mac: 0x0A, dom: "IntlBackslash"},
|
||||
{name: "Home", want: CodeHome, evdev: 102, xt: 0x47, xtExt: true, mac: 0x73, dom: "Home"},
|
||||
{name: "Delete", want: CodeDelete, evdev: 111, xt: 0x53, xtExt: true, mac: 0x75, dom: "Delete"},
|
||||
{name: "up", want: CodeArrowUp, evdev: 103, xt: 0x48, xtExt: true, mac: 0x7E, dom: "ArrowUp"},
|
||||
{name: "F1", want: CodeF1, evdev: 59, xt: 0x3B, mac: 0x7A, dom: "F1"},
|
||||
{name: "F12", want: CodeF12, evdev: 88, xt: 0x58, mac: 0x6F, dom: "F12"},
|
||||
{name: "F13", want: CodeF13, evdev: 183, xt: 0x64, mac: 0x69, dom: "F13"},
|
||||
{name: "context menu", want: CodeContextMenu, evdev: 127, xt: 0x5D, xtExt: true, mac: 0x6E, dom: "ContextMenu"},
|
||||
} {
|
||||
if got := KeyCodeForEvdev(c.evdev); got != c.want {
|
||||
t.Errorf("%s: evdev %d gives %#x, want %#x", c.name, c.evdev, got, c.want)
|
||||
}
|
||||
if got := KeyCodeForXT(c.xt, c.xtExt); got != c.want {
|
||||
t.Errorf("%s: XT %#x (extended %v) gives %#x, want %#x", c.name, c.xt, c.xtExt, got, c.want)
|
||||
}
|
||||
if !c.noMac {
|
||||
if got := KeyCodeForMac(c.mac); got != c.want {
|
||||
t.Errorf("%s: macOS %#x gives %#x, want %#x", c.name, c.mac, got, c.want)
|
||||
}
|
||||
}
|
||||
if got := KeyCodeForDOM(c.dom); got != c.want {
|
||||
t.Errorf("%s: DOM %q gives %#x, want %#x", c.name, c.dom, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyCodeUnmapped(t *testing.T) {
|
||||
if got := KeyCodeForEvdev(0); got != CodeUnknown {
|
||||
t.Errorf("evdev 0: %#x", got)
|
||||
}
|
||||
if got := KeyCodeForEvdev(1000); got != CodeUnknown {
|
||||
t.Errorf("evdev 1000: %#x", got)
|
||||
}
|
||||
if got := KeyCodeForXT(0, false); got != CodeUnknown {
|
||||
t.Errorf("XT 0: %#x", got)
|
||||
}
|
||||
if got := KeyCodeForXT(0x10, true); got != CodeUnknown {
|
||||
t.Errorf("extended XT 0x10: %#x", got)
|
||||
}
|
||||
if got := KeyCodeForMac(0x3F); got != CodeUnknown { // Fn
|
||||
t.Errorf("macOS Fn: %#x", got)
|
||||
}
|
||||
for _, code := range []string{"", "Unidentified", "Keya", "Digit", "F", "F0", "F25", "Fn", "Numpad", "NumpadX"} {
|
||||
if got := KeyCodeForDOM(code); got != CodeUnknown {
|
||||
t.Errorf("DOM %q: %#x", code, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Windows's codes that differ from the keyboard's: Alt+Print Screen,
|
||||
// Ctrl+Pause, and right Shift under a CJK input method.
|
||||
func TestKeyCodeWindowsQuirks(t *testing.T) {
|
||||
if got := KeyCodeForXT(0x54, false); got != CodePrintScreen {
|
||||
t.Errorf("Alt+Print Screen: %#x", got)
|
||||
}
|
||||
if got := KeyCodeForXT(0x46, true); got != CodePause {
|
||||
t.Errorf("Ctrl+Pause: %#x", got)
|
||||
}
|
||||
if got := KeyCodeForXT(0x36, true); got != CodeShiftRight {
|
||||
t.Errorf("right Shift with the extended bit: %#x", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMacFlagsChanged(t *testing.T) {
|
||||
const shift, command = 1 << 17, 1 << 20
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
keyCode uint16
|
||||
flags uint
|
||||
code KeyCode
|
||||
down bool
|
||||
}{
|
||||
{"left Command down", 0x37, command | 0x08, CodeSuperLeft, true},
|
||||
{"left Command up", 0x37, 0, CodeSuperLeft, false},
|
||||
{"right Command down", 0x36, command | 0x10, CodeSuperRight, true},
|
||||
{"right Shift down, left held", 0x3C, shift | 0x02 | 0x04, CodeShiftRight, true},
|
||||
{"right Shift up, left held", 0x3C, shift | 0x02, CodeShiftRight, false},
|
||||
{"left Shift up, right held", 0x38, shift | 0x04, CodeShiftLeft, false},
|
||||
{"made by a program, no sides", 0x38, shift, CodeShiftLeft, true},
|
||||
{"made by a program, up", 0x38, 0, CodeShiftLeft, false},
|
||||
{"right Option down", 0x3D, 1<<19 | 0x40, CodeAltRight, true},
|
||||
{"right Control down", 0x3E, 1<<18 | 0x2000, CodeControlRight, true},
|
||||
{"right Control up, left held", 0x3E, 1<<18 | 0x01, CodeControlRight, false},
|
||||
{"Caps Lock on", 0x39, 1 << 16, CodeCapsLock, true},
|
||||
{"Caps Lock off", 0x39, 0, CodeCapsLock, true},
|
||||
{"Fn", 0x3F, 1 << 23, CodeUnknown, false},
|
||||
{"of no modifier", 0x00, command | 0x08, CodeUnknown, false},
|
||||
} {
|
||||
code, down := MacFlagsChanged(c.keyCode, c.flags)
|
||||
if code != c.code || down != c.down {
|
||||
t.Errorf("%s: got %#x %v, want %#x %v", c.name, code, down, c.code, c.down)
|
||||
}
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package platform
|
||||
|
||||
// MenuIconSize is the box, in points (DIPs), that a menu item's icon is
|
||||
// drawn to fit, keeping its aspect: the size of the icons of the
|
||||
// system's own menus on macOS, Windows and Linux.
|
||||
const MenuIconSize = 16
|
||||
|
||||
// MenuIcon is the image a menu item shows beside its label. Package mygo
|
||||
// shares one between the snapshots of the items showing the same image,
|
||||
// and makes a new one when an item's image changes, so a backend tells a
|
||||
// change by the pointer and decodes each image once (Native).
|
||||
type MenuIcon struct {
|
||||
// PNG is the image, its bytes never changed once made.
|
||||
PNG []byte
|
||||
// Template is a black and transparent image, which takes the color of
|
||||
// the menu's text where the backend can tint it.
|
||||
Template bool
|
||||
|
||||
native any
|
||||
made bool
|
||||
}
|
||||
|
||||
// Native returns what make made of the icon the first time it was asked:
|
||||
// a backend's decoding of it, kept for as long as the icon is, which
|
||||
// make may free with runtime.AddCleanup. A nil result is kept too, as an
|
||||
// image that cannot be decoded. Backends call it on the main thread.
|
||||
func (ic *MenuIcon) Native(make func() any) any {
|
||||
if !ic.made {
|
||||
ic.native, ic.made = make(), true
|
||||
}
|
||||
return ic.native
|
||||
}
|
||||
|
||||
// FitIcon returns the size of an image of w by h pixels drawn to fit a box
|
||||
// of box by box pixels, keeping its aspect, at least a pixel each way.
|
||||
func FitIcon(w, h, box int) (int, int) {
|
||||
if w <= 0 || h <= 0 || box <= 0 {
|
||||
return 0, 0
|
||||
}
|
||||
if w >= h {
|
||||
return box, max(1, (h*box+w/2)/w)
|
||||
}
|
||||
return max(1, (w*box+h/2)/h), box
|
||||
}
|
||||
|
||||
// LabelWithSubtitle is the label of a backend that can't show the subtitle
|
||||
// on a line of its own.
|
||||
func (it *MenuItem) LabelWithSubtitle() string {
|
||||
if it.Subtitle == "" {
|
||||
return it.Label
|
||||
}
|
||||
return it.Label + " — " + it.Subtitle
|
||||
}
|
||||
|
||||
// LabelWithBadge is the label of a backend that shows the subtitle on a
|
||||
// line of its own, followed by the badge.
|
||||
func (it *MenuItem) LabelWithBadge() string {
|
||||
if it.Badge == "" {
|
||||
return it.Label
|
||||
}
|
||||
return it.Label + " " + it.Badge
|
||||
}
|
||||
|
||||
// LabelWithSubtitleAndBadge is the label of a backend that can show neither
|
||||
// the subtitle nor the badge on its own: both follow the label.
|
||||
func (it *MenuItem) LabelWithSubtitleAndBadge() string {
|
||||
label := it.LabelWithSubtitle()
|
||||
if it.Badge == "" {
|
||||
return label
|
||||
}
|
||||
return label + " " + it.Badge
|
||||
}
|
||||
|
||||
// Apply gives the items of the menu that it is a snapshot of, by ID, its
|
||||
// state: a backend that keeps a snapshot to build menus from later (a
|
||||
// tray's, the application menu for new windows) keeps it current with the
|
||||
// updates it is given.
|
||||
func (m *Menu) Apply(it *MenuItem) {
|
||||
if m == nil {
|
||||
return
|
||||
}
|
||||
for i, x := range m.Items {
|
||||
if x.ID == it.ID {
|
||||
c := *it
|
||||
m.Items[i] = &c
|
||||
continue
|
||||
}
|
||||
x.Submenu.Apply(it)
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package platform
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestFitIcon(t *testing.T) {
|
||||
for _, c := range []struct{ w, h, box, ww, wh int }{
|
||||
{16, 16, 16, 16, 16},
|
||||
{64, 64, 32, 32, 32},
|
||||
{60, 40, 16, 16, 11}, // a 3:2 flag
|
||||
{40, 60, 16, 11, 16},
|
||||
{4, 3, 24, 24, 18},
|
||||
{200, 1, 16, 16, 1}, // never thinner than a pixel
|
||||
{0, 10, 16, 0, 0},
|
||||
} {
|
||||
if w, h := FitIcon(c.w, c.h, c.box); w != c.ww || h != c.wh {
|
||||
t.Errorf("FitIcon(%d, %d, %d) = %d, %d, want %d, %d", c.w, c.h, c.box, w, h, c.ww, c.wh)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMenuIconNativeOnce(t *testing.T) {
|
||||
ic := &MenuIcon{PNG: []byte{1}}
|
||||
n := 0
|
||||
make := func() any { n++; return nil }
|
||||
ic.Native(make)
|
||||
ic.Native(make)
|
||||
if n != 1 {
|
||||
t.Errorf("made %d times, want once, a failure kept too", n)
|
||||
}
|
||||
}
|
||||
|
||||
// Apply keeps a snapshot a backend builds menus from later current.
|
||||
func TestMenuApply(t *testing.T) {
|
||||
icon := &MenuIcon{PNG: []byte{1}}
|
||||
m := &Menu{Items: []*MenuItem{
|
||||
{ID: 1, Label: "A"},
|
||||
{ID: 2, Label: "Sub", Type: MenuItemSubmenu, Submenu: &Menu{Items: []*MenuItem{
|
||||
{ID: 3, Label: "B", Type: MenuItemRadio},
|
||||
}}},
|
||||
}}
|
||||
old := m.Items[1].Submenu.Items[0]
|
||||
m.Apply(&MenuItem{ID: 3, Label: "B", Type: MenuItemRadio, Checked: true, Icon: icon})
|
||||
got := m.Items[1].Submenu.Items[0]
|
||||
if !got.Checked || got.Icon != icon {
|
||||
t.Errorf("item 3 = %+v, want checked with the icon", got)
|
||||
}
|
||||
if old.Checked {
|
||||
t.Error("Apply changed the item it replaced, which a menu being built may hold")
|
||||
}
|
||||
if m.Items[0].Label != "A" {
|
||||
t.Error("Apply changed another item")
|
||||
}
|
||||
(*Menu)(nil).Apply(got) // no menu, nothing to do
|
||||
}
|
||||
|
||||
// TestLabelWithSubtitleAndBadge checks the fallback of platforms that draw
|
||||
// neither the subtitle nor the badge on its own.
|
||||
func TestLabelWithSubtitleAndBadge(t *testing.T) {
|
||||
if got := (&MenuItem{Label: "Node"}).LabelWithBadge(); got != "Node" {
|
||||
t.Errorf("label without badge = %q", got)
|
||||
}
|
||||
if got := (&MenuItem{Label: "Node", Badge: "120 ms"}).LabelWithBadge(); got != "Node 120 ms" {
|
||||
t.Errorf("label with badge = %q", got)
|
||||
}
|
||||
if got := (&MenuItem{Label: "Node", Subtitle: "Hong Kong"}).LabelWithSubtitleAndBadge(); got != "Node — Hong Kong" {
|
||||
t.Errorf("label with subtitle = %q", got)
|
||||
}
|
||||
if got := (&MenuItem{Label: "Node", Subtitle: "Hong Kong", Badge: "120 ms"}).LabelWithSubtitleAndBadge(); got != "Node — Hong Kong 120 ms" {
|
||||
t.Errorf("label with subtitle and badge = %q", got)
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package platform
|
||||
|
||||
// TogglePictureInPicture is the script that moves the page's video into
|
||||
// picture in picture, or the one out back, for backends whose web view
|
||||
// has no call for it: the video playing, else the largest that loaded, of
|
||||
// the page's document. It runs as a user's gesture, which
|
||||
// requestPictureInPicture() needs.
|
||||
const TogglePictureInPicture = `(() => {
|
||||
if (document.pictureInPictureElement) {
|
||||
document.exitPictureInPicture().catch(() => {});
|
||||
return;
|
||||
}
|
||||
let video, most = -1;
|
||||
for (const v of document.querySelectorAll("video")) {
|
||||
if (v.disablePictureInPicture || v.readyState === 0) continue;
|
||||
const r = v.getBoundingClientRect(), score = (v.paused ? 0 : 1e9) + r.width * r.height;
|
||||
if (score > most) { video = v; most = score; }
|
||||
}
|
||||
if (video) video.requestPictureInPicture().catch(() => {});
|
||||
})()`
|
||||
|
||||
// PictureInPictureActive is the body of an async function that tells
|
||||
// whether a video of the page's document is in picture in picture: "true"
|
||||
// or "false".
|
||||
const PictureInPictureActive = "return String(!!document.pictureInPictureElement)"
|
||||
+1662
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,60 @@
|
||||
package platform
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestKeyForScancode(t *testing.T) {
|
||||
// Linux evdev KEY_* and Windows XT set 1 values of the main block.
|
||||
want := map[uint16]Key{
|
||||
2: Key1, 11: Key0, 12: KeyMinus, 13: KeyEqual,
|
||||
16: KeyQ, 25: KeyP, 26: KeyBracketLeft, 27: KeyBracketRight,
|
||||
30: KeyA, 31: KeyS, 38: KeyL, 39: KeySemicolon, 40: KeyQuote, 41: KeyBackquote, 43: KeyBackslash,
|
||||
44: KeyZ, 50: KeyM, 51: KeyComma, 52: KeyPeriod, 53: KeySlash,
|
||||
}
|
||||
for code, k := range want {
|
||||
if got := KeyForScancode(code); got != k {
|
||||
t.Errorf("scancode %d: got %v, want %v", code, got, k)
|
||||
}
|
||||
}
|
||||
// Escape, Backspace, Tab, Enter, Control, Shift, Space, the keypad.
|
||||
for _, code := range []uint16{0, 1, 14, 15, 28, 29, 42, 54, 55, 57, 71, 255} {
|
||||
if got := KeyForScancode(code); got != KeyUnknown {
|
||||
t.Errorf("scancode %d: got %v, want KeyUnknown", code, got)
|
||||
}
|
||||
}
|
||||
seen := map[Key]bool{}
|
||||
for code, k := range scancodeKeys {
|
||||
if seen[k] {
|
||||
t.Errorf("scancode %d: key %v mapped twice", code, k)
|
||||
}
|
||||
seen[k] = true
|
||||
}
|
||||
if len(scancodeKeys) != 26+10+11 {
|
||||
t.Errorf("scancodeKeys has %d entries, want 47", len(scancodeKeys))
|
||||
}
|
||||
}
|
||||
|
||||
func TestKeyByPosition(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
key, physical Key
|
||||
mods Modifiers
|
||||
want bool
|
||||
}{
|
||||
{"cyrillic chord", KeyUnknown, KeyS, ModCtrl, true},
|
||||
{"cyrillic super", KeyUnknown, KeyS, ModSuper, true},
|
||||
{"cyrillic alt", KeyUnknown, KeyS, ModAlt, true},
|
||||
{"cyrillic typing", KeyUnknown, KeyS, 0, false},
|
||||
{"cyrillic shifted typing", KeyUnknown, KeyS, ModShift, false},
|
||||
{"shifted exclamation chord", KeyForRune('!'), Key1, ModCtrl | ModShift, true},
|
||||
{"shifted plus chord", KeyForRune('+'), KeyEqual, ModCtrl | ModShift, true},
|
||||
{"German sharp S chord", KeyForRune('ß'), KeyMinus, ModCtrl, true},
|
||||
{"latin chord keeps the layout key", KeyS, KeyS, ModCtrl, false},
|
||||
{"known AZERTY layout key", KeyQ, KeyA, ModCtrl, false},
|
||||
{"known QWERTZ layout key", KeyZ, KeyY, ModCtrl, false},
|
||||
{"unmapped position", KeyUnknown, KeyUnknown, ModCtrl, false},
|
||||
} {
|
||||
if got := KeyByPosition(c.key, c.physical, c.mods); got != c.want {
|
||||
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+870
@@ -0,0 +1,870 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo/transfer"
|
||||
"image"
|
||||
)
|
||||
|
||||
// Surface is the drawing area of a window created with
|
||||
// WindowOptions.Surface, which shows content MyGo draws itself (package
|
||||
// ui) instead of a webview. Its methods run on the main thread.
|
||||
type Surface interface {
|
||||
// Native returns the native objects a GPU renderer draws into, which it
|
||||
// calls before making one: a surface that shows frames drawn in memory
|
||||
// through those objects (Windows' Composed) lets go of them then.
|
||||
Native() SurfaceNative
|
||||
// Size returns the size of the drawing area in DIPs and how many
|
||||
// device pixels a DIP is.
|
||||
Size() (width, height, scale float64)
|
||||
// RequestFrame asks for a SurfaceFrame event at the next opportunity
|
||||
// to draw: the next display refresh, WM_PAINT or GTK draw. Requests
|
||||
// made before it comes coalesce.
|
||||
RequestFrame()
|
||||
// RefreshRate returns how many times a second the display showing the
|
||||
// surface refreshes, at most, 0 when unknown.
|
||||
RefreshRate() float64
|
||||
// PresentPixels shows a frame drawn in memory: premultiplied BGRA rows
|
||||
// of stride bytes, width×height device pixels. It is called while
|
||||
// handling a SurfaceFrame event.
|
||||
PresentPixels(pix []byte, stride, width, height int)
|
||||
// SetCursor sets the pointer's shape over the surface.
|
||||
SetCursor(c Cursor)
|
||||
// SetTextInput turns text input (IME composition) on for an editable
|
||||
// element, telling input methods where its caret is and the text
|
||||
// around it, or off.
|
||||
SetTextInput(t TextInputState)
|
||||
// UpdateAccessibility gives assistive technology the content's
|
||||
// elements. The content calls it after every frame once the surface
|
||||
// sent AccessibilityOn.
|
||||
UpdateAccessibility(tree *AccessTree)
|
||||
// StartDataDrag starts a native transfer; CancelDataDrag cancels the
|
||||
// source owned by this surface. Both run on the main thread.
|
||||
StartDataDrag(DragRequest)
|
||||
CancelDataDrag()
|
||||
// SetDropFormats registers the formats the content can receive.
|
||||
SetDropFormats([]transfer.Format)
|
||||
// NewWebView creates a web view under the surface, hidden until
|
||||
// PlaceWebViews shows it. Of opts, the options of a webview apply
|
||||
// (UserScripts, Schemes, DevTools, UserAgent, Zoom, BackgroundColor,
|
||||
// Transparent); h hears of its page.
|
||||
NewWebView(opts *WindowOptions, h WindowHandler) (WebView, error)
|
||||
// PlaceWebViews shows the web views of the surface where the content's
|
||||
// last frame shows them, in the order it painted them, and hides the
|
||||
// others, which keep their pages. A press on one, which takes it,
|
||||
// comes as WebViewPress.
|
||||
PlaceWebViews(views []WebViewPlacement)
|
||||
}
|
||||
|
||||
// DamageSurface is a Surface that shows a frame drawn in memory by what
|
||||
// changed since the last one: Linux's, whose toolkit then repaints, and
|
||||
// the compositor takes, only that.
|
||||
type DamageSurface interface {
|
||||
// PresentDamage is PresentPixels for a frame that differs from the
|
||||
// last one presented only within damage, in device pixels.
|
||||
PresentDamage(pix []byte, stride, width, height int, damage []image.Rectangle)
|
||||
}
|
||||
|
||||
// OccludableSurface is a Surface that tells when nothing of it shows, as
|
||||
// when other windows cover its window, while the system may still give it
|
||||
// frames: the content then draws nothing that moves until it shows again.
|
||||
type OccludableSurface interface {
|
||||
// Occluded reports whether nothing of the surface shows on screen. The
|
||||
// surface sends SurfaceHidden as none of it shows any more, and
|
||||
// SurfaceShown once some of it shows again.
|
||||
Occluded() bool
|
||||
}
|
||||
|
||||
// WideGamutSurface is a Surface that tells whether its window's screen
|
||||
// shows colors outside the sRGB gamut (macOS's).
|
||||
type WideGamutSurface interface {
|
||||
// WideGamut reports whether the screen showing most of the window
|
||||
// shows colors outside the sRGB gamut, as Display P3 screens do.
|
||||
WideGamut() bool
|
||||
}
|
||||
|
||||
// GlassPlacement is where a surface shows the system's glass
|
||||
// (Surface.PlaceGlass), under its content, in DIPs from its top left.
|
||||
type GlassPlacement struct {
|
||||
// ID identifies the element showing the glass from one frame to the
|
||||
// next.
|
||||
ID uint64
|
||||
// Frame is the glass's box; Clip the part of it that shows.
|
||||
Frame, Clip RectF
|
||||
// Radii are the corners of the hole the content leaves, clockwise
|
||||
// from the top left, and CornerRadius the one the glass view takes,
|
||||
// where it takes one.
|
||||
Radii [4]float64
|
||||
CornerRadius float64
|
||||
// Style is NSGlassEffectView's style: 0 regular, 1 clear.
|
||||
Style int
|
||||
// Tint colors the glass, nil for none.
|
||||
Tint *Color
|
||||
}
|
||||
|
||||
// ViewSurface is a Surface that shows views of the platform's own under
|
||||
// it, as it shows web views: those of native modules (package native),
|
||||
// shown with ui.NativeView. macOS's surfaces are.
|
||||
type ViewSurface interface {
|
||||
// EmbedView puts view, an NSView on macOS, under the surface, hidden
|
||||
// until PlaceWebViews shows it as it shows a web view. The WebView it
|
||||
// returns stands for it there; of its Page, only what concerns a view
|
||||
// applies (Focus, TabInto, Close, which takes the view out of the
|
||||
// window and lets go of it). The surface keeps view while it shows it.
|
||||
EmbedView(view uintptr) (WebView, error)
|
||||
}
|
||||
|
||||
// GlassSurface is a Surface that draws the system's glass under its
|
||||
// content, as macOS 26's NSGlassEffectView does, where the content leaves a
|
||||
// hole.
|
||||
type GlassSurface interface {
|
||||
// NativeGlassSupported reports whether the system's glass is available.
|
||||
NativeGlassSupported() bool
|
||||
// PlaceGlass shows the glass where the content's last frame shows it,
|
||||
// and hides the rest.
|
||||
PlaceGlass(places []GlassPlacement)
|
||||
}
|
||||
|
||||
// MaterialSurface is a Surface whose window can show a material
|
||||
// (vibrancy) behind the content, wherever its frames are transparent.
|
||||
type MaterialSurface interface {
|
||||
// ShowsMaterial reports whether the window shows a material behind the
|
||||
// content now: what its frames leave transparent shows it, rather than
|
||||
// nothing.
|
||||
ShowsMaterial() bool
|
||||
}
|
||||
|
||||
// PacedSurface is a Surface whose frames following each other come at the
|
||||
// display's refreshes, marked Paced: a renderer that waits for the display
|
||||
// lets such a frame draw once the display can take it, with FrameNow.
|
||||
type PacedSurface interface {
|
||||
// FrameNow sends a SurfaceFrame at once, as a refresh would, for a
|
||||
// frame a Paced one left to draw.
|
||||
FrameNow()
|
||||
}
|
||||
|
||||
// RefreshSurface is a PacedSurface whose frames drawn in memory
|
||||
// (PresentPixels) show at once, and whose frames asked for (RequestFrame)
|
||||
// come at once, not at the display's refreshes, as Windows' do: after
|
||||
// each frame drawn in memory, the content waits for the next refresh off
|
||||
// the main thread, and Paced frames that come meanwhile wait for it.
|
||||
type RefreshSurface interface {
|
||||
// AwaitRefresh returns once the display shows its next refresh, or
|
||||
// at once when nothing is to show. It blocks, and is called from a
|
||||
// goroutine of its own, never the main thread.
|
||||
AwaitRefresh()
|
||||
}
|
||||
|
||||
// FrameRateSurface is a Surface that can have its display refresh less
|
||||
// often than it can while frames come at a lower rate, as macOS's display
|
||||
// links do on ProMotion displays.
|
||||
type FrameRateSurface interface {
|
||||
// SetFrameRate tells how many frames a second come from now on while
|
||||
// they follow each other, a whole fraction of RefreshRate, or 0 for
|
||||
// one each refresh.
|
||||
SetFrameRate(fps float64)
|
||||
}
|
||||
|
||||
// ImmediateFrameSurface is a Surface whose RequestFrame sends a
|
||||
// SurfaceFrame at once, as Windows' does, rather than at the display's next
|
||||
// refresh: a frame due at a later refresh waits on a timer instead.
|
||||
type ImmediateFrameSurface interface {
|
||||
// FramesAtOnce marks the surface.
|
||||
FramesAtOnce()
|
||||
}
|
||||
|
||||
// MaximizeButtonSurface is a Surface whose window makes the maximize
|
||||
// button its content draws (in a window without its own, as
|
||||
// WindowOptions.HideWindowButtons) the system's for the pointer: Windows
|
||||
// shows the snap layouts over it. Package ui reaches it only once a view
|
||||
// marks such a button (ui.Element.MaximizeButton), for apps that mark none
|
||||
// not to link it.
|
||||
type MaximizeButtonSurface interface {
|
||||
// SetMaximizeButton tells where the content shows the window's
|
||||
// maximize button, in DIPs from the top-left corner of the content.
|
||||
// The zero RectF is nowhere.
|
||||
SetMaximizeButton(r RectF)
|
||||
}
|
||||
|
||||
// InsetSurface is a Surface whose edges something covers, as the system's
|
||||
// bars, a display's cutout and the keyboard cover a phone's screen.
|
||||
type InsetSurface interface {
|
||||
// Insets are how far in from each edge the content is covered: the
|
||||
// content lays out inside them and paints its background under them.
|
||||
Insets() Insets
|
||||
}
|
||||
|
||||
// TouchSurface is a Surface of a touch screen, whose system has more to say
|
||||
// to fingers than pixels.
|
||||
type TouchSurface interface {
|
||||
// Haptic plays a haptic (DeviceBackend.Haptic).
|
||||
Haptic(kind string)
|
||||
// ShowEditMenu shows the system's menu of the editing commands named, of
|
||||
// "cut", "copy", "paste" and "selectAll", at a point in DIPs; they come as
|
||||
// SurfaceCommand.
|
||||
ShowEditMenu(x, y float64, actions []string)
|
||||
// ShowMagnifier shows the system's magnifier of what is at a point in
|
||||
// DIPs, as a finger drags a text handle, until HideMagnifier.
|
||||
ShowMagnifier(x, y float64)
|
||||
HideMagnifier()
|
||||
// SetBackAvailable tells whether the content takes the system's back:
|
||||
// without, it leaves the app, as the system's predictive back shows.
|
||||
SetBackAvailable(on bool)
|
||||
}
|
||||
|
||||
// StackSurface is a Surface whose window can show the pages of a Router as
|
||||
// the system's own stack of screens, as phones have: a navigation bar at
|
||||
// the top with the title of the page shown and a back button, and on iOS
|
||||
// the system's transitions and its swipe from the left edge
|
||||
// (ui.Router.SystemStack).
|
||||
type StackSurface interface {
|
||||
// CanStack reports whether the window can show a stack: a window of
|
||||
// its own scene, on an iPad, cannot.
|
||||
CanStack() bool
|
||||
// StackMoves reports whether the system moves the screens as they come
|
||||
// and go, as iOS does, and follows a finger going back: the content
|
||||
// then shows each page at once. Where it does not, as on Android, the
|
||||
// content moves its pages itself, under the system's bar.
|
||||
StackMoves() bool
|
||||
// SetStack shows screens as the stack: the first page and those
|
||||
// deeper, up to the one shown. The screens of the Keys the stack
|
||||
// shows stay; it pushes the screens after them, or pops back to them,
|
||||
// and replaces the others at once. It returns once the system took
|
||||
// what the surface shows for the screen going out of sight, so that
|
||||
// the frame presented next shows the page coming. No screens take the
|
||||
// stack away.
|
||||
SetStack(screens []StackScreen)
|
||||
// StackShown tells that the content presented the page the stack shows
|
||||
// last, after SetStack or SurfaceStackPopped.
|
||||
StackShown()
|
||||
}
|
||||
|
||||
// StackScreen is a screen of a StackSurface's stack: a page of a Router,
|
||||
// Key telling it apart from the other pages.
|
||||
type StackScreen struct {
|
||||
Key uint64
|
||||
Title string
|
||||
}
|
||||
|
||||
// PluginViewSurface is a Surface that holds native views of plugins' native
|
||||
// code, as it does web views: under it, where its frames leave holes. The
|
||||
// WebView of one has no page: only its place, its keyboard and Close do
|
||||
// anything.
|
||||
type PluginViewSurface interface {
|
||||
NewPluginView(viewType string, args []byte, h WindowHandler) (WebView, error)
|
||||
}
|
||||
|
||||
// IdleSurface is a Surface that can give back memory once frames stop.
|
||||
type IdleSurface interface {
|
||||
// Idle tells that no frame came for a while: the surface may give
|
||||
// back memory that drawing frames took and freed.
|
||||
Idle()
|
||||
}
|
||||
|
||||
// BackgroundSurface is a Surface told the color the content's frames fill
|
||||
// the window with, which its window shows where no frame of its size
|
||||
// shows yet: on Windows, DWM can show a window at its new size, as the
|
||||
// user drags its border, before the frame of that size, and would show
|
||||
// black where the window grew.
|
||||
type BackgroundSurface interface {
|
||||
// SetBackground sets the color, opaque, or transparent for none.
|
||||
SetBackground(c Color)
|
||||
}
|
||||
|
||||
// FirstFrameSurface is a Surface told when the content's first frame
|
||||
// reached it: a window made hidden draws that frame while hidden, which
|
||||
// no paint or refresh of the display asks for, and which makes it ready
|
||||
// to show. Windows' window also stays out of sight until then, rather
|
||||
// than show what it holds before, white.
|
||||
type FirstFrameSurface interface {
|
||||
// FirstFrame tells that the content presented its first frame. It is
|
||||
// called once, within the frame, before the window is told it is
|
||||
// ready to show.
|
||||
FirstFrame()
|
||||
}
|
||||
|
||||
// TextInputState is the state of the text input that has the keyboard,
|
||||
// for input methods.
|
||||
type TextInputState struct {
|
||||
// Active is true while an editable element has the keyboard.
|
||||
Active bool
|
||||
// Caret is the caret's rectangle, in DIPs relative to the surface.
|
||||
Caret RectF
|
||||
// Text is the input's text around the caret, and Start and End are the
|
||||
// selection in it, in runes: both the caret when nothing is selected.
|
||||
// Input methods read it to edit what was typed before, as the accents
|
||||
// of macOS's press and hold replace the letter they decorate.
|
||||
Text string
|
||||
Start, End int
|
||||
// Client supplies full text and geometry for a custom text element. The
|
||||
// Text/Start/End snapshot remains the plain-widget and TextCaret fallback.
|
||||
Client TextInputClient
|
||||
// NoInputMethod keeps input methods out while Active: keys type the
|
||||
// characters of the keyboard's layout as TextInput, and nothing is
|
||||
// composed, as winit's set_ime_allowed(false). Browsers cannot turn
|
||||
// input methods off, and ignore it.
|
||||
NoInputMethod bool
|
||||
// Traits describe the input to on-screen keyboards.
|
||||
Traits TextTraits
|
||||
// ShowKeyboard counts the requests for the on-screen keyboard to show,
|
||||
// as a finger taps the input again after the keyboard was dismissed
|
||||
// while it kept the focus.
|
||||
ShowKeyboard uint32
|
||||
}
|
||||
|
||||
// TextTraits describe a text input to on-screen keyboards, as phones have.
|
||||
// Other platforms ignore them. Zero values are the keyboard's defaults.
|
||||
type TextTraits struct {
|
||||
Keyboard KeyboardKind
|
||||
ReturnKey ReturnKeyKind
|
||||
Capitalize CapitalizeKind
|
||||
Autocorrect AutocorrectKind
|
||||
Autofill AutofillKind
|
||||
// Multiline and Secure tell a text area and a password field.
|
||||
Multiline, Secure bool
|
||||
}
|
||||
|
||||
// KeyboardKind is the layout of an on-screen keyboard.
|
||||
type KeyboardKind uint8
|
||||
|
||||
const (
|
||||
KeyboardDefault KeyboardKind = iota
|
||||
KeyboardEmail
|
||||
KeyboardNumber
|
||||
KeyboardDecimal
|
||||
KeyboardPhone
|
||||
KeyboardURL
|
||||
KeyboardSearch
|
||||
)
|
||||
|
||||
// ReturnKeyKind is what the return key of an on-screen keyboard says.
|
||||
type ReturnKeyKind uint8
|
||||
|
||||
const (
|
||||
ReturnDefault ReturnKeyKind = iota
|
||||
ReturnDone
|
||||
ReturnGo
|
||||
ReturnNext
|
||||
ReturnSearch
|
||||
ReturnSend
|
||||
)
|
||||
|
||||
// CapitalizeKind is what an on-screen keyboard capitalizes.
|
||||
type CapitalizeKind uint8
|
||||
|
||||
const (
|
||||
CapitalizeDefault CapitalizeKind = iota
|
||||
CapitalizeNone
|
||||
CapitalizeWords
|
||||
CapitalizeSentences
|
||||
CapitalizeCharacters
|
||||
)
|
||||
|
||||
// AutocorrectKind is whether an on-screen keyboard corrects what is typed.
|
||||
type AutocorrectKind uint8
|
||||
|
||||
const (
|
||||
AutocorrectDefault AutocorrectKind = iota
|
||||
AutocorrectOn
|
||||
AutocorrectOff
|
||||
)
|
||||
|
||||
// AutofillKind names what an input holds, for the system's passwords and
|
||||
// contacts.
|
||||
type AutofillKind uint8
|
||||
|
||||
const (
|
||||
AutofillNone AutofillKind = iota
|
||||
AutofillUsername
|
||||
AutofillPassword
|
||||
AutofillNewPassword
|
||||
AutofillOneTimeCode
|
||||
AutofillEmail
|
||||
AutofillName
|
||||
AutofillPhone
|
||||
AutofillAddress
|
||||
AutofillPostalCode
|
||||
AutofillCreditCard
|
||||
)
|
||||
|
||||
// SurfaceNative holds the native objects of a Surface.
|
||||
type SurfaceNative struct {
|
||||
// HWND is the surface's child window (Windows).
|
||||
HWND uintptr
|
||||
// Composed tells that the window has no redirection bitmap, which
|
||||
// would hide its material (Windows): a GPU renderer presents through
|
||||
// DirectComposition, with the frames' alpha, which the material shows
|
||||
// through.
|
||||
Composed bool
|
||||
// View is the surface's NSView and Layer its layer (macOS).
|
||||
View, Layer uintptr
|
||||
// Widget is the surface's GtkGLArea or GtkDrawingArea, and GLArea the
|
||||
// GtkGLArea while its render signal draws a frame with OpenGL, in the
|
||||
// context it made current (Linux).
|
||||
Widget, GLArea uintptr
|
||||
// Canvas is the number of the canvas's WebGL 2 context (package gl's
|
||||
// Context.ID), current while SurfaceFrame events are handled
|
||||
// (browsers).
|
||||
Canvas uintptr
|
||||
// Window is the surface's ANativeWindow, which an EGL context draws
|
||||
// into (Android); Layer is its CAMetalLayer on iOS.
|
||||
Window uintptr
|
||||
}
|
||||
|
||||
// RectF is a rectangle in DIPs with fractional coordinates.
|
||||
type RectF struct{ X, Y, W, H float64 }
|
||||
|
||||
// Contains reports whether the point is inside r.
|
||||
func (r RectF) Contains(x, y float64) bool {
|
||||
return x >= r.X && y >= r.Y && x < r.X+r.W && y < r.Y+r.H
|
||||
}
|
||||
|
||||
// Insets are how far in from each edge of a surface its content is
|
||||
// covered, in DIPs: by the system's bars, a display's cutout or rounded
|
||||
// corners, or the keyboard (phones).
|
||||
type Insets struct{ Top, Left, Bottom, Right float64 }
|
||||
|
||||
// SurfaceEventKind is the kind of a SurfaceEvent.
|
||||
type SurfaceEventKind uint8
|
||||
|
||||
const (
|
||||
// SurfaceFrame asks the content to draw a frame now.
|
||||
SurfaceFrame SurfaceEventKind = iota
|
||||
// SurfaceResize reports a new Size; a frame follows.
|
||||
SurfaceResize
|
||||
// PointerMove reports the pointer at X, Y.
|
||||
PointerMove
|
||||
// PointerDown and PointerUp report Button pressed or released at X,
|
||||
// Y; Clicks counts quick successive presses (2 for a double click),
|
||||
// by the system's double-click settings. A release may leave it 0, for
|
||||
// its press's.
|
||||
PointerDown
|
||||
PointerUp
|
||||
// PointerCancel reports that the system ended the pointer's press
|
||||
// without a release, as Pointer Events' pointercancel: every button
|
||||
// held is let go of, and no PointerUp follows for them. The content
|
||||
// commits nothing a release would. Backends send it when they lose the
|
||||
// press to the system (a browser's pointercancel, a window losing the
|
||||
// mouse capture or a pointer grab while a button is down, a menu's
|
||||
// loop taking the release), and the content ignores one while nothing
|
||||
// is pressed.
|
||||
PointerCancel
|
||||
// PointerLeave reports the pointer left the surface.
|
||||
PointerLeave
|
||||
// PointerScroll scrolls by DX, DY DIPs at X, Y: positive DY moves the
|
||||
// view down the content, as dragging a scroll bar's thumb down does.
|
||||
PointerScroll
|
||||
// PointerZoom zooms by Scale at X, Y, as pinching a touchpad does: 2
|
||||
// shows the content twice as large as it was.
|
||||
PointerZoom
|
||||
// KeyPressed and KeyReleased report Key with Mods; Repeat marks
|
||||
// auto-repeat.
|
||||
KeyPressed
|
||||
KeyReleased
|
||||
// ModifiersChanged reports the modifier keys held, Mods, as one of
|
||||
// them goes down or up on its own.
|
||||
ModifiersChanged
|
||||
// RawKeyPressed and RawKeyReleased report a key by its position, Code,
|
||||
// that KeyPressed and KeyReleased leave out: a modifier, a lock key, or
|
||||
// one the layout types no Key for. PhysicalKey is set where it can be,
|
||||
// Key never is. The content reports whether it took the press or the
|
||||
// release, which then goes no further in the system, as Alt opening
|
||||
// the window's menu bar.
|
||||
RawKeyPressed
|
||||
RawKeyReleased
|
||||
// TextInput inserts Text, typed or committed by an input method.
|
||||
TextInput
|
||||
// TextComposition shows Text as the input method's composition, its
|
||||
// caret at rune Caret; an empty Text ends the composition.
|
||||
TextComposition
|
||||
// SurfaceFocus and SurfaceBlur report the surface gaining or losing
|
||||
// the keyboard.
|
||||
SurfaceFocus
|
||||
SurfaceBlur
|
||||
// SurfaceCommand performs the edit command Text: "copy", "cut",
|
||||
// "paste", "pasteAndMatchStyle", "selectAll", "undo", "redo" or
|
||||
// "delete" (Edit menu roles), or a Format menu role's: "bold",
|
||||
// "italic", "underline", "strikethrough", "alignLeft", "alignCenter"
|
||||
// or "alignRight".
|
||||
SurfaceCommand
|
||||
// SurfaceCommandEnabled asks whether SurfaceCommand with Text would
|
||||
// act now, for a menu to enable its item: WindowHandler.SurfaceEvent
|
||||
// reports it.
|
||||
SurfaceCommandEnabled
|
||||
// FileDragOver reports files of another app dragged over X, Y, and
|
||||
// FileDragLeave that they left. FileDrop drops Files at X, Y.
|
||||
// WindowHandler.SurfaceEvent returns whether the content takes them
|
||||
// there.
|
||||
FileDragOver
|
||||
FileDragLeave
|
||||
FileDrop
|
||||
// AccessibilityOn reports that assistive technology asked about the
|
||||
// surface: the content calls UpdateAccessibility at once and after
|
||||
// every frame from then on.
|
||||
AccessibilityOn
|
||||
// AccessAction performs Action on the element ID of the accessibility
|
||||
// tree, with Text the value of AccessSetValue.
|
||||
AccessAction
|
||||
// SurfaceShown reports that some of an OccludableSurface shows again
|
||||
// after none did, and SurfaceHidden that none of it shows any more.
|
||||
SurfaceShown
|
||||
SurfaceHidden
|
||||
// DataDragOver queries a destination; DataDrop commits a transfer.
|
||||
// DataDragLeave clears its hover state. Drag carries the query/result.
|
||||
DataDragOver
|
||||
DataDragLeave
|
||||
DataDrop
|
||||
// SurfaceRenew reports that the native objects a GPU renderer draws
|
||||
// into changed (Surface.Native), as a window of Windows composes its
|
||||
// frames once it has web views: the content makes its renderer again.
|
||||
SurfaceRenew
|
||||
// WebViewPress reports that Button went down at X, Y on a web view
|
||||
// the content shows there (Surface.PlaceWebViews), which takes the
|
||||
// press and what follows: the content notes it, as popovers close for
|
||||
// a press outside them, but handles none of it.
|
||||
WebViewPress
|
||||
// WebViewTabOut reports that Tab moved the keyboard out of WebView
|
||||
// past its page's last element, or Shift+Tab (Mods) past its first:
|
||||
// the surface has the keyboard again, and the content moves the focus
|
||||
// on from the web view's element.
|
||||
WebViewTabOut
|
||||
// SurfaceLowMemory reports that the system is short of memory: the
|
||||
// content lets go of what it can make again.
|
||||
SurfaceLowMemory
|
||||
// SurfaceBackGesture reports the system's gesture of going back as it
|
||||
// goes, Android's predictive back: Text is "started", "progress" with
|
||||
// how far in Scale, from 0 to 1, or "cancelled"; going back comes as the
|
||||
// back key.
|
||||
SurfaceBackGesture
|
||||
// SurfaceScrollToTop reports a tap on iOS's status bar, which sends what
|
||||
// scrolls under it back to its top.
|
||||
SurfaceScrollToTop
|
||||
// SurfaceStackPopped reports that the user took screens off the stack
|
||||
// of StackSurface.SetStack, with its back button or a swipe: To is how
|
||||
// many screens stay.
|
||||
SurfaceStackPopped
|
||||
// WebViewKey reports Key with Mods, pressed in the page of WebView,
|
||||
// which has the keyboard, and which the page left unhandled: it did
|
||||
// not cancel it, type it into an editable element or compose with it,
|
||||
// and it is neither Tab nor a modifier key on its own. The content
|
||||
// takes it as if the web view's element had the focus, and the
|
||||
// keyboard stays with the page.
|
||||
WebViewKey
|
||||
// TouchDown, TouchMove, TouchUp and TouchCancel report a finger on a
|
||||
// touchscreen landing, moving, lifting or taken by the system (as for
|
||||
// an edge's gesture, where no TouchUp follows) at X, Y, with Pressure
|
||||
// and the size of its contact (Width, Height) where the device tells
|
||||
// them. ID tells the fingers down at once apart
|
||||
// from the TouchDown to the TouchUp or TouchCancel; it may be used
|
||||
// again after. They come besides the pointer events a backend makes of
|
||||
// the fingers (taps, scrolls, pinches), which they leave as they are:
|
||||
// the content tracks them only for elements that ask (ui.Element.Touches).
|
||||
// Windows (WM_POINTER), Linux (GDK's touch sequences) and browsers
|
||||
// (Pointer Events of pointerType touch) send them; macOS has no
|
||||
// touchscreen, and a trackpad's fingers are not points on the screen.
|
||||
TouchDown
|
||||
TouchMove
|
||||
TouchUp
|
||||
TouchCancel
|
||||
// DragRegionAt asks whether a finger landing at X, Y moves the
|
||||
// window, as the mouse's press does on a drag region of a title bar
|
||||
// the content draws (ui's DragWindow), but for one that scrolls, which
|
||||
// the finger scrolls: WindowHandler.SurfaceEvent reports it, and
|
||||
// changes nothing. A backend that makes taps of fingers itself
|
||||
// (TouchGesture), which press only as they lift, asks as a finger
|
||||
// lands, and leaves one that does to the system's mouse, whose press
|
||||
// moves the window (Windows).
|
||||
DragRegionAt
|
||||
)
|
||||
|
||||
// EditCommands are the menu roles of edit commands, which native UI takes as
|
||||
// a SurfaceCommand and answers SurfaceCommandEnabled for.
|
||||
var EditCommands = map[string]bool{
|
||||
"undo": true, "redo": true, "cut": true, "copy": true, "paste": true, "pasteAndMatchStyle": true,
|
||||
"delete": true, "selectAll": true,
|
||||
}
|
||||
|
||||
// SurfaceEvent is input on a Surface, or a change of it.
|
||||
type SurfaceEvent struct {
|
||||
Kind SurfaceEventKind
|
||||
// X and Y locate the pointer in DIPs relative to the surface.
|
||||
X, Y float64
|
||||
// Button is 0 for the primary button, 1 the secondary, 2 the middle.
|
||||
Button int
|
||||
Clicks int
|
||||
// DX and DY are scroll distances in DIPs; Precise marks touchpads and
|
||||
// other devices that scroll by pixels rather than by lines. Momentum
|
||||
// marks scrolling that continues after the fingers leave a touchpad.
|
||||
DX, DY float64
|
||||
Precise bool
|
||||
Momentum bool
|
||||
// Scale is PointerZoom's, and Rotation the radians clockwise two fingers
|
||||
// turned since the last, on touch screens.
|
||||
Scale, Rotation float64
|
||||
// Pointer is the device of PointerMove, PointerDown and PointerUp, as
|
||||
// Pointer Events' pointerType, and Pressure how hard a pen or a finger
|
||||
// presses, from 0 to 1, where the device tells: 0 where it does not,
|
||||
// as a mouse, which the content takes for Pointer Events' default.
|
||||
Pointer PointerKind
|
||||
Pressure float64
|
||||
// Width and Height are the size of a finger's contact with the
|
||||
// touchscreen in DIPs, of TouchDown and TouchMove, where the device
|
||||
// tells it: 0 where it does not.
|
||||
Width, Height float64
|
||||
Key Key
|
||||
// PhysicalKey is the key by its position on an ANSI US keyboard,
|
||||
// whatever the active layout types; KeyUnknown where the backend does
|
||||
// not report it. Key and PhysicalKey agree on a US layout.
|
||||
PhysicalKey Key
|
||||
// Code is the key by its position, on any keyboard and with the sides
|
||||
// of the modifiers told apart; CodeUnknown where the backend does not
|
||||
// report it. KeyPressed, KeyReleased and the raw keys have it.
|
||||
Code KeyCode
|
||||
Mods Modifiers
|
||||
Repeat bool
|
||||
Text string
|
||||
Caret int
|
||||
// Replace makes TextInput replace, and TextComposition compose over,
|
||||
// the runes From to To of the last TextInputState.Text, instead of the
|
||||
// selection.
|
||||
Replace bool
|
||||
From, To int
|
||||
// Files are the paths of FileDrop's files, or original native paths
|
||||
// for DataDrop's legacy file-listener fallback.
|
||||
Files []string
|
||||
Drag *DataDragEvent
|
||||
// ID and Action are AccessAction's; ID is also the finger of
|
||||
// TouchDown, TouchMove, TouchUp and TouchCancel.
|
||||
ID uint64
|
||||
Action AccessActionKind
|
||||
// WebView is WebViewTabOut's and WebViewKey's.
|
||||
WebView WebView
|
||||
// Canceled marks a PointerUp of a finger the system took away, as a second
|
||||
// finger or its own gesture does: it clicks nothing and throws nothing.
|
||||
Canceled bool
|
||||
// Touch marks pointer events of a finger on a touch screen, which
|
||||
// has no hover: a drag of one pans what scrolls under it, and no
|
||||
// pointer stays over the content after it lifts.
|
||||
Touch bool
|
||||
// Paced marks a SurfaceFrame of frames following each other at the
|
||||
// display's refreshes (PacedSurface): the content may draw it later,
|
||||
// once the display can take it, which it tells by returning true from
|
||||
// SurfaceEvent; the refreshes go on meanwhile.
|
||||
Paced bool
|
||||
}
|
||||
|
||||
// PointerKind is the kind of device of a pointer event.
|
||||
type PointerKind uint8
|
||||
|
||||
const (
|
||||
// PointerMouse is a mouse, or a touchpad, which moves the pointer as
|
||||
// one does.
|
||||
PointerMouse PointerKind = iota
|
||||
// PointerPen is a pen on a tablet or a screen, its eraser too.
|
||||
PointerPen
|
||||
// PointerTouch is a finger on a touchscreen.
|
||||
PointerTouch
|
||||
)
|
||||
|
||||
// Modifiers are the modifier keys held during an event.
|
||||
type Modifiers uint8
|
||||
|
||||
const (
|
||||
ModShift Modifiers = 1 << iota
|
||||
ModCtrl
|
||||
ModAlt
|
||||
// ModSuper is Command on macOS and the Windows key elsewhere.
|
||||
ModSuper
|
||||
)
|
||||
|
||||
// Key identifies a key. Letter and digit keys follow the keyboard layout:
|
||||
// KeyA is the key that types an a.
|
||||
type Key uint16
|
||||
|
||||
const (
|
||||
KeyUnknown Key = iota
|
||||
KeyEnter
|
||||
KeyEscape
|
||||
KeyBackspace
|
||||
KeyTab
|
||||
KeySpace
|
||||
KeyDelete
|
||||
KeyInsert
|
||||
KeyHome
|
||||
KeyEnd
|
||||
KeyPageUp
|
||||
KeyPageDown
|
||||
KeyLeft
|
||||
KeyRight
|
||||
KeyUp
|
||||
KeyDown
|
||||
KeyF1
|
||||
KeyF2
|
||||
KeyF3
|
||||
KeyF4
|
||||
KeyF5
|
||||
KeyF6
|
||||
KeyF7
|
||||
KeyF8
|
||||
KeyF9
|
||||
KeyF10
|
||||
KeyF11
|
||||
KeyF12
|
||||
KeyMinus
|
||||
KeyEqual
|
||||
KeyComma
|
||||
KeyPeriod
|
||||
KeySlash
|
||||
KeySemicolon
|
||||
KeyQuote
|
||||
KeyBracketLeft
|
||||
KeyBracketRight
|
||||
KeyBackslash
|
||||
KeyBackquote
|
||||
KeyContextMenu
|
||||
Key0
|
||||
Key1
|
||||
Key2
|
||||
Key3
|
||||
Key4
|
||||
Key5
|
||||
Key6
|
||||
Key7
|
||||
Key8
|
||||
Key9
|
||||
KeyA
|
||||
KeyB
|
||||
KeyC
|
||||
KeyD
|
||||
KeyE
|
||||
KeyF
|
||||
KeyG
|
||||
KeyH
|
||||
KeyI
|
||||
KeyJ
|
||||
KeyK
|
||||
KeyL
|
||||
KeyM
|
||||
KeyN
|
||||
KeyO
|
||||
KeyP
|
||||
KeyQ
|
||||
KeyR
|
||||
KeyS
|
||||
KeyT
|
||||
KeyU
|
||||
KeyV
|
||||
KeyW
|
||||
KeyX
|
||||
KeyY
|
||||
KeyZ
|
||||
// KeyBack and KeyForward go back and forward in a history: the side
|
||||
// buttons of a mouse, the keys of keyboards that have them, and on
|
||||
// macOS swipes between pages.
|
||||
KeyBack
|
||||
KeyForward
|
||||
)
|
||||
|
||||
// KeyForRune returns the key typing r unshifted, KeyUnknown for others.
|
||||
func KeyForRune(r rune) Key {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z':
|
||||
return KeyA + Key(r-'a')
|
||||
case r >= 'A' && r <= 'Z':
|
||||
return KeyA + Key(r-'A')
|
||||
case r >= '0' && r <= '9':
|
||||
return Key0 + Key(r-'0')
|
||||
}
|
||||
switch r {
|
||||
case '-':
|
||||
return KeyMinus
|
||||
case '=':
|
||||
return KeyEqual
|
||||
case ',':
|
||||
return KeyComma
|
||||
case '.':
|
||||
return KeyPeriod
|
||||
case '/':
|
||||
return KeySlash
|
||||
case ';':
|
||||
return KeySemicolon
|
||||
case '\'':
|
||||
return KeyQuote
|
||||
case '[':
|
||||
return KeyBracketLeft
|
||||
case ']':
|
||||
return KeyBracketRight
|
||||
case '\\':
|
||||
return KeyBackslash
|
||||
case '`':
|
||||
return KeyBackquote
|
||||
case ' ':
|
||||
return KeySpace
|
||||
}
|
||||
return KeyUnknown
|
||||
}
|
||||
|
||||
// scancodeKeys maps the scancodes of the letter, digit and punctuation keys
|
||||
// of an ANSI US keyboard to the key at that position. The main block's
|
||||
// codes are the same in Linux's evdev and in XT set 1, which Windows
|
||||
// reports.
|
||||
var scancodeKeys = map[uint16]Key{
|
||||
2: Key1, 3: Key2, 4: Key3, 5: Key4, 6: Key5, 7: Key6, 8: Key7, 9: Key8, 10: Key9, 11: Key0,
|
||||
12: KeyMinus, 13: KeyEqual,
|
||||
16: KeyQ, 17: KeyW, 18: KeyE, 19: KeyR, 20: KeyT, 21: KeyY, 22: KeyU, 23: KeyI, 24: KeyO, 25: KeyP,
|
||||
26: KeyBracketLeft, 27: KeyBracketRight,
|
||||
30: KeyA, 31: KeyS, 32: KeyD, 33: KeyF, 34: KeyG, 35: KeyH, 36: KeyJ, 37: KeyK, 38: KeyL,
|
||||
39: KeySemicolon, 40: KeyQuote, 41: KeyBackquote, 43: KeyBackslash,
|
||||
44: KeyZ, 45: KeyX, 46: KeyC, 47: KeyV, 48: KeyB, 49: KeyN, 50: KeyM,
|
||||
51: KeyComma, 52: KeyPeriod, 53: KeySlash,
|
||||
}
|
||||
|
||||
// KeyForScancode returns the key at a scancode's position on an ANSI US
|
||||
// keyboard, whatever the layout types (SurfaceEvent.PhysicalKey), or
|
||||
// KeyUnknown for a key it does not map. A scancode is Linux's evdev code
|
||||
// (the X keycode less 8) or Windows's XT set 1 code without the extended
|
||||
// flag.
|
||||
func KeyForScancode(code uint16) Key { return scancodeKeys[code] }
|
||||
|
||||
// KeyByPosition reports whether a key press whose layout key is key may
|
||||
// stand for its physical key: only when the layout types no US key, and a
|
||||
// shortcut modifier is held, so that typing stays on the layout.
|
||||
func KeyByPosition(key, physical Key, mods Modifiers) bool {
|
||||
return key == KeyUnknown && physical != KeyUnknown && mods&(ModCtrl|ModAlt|ModSuper) != 0
|
||||
}
|
||||
|
||||
// Cursor is a pointer shape.
|
||||
type Cursor uint8
|
||||
|
||||
const (
|
||||
CursorDefault Cursor = iota
|
||||
CursorPointer
|
||||
CursorText
|
||||
CursorMove
|
||||
CursorResizeEW
|
||||
CursorResizeNS
|
||||
CursorResizeNWSE
|
||||
CursorResizeNESW
|
||||
CursorNotAllowed
|
||||
CursorCrosshair
|
||||
CursorGrab
|
||||
CursorGrabbing
|
||||
CursorResizeN
|
||||
CursorResizeE
|
||||
CursorResizeS
|
||||
CursorResizeW
|
||||
CursorResizeColumn
|
||||
CursorResizeRow
|
||||
CursorVerticalText
|
||||
CursorCopy
|
||||
CursorAlias
|
||||
CursorContextMenu
|
||||
CursorNone
|
||||
CursorProgress
|
||||
CursorWait
|
||||
CursorHelp
|
||||
CursorCell
|
||||
CursorZoomIn
|
||||
CursorZoomOut
|
||||
CursorAllScroll
|
||||
CursorNoDrop
|
||||
)
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"unicode/utf16"
|
||||
)
|
||||
|
||||
// TextRange is a half-open range in UTF-16 code units of a text client's
|
||||
// document. Native input protocols use these units, independently of UTF-8
|
||||
// storage or the client's choice of buffer.
|
||||
type TextRange struct{ Start, End int }
|
||||
|
||||
// TextSelection is the primary selection exposed to input methods. A client
|
||||
// may own additional selections. Reversed puts the caret at Range.Start.
|
||||
type TextSelection struct {
|
||||
Range TextRange
|
||||
Reversed bool
|
||||
}
|
||||
|
||||
func (s TextSelection) Caret() int {
|
||||
if s.Reversed {
|
||||
return s.Range.Start
|
||||
}
|
||||
return s.Range.End
|
||||
}
|
||||
|
||||
// TextInputClient supplies a focused custom element's text to native input
|
||||
// methods. All calls are synchronous on the main thread. Ranges are absolute
|
||||
// UTF-16 document offsets, including marked text. Nil replacement ranges mean
|
||||
// the marked range, if present, otherwise the selection.
|
||||
type TextInputClient interface {
|
||||
TextForRange(TextRange) (string, TextRange)
|
||||
Selection() TextSelection
|
||||
MarkedRange() (TextRange, bool)
|
||||
ReplaceText(*TextRange, string)
|
||||
SetMarkedText(*TextRange, string, TextRange)
|
||||
UnmarkText()
|
||||
BoundsForRange(TextRange) (RectF, TextRange, bool)
|
||||
IndexForPoint(x, y float64) (int, bool)
|
||||
}
|
||||
|
||||
// TextSelectionSetter is a TextInputClient whose selection a native text
|
||||
// service may move, as phones' keyboards do with their space bar's cursor.
|
||||
type TextSelectionSetter interface {
|
||||
SetTextSelection(TextRange)
|
||||
}
|
||||
|
||||
// InputComposition preserves the native end-preedit/commit ordering without
|
||||
// owning text. Some input methods unmark before delivering their result.
|
||||
type InputComposition struct{ pending *TextRange }
|
||||
|
||||
func (c *InputComposition) Reset() { c.pending = nil }
|
||||
func (c *InputComposition) End(client TextInputClient) {
|
||||
if r, ok := client.MarkedRange(); ok {
|
||||
c.pending = &r
|
||||
}
|
||||
client.UnmarkText()
|
||||
}
|
||||
|
||||
// Cancel discards the marked text, for an input method that gives its
|
||||
// composition up without emptying it first. The rest of the document,
|
||||
// the selection included, stays as it is.
|
||||
func (c *InputComposition) Cancel(client TextInputClient) {
|
||||
c.pending = nil
|
||||
if _, ok := client.MarkedRange(); ok {
|
||||
client.SetMarkedText(nil, "", TextRange{})
|
||||
client.UnmarkText()
|
||||
}
|
||||
}
|
||||
func (c *InputComposition) Replace(client TextInputClient, r *TextRange, text string) {
|
||||
if r == nil && c.pending != nil {
|
||||
r = c.pending
|
||||
}
|
||||
c.pending = nil
|
||||
client.ReplaceText(r, text)
|
||||
}
|
||||
|
||||
// UTF16Len counts native text offsets without allocating an encoded string.
|
||||
func UTF16Len(s string) (n int) {
|
||||
for _, r := range s {
|
||||
n += utf16.RuneLen(r)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// UTF16ByteOffset rounds an offset inside a surrogate pair down to its rune.
|
||||
func UTF16ByteOffset(s string, offset int) int {
|
||||
for i, r := range s {
|
||||
if offset < utf16.RuneLen(r) {
|
||||
return i
|
||||
}
|
||||
offset -= utf16.RuneLen(r)
|
||||
}
|
||||
return len(s)
|
||||
}
|
||||
|
||||
func NormalizeTextRange(r TextRange) TextRange {
|
||||
r.Start, r.End = max(0, min(r.Start, r.End)), max(0, max(r.Start, r.End))
|
||||
return r
|
||||
}
|
||||
|
||||
// TextContext is a bounded window of a client document, with preedit removed
|
||||
// as GTK and IMM32 surrounding-text protocols expect. Positions in Text are
|
||||
// UTF-16 units; Range maps them back to the client's document.
|
||||
type TextContext struct {
|
||||
Text string
|
||||
Start, End int
|
||||
Caret int
|
||||
Base int
|
||||
mark TextRange
|
||||
hasMark bool
|
||||
}
|
||||
|
||||
func ClientTextContext(client TextInputClient) TextContext {
|
||||
return clientTextContext(client, 1024, 1024)
|
||||
}
|
||||
|
||||
func clientTextContext(client TextInputClient, before, after int) TextContext {
|
||||
sel := client.Selection()
|
||||
r := NormalizeTextRange(sel.Range)
|
||||
mark, marked := client.MarkedRange()
|
||||
if marked {
|
||||
mark = NormalizeTextRange(mark)
|
||||
r.Start, r.End = min(r.Start, mark.Start), max(r.End, mark.End)
|
||||
}
|
||||
// A selection may cover a huge document. Query a bounded window around
|
||||
// its active end; full text remains available through TextForRange.
|
||||
caret := max(0, sel.Caret())
|
||||
if marked {
|
||||
caret = mark.Start
|
||||
}
|
||||
wanted := TextRange{Start: max(0, caret-before), End: caret + after}
|
||||
if marked {
|
||||
wanted.Start, wanted.End = min(wanted.Start, mark.Start), max(wanted.End, mark.End)
|
||||
}
|
||||
text, actual := client.TextForRange(wanted)
|
||||
actual = NormalizeTextRange(actual)
|
||||
c := TextContext{Text: text, Base: actual.Start, mark: mark, hasMark: marked && mark.Start >= actual.Start && mark.End <= actual.End}
|
||||
if c.hasMark {
|
||||
a, z := UTF16ByteOffset(text, mark.Start-actual.Start), UTF16ByteOffset(text, mark.End-actual.Start)
|
||||
c.Text = text[:a] + text[z:]
|
||||
}
|
||||
local := func(i int) int {
|
||||
if c.hasMark {
|
||||
if i >= mark.End {
|
||||
i -= mark.End - mark.Start
|
||||
} else if i > mark.Start {
|
||||
i = mark.Start
|
||||
}
|
||||
}
|
||||
return max(0, min(i-c.Base, UTF16Len(c.Text)))
|
||||
}
|
||||
c.Start, c.End = local(r.Start), local(r.End)
|
||||
c.Caret = local(sel.Caret())
|
||||
if marked {
|
||||
c.Start, c.End = local(mark.Start), local(mark.Start)
|
||||
c.Caret = c.Start
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// Range maps a range of the surrounding text to the actual document. A
|
||||
// collapsed position at preedit stays collapsed; an explicit range crossing
|
||||
// it includes preedit, so replacement remains one client operation.
|
||||
func (c TextContext) Range(r TextRange) TextRange {
|
||||
r = NormalizeTextRange(r)
|
||||
n := UTF16Len(c.Text)
|
||||
r.Start, r.End = min(r.Start, n)+c.Base, min(r.End, n)+c.Base
|
||||
if c.hasMark {
|
||||
if r.Start > c.mark.Start {
|
||||
r.Start += c.mark.End - c.mark.Start
|
||||
}
|
||||
if r.End > c.mark.Start {
|
||||
r.End += c.mark.End - c.mark.Start
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// DeleteRange maps GTK character offsets around the selection's end, rather
|
||||
// than confusing Unicode characters with UTF-16 or UTF-8 offsets.
|
||||
func (c TextContext) DeleteRange(offset, count int) TextRange {
|
||||
caretByte := UTF16ByteOffset(c.Text, c.Caret)
|
||||
caretRune := len([]rune(c.Text[:caretByte]))
|
||||
runes := []rune(c.Text)
|
||||
a := max(0, min(caretRune+offset, len(runes)))
|
||||
z := max(a, min(a+max(count, 0), len(runes)))
|
||||
return c.Range(TextRange{Start: UTF16Len(string(runes[:a])), End: UTF16Len(string(runes[:z]))})
|
||||
}
|
||||
|
||||
// ClientDeleteRange can query beyond the usual surrounding window when an
|
||||
// input method asks to replace more text. GTK offsets count Unicode runes.
|
||||
func ClientDeleteRange(client TextInputClient, offset, count int) TextRange {
|
||||
before, after := max(0, -offset)*2, max(0, offset+max(count, 0))*2
|
||||
return clientTextContext(client, before, after).DeleteRange(offset, count)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package platform
|
||||
|
||||
import "unicode/utf16"
|
||||
|
||||
// RunesInUTF16 returns how many runes of s the first units UTF-16 units hold.
|
||||
func RunesInUTF16(s string, units int) int {
|
||||
n := 0
|
||||
for _, r := range s {
|
||||
if units <= 0 {
|
||||
break
|
||||
}
|
||||
units -= max(utf16.RuneLen(r), 1)
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package platform
|
||||
|
||||
import "sync/atomic"
|
||||
|
||||
// Texts are the words backends say of their own, in the language the app
|
||||
// shows, as package mygo sets them (SetTexts): the buttons of the panels
|
||||
// of pages' alert, confirm and prompt, the titles and buttons of file
|
||||
// dialogs, and the title of the about panel. Backends read them with
|
||||
// CurrentTexts from any thread.
|
||||
type Texts struct {
|
||||
OK, Cancel, Open, Save, SelectFolder string
|
||||
// About is the title of the about panel with "\x00" for the app's
|
||||
// name: "About \x00".
|
||||
About string
|
||||
}
|
||||
|
||||
// DefaultTexts are the texts in English, before package mygo sets others.
|
||||
var DefaultTexts = Texts{OK: "OK", Cancel: "Cancel", Open: "Open", Save: "Save", SelectFolder: "Select Folder", About: "About \x00"}
|
||||
|
||||
var texts atomic.Pointer[Texts]
|
||||
|
||||
// SetTexts sets the texts backends say.
|
||||
func SetTexts(t Texts) { texts.Store(&t) }
|
||||
|
||||
// CurrentTexts returns the texts backends say.
|
||||
func CurrentTexts() Texts {
|
||||
if t := texts.Load(); t != nil {
|
||||
return *t
|
||||
}
|
||||
return DefaultTexts
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"math"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// Fingers on a touchscreen do what the mouse and a touchpad do, as on
|
||||
// phones: a tap clicks where it lands, and one held there LongPress or
|
||||
// longer right-clicks, as Windows's press and hold does; a finger moving
|
||||
// further than TouchSlop scrolls the content under it along with it,
|
||||
// and two pinch to zoom between them and scroll as they move together.
|
||||
// The systems make the first finger the mouse, which pressed where it
|
||||
// landed and selected text as it moved: backends take the touches
|
||||
// instead and give them to a TouchGesture (GTK's touch events on Linux,
|
||||
// WM_POINTER's on Windows).
|
||||
const (
|
||||
TouchSlop = 8 // DIPs
|
||||
LongPress = 500 // milliseconds
|
||||
)
|
||||
|
||||
// TouchGesture follows the fingers on a surface, by ids the backend
|
||||
// gives them, and turns them into surface events. Its zero value has no
|
||||
// finger down.
|
||||
type TouchGesture struct {
|
||||
// fingers are down, in the order they landed; the first two count.
|
||||
fingers []touchFinger
|
||||
// tap tells that the only finger down stayed within TouchSlop of
|
||||
// where it landed, at startX, startY at time start.
|
||||
tap bool
|
||||
startX, startY float64
|
||||
start uint32
|
||||
// x, y is where the fingers last scrolled from: the finger, or the
|
||||
// midpoint of two, dist apart.
|
||||
x, y, dist float64
|
||||
}
|
||||
|
||||
type touchFinger struct {
|
||||
id uintptr
|
||||
x, y float64
|
||||
}
|
||||
|
||||
// Reset forgets the fingers down, as when the first finger of new
|
||||
// touches lands and those before ended unseen, as under a grab.
|
||||
func (g *TouchGesture) Reset() { g.fingers, g.tap = g.fingers[:0], false }
|
||||
|
||||
// Holds reports whether the finger id is down.
|
||||
func (g *TouchGesture) Holds(id uintptr) bool { return g.find(id) >= 0 }
|
||||
|
||||
// Begin puts a finger down at x, y, in DIPs, at time t, in milliseconds.
|
||||
func (g *TouchGesture) Begin(id uintptr, x, y float64, t uint32) []SurfaceEvent {
|
||||
if g.find(id) >= 0 {
|
||||
return nil
|
||||
}
|
||||
g.fingers = append(g.fingers, touchFinger{id, x, y})
|
||||
g.tap = len(g.fingers) == 1
|
||||
if g.tap {
|
||||
g.startX, g.startY, g.start = x, y, t
|
||||
}
|
||||
g.anchor()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Move moves a finger to x, y.
|
||||
func (g *TouchGesture) Move(id uintptr, x, y float64) []SurfaceEvent {
|
||||
i := g.find(id)
|
||||
if i < 0 {
|
||||
return nil
|
||||
}
|
||||
g.fingers[i].x, g.fingers[i].y = x, y
|
||||
var out []SurfaceEvent
|
||||
switch {
|
||||
case i >= 2:
|
||||
case len(g.fingers) == 1:
|
||||
if g.tap && math.Hypot(x-g.startX, y-g.startY) < TouchSlop {
|
||||
break
|
||||
}
|
||||
g.tap = false
|
||||
out = g.scroll(out, x, y)
|
||||
default:
|
||||
a, b := g.fingers[0], g.fingers[1]
|
||||
mx, my := (a.x+b.x)/2, (a.y+b.y)/2
|
||||
out = g.scroll(out, mx, my)
|
||||
if d := math.Hypot(a.x-b.x, a.y-b.y); d > 0 {
|
||||
if g.dist > 0 && d != g.dist {
|
||||
out = append(out, SurfaceEvent{Kind: PointerZoom, X: mx, Y: my, Scale: d / g.dist})
|
||||
}
|
||||
g.dist = d
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// End lifts a finger at x, y at time t; canceled, as when the system
|
||||
// takes the touch for its own gesture, it neither moves nor taps.
|
||||
func (g *TouchGesture) End(id uintptr, x, y float64, t uint32, canceled bool) []SurfaceEvent {
|
||||
i := g.find(id)
|
||||
if i < 0 {
|
||||
return nil
|
||||
}
|
||||
var out []SurfaceEvent
|
||||
if !canceled {
|
||||
out = g.Move(id, x, y)
|
||||
}
|
||||
g.fingers = slices.Delete(g.fingers, i, i+1)
|
||||
if len(g.fingers) > 0 {
|
||||
g.anchor()
|
||||
return out
|
||||
}
|
||||
if g.tap && !canceled {
|
||||
button := 0
|
||||
if t-g.start >= LongPress {
|
||||
button = 1
|
||||
}
|
||||
out = append(out,
|
||||
SurfaceEvent{Kind: PointerDown, X: g.startX, Y: g.startY, Button: button},
|
||||
SurfaceEvent{Kind: PointerUp, X: g.startX, Y: g.startY, Button: button})
|
||||
}
|
||||
g.tap = false
|
||||
// Nothing hovers once the fingers are gone.
|
||||
return append(out, SurfaceEvent{Kind: PointerLeave})
|
||||
}
|
||||
|
||||
// scroll scrolls the content at the last point along to x, y, following
|
||||
// the fingers: the other way from a scroll bar's thumb.
|
||||
func (g *TouchGesture) scroll(out []SurfaceEvent, x, y float64) []SurfaceEvent {
|
||||
if x != g.x || y != g.y {
|
||||
out = append(out, SurfaceEvent{Kind: PointerScroll, X: g.x, Y: g.y, DX: g.x - x, DY: g.y - y, Precise: true})
|
||||
}
|
||||
g.x, g.y = x, y
|
||||
return out
|
||||
}
|
||||
|
||||
// anchor scrolls and pinches from where the fingers are now.
|
||||
func (g *TouchGesture) anchor() {
|
||||
a := g.fingers[0]
|
||||
g.x, g.y, g.dist = a.x, a.y, 0
|
||||
if len(g.fingers) > 1 {
|
||||
b := g.fingers[1]
|
||||
g.x, g.y, g.dist = (a.x+b.x)/2, (a.y+b.y)/2, math.Hypot(a.x-b.x, a.y-b.y)
|
||||
}
|
||||
}
|
||||
|
||||
func (g *TouchGesture) find(id uintptr) int {
|
||||
return slices.IndexFunc(g.fingers, func(f touchFinger) bool { return f.id == id })
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"math"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestTouchGesture checks what fingers on a touchscreen do: taps click,
|
||||
// a finger dragging scrolls the content along with it, two pinch and
|
||||
// scroll (#797).
|
||||
func TestTouchGesture(t *testing.T) {
|
||||
type touch struct {
|
||||
kind byte // b begin, m move, e end, c cancel, r reset
|
||||
seq uintptr
|
||||
x, y float64
|
||||
ms uint32
|
||||
}
|
||||
down := func(x, y float64, button int) SurfaceEvent {
|
||||
return SurfaceEvent{Kind: PointerDown, X: x, Y: y, Button: button}
|
||||
}
|
||||
up := func(x, y float64, button int) SurfaceEvent {
|
||||
return SurfaceEvent{Kind: PointerUp, X: x, Y: y, Button: button}
|
||||
}
|
||||
scroll := func(x, y, dx, dy float64) SurfaceEvent {
|
||||
return SurfaceEvent{Kind: PointerScroll, X: x, Y: y, DX: dx, DY: dy, Precise: true}
|
||||
}
|
||||
zoom := func(x, y, scale float64) SurfaceEvent {
|
||||
return SurfaceEvent{Kind: PointerZoom, X: x, Y: y, Scale: scale}
|
||||
}
|
||||
leave := SurfaceEvent{Kind: PointerLeave}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
touches []touch
|
||||
want []SurfaceEvent
|
||||
}{
|
||||
{"tap", []touch{{kind: 'b', seq: 1, x: 10, y: 20}, {kind: 'e', seq: 1, x: 10, y: 20, ms: 100}},
|
||||
[]SurfaceEvent{down(10, 20, 0), up(10, 20, 0), leave}},
|
||||
{"tap within the slop", []touch{{kind: 'b', seq: 1, x: 10, y: 20}, {kind: 'm', seq: 1, x: 14, y: 24}, {kind: 'e', seq: 1, x: 15, y: 25, ms: 100}},
|
||||
[]SurfaceEvent{down(10, 20, 0), up(10, 20, 0), leave}},
|
||||
{"long press", []touch{{kind: 'b', seq: 1, x: 10, y: 20, ms: 1000}, {kind: 'e', seq: 1, x: 10, y: 20, ms: 1000 + LongPress}},
|
||||
[]SurfaceEvent{down(10, 20, 1), up(10, 20, 1), leave}},
|
||||
{"long press as the clock wraps", []touch{{kind: 'b', seq: 1, x: 10, y: 20, ms: 1<<32 - 100}, {kind: 'e', seq: 1, x: 10, y: 20, ms: 1000}},
|
||||
[]SurfaceEvent{down(10, 20, 1), up(10, 20, 1), leave}},
|
||||
{"canceled tap", []touch{{kind: 'b', seq: 1, x: 10, y: 20}, {kind: 'c', seq: 1, x: 10, y: 20, ms: 100}},
|
||||
[]SurfaceEvent{leave}},
|
||||
// Past the slop the content under the finger follows it, from
|
||||
// where it landed: dragging up scrolls down the content.
|
||||
{"drag", []touch{{kind: 'b', seq: 1, x: 100, y: 100}, {kind: 'm', seq: 1, x: 100, y: 95}, {kind: 'm', seq: 1, x: 100, y: 90}, {kind: 'm', seq: 1, x: 103, y: 70}, {kind: 'e', seq: 1, x: 103, y: 70, ms: 100}},
|
||||
[]SurfaceEvent{scroll(100, 100, 0, 10), scroll(100, 90, -3, 20), leave}},
|
||||
{"drag ending further", []touch{{kind: 'b', seq: 1, x: 100, y: 100}, {kind: 'm', seq: 1, x: 100, y: 80}, {kind: 'e', seq: 1, x: 100, y: 75}},
|
||||
[]SurfaceEvent{scroll(100, 100, 0, 20), scroll(100, 80, 0, 5), leave}},
|
||||
{"pinch", []touch{
|
||||
{kind: 'b', seq: 1, x: 100, y: 100}, {kind: 'b', seq: 2, x: 200, y: 100},
|
||||
{kind: 'm', seq: 2, x: 300, y: 100},
|
||||
{kind: 'm', seq: 1, x: 0, y: 100},
|
||||
{kind: 'e', seq: 1, x: 0, y: 100}, {kind: 'e', seq: 2, x: 300, y: 100},
|
||||
}, []SurfaceEvent{
|
||||
scroll(150, 100, -50, 0), zoom(200, 100, 2),
|
||||
scroll(200, 100, 50, 0), zoom(150, 100, 1.5),
|
||||
leave,
|
||||
}},
|
||||
{"two fingers scrolling", []touch{
|
||||
{kind: 'b', seq: 1, x: 100, y: 100}, {kind: 'b', seq: 2, x: 200, y: 100},
|
||||
{kind: 'm', seq: 1, x: 100, y: 60}, {kind: 'm', seq: 2, x: 200, y: 60},
|
||||
{kind: 'e', seq: 1, x: 100, y: 60}, {kind: 'e', seq: 2, x: 200, y: 60},
|
||||
}, []SurfaceEvent{
|
||||
scroll(150, 100, 0, 20), zoom(150, 80, math.Hypot(100, 40)/100),
|
||||
scroll(150, 80, 0, 20), zoom(150, 60, 100/math.Hypot(100, 40)),
|
||||
leave,
|
||||
}},
|
||||
// The finger left scrolls on from where it is, without a jump.
|
||||
{"pinch, then one finger", []touch{
|
||||
{kind: 'b', seq: 1, x: 100, y: 100}, {kind: 'b', seq: 2, x: 200, y: 100},
|
||||
{kind: 'e', seq: 2, x: 200, y: 100},
|
||||
{kind: 'm', seq: 1, x: 100, y: 101},
|
||||
{kind: 'e', seq: 1, x: 100, y: 101},
|
||||
}, []SurfaceEvent{scroll(100, 100, 0, -1), leave}},
|
||||
{"a second finger is no tap", []touch{
|
||||
{kind: 'b', seq: 1, x: 100, y: 100}, {kind: 'b', seq: 2, x: 200, y: 100},
|
||||
{kind: 'e', seq: 2, x: 200, y: 100}, {kind: 'e', seq: 1, x: 100, y: 100},
|
||||
}, []SurfaceEvent{leave}},
|
||||
{"a third finger does nothing", []touch{
|
||||
{kind: 'b', seq: 1, x: 100, y: 100}, {kind: 'b', seq: 2, x: 200, y: 100}, {kind: 'b', seq: 3, x: 50, y: 50},
|
||||
{kind: 'm', seq: 3, x: 0, y: 0},
|
||||
}, nil},
|
||||
{"unknown sequences", []touch{{kind: 'm', seq: 9, x: 1, y: 1}, {kind: 'e', seq: 9, x: 1, y: 1}}, nil},
|
||||
{"taps in a row", []touch{
|
||||
{kind: 'b', seq: 1, x: 10, y: 20}, {kind: 'e', seq: 1, x: 10, y: 20, ms: 50},
|
||||
{kind: 'b', seq: 2, x: 12, y: 21, ms: 150}, {kind: 'e', seq: 2, x: 12, y: 21, ms: 200},
|
||||
}, []SurfaceEvent{down(10, 20, 0), up(10, 20, 0), leave, down(12, 21, 0), up(12, 21, 0), leave}},
|
||||
// A finger whose end went unseen is forgotten as new touches
|
||||
// begin: the next one taps, rather than counting as a second.
|
||||
{"reset", []touch{
|
||||
{kind: 'b', seq: 1, x: 100, y: 100},
|
||||
{kind: 'r'}, {kind: 'b', seq: 2, x: 10, y: 20}, {kind: 'e', seq: 2, x: 10, y: 20},
|
||||
}, []SurfaceEvent{down(10, 20, 0), up(10, 20, 0), leave}},
|
||||
} {
|
||||
var g TouchGesture
|
||||
var got []SurfaceEvent
|
||||
for _, tt := range tc.touches {
|
||||
switch tt.kind {
|
||||
case 'b':
|
||||
got = append(got, g.Begin(tt.seq, tt.x, tt.y, tt.ms)...)
|
||||
case 'm':
|
||||
got = append(got, g.Move(tt.seq, tt.x, tt.y)...)
|
||||
case 'e', 'c':
|
||||
got = append(got, g.End(tt.seq, tt.x, tt.y, tt.ms, tt.kind == 'c')...)
|
||||
case 'r':
|
||||
g.Reset()
|
||||
}
|
||||
}
|
||||
if !reflect.DeepEqual(got, tc.want) {
|
||||
t.Errorf("%s:\n got %+v\nwant %+v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
)
|
||||
|
||||
// FileWatchTarget is a file or directory the core enrolls in a FileWatch.
|
||||
// IDs are never reused within a FileWatch.
|
||||
type FileWatchTarget struct {
|
||||
ID uint64
|
||||
Path string
|
||||
// Directory says the target is a directory. A backend that watches a
|
||||
// file only through its directory, which the core enrolls before it
|
||||
// lists it, returns ErrUnsupported for a target that isn't one, and
|
||||
// the core enrolls no more files.
|
||||
Directory bool
|
||||
// Info is what the core's scan saw at Path. Backends open the target
|
||||
// and check it is still the same file, so that a replacement racing
|
||||
// the enrollment is not watched in its place.
|
||||
Info fs.FileInfo
|
||||
// Subtree asks to watch everything beneath the directory with this one
|
||||
// target, and to name what changes deeper down by its slash-separated
|
||||
// path relative to it. A backend that can't returns ErrUnsupported,
|
||||
// and the core enrolls every directory instead.
|
||||
Subtree bool
|
||||
}
|
||||
|
||||
// FileWatchKind says what changed. Backends report what the system tells
|
||||
// them; the core rescans what a notice names, so a kind is only a hint.
|
||||
type FileWatchKind uint8
|
||||
|
||||
const (
|
||||
// FileWatchDirty means something about the target or its child changed.
|
||||
FileWatchDirty FileWatchKind = iota
|
||||
FileWatchWrite
|
||||
FileWatchCreate
|
||||
FileWatchRemove
|
||||
FileWatchMoveFrom
|
||||
FileWatchMoveTo
|
||||
// FileWatchLost means the system stopped watching the target, for
|
||||
// example because it was deleted; the core enrolls it again if it
|
||||
// still exists.
|
||||
FileWatchLost
|
||||
)
|
||||
|
||||
// FileWatchNotice reports a change to a target (Name empty) or to one of
|
||||
// the immediate children of a directory target (Name its name; a path for
|
||||
// a Subtree target). A notice with Err set ends the watch, except
|
||||
// ErrFileWatchOverflow, after which the core rescans everything.
|
||||
type FileWatchNotice struct {
|
||||
Target uint64
|
||||
Kind FileWatchKind
|
||||
Name string
|
||||
Err error
|
||||
}
|
||||
|
||||
// ErrFileWatchOverflow is the Err of a notice when the system dropped
|
||||
// changes, for example because its queue overflowed.
|
||||
var ErrFileWatchOverflow = errors.New("file watch queue overflow")
|
||||
|
||||
// FileWatch watches the targets the core adds. Its methods may be called
|
||||
// from any goroutine, one at a time. Close stops the watch and waits until
|
||||
// every handle is released and notify will not be called again; it must
|
||||
// not be called from notify.
|
||||
type FileWatch interface {
|
||||
Add(target FileWatchTarget) error
|
||||
Remove(id uint64)
|
||||
Close()
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package platform
|
||||
|
||||
import "testing"
|
||||
|
||||
// A placement's page takes the pointer in its clip, inside its rounded
|
||||
// corners, as it shows scaled, and where nothing covers it.
|
||||
func TestWebViewPlacementAt(t *testing.T) {
|
||||
// A page 200 by 100 shown at half its size, from 10, 20, its corners
|
||||
// rounded by 20 of its DIPs: 10 of the surface's.
|
||||
p := WebViewPlacement{
|
||||
Frame: RectF{X: 10, Y: 20, W: 100, H: 50}, Clip: RectF{X: 10, Y: 20, W: 100, H: 50},
|
||||
Width: 200, Height: 100, Radii: [4]float64{20, 20, 20, 0},
|
||||
Covers: []RectF{{X: 50, Y: 40, W: 10, H: 10}},
|
||||
}
|
||||
if sx, sy := p.Scale(); sx != 0.5 || sy != 0.5 {
|
||||
t.Errorf("scale %v, %v: want a half", sx, sy)
|
||||
}
|
||||
if x, y := p.ToPage(60, 45); x != 100 || y != 50 {
|
||||
t.Errorf("the surface's 60, 45 is the page's %v, %v: want its center", x, y)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
x, y float64
|
||||
want bool
|
||||
}{
|
||||
{60, 30, true}, // inside
|
||||
{11, 21, false}, // cut off by the top-left corner
|
||||
{109, 21, false}, // the top-right
|
||||
{109, 69, false}, // the bottom-right
|
||||
{11, 69, true}, // the bottom-left is square
|
||||
{13, 23, true}, // inside the top-left corner's curve
|
||||
{11, 30, true}, // below the top-left corner
|
||||
{55, 45, false}, // covered
|
||||
{5, 30, false}, // outside the clip
|
||||
} {
|
||||
if got := p.At(c.x, c.y); got != c.want {
|
||||
t.Errorf("At(%v, %v) = %v, want %v", c.x, c.y, got, c.want)
|
||||
}
|
||||
}
|
||||
// Without a size, the page is the frame's.
|
||||
q := WebViewPlacement{Frame: RectF{W: 40, H: 30}, Clip: RectF{W: 40, H: 30}}
|
||||
if w, h := q.Size(); w != 40 || h != 30 || !q.At(1, 1) || q.Rounded() {
|
||||
t.Errorf("a placement without a size or corners: size %v by %v", w, h)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user