system

package
v0.3.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 19, 2024 License: BSD-3-Clause Imports: 18 Imported by: 5

README

system

System provides a Go operating system interface framework to support events, window management, and other OS-specific functionality needed for full GUI support.

The following implementations of the higher-level system interfaces are supported (see the driver directory):

  • desktop uses glfw and other OS-specific code to support Windows, MacOS, X11, and Wayland.
  • ios supports the Apple iOS mobile platform.
  • android supports the Android mobile platform.
  • web supports running apps on web browsers through WASM.
  • offscreen supports running apps detached from any outside platform.

The Platform type enumerates these supported platforms and should be used to conditionalize behavior, instead of the GOOS value typically used in Go.

IMPORTANT

After making any changes to GoNativeActivity.java in the Android driver, you need to run go generate in ../cmd/core/mobile and reinstall the core tool.

Documentation

Overview

Package system provides a Go operating system interface framework to support events, window management, and other OS-specific functionality needed for full GUI support.

Index

Constants

View Source
const (
	// Unchanged should be used for the unchanged argument in drawer calls,
	// when the caller knows that the image is unchanged.
	Unchanged = true

	// Changed should be used for the unchanged argument to drawer calls,
	// when the image has changed since last time or its status is unknown
	Changed
)

Variables

View Source
var (
	// TheApp is the current [App]; only one is ever in effect.
	TheApp App

	// AppVersion is the version of the current app.
	// It is set by a linker flag in the core command line tool.
	AppVersion = "dev"

	// CoreVersion is the version of Cogent Core that the current app is using.
	// It is set by a linker flag in the core command line tool.
	CoreVersion = "dev"

	// ReservedWebShortcuts is a list of shortcuts that are reserved on the web
	// platform, meaning that they are handled by the browser instead of Cogent Core.
	// By default, this list contains important web shortcuts like Command+r and Command+(1-9).
	// All instances of "Command" are automatically converted to "Control" on non-macOS system
	// platforms, meaning that shortcuts should typically be expressed using "Command" for
	// cross-platform support. Modifiers should be specified in the order of [key.Modifiers]:
	// Shift, Control, Alt, Command. Shortcuts can be removed from this list by an app whose use of
	// them is more important than the default web action for that shortcut.
	ReservedWebShortcuts = []string{"Command+r", "Command+Shift+r", "Command+w", "Command+t", "Command+Shift+t", "Command+q", "Command+n", "Command+m", "Command+l", "Command+h", "Command+Shift+j", "Command+Alt+j", "Command+Alt+∆", "Command+1", "Command+2", "Command+3", "Command+4", "Command+5", "Command+6", "Command+7", "Command+8", "Command+9"}
)
View Source
var (
	// NeedsCapture is whether the app drawer needs to capture its next
	// frame. End-user code should just use [Capture].
	NeedsCapture bool
	// CaptureImage is the variable that stores the image captured in
	// [Capture]. End-user code should just use [Capture].
	CaptureImage *image.RGBA
)
View Source
var (
	// LogicalDPIScale is the default scaling factor for Logical DPI
	// as a multiplier on Physical DPI.
	// Smaller numbers produce smaller font sizes etc.
	LogicalDPIScale = float32(1)

	// LogicalDPIScales are per-screen name versions of LogicalDPIScale
	// these can be set from preferences (as in gi/prefs) on a per-screen
	// basis.
	LogicalDPIScales map[string]float32
)
View Source
var HandleRecover = func(r any) {
	HandleRecoverBase(r)
	HandleRecoverPanic(r)
}

HandleRecover takes the given value of recover, and, if it is not nil, handles it. The behavior of HandleRecover can be customized by changing it to a custom function, but by default it calls HandleRecoverBase and HandleRecoverPanic, which safely prints a stack trace, saves a crash log, and panics on non-mobile platforms. It is set in core to a function that does the aforementioned things in addition to creating a GUI error dialog. HandleRecover should be called at the start of every goroutine whenever possible. The correct usage of HandleRecover is:

func myFunc() {
	defer func() { system.HandleRecover(recover()) }()
	...
}
View Source
var InitScreenLogicalDPIFunc func()

InitScreenLogicalDPIFunc is a function that can be set to initialize the screen LogicalDPI values based on user preferences etc. Called just before first window is opened.

View Source
var OnSystemWindowCreated chan struct{}

OnSystemWindowCreated is a channel used to communicate that the underlying system window has been created on iOS and Android. If it is nil, it indicates that the current platform does not have an underlying system window that is created asynchronously, or that system window has already been created and thus this is no longer applicable. If it is non-nil, no actions with the window should be taken until a signal is sent.

Functions

func AssertCapture

func AssertCapture(t imagex.TestingT, filename string)

AssertCapture asserts that the result of Capture is equivalent to the image stored at the given filename in the testdata directory, with ".png" added to the filename if there is no extension (eg: "button" becomes "testdata/button.png"). If it is not, it fails the test with an error, but continues its execution. If there is no image at the given filename in the testdata directory, it creates the image.

func Capture

func Capture() *image.RGBA

Capture tells the app drawer to capture its next frame as an image. Once it gets that image, it returns it. It is currently only supported on platform Offscreen.

func CaptureAs

func CaptureAs(filename string) error

CaptureAs is a helper function that saves the result of Capture to the given filename. It automatically logs any error in addition to returning it.

func CrashLogText

func CrashLogText(r any, stack string) string

CrashLogText returns an appropriate crash log string for the given recover value and stack trace.

func HandleRecoverBase

func HandleRecoverBase(r any)

HandleRecoverBase is the default base value of HandleRecover. It can be extended to form a different value of HandleRecover. It prints a panic message and a stack trace, using a string-based log method that guarantees that the stack trace will be printed before the program exits. This is needed because, without this, the program may exit before it can print the stack trace on some systems like Android, which makes debugging nearly impossible. It also saves a crash log to [App.AppDataDir].

func HandleRecoverPanic

func HandleRecoverPanic(r any)

HandleRecoverPanic panics on r if r is non-nil and [TheApp.Platform] is not mobile. This is because panicking screws up logging on mobile, but is necessary for debugging on desktop.

func LogicalFromPhysicalDPI

func LogicalFromPhysicalDPI(logScale, pdpi float32) float32

LogicalFromPhysicalDPI computes the logical DPI used in actual screen scaling based on the given logical DPI scale factor (logScale), and also makes it a multiple of 6 to make normal font sizes look best.

func SetLogicalDPIScale

func SetLogicalDPIScale(scrnName string, dpiScale float32)

SetLogicalDPIScale sets the LogicalDPIScale factor for given screen name

func WindowFlagsToBool

func WindowFlagsToBool(flags WindowFlags) (dialog, modal, tool, fullscreen bool)

Types

type App

type App interface {

	// Platform returns the platform type, which can be used
	// for conditionalizing behavior
	Platform() Platforms

	// SystemPlatform returns the platform type of the underlying
	// system, which can be used for conditionalizing behavior. On platforms
	// other than [Web], this is the same as [App.Platform]. On [Web], it
	// returns the platform of the underlying operating system.
	SystemPlatform() Platforms

	// SystemInfo returns any additional information about the underlying system
	// that is not otherwise given. It is used in crash logs.
	SystemInfo() string

	// Name is the overall name of the application -- used for specifying an
	// application-specific preferences directory, etc
	Name() string

	// SetName sets the application name -- defaults to Cogent Core if not otherwise set
	SetName(name string)

	// GetScreens gets the current list of screens
	GetScreens()

	// NScreens returns the number of different logical and/or physical
	// screens managed under this overall screen hardware
	NScreens() int

	// Screen returns screen for given screen number, or nil if not a
	// valid screen number.
	Screen(n int) *Screen

	// ScreenByName returns screen for given screen name, or nil if not a
	// valid screen name.
	ScreenByName(name string) *Screen

	// NWindows returns the number of windows open for this app.
	NWindows() int

	// Window returns given window in list of windows opened under this screen
	// -- list is not in any guaranteed order, but typically in order of
	// creation (see also WindowByName) -- returns nil for invalid index.
	Window(win int) Window

	// WindowByName returns given window in list of windows opened under this
	// screen, by name -- nil if not found.
	WindowByName(name string) Window

	// WindowInFocus returns the window currently in focus (receiving keyboard
	// input) -- could be nil if none are.
	WindowInFocus() Window

	// ContextWindow returns the window passed as context for clipboard, cursor, etc calls.
	ContextWindow() Window

	// NewWindow returns a new Window for this screen. A nil opts is valid and
	// means to use the default option values.
	NewWindow(opts *NewWindowOptions) (Window, error)

	// RemoveWindow removes the given Window from the app's list of windows.
	// It does not actually close it; see [Window.Close] for that.
	RemoveWindow(win Window)

	// Clipboard returns the [Clipboard] handler for the system,
	// in context of given window, which is optional (can be nil)
	// but can provide useful context on some systems.
	Clipboard(win Window) Clipboard

	// Cursor returns the [Cursor] handler for the system, in the context
	// of the given window.
	Cursor(win Window) Cursor

	// DataDir returns the OS-specific data directory: Mac: ~/Library,
	// Linux: ~/.config, Windows: ~/AppData/Roaming
	DataDir() string

	// AppDataDir returns the application-specific data directory: [App.DataDir] +
	// [App.Name]. It ensures that the directory exists first.
	AppDataDir() string

	// CogentCoreDataDir returns the Cogent Core data directory: [App.DataDir] +
	// "Cogent Core". It ensures that the directory exists first.
	CogentCoreDataDir() string

	// OpenURL opens the given URL in the user's default browser.  On Linux
	// this requires that xdg-utils package has been installed, since it uses
	// the xdg-open command.
	OpenURL(url string)

	// OpenFiles returns file names that have been set to be open at startup.
	OpenFiles() []string

	// SetQuitReqFunc sets the function that is called whenever there is a
	// request to quit the app (via a OS or a call to QuitReq() method).  That
	// function can then adjudicate whether and when to actually call Quit.
	SetQuitReqFunc(fun func())

	// AddQuitCleanFunc adds the given function to a list that is called whenever
	// app is actually about to quit (irrevocably). Can do any necessary
	// last-minute cleanup here.
	AddQuitCleanFunc(fun func())

	// QuitReq is a quit request, triggered either by OS or user call (e.g.,
	// via Quit menu action) -- calls function previously registered by
	// SetQuitReqFunc, which is then solely responsible for actually calling
	// Quit.
	QuitReq()

	// IsQuitting returns true when the app is actually quitting -- it is set
	// to true just before the QuitClean function is called, and before all
	// the windows are closed.
	IsQuitting() bool

	// QuitClean calls the function setup in SetQuitCleanFunc and does other
	// app cleanup -- called on way to quitting. If it returns false, then
	// the app should not quit.
	QuitClean() bool

	// Quit closes all windows and exits the program.
	Quit()

	// MainLoop runs the main loop of the app.
	MainLoop()

	// RunOnMain runs given function on main thread (where [App.MainLoop] is running).
	// Some functions (GUI-specific etc) must run on this initial main thread for the
	// overall app. If [App.MainLoop] has not been called yet, RunOnMain assumes that
	// it is being called from the main thread and thus just calls the given function
	// directly.
	RunOnMain(f func())

	// SendEmptyEvent sends an empty, blank event to global event processing
	// system, which has the effect of pushing the system along during cases when
	// the event loop needs to be "pinged" to get things moving along.
	// See also similar method on Window.
	SendEmptyEvent()

	// ShowVirtualKeyboard shows a virtual keyboard of the given type.
	// ShowVirtualKeyboard only has an effect on mobile platforms (iOS, Android, and Web).
	// It should not be called with [styles.NoKeyboard].
	ShowVirtualKeyboard(typ styles.VirtualKeyboards)

	// HideVirtualKeyboard hides the virtual keyboard.
	// HideVirtualKeyboard only has an effect on mobile platforms (iOS, Android, and Web).
	HideVirtualKeyboard()

	// IsDark returns whether the system color theme is dark (as oppposed to light).
	IsDark() bool
}

App represents the overall OS GUI hardware, and creates Images, Textures and Windows, appropriate for that hardware / OS, and maintains data about the physical screen(s)

type Clipboard

type Clipboard interface {

	// IsEmpty returns true if there is nothing on the clipboard to read.
	// Can be used for disabling a Paste menu.
	IsEmpty() bool

	// Read attempts to read data of the given MIME type(s), in preference
	// order, from the clipboard, returning mimedata.Mimes which can
	// potentially have multiple types / multiple items, etc. If the first type
	// listed is a text type, then text-based retrieval is assumed; always
	// put the most specific desired type first; anything else present will
	// be returned
	Read(types []string) mimedata.Mimes

	// Write writes given mimedata to the clipboard; in general having a
	// text/plain representation of the data in addition to a more specific
	// format is a good idea for anything more complex than plain text; if
	// data has > 1 element, it is all encoded as a multipart MIME text string
	Write(data mimedata.Mimes) error

	// Clear clears the clipboard.
	Clear()
}

Clipboard defines the methods for reading and writing data to the system clipboard, which use mimedata to represent the data. Due to limitations of Windows (and Linux to a lesser extent), a multipart MIME formatted string is used if there are multiple elements in the mimedata, with any binary data text-encoded using base64.

type ClipboardBase

type ClipboardBase struct{}

ClipboardBase is a basic implementation of Clipboard that does nothing.

func (*ClipboardBase) Clear

func (bb *ClipboardBase) Clear()

func (*ClipboardBase) IsEmpty

func (bb *ClipboardBase) IsEmpty() bool

func (*ClipboardBase) Read

func (bb *ClipboardBase) Read(types []string) mimedata.Mimes

func (*ClipboardBase) Write

func (bb *ClipboardBase) Write(data mimedata.Mimes) error

type Cursor

type Cursor interface {

	// Current returns the current cursor as an enum, which is a
	// [cogentcore.org/core/cursors.Cursor]
	// by default, but could be something else if you are extending
	// the default cursor set.
	Current() enums.Enum

	// Set sets the active cursor to the given cursor as an enum, which is typically
	// a [cursors.Cursor], unless you are extending the default cursor set, in
	// which case it should be a type you defined. The string version of the
	// enum value must correspond to a filename of the form "name.svg" in
	// [cogentcore.org/core/cursors.Cursors]; this will be satisfied automatically by all
	// [cursor.Cursor] values.
	Set(cursor enums.Enum) error

	// IsVisible returns whether cursor is currently visible (according to [Cursor.Hide] and [Cursor.Show] actions)
	IsVisible() bool

	// Hide hides the cursor if it is not already hidden.
	Hide()

	// Show shows the cursor after a hide if it is hidden.
	Show()

	// SetSize sets the size that cursors are rendered at.
	SetSize(size int)
}

Cursor manages the mouse cursor / pointer appearance.

type CursorBase

type CursorBase struct {
	// Cur is the current cursor, which is maintained by the standard methods.
	Cur enums.Enum

	// Vis is whether the cursor is visible; be sure to initialize to true!
	Vis bool

	// Size is the size that cursors are rendered at
	Size int
}

CursorBase provides the common infrastructure for the Cursor interface, to be extended on desktop platforms. It can also be used as an empty implementation of the Cursor interface on mobile platforms, as they do not have cursors.

func (*CursorBase) Current

func (c *CursorBase) Current() enums.Enum

func (*CursorBase) Hide

func (c *CursorBase) Hide()

func (*CursorBase) IsVisible

func (c *CursorBase) IsVisible() bool

func (*CursorBase) Set

func (c *CursorBase) Set(cursor enums.Enum) error

func (*CursorBase) SetSize

func (c *CursorBase) SetSize(size int)

func (*CursorBase) Show

func (c *CursorBase) Show()

type Drawer

type Drawer interface {
	// DestBounds returns the bounds of the render destination
	DestBounds() image.Rectangle

	// Start starts recording a sequence of draw / fill actions,
	// which will be performed on the GPU at End().
	// This must be called prior to any Drawer operations.
	Start()

	// End ends image drawing rendering process on render target.
	End()

	// Copy copies the given Go source image to the render target, with the
	// same semantics as golang.org/x/image/draw.Copy, with the destination
	// implicit in the Drawer target.
	//   - Must have called Start first!
	//   - dp is the destination point.
	//   - src is the source image. If an image.Uniform, fast Fill is done.
	//   - sr is the source region, if zero full src is used; must have for Uniform.
	//   - op is the drawing operation: Src = copy source directly (blit),
	//     Over = alpha blend with existing.
	//   - unchanged should be true if caller knows that this image is unchanged
	//     from the last time it was used -- saves re-uploading to gpu.
	Copy(dp image.Point, src image.Image, sr image.Rectangle, op draw.Op, unchanged bool)

	// Scale copies the given Go source image to the render target,
	// scaling the region defined by src and sr to the destination
	// such that sr in src-space is mapped to dr in dst-space,
	// and applying an optional rotation of the source image.
	// Has the same general semantics as golang.org/x/image/draw.Scale, with the
	// destination implicit in the Drawer target.
	// If src image is an
	//   - Must have called Start first!
	//   - dr is the destination rectangle; if zero uses full dest image.
	//   - src is the source image. Uniform does not work (or make sense) here.
	//   - sr is the source region, if zero full src is used; must have for Uniform.
	//   - rotateDeg = rotation degrees to apply in the mapping:
	//     90 = left, -90 = right, 180 = invert.
	//   - op is the drawing operation: Src = copy source directly (blit),
	//     Over = alpha blend with existing.
	//   - unchanged should be true if caller knows that this image is unchanged
	//     from the last time it was used -- saves re-uploading to gpu.
	Scale(dr image.Rectangle, src image.Image, sr image.Rectangle, rotateDeg float32, op draw.Op, unchanged bool)

	// Transform copies the given Go source image to the render target,
	// with the same semantics as golang.org/x/image/draw.Transform, with the
	// destination implicit in the Drawer target.
	//   - xform is the transform mapping source to destination coordinates.
	//   - src is the source image. Uniform does not work (or make sense) here.
	//   - sr is the source region, if zero full src is used; must have for Uniform.
	//   - op is the drawing operation: Src = copy source directly (blit),
	//     Over = alpha blend with existing.
	//   - unchanged should be true if caller knows that this image is unchanged
	//     from the last time it was used -- saves re-uploading to gpu.
	Transform(xform math32.Matrix3, src image.Image, sr image.Rectangle, op draw.Op, unchanged bool)

	// Renderer is the gpu device being drawn to.
	// Could be nil on unsupported devices (such as offscreen).
	Renderer() any
}

Drawer is an interface for image/draw style image compositing functionality, which is implemented for the GPU in *cogentcore.org/core/gpu/gpudraw.Drawer and in offscreen drivers. This is used for compositing the stack of images that together comprise the content of a window.

type DrawerBase

type DrawerBase struct {
	// Image is the target render image
	Image *image.RGBA
}

DrawerBase is a base implementation of Drawer with basic no-ops for most methods. Embedders need to implement DestBounds and End.

func (*DrawerBase) Copy

func (dw *DrawerBase) Copy(dp image.Point, src image.Image, sr image.Rectangle, op draw.Op, unchanged bool)

Copy copies the given Go source image to the render target, with the same semantics as golang.org/x/image/draw.Copy, with the destination implicit in the Drawer target.

  • Must have called Start first!
  • dp is the destination point.
  • src is the source image. If an image.Uniform, fast Fill is done.
  • sr is the source region, if zero full src is used; must have for Uniform.
  • op is the drawing operation: Src = copy source directly (blit), Over = alpha blend with existing.
  • unchanged should be true if caller knows that this image is unchanged from the last time it was used -- saves re-uploading to gpu.

func (*DrawerBase) Renderer added in v0.3.2

func (dw *DrawerBase) Renderer() any

func (*DrawerBase) Scale

func (dw *DrawerBase) Scale(dr image.Rectangle, src image.Image, sr image.Rectangle, rotateDeg float32, op draw.Op, unchanged bool)

Scale copies the given Go source image to the render target, scaling the region defined by src and sr to the destination such that sr in src-space is mapped to dr in dst-space, and applying an optional rotation of the source image. Has the same general semantics as golang.org/x/image/draw.Scale, with the destination implicit in the Drawer target. If src image is an

  • Must have called Start first!
  • dr is the destination rectangle; if zero uses full dest image.
  • src is the source image. Uniform does not work (or make sense) here.
  • sr is the source region, if zero full src is used; must have for Uniform.
  • rotateDeg = rotation degrees to apply in the mapping: 90 = left, -90 = right, 180 = invert.
  • op is the drawing operation: Src = copy source directly (blit), Over = alpha blend with existing.
  • unchanged should be true if caller knows that this image is unchanged from the last time it was used -- saves re-uploading to gpu.

func (*DrawerBase) Start added in v0.3.2

func (dw *DrawerBase) Start()

Start starts recording a sequence of draw / fill actions, which will be performed on the GPU at End(). This must be called prior to any Drawer operations.

func (*DrawerBase) Transform added in v0.3.2

func (dw *DrawerBase) Transform(xform math32.Matrix3, src image.Image, sr image.Rectangle, op draw.Op, unchanged bool)

Transform copies the given Go source image to the render target, with the same semantics as golang.org/x/image/draw.Transform, with the destination implicit in the Drawer target.

  • xform is the transform mapping source to destination coordinates.
  • src is the source image. Uniform does not work (or make sense) here.
  • sr is the source region, if zero full src is used; must have for Uniform.
  • op is the drawing operation: Src = copy source directly (blit), Over = alpha blend with existing.
  • unchanged should be true if caller knows that this image is unchanged from the last time it was used -- saves re-uploading to gpu.

type NewWindowOptions

type NewWindowOptions struct {
	// Size specifies the dimensions of the new window, either in raw pixels
	// or std 96 dpi pixels depending on StdPixels. If Width or Height are
	// zero, a driver-dependent default will be used for each zero value
	// dimension
	Size image.Point

	// StdPixels means use standardized "pixel" units for the window size (96
	// per inch), not the actual underlying raw display dot pixels
	StdPixels bool

	// Pos specifies the position of the window, if non-zero -- always in
	// device-specific raw pixels
	Pos image.Point

	// Title specifies the window title.
	Title string

	// Icon specifies the window icon (see [Window.SetIcon] for more info).
	Icon []image.Image

	// Flags can be set using WindowFlags to request different types of windows
	Flags WindowFlags
}

NewWindowOptions are optional arguments to NewWindow.

func (*NewWindowOptions) Fixup

func (o *NewWindowOptions) Fixup()

Fixup fills in defaults and updates everything based on current screen and window context Specific hardware can fine-tune this as well, in driver code

func (*NewWindowOptions) GetTitle

func (o *NewWindowOptions) GetTitle() string

GetTitle returns a sanitized form of o.Title. In particular, its length will not exceed 4096, and it may be further truncated so that it is valid UTF-8 and will not contain the NUL byte.

o may be nil, in which case "" is returned.

func (*NewWindowOptions) SetDialog

func (o *NewWindowOptions) SetDialog()

func (*NewWindowOptions) SetFullscreen

func (o *NewWindowOptions) SetFullscreen()

func (*NewWindowOptions) SetModal

func (o *NewWindowOptions) SetModal()

func (*NewWindowOptions) SetTool

func (o *NewWindowOptions) SetTool()

type Platforms

type Platforms int32 //enums:enum

Platforms are all the supported platforms for system

const (
	// MacOS is a Mac OS machine (aka Darwin)
	MacOS Platforms = iota

	// Linux is a Linux OS machine
	Linux

	// Windows is a Microsoft Windows machine
	Windows

	// IOS is an Apple iOS or iPadOS mobile phone or iPad
	IOS

	// Android is an Android mobile phone or tablet
	Android

	// Web is a web browser running the app through WASM
	Web

	// Offscreen is an offscreen driver typically used for testing,
	// specified using the "offscreen" build tag
	Offscreen
)
const PlatformsN Platforms = 7

PlatformsN is the highest valid value for type Platforms, plus one.

func PlatformsValues

func PlatformsValues() []Platforms

PlatformsValues returns all possible values for the type Platforms.

func (Platforms) Desc

func (i Platforms) Desc() string

Desc returns the description of the Platforms value.

func (Platforms) Int64

func (i Platforms) Int64() int64

Int64 returns the Platforms value as an int64.

func (Platforms) IsMobile

func (p Platforms) IsMobile() bool

IsMobile returns whether the platform is a mobile platform (iOS, Android, Web, or Offscreen). Web and Offscreen are considered mobile platforms because they only support one window.

func (Platforms) MarshalText

func (i Platforms) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*Platforms) SetInt64

func (i *Platforms) SetInt64(in int64)

SetInt64 sets the Platforms value from an int64.

func (*Platforms) SetString

func (i *Platforms) SetString(s string) error

SetString sets the Platforms value from its string representation, and returns an error if the string is invalid.

func (Platforms) String

func (i Platforms) String() string

String returns the string representation of this Platforms value.

func (*Platforms) UnmarshalText

func (i *Platforms) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (Platforms) Values

func (i Platforms) Values() []enums.Enum

Values returns all possible values for the type Platforms.

type Screen

type Screen struct {
	// ScreenNumber is the index of this screen in the list of screens
	// maintained under Screen.
	ScreenNumber int

	// Geometry contains the geometry of the screen in window manager
	// size units, which may not be same as raw pixels (dots)
	Geometry image.Rectangle

	// DevicePixelRatio is a factor that scales the screen's
	// "natural" pixel coordinates into actual device pixels.
	// On OS-X, it is backingScaleFactor = 2.0 on "retina"
	DevicePixelRatio float32

	// PixSize is the number of actual pixels in the screen
	// (raw display dots), computed as Size * DevicePixelRatio
	PixSize image.Point

	// PhysicalSize is the actual physical size of the screen, in mm.
	PhysicalSize image.Point

	// LogicalDPI is the logical dots per inch of the screen,
	// which is used for all rendering.
	// It is: transient zoom factor * screen-specific multiplier * PhysicalDPI
	LogicalDPI float32

	// PhysicalDPI is the physical dots per inch of the screen,
	// for generating true-to-physical-size output.
	// It is computed as 25.4 * (PixSize.X / PhysicalSize.X)
	// where 25.4 is the number of mm per inch.
	PhysicalDPI float32

	// Color depth of the screen, in bits.
	Depth int

	// Refresh rate in Hz
	RefreshRate float32

	Orientation        ScreenOrientation
	NativeOrientation  ScreenOrientation
	PrimaryOrientation ScreenOrientation

	Name         string
	Manufacturer string
	Model        string
	SerialNumber string
}

Screen contains data about each physical and / or logical screen

func (*Screen) ConstrainWinGeom

func (sc *Screen) ConstrainWinGeom(sz, pos image.Point) (csz, cpos image.Point)

ConstrainWinGeom constrains window geometry to fit in the screen. Size is in pixel units.

func (*Screen) UpdateLogicalDPI

func (sc *Screen) UpdateLogicalDPI()

UpdateLogicalDPI updates the logical DPI of the screen based on ZoomFactor and LogicalDPIScale (per screen if exists)

func (*Screen) UpdatePhysicalDPI

func (sc *Screen) UpdatePhysicalDPI()

UpdatePhysicalDPI updates the value of [Screen.PhysicalDPI] based on [Screen.PixSize] and [Screen.PhysicalSize]

func (*Screen) WinSizeFromPix

func (sc *Screen) WinSizeFromPix(sz image.Point) image.Point

WinSizeFromPix returns window manager size units (where DevicePixelRatio is ignored) converted from pixel units -- i.e., divide by DevicePixelRatio

func (*Screen) WinSizeToPix

func (sc *Screen) WinSizeToPix(sz image.Point) image.Point

WinSizeToPix returns window manager size units (where DevicePixelRatio is ignored) converted to pixel units -- i.e., multiply by DevicePixelRatio

type ScreenOrientation

type ScreenOrientation int32 //enums:enum

ScreenOrientation is the orientation of the device screen.

const (
	// OrientationUnknown means device orientation cannot be determined.
	//
	// Equivalent on Android to Configuration.ORIENTATION_UNKNOWN
	// and on iOS to:
	//	UIDeviceOrientationUnknown
	//	UIDeviceOrientationFaceUp
	//	UIDeviceOrientationFaceDown
	OrientationUnknown ScreenOrientation = iota

	// Portrait is a device oriented so it is tall and thin.
	//
	// Equivalent on Android to Configuration.ORIENTATION_PORTRAIT
	// and on iOS to:
	//	UIDeviceOrientationPortrait
	//	UIDeviceOrientationPortraitUpsideDown
	Portrait

	// Landscape is a device oriented so it is short and wide.
	//
	// Equivalent on Android to Configuration.ORIENTATION_LANDSCAPE
	// and on iOS to:
	//	UIDeviceOrientationLandscapeLeft
	//	UIDeviceOrientationLandscapeRight
	Landscape
)
const ScreenOrientationN ScreenOrientation = 3

ScreenOrientationN is the highest valid value for type ScreenOrientation, plus one.

func ScreenOrientationValues

func ScreenOrientationValues() []ScreenOrientation

ScreenOrientationValues returns all possible values for the type ScreenOrientation.

func (ScreenOrientation) Desc

func (i ScreenOrientation) Desc() string

Desc returns the description of the ScreenOrientation value.

func (ScreenOrientation) Int64

func (i ScreenOrientation) Int64() int64

Int64 returns the ScreenOrientation value as an int64.

func (ScreenOrientation) MarshalText

func (i ScreenOrientation) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*ScreenOrientation) SetInt64

func (i *ScreenOrientation) SetInt64(in int64)

SetInt64 sets the ScreenOrientation value from an int64.

func (*ScreenOrientation) SetString

func (i *ScreenOrientation) SetString(s string) error

SetString sets the ScreenOrientation value from its string representation, and returns an error if the string is invalid.

func (ScreenOrientation) String

func (i ScreenOrientation) String() string

String returns the string representation of this ScreenOrientation value.

func (*ScreenOrientation) UnmarshalText

func (i *ScreenOrientation) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (ScreenOrientation) Values

func (i ScreenOrientation) Values() []enums.Enum

Values returns all possible values for the type ScreenOrientation.

type Window

type Window interface {

	// Name returns the name of the window -- name is used strictly for
	// internal tracking and finding of windows -- see Title for the displayed
	// title of the window.
	Name() string

	// SetName sets the name of the window.
	SetName(name string)

	// Title returns the current title of the window, which is displayed in the GUI.
	Title() string

	// SetTitle sets the current title of the window, which is displayed in the GUI.
	SetTitle(title string)

	// SetIcon sets the icon of the window, which is displayed in the title bar
	// and taskbar on Windows. It takes a list of candidate images and uses the
	// one closest to the required size. Good sizes are 16x16, 32x32, and 48x48.
	SetIcon(images []image.Image)

	// Size returns the current size of the window, in raw underlying dots / pixels.
	// This includes any high DPI factors that may not be used in OS window sizing
	//  (see WinSize for that size).
	Size() image.Point

	// WinSize returns the current size of the window, in OS-specific window manager
	// units that may not include any high DPI factors.
	WinSize() image.Point

	// Position returns the current left-top position of the window relative to
	// underlying screen, in OS-specific window manager coordinates.
	Position() image.Point

	// RenderGeom returns the actual effective geometry of the window used
	// for rendering content, which may be different from {0, [Window.Size]}
	// due to insets caused by things like status bars and button overlays.
	RenderGeom() math32.Geom2DInt

	// SetWinSize sets the size of the window, in OS-specific window manager
	// units that may not include any high DPI factors (DevPixRatio)
	// (i.e., the same units as returned in WinSize())
	SetWinSize(sz image.Point)

	// SetSize sets the size of the window, in actual pixel units
	// (i.e., the same units as returned by Size())
	// Divides by DevPixRatio before calling SetWinSize.
	SetSize(sz image.Point)

	// SetPos sets the position of the window, in OS window manager
	// coordinates, which may be different from Size() coordinates
	// that reflect high DPI
	SetPos(pos image.Point)

	// SetGeom sets the position and size in one call -- use this if doing
	// both because sequential calls to SetPos and SetSize might fail on some
	// platforms.  Size is in actual pixel units (i.e., same units as returned by Size()),
	// and Pos is in OS-specific window manager units (i.e., as returned in Pos())
	SetGeom(pos image.Point, sz image.Point)

	// Raise requests that the window be at the top of the stack of windows,
	// and receive focus.  If it is iconified, it will be de-iconified.  This
	// is the only supported mechanism for de-iconifying.
	Raise()

	// Minimize requests that the window be iconified, making it no longer
	// visible or active -- rendering should not occur for minimized windows.
	Minimize()

	// PhysicalDPI is the physical dots per inch of the window, for generating
	// true-to-physical-size output, for example -- see the gi/units package for
	// translating into various other units.
	PhysicalDPI() float32

	// LogicalDPI returns the current logical dots-per-inch resolution of the
	// window, which should be used for most conversion of standard units --
	// physical DPI can be found in the Screen.
	LogicalDPI() float32

	// SetLogicalDPI sets the current logical dots-per-inch resolution of the
	// window, which should be used for most conversion of standard units --
	// physical DPI can be found in the Screen.
	SetLogicalDPI(dpi float32)

	// Screen returns the screen for this window, with all the relevant
	// information about its properties.
	Screen() *Screen

	// Flags returns the bit flags for this window's properties set according
	// to WindowFlags bits.
	Flags() WindowFlags

	// Is returns whether the window has the given flag.
	Is(flag WindowFlags) bool

	// IsClosed returns true if this window has been closed (but some threads
	// may have not received the news yet)
	IsClosed() bool

	// IsVisible returns true if this window is not closed or minimized and
	// there are active screens
	IsVisible() bool

	// SetCloseReqFunc sets the function that is called whenever there is a
	// request to close the window (via a OS or a call to CloseReq() method).  That
	// function can then adjudicate whether and when to actually call Close.
	SetCloseReqFunc(fun func(win Window))

	// SetCloseCleanFunc sets the function that is called whenever window is
	// actually about to close (irrevocably) -- can do any necessary
	// last-minute cleanup here.
	SetCloseCleanFunc(fun func(win Window))

	// CloseReq is a close request, triggered either by OS or user call (e.g.,
	// via Close menu action) -- calls function previously registered by
	// SetCloseReqFunc, which is then solely responsible for actually calling
	// Close.
	CloseReq()

	// CloseClean calls the function setup in SetCloseCleanFunc and does other
	// window cleanup -- called on way to closing.
	CloseClean()

	// Close requests that the window be closed. The behavior of the Window
	// after this, whether calling its methods or passing it as an argument,
	// is undefined.  See App.Quit methods to quit overall app.
	Close()

	// Sets the mouse position to given values
	SetMousePos(x, y float64)

	// Sets the mouse cursor to be enabled (true by default) or disabled (false).
	// If disabled, setting raw to true will enable raw mouse movement
	// which can provide better control in a game environment (not avail on Mac).
	SetCursorEnabled(enabled, raw bool)

	// IsCursorEnabled returns true or false if cursor is enabled
	IsCursorEnabled() bool

	// Drawer returns the drawing system attached to this window surface.
	// This is typically used for high-performance rendering to the surface.
	// Wrap access in Lock() / Unlock() calls.
	Drawer() Drawer

	// Lock attempts to grab the overall window Mutex lock
	// and returns true if the window is still open and ready for business.
	// Otherwise, it might have been closed and any further use should be
	// abandoned.  Do this before any use of window resources
	// (eg. rendering to the Drawer).
	Lock() bool

	// Unlock unlocks the Mutex.  Must be called after Lock() is done.
	Unlock()

	// SetDestroyGPUResourcesFunc sets the given function
	// that will be called on the main thread just prior
	// to destroying the drawer and surface.
	SetDestroyGPUResourcesFunc(f func())

	// SetFPS sets the frames per second for Paint events that drive
	// updating of the window at regular intervals.  60 is default.
	// 0 disables -- no regular Paint events are sent.
	// This only takes effect prior to opening a new window.
	SetFPS(fps int)

	// SetTitleBarIsDark sets whether the color theme of the window
	// title bar is dark (as opposed to light).
	SetTitleBarIsDark(isDark bool)

	// Events returns the [events.Source] for this window,
	// which manages all of the event sending.
	Events() *events.Source
}

Window is a double-buffered OS-specific hardware window.

It provides basic GPU support functions, and is currently implemented via WebGPU. It uses glfw on desktop and native APIs on mobile and web.

The Window maintains its own Drawer drawing system for rendering bitmap images and filled regions onto the window surface.

The base full-window image should be drawn with a Scale call first, followed by any overlay images such as sprites or direct upload images already on the GPU (e.g., from 3D render frames)

type WindowFlags

type WindowFlags int64 //enums:bitflag

WindowFlags contains all the binary properties of a window -- by default with no other relevant flags a window is a main top-level window.

const (
	// Dialog indicates that this is a temporary, pop-up window.
	Dialog WindowFlags = iota

	// Modal indicates that this dialog window blocks events going to other
	// windows until it is closed.
	Modal

	// Tool indicates that this is a floating tool window that has minimized
	// window decoration.
	Tool

	// Fullscreen indicates a window that occupies the entire screen.
	Fullscreen

	// Minimized indicates a window reduced to an icon, or otherwise no longer
	// visible or active.  Otherwise, the window should be assumed to be
	// visible.
	Minimized

	// Focused indicates that the window has the focus.
	Focused
)
const WindowFlagsN WindowFlags = 6

WindowFlagsN is the highest valid value for type WindowFlags, plus one.

func WindowFlagsValues

func WindowFlagsValues() []WindowFlags

WindowFlagsValues returns all possible values for the type WindowFlags.

func (WindowFlags) BitIndexString

func (i WindowFlags) BitIndexString() string

BitIndexString returns the string representation of this WindowFlags value if it is a bit index value (typically an enum constant), and not an actual bit flag value.

func (WindowFlags) Desc

func (i WindowFlags) Desc() string

Desc returns the description of the WindowFlags value.

func (*WindowFlags) HasFlag

func (i *WindowFlags) HasFlag(f enums.BitFlag) bool

HasFlag returns whether these bit flags have the given bit flag set.

func (WindowFlags) Int64

func (i WindowFlags) Int64() int64

Int64 returns the WindowFlags value as an int64.

func (WindowFlags) MarshalText

func (i WindowFlags) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*WindowFlags) SetFlag

func (i *WindowFlags) SetFlag(on bool, f ...enums.BitFlag)

SetFlag sets the value of the given flags in these flags to the given value.

func (*WindowFlags) SetInt64

func (i *WindowFlags) SetInt64(in int64)

SetInt64 sets the WindowFlags value from an int64.

func (*WindowFlags) SetString

func (i *WindowFlags) SetString(s string) error

SetString sets the WindowFlags value from its string representation, and returns an error if the string is invalid.

func (*WindowFlags) SetStringOr

func (i *WindowFlags) SetStringOr(s string) error

SetStringOr sets the WindowFlags value from its string representation while preserving any bit flags already set, and returns an error if the string is invalid.

func (WindowFlags) String

func (i WindowFlags) String() string

String returns the string representation of this WindowFlags value.

func (*WindowFlags) UnmarshalText

func (i *WindowFlags) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (WindowFlags) Values

func (i WindowFlags) Values() []enums.Enum

Values returns all possible values for the type WindowFlags.

Directories

Path Synopsis
base
Package base provides base driver types that platform-specific drivers can extend to implement interfaces defined in package system.
Package base provides base driver types that platform-specific drivers can extend to implement interfaces defined in package system.
mobile/mobileinit
Package mobileinit contains common initialization logic for mobile platforms that is relevant to both all-Go apps and gobind-based apps.
Package mobileinit contains common initialization logic for mobile platforms that is relevant to both all-Go apps and gobind-based apps.
offscreen
Package offscreen provides placeholder implementations of system interfaces to allow for offscreen testing and capturing of apps.
Package offscreen provides placeholder implementations of system interfaces to allow for offscreen testing and capturing of apps.
web
Package web implements system interfaces on the web through WASM
Package web implements system interfaces on the web through WASM
web/jsfs
Package jsfs provides a Node.js style filesystem API in Go that can be used to allow os functions to work on wasm.
Package jsfs provides a Node.js style filesystem API in Go that can be used to allow os functions to work on wasm.
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL