# Runtime API reference

Access the runtime API with `#include <playbit/sys/sys.h>`

This reference is also available in [markdown format](api.md) and as [structured JSON data](api.json)

## Types

### `PBSysErr`

```c
typedef enum PB_ENUM_TYPE(int32_t) {
    PBSysErr_NONE = 0,            // no error
    PBSysErr_INVALID = -1,        // invalid data
    PBSysErr_NO_MEM = -2,         // cannot allocate memory
    PBSysErr_BAD_HANDLE = -3,     // invalid handle
    PBSysErr_BAD_NAME = -4,       // invalid or misformed name
    PBSysErr_NOT_FOUND = -5,      // resource not found
    PBSysErr_NAME_TOO_LONG = -6,  // name too long
    PBSysErr_CANCELED = -7,       // operation canceled
    PBSysErr_NOT_SUPPORTED = -8,  // not supported
    PBSysErr_EXISTS = -9,         // already exists
    PBSysErr_END = -10,           // end of resource
    PBSysErr_ACCESS_DENIED = -11, // access denied
    PBSysErr_AGAIN = -12,         // temporarily unavailable
    PBSysErr_DEFERRED = -13,      // operation deferred
    PBSysErr_ALREADY = -14,       // operation already in progress
    PBSysErr_IO_ERR = -15,        // I/O error
    PBSysErr_BAD_ADDRESS = -16,   // bad address

    /*
    PBSysErr_SHOULD_WAIT indicates that the operation cannot currently be performed but could succeed if the caller waits for a prerequisite to be satisfied. For example, waiting for a thread to terminate before reading its exit status.
    */
    PBSysErr_SHOULD_WAIT = -17,

    PBSysErr_TIMEOUT = -18, // deadline reached

    // PBSysErr_BUFFER_TOO_SMALL indicates that a caller-provided buffer is too small
    PBSysErr_BUFFER_TOO_SMALL = -19,

    PBSysErr_BAD_MODE = -20,  // unsupported or invalid mode
    PBSysErr_TOO_LARGE = -21, // value too large, e.g. overflow or limit

    PBSysErr_UNKNOWN = -2000000000, // unknown or internal error
} PBSysErr;
```

PBSysErr defines error codes

### `PBSysThreadFlags`

```c
typedef enum PB_ENUM_TYPE(u64) {
    PBSysThread_NOGUI = 1u << 0, // disable GUI (only has an effect on the main thread)
    PBSysThread_AUDIO = 1u << 1, // thread produces audio output
} PBSysThreadFlags;
```

### `PBSysThreadSignals`

```c
typedef enum PB_ENUM_TYPE(uint32_t) {
    PBSysThreadSignal_RUNNING = 1u << 0,
    PBSysThreadSignal_TERMINATED = 1u << 1,
    PBSysThreadSignal_WRITABLE = 1u << 2, // room for writing at least one message
    PBSysThreadSignal_READABLE = 1u << 3, // at least one message can be read
} PBSysThreadSignals;
```

### `PBSysObjectType`

```c
typedef enum PBSysObjectType PB_ENUM_TYPE(uint16_t){
    PBSysObject_None = 0, // invalid
    PBSysObject_Audio = 16,
    PBSysObject_Bundle = 18,
    PBSysObject_Channel = 7,
    PBSysObject_Clock = 1,
    PBSysObject_File = 12,
    PBSysObject_FileList = 14,
    PBSysObject_Gui = 8,
    PBSysObject_Net = 9,
    PBSysObject_NetSession = 10,
    PBSysObject_Stream = 2,
    PBSysObject_Textplan = 3,
    PBSysObject_Texture = 15,
    PBSysObject_Thread = 4,
    PBSysObject_Window = 6,
} PBSysObjectType;
```

### `PBSysRights`

```c
typedef u32 PBSysRights;
```

PBSysRights are associated with handles and convey privileges to perform actions on either the associated handle or the object associated with the handle.

### `PBSysRightsBits`

```c
enum PBSysRightsBits PB_ENUM_TYPE(PBSysRights){
    PBSysRight_NONE = 0u,

    PBSysRight_TRANSFER = 1u << 0,
    PBSysRight_DUPLICATE = 1u << 1,
    PBSysRight_READ = 1u << 4,
    PBSysRight_WRITE = 1u << 5,
    PBSysRight_MANAGE_PROCESS = 1u << 6, // start & terminate process
    PBSysRight_MANAGE_THREAD = 1u << 7,  // start & terminate threads
    PBSysRight_NETWORK = 1u << 8,        // can connect to networks [DEPRECATED]
    PBSysRight_OBSERVE = 1u << 9,        // can observe signals
    PBSysRight_SIGNAL = 1u << 10,        // can manage user signals
    PBSysRight_GET_PROPERTY = 1u << 11,  // can read object properties
    PBSysRight_SET_PROPERTY = 1u << 12,  // can change object properties

    PBSysRight_SAME_RIGHTS = 1u << 31,
};
```

### `PBSysAudioBuffer`

```c
typedef i64 PBSysAudioBuffer;
```

`Handle` to the sound mixer buffer and sound handles (u32 id, gen)

### `PBSysAudioSound`

```c
typedef i64 PBSysAudioSound;
```

### `PBSysChannelFlags`

```c
enum PBSysChannelFlags PB_ENUM_TYPE(uint32_t){
    PBSysChannel_DUPLEX = 1u << 0,           // created handles support both reading and writing
    PBSysChannel_MULTIPLE_WRITERS = 1u << 1, // support multiple concurrent threads writing
    PBSysChannel_MULTIPLE_READERS = 1u << 2, // support multiple concurrent threads reading
};
```

### `PBSysClockInfo`

```c
typedef struct PBSysClockInfo {
    char timeZoneName[63]; // IANA time zone identifier (e.g. "")
    u8   timeZoneNameLen;  // length of timeZoneName
} PBSysClockInfo;
```

### `PBSysPointerKind`

```c
typedef enum PBSysPointerKind PB_ENUM_TYPE(u8){
    PBSysPointerKind_MOUSE = 1,
    PBSysPointerKind_TOUCH = 2,
    PBSysPointerKind_TRACKPAD = 3, // used mainly for scroll/gesture sources
    PBSysPointerKind_PEN = 4,
} PBSysPointerKind;
```

### `PBSysPointerFlags`

```c
typedef enum PBSysPointerFlags PB_ENUM_TYPE(u16){
    PBSysPointerFlag_PRIMARY = 1u << 0,    // primary pointer for this device
    PBSysPointerFlag_IN_CONTACT = 1u << 1, // touch/pen in contact
    PBSysPointerFlag_ERASER = 1u << 2,     // pen eraser side/end
    PBSysPointerFlag_INVERTED = 1u << 3,   // if a platform reports pen inversion
    PBSysPointerFlag_COALESCED = 1u << 4,  // if event is a coalesced/aggregated update
    PBSysPointerFlag_PREDICTED = 1u << 5,  // if predicted (some systems provide)
} PBSysPointerFlags;
```

### `PBSysScrollPhase`

```c
typedef enum PBSysScrollPhase PB_ENUM_TYPE(u8){
    PBSysScrollPhase_CHANGED = 0, // default if platform doesn't provide phases
    PBSysScrollPhase_BEGAN = 1,
    PBSysScrollPhase_ENDED = 2,
    PBSysScrollPhase_MOMENTUM = 3, // inertia phase (macOS trackpad, iOS)
} PBSysScrollPhase;
```

### `PBSysScrollFlags`

```c
typedef enum PBSysScrollFlags PB_ENUM_TYPE(u16){
    PBSysScrollFlag_PRECISE = 1u << 0,    // high-resolution scrolling (trackpad)
    PBSysScrollFlag_INVERTED = 1u << 1,   // "natural" direction applied or not
    PBSysScrollFlag_UNIT_LINES = 1u << 2, // deltas are in lines (vs pixels/dp)
    PBSysScrollFlag_UNIT_PAGES = 1u << 3, // deltas are pages
} PBSysScrollFlags;
```

### `PBSysGesturePhase`

```c
typedef enum PBSysGesturePhase PB_ENUM_TYPE(u8){
    PBSysGesturePhase_CHANGED = 0, // default if platform doesn't provide phases
    PBSysGesturePhase_BEGAN = 1,
    PBSysGesturePhase_ENDED = 2,
} PBSysGesturePhase;
```

### `PBSysKeyboardFlags`

```c
typedef enum PBSysKeyboardFlags PB_ENUM_TYPE(u16){
    PBSysKeyboardFlag_REPEAT = 1u << 0, // i.e. key is being held down
} PBSysKeyboardFlags;
```

### `PBSysKeyboardModifiers`

```c
typedef enum PBSysKeyboardModifiers PB_ENUM_TYPE(u16){
    PBSysKeyboardModifier_SHIFT = 1u << 0,     // shift
    PBSysKeyboardModifier_CTRL = 1u << 1,      // control
    PBSysKeyboardModifier_ALT = 1u << 2,       // aka "option" on mac
    PBSysKeyboardModifier_META = 1u << 3,      // aka "command", "windows key", "super"
    PBSysKeyboardModifier_CAPS_LOCK = 1u << 4, // caps lock
    PBSysKeyboardModifier_FN = 1u << 5,        // "function"
} PBSysKeyboardModifiers;
```

### `PBSysKeyboardKey`

```c
typedef enum PBSysKeyboardKey PB_ENUM_TYPE(u16){
    PBSysKeyboardKey_None = 0x0000,

    // ASCII / Unicode printable (match codepoint)
    PBSysKeyboardKey_Space = 0x0020,
    PBSysKeyboardKey_Quote = 0x0027,
    PBSysKeyboardKey_Comma = 0x002C,
    PBSysKeyboardKey_Minus = 0x002D,
    PBSysKeyboardKey_Period = 0x002E,
    PBSysKeyboardKey_Slash = 0x002F,

    PBSysKeyboardKey_0 = 0x0030,
    PBSysKeyboardKey_1 = 0x0031,
    PBSysKeyboardKey_2 = 0x0032,
    PBSysKeyboardKey_3 = 0x0033,
    PBSysKeyboardKey_4 = 0x0034,
    PBSysKeyboardKey_5 = 0x0035,
    PBSysKeyboardKey_6 = 0x0036,
    PBSysKeyboardKey_7 = 0x0037,
    PBSysKeyboardKey_8 = 0x0038,
    PBSysKeyboardKey_9 = 0x0039,

    PBSysKeyboardKey_Semicolon = 0x003B,
    PBSysKeyboardKey_Equal = 0x003D,

    PBSysKeyboardKey_A = 0x0041,
    PBSysKeyboardKey_B = 0x0042,
    PBSysKeyboardKey_C = 0x0043,
    PBSysKeyboardKey_D = 0x0044,
    PBSysKeyboardKey_E = 0x0045,
    PBSysKeyboardKey_F = 0x0046,
    PBSysKeyboardKey_G = 0x0047,
    PBSysKeyboardKey_H = 0x0048,
    PBSysKeyboardKey_I = 0x0049,
    PBSysKeyboardKey_J = 0x004A,
    PBSysKeyboardKey_K = 0x004B,
    PBSysKeyboardKey_L = 0x004C,
    PBSysKeyboardKey_M = 0x004D,
    PBSysKeyboardKey_N = 0x004E,
    PBSysKeyboardKey_O = 0x004F,
    PBSysKeyboardKey_P = 0x0050,
    PBSysKeyboardKey_Q = 0x0051,
    PBSysKeyboardKey_R = 0x0052,
    PBSysKeyboardKey_S = 0x0053,
    PBSysKeyboardKey_T = 0x0054,
    PBSysKeyboardKey_U = 0x0055,
    PBSysKeyboardKey_V = 0x0056,
    PBSysKeyboardKey_W = 0x0057,
    PBSysKeyboardKey_X = 0x0058,
    PBSysKeyboardKey_Y = 0x0059,
    PBSysKeyboardKey_Z = 0x005A,

    PBSysKeyboardKey_LeftBracket = 0x005B,
    PBSysKeyboardKey_Backslash = 0x005C,
    PBSysKeyboardKey_RightBracket = 0x005D,
    PBSysKeyboardKey_Grave = 0x0060,

    // Unicode symbols
    PBSysKeyboardKey_Escape = 0x238B,    // ESC
    PBSysKeyboardKey_Enter = 0x23CE,     // RETURN SYMBOL
    PBSysKeyboardKey_Tab = 0x21E5,       // TAB
    PBSysKeyboardKey_Backspace = 0x232B, // ERASE TO THE LEFT
    PBSysKeyboardKey_Insert = 0x2380,    // INSERT
    PBSysKeyboardKey_Delete = 0x2326,    // ERASE TO THE RIGHT
    PBSysKeyboardKey_Left = 0x2190,
    PBSysKeyboardKey_Right = 0x2192,
    PBSysKeyboardKey_Down = 0x2193,
    PBSysKeyboardKey_Up = 0x2191,
    PBSysKeyboardKey_PageUp = 0x21DE,
    PBSysKeyboardKey_PageDown = 0x21DF,
    PBSysKeyboardKey_Home = 0x21F1,
    PBSysKeyboardKey_End = 0x21F2,

    PBSysKeyboardKey_CapsLock = 0x21EA,
    PBSysKeyboardKey_LeftShift = 0x21E7,
    PBSysKeyboardKey_LeftCtrl = 0x2303,
    PBSysKeyboardKey_LeftAlt = 0x2325,
    PBSysKeyboardKey_LeftSuper = 0x2318,

    PBSysKeyboardKey_MediaNext = 0x23ED,
    PBSysKeyboardKey_MediaPrev = 0x23EE,
    PBSysKeyboardKey_MediaPlay = 0x23F5,
    PBSysKeyboardKey_MediaStop = 0x23F9,

    // Private use area (0xE000-0xEFFF)
    PBSysKeyboardKey_World1 = 0xE000,
    PBSysKeyboardKey_World2 = 0xE001,

    PBSysKeyboardKey_ScrollLock = 0xE010,
    PBSysKeyboardKey_NumLock = 0xE011,
    PBSysKeyboardKey_PrintScreen = 0xE012,
    PBSysKeyboardKey_Pause = 0xE013,

    PBSysKeyboardKey_F1 = 0xE100,
    PBSysKeyboardKey_F2 = 0xE101,
    PBSysKeyboardKey_F3 = 0xE102,
    PBSysKeyboardKey_F4 = 0xE103,
    PBSysKeyboardKey_F5 = 0xE104,
    PBSysKeyboardKey_F6 = 0xE105,
    PBSysKeyboardKey_F7 = 0xE106,
    PBSysKeyboardKey_F8 = 0xE107,
    PBSysKeyboardKey_F9 = 0xE108,
    PBSysKeyboardKey_F10 = 0xE109,
    PBSysKeyboardKey_F11 = 0xE10A,
    PBSysKeyboardKey_F12 = 0xE10B,
    PBSysKeyboardKey_F13 = 0xE10C,
    PBSysKeyboardKey_F14 = 0xE10D,
    PBSysKeyboardKey_F15 = 0xE10E,
    PBSysKeyboardKey_F16 = 0xE10F,
    PBSysKeyboardKey_F17 = 0xE110,
    PBSysKeyboardKey_F18 = 0xE111,
    PBSysKeyboardKey_F19 = 0xE112,
    PBSysKeyboardKey_F20 = 0xE113,
    PBSysKeyboardKey_F21 = 0xE114,
    PBSysKeyboardKey_F22 = 0xE115,
    PBSysKeyboardKey_F23 = 0xE116,
    PBSysKeyboardKey_F24 = 0xE117,

    PBSysKeyboardKey_Numpad0 = 0xE200,
    PBSysKeyboardKey_Numpad1 = 0xE201,
    PBSysKeyboardKey_Numpad2 = 0xE202,
    PBSysKeyboardKey_Numpad3 = 0xE203,
    PBSysKeyboardKey_Numpad4 = 0xE204,
    PBSysKeyboardKey_Numpad5 = 0xE205,
    PBSysKeyboardKey_Numpad6 = 0xE206,
    PBSysKeyboardKey_Numpad7 = 0xE207,
    PBSysKeyboardKey_Numpad8 = 0xE208,
    PBSysKeyboardKey_Numpad9 = 0xE209,
    PBSysKeyboardKey_NumpadDot = 0xE20A,
    PBSysKeyboardKey_NumpadDivide = 0xE20B,
    PBSysKeyboardKey_NumpadMultiply = 0xE20C,
    PBSysKeyboardKey_NumpadSubtract = 0xE20D,
    PBSysKeyboardKey_NumpadAdd = 0xE20E,
    PBSysKeyboardKey_NumpadEnter = 0xE20F,
    PBSysKeyboardKey_NumpadEquals = 0xE210,
    PBSysKeyboardKey_NumpadClear = 0xE211,

    PBSysKeyboardKey_RightShift = 0xE300,
    PBSysKeyboardKey_RightCtrl = 0xE301,
    PBSysKeyboardKey_RightAlt = 0xE302,
    PBSysKeyboardKey_RightSuper = 0xE303,

    PBSysKeyboardKey_Menu = 0xE310,

    PBSysKeyboardKey_VolumeUp = 0xE320,
    PBSysKeyboardKey_VolumeDown = 0xE321,
    PBSysKeyboardKey_Mute = 0xE322,

    PBSysKeyboardKey_COUNT
} PBSysKeyboardKey;
```

### `PBSysMouseButton`

```c
typedef enum PBSysMouseButton PB_ENUM_TYPE(u16){
    PBSysMouseButton_Left = 0,
    PBSysMouseButton_Right = 1,
    PBSysMouseButton_Middle = 2,
    PBSysMouseButton_X1 = 3,
    PBSysMouseButton_X2 = 4,
    // NOTE: unnamed buttons here
    PBSysMouseButton_COUNT = 16,
} PBSysMouseButton;
```

### `PBSysEventType`

```c
typedef enum PBSysEventType PB_ENUM_TYPE(u16){
    PBSysEventType_INVALID = 0,

    // signal
    PBSysEventType_SIGNAL,

    // pointer
    PBSysEventType_POINTER_ENTER, // pointer started being "in" the surface/window
    PBSysEventType_POINTER_LEAVE, // pointer left the surface/window
    PBSysEventType_POINTER_DOWN,
    PBSysEventType_POINTER_UP,
    PBSysEventType_POINTER_MOVE,
    PBSysEventType_POINTER_CANCEL, // system canceled a sequence (e.g. OS interruption)

    // scroll
    PBSysEventType_SCROLL,

    // gesture
    PBSysEventType_GESTURE_PAN,    // translation (typically dp)
    PBSysEventType_GESTURE_PINCH,  // scale factor (relative)
    PBSysEventType_GESTURE_ROTATE, // radians (relative)

    // keyboard
    PBSysEventType_KEY_DOWN,
    PBSysEventType_KEY_UP,
} PBSysEventType;
```

### `PBSysEvent`

```c
typedef struct PBSysEvent {
    u16           size;     // size of the event
    u16           type;     // PBSysEventType
    PBSysObjectId objectId; // originating object ID, e.g. window (0 means "unknown")
} PB_ATTR_ALIGNED(8) PBSysEvent;
```

### `PBSysSignalEvent`

```c
typedef struct PBSysSignalEvent {
    PBSysEvent      event;
    PBSysHandle     handle;
    PBSysSignals    signals;
    PBSysSignals    pulseSignals;
    PBSysObjectType objectType;
    u16             _reserved;
} PBSysSignalEvent;
```

### `PBSysInputEvent`

```c
typedef struct PBSysInputEvent {
    PBSysEvent event;
    PBSysTime  timestamp; // time the event occurred
    u32        clientId;  // originating client ID (0 for "local")
    u32        deviceId;  // stable per HID
    u16        modifiers; // PBSysKeyboardModifiers
    u16        _reserved;
} PBSysInputEvent;
```

### `PBSysPointerEvent`

```c
typedef struct PBSysPointerEvent {
    PBSysInputEvent  inputEvent;
    u32              pointerId;  // logical; stable per active contact/stream
    u16              flags;      // PBSysPointerFlags
    u16              buttons;    // current button bitmask (mouse/pen)
    u8               button;     // "changed" button for DOWN/UP/CLICK (0 if n/a)
    PBSysPointerKind kind;       //
    u8               clickCount; // for CLICK (and optionally DOWN/UP if platform provides)
    u8               _reserved;  //
    f32              x, y;       // position in window coords (dp)
    f32              dx, dy;     // delta since last event for this pointerId (dp). 0 if unknown.
} PBSysPointerEvent;
```

### `PBSysPenPointerEvent`

```c
typedef struct PBSysPenPointerEvent {
    PBSysPointerEvent pointerEvent;
    f32               pressure;           // [0..1]
    f32               tangentialPressure; // [0..1] barrel pressure (pen)
    f32               tiltX, tiltY;       // [-1, +1] 0 = perpendicular
    f32               twist;              // degrees [0, 359]; barrel rotation (pen)
    f32               width, height;      // contact ellipse in dp (touch/pen)
    f32               altitudeAngle;      // [0, π/2] radians (0 = parallel, π/2 = perpendicular)
    f32               azimuthAngle;       // [0, π/2] radians, direction in the screen plane
} PBSysPenPointerEvent;
```

### `PBSysScrollEvent`

```c
typedef struct PBSysScrollEvent {
    PBSysInputEvent  inputEvent;
    PBSysPointerKind kind;
    PBSysScrollPhase phase;
    u16              flags;  // PBSysScrollFlags
    f32              x, y;   // focus point in window coords if known, else 0
    f32              dx, dy; // scroll delta (dp or lines/pages depending on flags)
    f32              wheelZ; // optional for 3D wheels; else 0
} PBSysScrollEvent;
```

### `PBSysGestureEvent`

```c
typedef struct PBSysGestureEvent {
    PBSysInputEvent   inputEvent;
    PBSysGesturePhase phase;
    u8                _reserved;
    u16               flags;    // currenty unused
    f32               x, y;     // gesture center in window coords (dp) if known
    f32               dx, dy;   // pan delta (dp) for PAN; else 0
    f32               scale;    // relative scale delta for PINCH (1.0 means no change; e.g. 1.02)
    f32               rotation; // relative rotation delta in radians for ROTATE
} PBSysGestureEvent;
```

### `PBSysKeyboardEvent`

```c
typedef struct PBSysKeyboardEvent {
    PBSysInputEvent  inputEvent;
    PBSysKeyboardKey keyCode;    // logical code for the key, i.e. "the A key"
    PBSysKeyboardKey deviceCode; // physical key, i.e. "3rd key on 4th row"
    u32              text[8];    // Unicode representation
    u8               textLen;    // number of codepoints in text array
    u8               _reserved;  //
    u16              flags;      // PBSysKeyboardFlags
} PBSysKeyboardEvent;
```

### `PBSysFileId`

```c
typedef struct PBSysFileId {
    u8 data[32];
} PBSysFileId;
```

### `PBSysFileMode`

```c
typedef u16 PBSysFileMode;
```

### `PBSysFileModes`

```c
enum PBSysFileModes PB_ENUM_TYPE(PBSysFileMode){
    PBSysFileMode_USER_R = 0400,    // user (file owner) has read permission
    PBSysFileMode_USER_W = 0200,    // user has write permission
    PBSysFileMode_USER_X = 0100,    // user has execute permission
    PBSysFileMode_USER_RW = 0600,   // user has read and write permissions
    PBSysFileMode_USER_RWX = 0700,  // user has read, write, and execute permissions
    PBSysFileMode_GROUP_R = 0040,   // group has read permission
    PBSysFileMode_GROUP_W = 0020,   // group has write permission
    PBSysFileMode_GROUP_X = 0010,   // group has execute permission
    PBSysFileMode_GROUP_RW = 0060,  // group has read and write execute permissions
    PBSysFileMode_GROUP_RWX = 0070, // group has read, write, and execute permissions
    PBSysFileMode_OTHER_R = 0004,   // others have read permission
    PBSysFileMode_OTHER_W = 0002,   // others have write permission
    PBSysFileMode_OTHER_X = 0001,   // others have execute permission
    PBSysFileMode_OTHER_RW = 0006,  // others have read and write execute permissions
    PBSysFileMode_OTHER_RWX = 0007, // others have read, write, and execute permissions
};
```

### `PBSysFileOpenFlags`

```c
typedef enum PBSysFileOpenFlags PB_ENUM_TYPE(u64){
    PBSysFileOpenFlag_READ = 1 << 0,                               // give file PBSysRight_READ
    PBSysFileOpenFlag_WRITE = 1 << 1,                              // give file PBSysRight_WRITE
    PBSysFileOpenFlag_APPEND = (1 << 2) | PBSysFileOpenFlag_WRITE, // open in append mode
    PBSysFileOpenFlag_CREATE = 1 << 7, // create file if it does not exist

    // PBSysFileOpenFlag_MODE_MASK masks mode bits in flags, for use with CREATE flag
    PBSysFileOpenFlag_MODE_MASK = 0xffff << 8,
    PBSysFileOpenFlag_MODE_USER_R = PBSysFileMode_USER_R << 8,
    PBSysFileOpenFlag_MODE_USER_W = PBSysFileMode_USER_W << 8,
    PBSysFileOpenFlag_MODE_USER_X = PBSysFileMode_USER_X << 8,
    PBSysFileOpenFlag_MODE_USER_RWX = PBSysFileMode_USER_RWX << 8,
    PBSysFileOpenFlag_MODE_GROUP_R = PBSysFileMode_GROUP_R << 8,
    PBSysFileOpenFlag_MODE_GROUP_W = PBSysFileMode_GROUP_W << 8,
    PBSysFileOpenFlag_MODE_GROUP_X = PBSysFileMode_GROUP_X << 8,
    PBSysFileOpenFlag_MODE_GROUP_RWX = PBSysFileMode_GROUP_RWX << 8,
    PBSysFileOpenFlag_MODE_OTHER_R = PBSysFileMode_OTHER_R << 8,
    PBSysFileOpenFlag_MODE_OTHER_W = PBSysFileMode_OTHER_W << 8,
    PBSysFileOpenFlag_MODE_OTHER_X = PBSysFileMode_OTHER_X << 8,
    PBSysFileOpenFlag_MODE_OTHER_RWX = PBSysFileMode_OTHER_RWX << 8,
} PBSysFileOpenFlags;
```

### `PBSysFileReadFlags`

```c
typedef enum PBSysFileReadFlags PB_ENUM_TYPE(u64){
    PBSysFileReadFlag_SYNC = 1 << 0, // blocking read
} PBSysFileReadFlags;
```

### `PBSysFileWriteFlags`

```c
typedef enum PBSysFileWriteFlags PB_ENUM_TYPE(u64){
    PBSysFileWriteFlag_SYNC = 1 << 0, // blocking write
} PBSysFileWriteFlags;
```

### `PBSysFileListEntryType`

```c
typedef enum PBSysFileListEntryType PB_ENUM_TYPE(u8){
    PBSysFileListEntryType_UNKNOWN = 0,   // underlying filesyestem does not report types
    PBSysFileListEntryType_DIR = 1,       // directory
    PBSysFileListEntryType_FILE = 2,      // regular file
    PBSysFileListEntryType_LINK = 3,      // symbolic link
    PBSysFileListEntryType_SOCKET = 4,    // local socket
    PBSysFileListEntryType_SPECIAL = 100, // none of the above (e.g. fifo, char dev. etc.)
} PBSysFileListEntryType;
```

### `PBSysFileListEntry`

```c
typedef struct PBSysFileListEntry {
    u64                    id; // file's unique ID within the file system (inode ID or similar)
    PBSysFileListEntryType type;
} PBSysFileListEntry;
```

### `PBSysCursorStyle`

```c
typedef enum PBSysCursorStyle PB_ENUM_TYPE(uint16_t){
    PBSysCursorStyle_NONE = 0, //
    PBSysCursorStyle_IMAGE,    //
    PBSysCursorStyle_POINTER,  //
    PBSysCursorStyle_HAND,     //
    PBSysCursorStyle_TEXT,     //
    PBSysCursorStyle_HIDDEN,   //
    PBSysCursorStyle_LOADING,  //
    PBSysCursorStyle_BLOCKED,  //
    PBSysCursorStyle_PAN,      //
    PBSysCursorStyle_SIZEH,    //
    PBSysCursorStyle_SIZEV,    //
    PBSysCursorStyle_SIZENESW, //
    PBSysCursorStyle_SIZENWSE, //
    PBSysCursorStyle_SCROLLNS, //
    PBSysCursorStyle_SCROLLN,  //
    PBSysCursorStyle_SCROLLS,  //
} PBSysCursorStyle;
```

### `PBSysHandleName`

```c
typedef u16 PBSysHandleName;
```

PBSysHandleName names special well-defined objects

### `PBSysHandleInfo`

```c
typedef struct PBSysHandleInfo {
    PBSysHandle     handle;
    PBSysRights     rights;
    PBSysHandleName name;
    PBSysObjectType objectType;
    PBSysObjectId   objectId;
} PBSysHandleInfo;
```

### `PBSysNetSessionConfig`

```c
typedef struct PBSysNetSessionConfig {
    u64                flags;         // unused, set to 0
    u64                authId;        // local auth state key. Use 0 for default.
    const u8* nullable serverAddr;    // "host:port" as UTF-8 text. Leave empty for default.
    u32                serverAddrLen; // number of bytes at serverAddr
} PBSysNetSessionConfig;
```

### `PBSysNetConnectConfig`

```c
typedef struct PBSysNetConnectConfig {
    u64 flags; // unused, set to 0
} PBSysNetConnectConfig;
```

### `PBSysStreamWriteFlags`

```c
typedef enum PBSysStreamWriteFlags PB_ENUM_TYPE(u32){
    PBSysStreamWrite_SYNC = 1, // complete write immediately or fail with PBSysErr_AGAIN
} PBSysStreamWriteFlags;
```

### `PBSysStreamStats`

```c
typedef struct PBSysStreamStats {
    PBSysTime timestamp; // time at which the statistics were gathered

    /*
    bytesReceived indicates the number of bytes received by this stream, up to the first missing byte. The number does not include any network or transport overhead, and can only increase over time.
    */
    u64 bytesReceived;

    /*
    bytesRead indicates the number of bytes the application has read from this stream. This number can only increase, and is always less than or equal to bytesReceived.
    */
    u64 bytesRead;
} PBSysStreamStats;
```

### `PBSysTextplanSelectionRect`

```c
typedef struct PBSysTextplanSelectionRect {
    i32 x, y;
    i32 width, height;
} PBSysTextplanSelectionRect;
```

### `PBSysTextplanSelection`

```c
typedef struct PBSysTextplanSelection {
    u64 anchor;
    u64 caret;
    u64 lastDown;
} PBSysTextplanSelection;
```

### `PBSysWindowSignals`

```c
typedef enum PB_ENUM_TYPE(u32) {
    // PBSysWindowSignal_RESIZE is pulsed when the window's size and/or pixel density changes
    PBSysWindowSignal_RESIZE = 1u << 0, // pulse

    // PBSysWindowSignal_MOVE is pulsed when the window's position on screen change
    PBSysWindowSignal_MOVE = 1u << 1, // pulse

    /*
    PBSysWindowSignal_FRAME_SYNC is pulsed when the window's display finised presenting a frame. You can retrieve the estimated presentation time of the next frame via frameTime from PBSysWindowInfoGet.
    */
    PBSysWindowSignal_FRAME_SYNC = 1u << 2,

    /*
    PBSysWindowSignal_REPAINT is pulsed when the window's content need to be drawn again. This signal is only used on hosts which does not retain the window contents when a window is not displayed on screen.
    */
    PBSysWindowSignal_REPAINT = 1u << 3, // pulse

    // PBSysWindowSignal_KEY is active when the window is the key window of the application
    PBSysWindowSignal_KEY = 1u << 4,
} PBSysWindowSignals;
```

### `PBSysThreadConfig`

```c
typedef struct PBSysThreadConfig {
    PBSysThreadEntry entry;
    u64              arg1, arg2;

    // thread stack memory
    void* stack;
    u32   stackSize;

    /*
    rights for the new thread's SELF_THREAD handle. Usually you want this to be PBSysRight_SAME_RIGHTS
    */
    PBSysRights rights;

    // handles to be transferred from the caller to the new thread
    const PBSysHandle* nullable transferHandles;
    u32                         transferHandlesCount;
} PBSysThreadConfig;
```

### `PBSysWindowSetRectFlags`

```c
typedef u64 PBSysWindowSetRectFlags;
```

### `PBSysWindowCreateTextureFlags`

```c
typedef u32 PBSysWindowCreateTextureFlags;
```

### `PBSysWindowStyle`

```c
typedef u64 PBSysWindowStyle;
```

### `PBSysWindowConfig`

```c
typedef struct PBSysWindowConfig {
    f32                x, y;          // location on screen in dp (-1 = default location)
    f32                width, height; // content size in dp (0 = default size)
    const u8* nullable title;         // UTF-8 text
    u32                titleLen;      // number of bytes at 'title'
    u64                _reserved[4];
} PBSysWindowConfig;
```

### `PBSysWindowInfo`

```c
typedef struct PBSysWindowInfo {
    f32              x, y;                        // position of top-left corner on screen, in dp
    f32              width, height;               // size of window in dp (including OS decorations)
    f32              minWidth, minHeight;         // lower limit of width & height
    f32              maxWidth, maxHeight;         // upper limit of width & height
    f32              contentX, contentY;          // offset of content relative to the window frame
    f32              contentWidth, contentHeight; // size of window contents in dp
    f32              dpScale;                     // number of pixels per dp
    u32              _reserved1;
    PBSysWindowStyle style;
    PBSysTime        frameTime; // estimated presentation time of next frame
} PBSysWindowInfo;
```

### `PBSysWindowRendererShapeItem`

```c
typedef struct PBSysWindowRendererShapeItem {
    struct {
        f32 x, y, z, w;
    } bounds; // (minX, minY, maxX, maxY)

    struct {
        u16 x, y, z, w;
    } cornerRadius; // Per-corner radii (pixels): (tl, tr, br, bl)

    u64 fillColor; // 0xAAAARRRRGGGGBBBB
    u64 fillColors[4];
    u64 strokeColor; // 0xAAAARRRRGGGGBBBB
    f32 strokeWidth; // px
    u32 flags;       // 1=stroke_inside, 2=stroke_outside, 4=clip
    f32 blur;        // px
    f32 opacity;     // 0->1 percent

    // UV sub-rectangle for texture sampling.
    struct {
        f32 x, y;
    } uvMin; // top-left UV
    struct {
        f32 x, y;
    } uvMax; // bottom-right UV

    u8 padding[8];
} PBSysWindowRendererShapeItem;
```

### `PBSysWindowRendererTextItem`

```c
typedef struct PBSysWindowRendererTextItem {
    struct {
        f32 x, y, z, w;
    } bounds;

    PBSysHandle textPlan;

    u64 overrideColor; // 0xAAAARRRRGGGGBBBB
    u32 flags;         // 1=override color
    u8  padding[4];
} PBSysWindowRendererTextItem;
```

### `PBSysWindowRendererClipItem`

```c
typedef struct PBSysWindowRendererClipItem {
    struct {
        f32 x, y, z, w;
    } bounds;
} PBSysWindowRendererClipItem;
```

### `PBSysWindowRendererInstructionKind`

```c
typedef enum PBSysWindowRendererInstructionKind {
    PBSysWindowRendererInstructionKind_SHAPE,
    PBSysWindowRendererInstructionKind_TEXT,
    PBSysWindowRendererInstructionKind_CLIP_PUSH,
    PBSysWindowRendererInstructionKind_CLIP_POP,
    PBSysWindowRendererInstructionKind_TEXTURE_SET, // set/clear the active texture for SHAPE draws
} PBSysWindowRendererInstructionKind;
```

### `PBSysWindowRendererInstruction`

```c
typedef struct PBSysWindowRendererInstruction {
    PBSysWindowRendererInstructionKind kind;

    union {
        // a run of renderable "content"
        struct {
            u32 runLength;
        } content;
        // TEXTURE_SET: set active texture; PBSysHandle_INVALID clears to default (no texture)
        struct {
            PBSysHandle texture;
        } setTexture;
    };
} PBSysWindowRendererInstruction;
```

### `PBSysWindowRendererPackage`

```c
typedef struct PBSysWindowRendererPackage {
    u64 backgroundColor; // 0xAAAARRRRGGGGBBBB

    const PBSysWindowRendererShapeItem* shapes;
    u32                                 shapesLen;
    u32                                 shapeSize;

    const PBSysWindowRendererTextItem* texts;
    u32                                textsLen;
    u32                                textSize;

    const PBSysWindowRendererInstruction* instructions;
    u32                                   instructionsLen;
    u32                                   instructionSize;

    const PBSysWindowRendererClipItem* clips;
    u32                                clipsLen;
    u32                                clipSize;
} PBSysWindowRendererPackage;
```

### `PBSysCallOp`

```c
typedef enum PBSysCallOp PB_ENUM_TYPE(uint32_t){
    PBSysCallOp_None = 0, // invalid
    PBSysCallOp_AudioBufferCreate = 117,
    PBSysCallOp_AudioBufferCreateFromFile = 121,
    PBSysCallOp_AudioBufferDestroy = 118,
    PBSysCallOp_AudioBufferPlay = 119,
    PBSysCallOp_AudioOutputInit = 122,
    PBSysCallOp_AudioSetVolume = 120,
    PBSysCallOp_BundleGetResource = 125,
    PBSysCallOp_ChannelCreate = 65,
    PBSysCallOp_ChannelDisableWrite = 68,
    PBSysCallOp_ChannelRead = 66,
    PBSysCallOp_ChannelWrite = 67,
    PBSysCallOp_ClockMonotonic = 56,
    PBSysCallOp_ClockRead = 25,
    PBSysCallOp_ClockReadInfo = 60,
    PBSysCallOp_EventPoll = 58,
    PBSysCallOp_FileListOpen = 98,
    PBSysCallOp_FileOpen = 103,
    PBSysCallOp_FileRead = 104,
    PBSysCallOp_FileWrite = 105,
    PBSysCallOp_FileListNext = 102,
    PBSysCallOp_GuiCursorStyleSet = 69,
    PBSysCallOp_HandleClose = 70,
    PBSysCallOp_HandleDuplicate = 71,
    PBSysCallOp_HandleList = 77,
    PBSysCallOp_NetConnect = 95,
    PBSysCallOp_NetSessionOpen = 90,
    PBSysCallOp_NetSessionId = 93,
    PBSysCallOp_NetSessionOpenStream = 91,
    PBSysCallOp_ObjectObserve = 57,
    PBSysCallOp_ObjectSignal = 55,
    PBSysCallOp_StreamOpenPipePair = 92,
    PBSysCallOp_StreamRead = 46,
    PBSysCallOp_StreamStatsRead = 94,
    PBSysCallOp_StreamWrite = 28,
    PBSysCallOp_TextplanGetCaretBounds = 81,
    PBSysCallOp_TextplanGetSelectionRects = 83,
    PBSysCallOp_TextplanGetSize = 38,
    PBSysCallOp_TextplanHitTest = 82,
    PBSysCallOp_TextplanLayout = 40,
    PBSysCallOp_TextplanMoveSelection = 85,
    PBSysCallOp_TextplanMoveSelectionToPoint = 84,
    PBSysCallOp_TextplanMoveSelectionVertical = 88,
    PBSysCallOp_TextureWrite = 106,
    PBSysCallOp_ThreadEnterMain = 59,
    PBSysCallOp_ThreadExit = 30,
    PBSysCallOp_ThreadExitProcess = 31,
    PBSysCallOp_ThreadExitStatus = 47,
    PBSysCallOp_ThreadHostControllerConnect = 79,
    PBSysCallOp_ThreadLogWrite = 32,
    PBSysCallOp_ThreadNetConnect = 42,
    PBSysCallOp_ThreadRead = 76,
    PBSysCallOp_ThreadStart = 33,
    PBSysCallOp_ThreadWindowCreate = 41,
    PBSysCallOp_ThreadWrite = 75,
    PBSysCallOp_WindowClipboardReadText = 107,
    PBSysCallOp_WindowClipboardWriteText = 108,
    PBSysCallOp_WindowCopyTitle = 126,
    PBSysCallOp_WindowCreateTexture = 109,
    PBSysCallOp_WindowCreateTextureFromData = 110,
    PBSysCallOp_WindowFrameSyncEnable = 63,
    PBSysCallOp_WindowInfoGet = 64,
    PBSysCallOp_WindowRendererPackageWrite = 78,
    PBSysCallOp_WindowSetRect = 87,
    PBSysCallOp_WindowSetStyle = 127,
    PBSysCallOp_WindowSetTitle = 80,
    PBSysCallOp_WindowSizeLimitsSet = 128,
    PBSysCallOp_WindowTextplanCreate = 36,
    PBSysCallOp_READ = 9,               // legacy
    PBSysCallOp_WGPU = 10,              // legacy
    PBSysCallOp_CURSOR = 14,            // legacy
    PBSysCallOp_RES_CREATE = 15,        // legacy
    PBSysCallOp_RES_MUTATE = 16,        // legacy
    PBSysCallOp_RES_ADVERTISE_NEW = 17, // legacy
    PBSysCallOp_TAKE_ROOT_CAP = 18,     // legacy
    PBSysCallOp_OPEN = 19,              // legacy
} PBSysCallOp;
```

### `PBSysHandle`

```c
typedef i32 PBSysHandle;
```

PBSysHandle represents a handle to a runtime object.
A handle can be thought of as a session or connection to a particular runtime object.
Note: negative values signifies `PBSysErr` and are invalid as handles.

### `PBSysHandlePair`

```c
typedef struct PBSysHandlePair {
    PBSysHandle a, b;
} PBSysHandlePair;
```

### `PBSysTime`

```c
typedef u64 PBSysTime;
```

PBSysTime represents a point in system time (nanoseconds in monotonic-clock space)

### `PBSysDuration`

```c
typedef i64 PBSysDuration;
```

PBSysDuration represents a duration of time, measured in nanoseconds.

### `PBSysDate`

```c
typedef i64 PBSysDate;
```

PBSysDate represents a point in "real" time (microseconds since 1970-01-01 00:00:00 UTC.)
Range limit: [290309 BCE, Dec 22, 19:59:05 UTC - 294247, Jan 10, 04:00:54 UTC]

### `PBSysStr`

```c
typedef struct PBSysStr {
    uint32_t len;
    uint8_t  bytes[];
} PBSysStr;
```

### `PBSysBuf`

```c
typedef struct PBSysBuf {
    const uint8_t* nullable bytes;
    size_t                  len;
} PBSysBuf;
```

### `PBSysObjectId`

```c
typedef u32 PBSysObjectId;
```

PBSysObjectId uniquely identifies a system object

### `PBSysSignals`

```c
typedef u32 PBSysSignals;
```

PBSysSignals is a bitset of signals.
- Bits 1 through 24 are reserved for the system.
- Bits 25 through 32 are reserved for user-defined signals.

### `PBSysEventLegacy`

```c
typedef struct PBSysEventLegacy {
    uint16_t type; // PBSysEventLegacyType
    uint8_t  _reserved[6];
    union {
        struct { // PBSysEventLegacy_START
            uint32_t                  flags;
            uint32_t                  sysbufSize;
            void*                     sysbuf;
            PBSysHandleInfo* nullable handles;
            uint32_t                  handlesCount;
            uint64_t                  arg1, arg2; // values passed to PBSysThreadStart
        } start;
        struct { // PBSysEventLegacy_READ
            int32_t     result;
            PBSysHandle from;
            uint64_t    ud; // associated user data
        } read;
        struct { // PBSysEventLegacy_WRITE
            int32_t     result;
            PBSysHandle to;
            uint64_t    ud; // associated user data
        } write;
        struct { // PBSysEventLegacy_INPUT
            uint32_t type;
            uint32_t window;
            uint16_t index;
            uint16_t flags;
            uint32_t value;
            uint32_t extra1;
            uint32_t extra2;
        } input;
        struct { // PBSysEventLegacy_AUDIO_OUT
            uint16_t channelCount;
            uint16_t _reserved;
            uint32_t sampleCount; // per channel
            float    sampleRate;  // HZ
            float*   samples;     // interleaved, channels * sampleCount
        } audioOut;
        struct {                  // PBSysEventLegacy_RESIZE
            uint32_t width;       // TODO(rsms): unit?
            uint32_t height;      // TODO(rsms): unit?
            uint32_t scaleFactor; // percentage. TODO(rsms): change to f32 or f64
        } resize;
        struct { // PBSysEventLegacy_DISPLAY_SYNC
            uint32_t displayId;
            uint32_t width;
            uint32_t height;
            uint32_t scaleFactor;
            uint64_t frameTime; // in PBSysOp_CLOCK space
        } displaySync;
        struct { // PBSysEventLegacy_WGPU_CALLBACK
            PBWgpuCallbackKind            kind;
            PBSysEventLegacy_WgpuCallback data;
        } wgpuCallback;
        struct {                    // PBSysEventLegacy_THREAD_EXIT
            PBSysHandle thread;     // what thread exited
            int32_t     status;     // value passed to PBSysThreadExit
            void*       sysbuf;     // value passed to PBSysThreadStart
            uint32_t    sysbufSize; // value passed to PBSysThreadStart
            uint64_t    arg1, arg2; // values passed to PBSysThreadStart
        } threadExit;
        struct {               // PBSysEventLegacy_TIMER
            PBSysHandle timer; // what timer rang
        } timer;
        struct { // PBSysEventLegacy_SIGNAL
            PBSysSignals signals;
            PBSysHandle  handle;
            uint64_t     ud; // value provided to PBSysObjectObserve
        } signal;
        uint8_t _info[64];
    };
} PBSysEventLegacy;
```

PBSysEventLegacy describes an event produced by the Playbit system.
See sysevents.h for complete definition.

### `PBSysThreadEntry`

```c
typedef void (*PBSysThreadEntry)(uint64_t, uint64_t);
```

PBSysThreadEntry

### `PBSysTextureFormat`

```c
typedef enum PB_ENUM_TYPE(u32) {
    PBSysTextureFormat_UNKNOWN,
    PBSysTextureFormat_RGBA8,
} PBSysTextureFormat;
```

### `PBSysNetSessionSignals`

```c
typedef enum PB_ENUM_TYPE(uint32_t) {
    /*
    PBSysNetSessionSignal_AVAILABLE means the session's underlying AP transport is connected. The runtime may still be authenticating the session while this signal is active without `PBSysNetSessionSignal_READY`.
    */
    PBSysNetSessionSignal_AVAILABLE = 1u << 4,

    /*
    PBSysNetSessionSignal_READY means the session is authenticated and its AP streams may become writable. When this signal is active, `PBSysNetSessionSignal_AVAILABLE` is also active.
    */
    PBSysNetSessionSignal_READY = 1u << 0,
} PBSysNetSessionSignals;
```

This file defines all syscalls.

Syscalls are executed via `pb_syscall` defined in abi.h.

The API only evolves forward; syscalls are backwards compatible, (i.e. a program built for an older system works on newer systems.)

### `PBSysChannelSignals`

```c
typedef enum PB_ENUM_TYPE(uint32_t) {
    PBSysChannelSignal_READABLE = 1u << 0,       // there are entries to read
    PBSysChannelSignal_WRITABLE = 1u << 1,       // there's space for writing at least one entry
    PBSysChannelSignal_WRITE_DISABLED = 1u << 2, // writing has been closed
} PBSysChannelSignals;
```

### `PBSysClockSignals`

```c
typedef enum PB_ENUM_TYPE(uint32_t) {
    PBSysClockSignal_TIME_ZONE = 1u << 0, // time zone changed (pulse)
} PBSysClockSignals;
```

### `PBSysStreamSignals`

```c
typedef enum PB_ENUM_TYPE(uint32_t) {
    PBSysStreamSignal_READABLE = 1u << 0,
    PBSysStreamSignal_WRITABLE = 1u << 1,
    PBSysStreamSignal_PEER_CLOSED = 1u << 2,
    PBSysStreamSignal_PEER_WRITE_DISABLED = 1u << 3,
    PBSysStreamSignal_WRITE_DISABLED = 1u << 4,
} PBSysStreamSignals;
```

### `PBSysHandleListFlags`

```c
typedef enum PB_ENUM_TYPE(u64) {
    PBSysHandleList_FILTER = 0xff, // mask for a PBSysHandleListFilter_ value
} PBSysHandleListFlags;
```

### `PBSysHandleListFilter`

```c
typedef enum PB_ENUM_TYPE(u8) {
    PBSysHandleListFilter_BY_NAME = 1,        // predicate is of type PBSysHandleName
    PBSysHandleListFilter_BY_OBJECT_ID = 2,   // predicate is of type PBSysObjectId
    PBSysHandleListFilter_BY_OBJECT_TYPE = 3, // predicate is of type PBSysObjectType
} PBSysHandleListFilter;
```

## Constants

| Name | Type | Value | Description |
| --- | --- | --- | --- |
| `PBSysHandle_INVALID` | `PBSysHandle` | `0` |  |
| `PBSysHandle_SELF_THREAD` | `PBSysHandle` | `1` | current thread |
| `PBSysHandleName_CONSOLE` | `PBSysHandleName` | `` | the console |
| `PBSysHandleName_NONE` | `PBSysHandleName` | `0` |  |
| `PBSysHandleName_USER_MAX` | `PBSysHandleName` | `32767` |  |
| `PBSysNetSessionChannelIdMaxLen` | `int` | `64` | max allowed length of a channelId |
| `PBSysNetSessionIdMaxLen` | `int` | `64` | max allowed length of a sessionId |
| `PBSysObjectId_MAIN_THREAD` | `PBSysObjectId` | `1` |  |
| `PBSysObjectId_ROOT_FS` | `PBSysObjectId` | `2` |  |
| `PBSysObjectObserve_ADD` | `u32` | `2` |     PBSysObjectObserve_ADD causes `signals` to be added to any signals already observed for the handle. Without this flag, the behavior is that `signals` replaces any already-observed signals. The ADD flag is mainly useful in combination with the ONCE flag. |
| `PBSysObjectObserve_ONCE` | `u32` | `1` | PBSysObjectObserve_ONCE changes the behavior of event delivery to being "edge" triggered |
| `PBSysSignal_ALL` | `u32` | `4294967295` |  |
| `PBSysSignal_SYSTEM_ALL` | `u32` | `16777215` |  |
| `PBSysSignal_USER_0` | `u32` | `16777216` |  |
| `PBSysSignal_USER_1` | `u32` | `33554432` |  |
| `PBSysSignal_USER_2` | `u32` | `67108864` |  |
| `PBSysSignal_USER_3` | `u32` | `134217728` |  |
| `PBSysSignal_USER_4` | `u32` | `268435456` |  |
| `PBSysSignal_USER_5` | `u32` | `536870912` |  |
| `PBSysSignal_USER_6` | `u32` | `1073741824` |  |
| `PBSysSignal_USER_7` | `u32` | `2147483648` |  |
| `PBSysSignal_USER_ALL` | `u32` | `4278190080` |  |
| `PBSysTextplanSelectionAdjustment_ALL_GRANULARITY` | `int` | `4` |  |
| `PBSysTextplanSelectionAdjustment_BACKWARDS` | `int` | `8` |  |
| `PBSysTextplanSelectionAdjustment_DELETE_AFTERWARDS` | `int` | `64` |  |
| `PBSysTextplanSelectionAdjustment_IN_LINE_GRANULARITY` | `int` | `32` |  |
| `PBSysTextplanSelectionAdjustment_LINE_ENDS_GRANULARITY` | `int` | `128` |  |
| `PBSysTextplanSelectionAdjustment_LINE_GRANULARITY` | `int` | `2` |  |
| `PBSysTextplanSelectionAdjustment_MAKE_SELECTION` | `int` | `16` |  |
| `PBSysTextplanSelectionAdjustment_TO_MOUSE_RIGHT_CLICK` | `int` | `2147483648` |  |
| `PBSysTextplanSelectionAdjustment_WORD_GRANULARITY` | `int` | `1` |  |
| `PBSysWindowCreateTextureFlag_NEAREST` | `PBSysWindowCreateTextureFlags` | `2` | nearest-neighbor filtering (default: linear) |
| `PBSysWindowCreateTextureFlag_STREAMING` | `PBSysWindowCreateTextureFlags` | `1` | hint: texture will be updated frequently |
| `PBSysWindowCreateTextureFlag_WRAP_U` | `PBSysWindowCreateTextureFlags` | `4` | repeat along U axis (default: clamp) |
| `PBSysWindowCreateTextureFlag_WRAP_V` | `PBSysWindowCreateTextureFlags` | `8` | repeat along V axis (default: clamp) |
| `PBSysWindowSetRectFlag_ANIMATE` | `PBSysWindowSetRectFlags` | `8` | animated resize |
| `PBSysWindowSetRectFlag_CENTER` | `PBSysWindowSetRectFlags` | `16` | center on screen |
| `PBSysWindowSetRectFlag_ORIGIN` | `PBSysWindowSetRectFlags` | `2` | set position but keep size unchanged |
| `PBSysWindowSetRectFlag_OUTER` | `PBSysWindowSetRectFlags` | `1` | set outer size, including OS decorations |
| `PBSysWindowSetRectFlag_SIZE` | `PBSysWindowSetRectFlags` | `4` | set size but keep position unchanged |
| `PBSysWindowStyle_CLOSABLE` | `PBSysWindowStyle` | `2` | can be closed; has close button |
| `PBSysWindowStyle_FULLSIZE_CONTENT` | `PBSysWindowStyle` | `64` |     PBSysWindowStyle_FULLSIZE_CONTENT enables the content of the window to be drawn underneath the titlebar |
| `PBSysWindowStyle_HIDDEN_TITLE` | `PBSysWindowStyle` | `32` |     PBSysWindowStyle_HIDDEN_TITLE makes the title hidden, not drawn. The title may still appear in other places in the OS, like task switchers. |
| `PBSysWindowStyle_MINIMIZABLE` | `PBSysWindowStyle` | `4` | can be minimized |
| `PBSysWindowStyle_RESIZABLE` | `PBSysWindowStyle` | `8` | can be resized |
| `PBSysWindowStyle_THEME_BRIGHT` | `PBSysWindowStyle` | `128` |     PBSysWindowStyle_THEME_BRIGHT overrides the OS default and configures the window to use the OS's bright UI theme |
| `PBSysWindowStyle_THEME_DARK` | `PBSysWindowStyle` | `256` |     PBSysWindowStyle_THEME_DARK overrides the OS default and configures the window to use the OS's dark UI theme |
| `PBSysWindowStyle_TITLEBAR` | `PBSysWindowStyle` | `1` | has titlebar |
| `PBSysWindowStyle_TRANSPARENT_TITLEBAR` | `PBSysWindowStyle` | `16` |     PBSysWindowStyle_TRANSPARENT_TITLEBAR makes the titlebar is transparent. Implies PBSysWindowStyle_FULLSIZE_CONTENT |

## Macros

### `PBSysObject_FOREACH`

```c
macro void PBSysObject_FOREACH(macro(NAME) m)
```

calls a macro `m` for each object name, e.g. `m(Thread)`


### `PBSysEventSize_MAX`

```c
#define PBSysEventSize_MAX usize
```

PBSysEventSize_MAX is the maximum size used for any single event. In practice only IME events have a chance of being limited by this.


### `PB_ENUM_TYPE`

```c
macro PB_ENUM_TYPE(T) -> :T
```

Usage example:

    enum Foo PB_ENUM_TYPE(uint16_t) { Foo_A, Foo_B };


### `PBSys_START_MAIN`

```c
#define PBSys_START_MAIN …
```

the main thread is starting


## Functions

### `PBSysAudioBufferCreate`

```c
PBSysAudioBuffer PBSysAudioBufferCreate(PBSysHandle audio,
                                        const void* data,
                                        usize       dataSize,
                                        u32         numChannels,
                                        u32         sampleRate,
                                        u32         totalSampleCount);
```

Creates a new `audio` buffer and uploads it to the sound mixer.

- Required rights: none

### `PBSysAudioOutputInit`

```c
bool PBSysAudioOutputInit(PBSysHandle audio);
```

Inits the `audio` output backend for sound playback (globally).
It has been observed that sometimes this can take a little while (e.g. ~200ms when using bluetooth headphones on MacOS).
As such, you should call this at the start of your program if you intend to play `audio`.

- Required rights: none

### `PBSysAudioBufferCreateFromFile`

```c
PBSysAudioBuffer PBSysAudioBufferCreateFromFile(PBSysHandle audio,
                                                const void* data,
                                                usize       dataSize);
```

Creates an `audio` buffer from a file.
At the present moment, we only support raw WAV file `data`.
This function will be extended in the future to support more formats.

- Required rights: none

### `PBSysAudioBufferDestroy`

```c
PBSysErr PBSysAudioBufferDestroy(PBSysHandle      audio,
                                 PBSysAudioBuffer buffer);
```

Destroys an `audio` `buffer` (and frees the associated memory with it).

- Required rights: none

### `PBSysAudioBufferPlay`

```c
PBSysAudioSound PBSysAudioBufferPlay(PBSysHandle      audio,
                                     PBSysAudioBuffer buffer);
```

Starts playing an instance of an `audio` `buffer`.

- Required rights: none

### `PBSysAudioSetVolume`

```c
PBSysErr PBSysAudioSetVolume(PBSysHandle audio,
                             f32         volume);
```

Sets the global `volume` of the sound mixer.

- Required rights: none

### `PBSysBundleGetResource`

```c
i64 PBSysBundleGetResource(PBSysHandle bundle,
                           const u8*   name,
                           usize       nameLen,
                           u8*         dest,
                           usize       destLen);
```

PBSysBundleGetResource retrieves a bundles resource, as described by the app's manifest at build time.

- `dest`: The memory location in the guest program where the runtime will copy the resource
- `destLen`: How large of a space in guest memory for the runtime to copy into
- Returns: The size of the resource which has been loaded, or a `PBSysErr` value if < 0
- Required rights: `PBSysRight_READ`

### `PBSysChannelCreate`

```c
PBSysHandle PBSysChannelCreate(u32          entSize,
                               u32          cap,
                               u32          maxCap,
                               PBSysHandle* readHandleOut,
                               u64          flags);
```

PBSysChannelCreate creates a channel which supports writing entries of `entSize` bytes.

If the `PBSysChannel_DUPLEX` flag is set, the returned handles will have both `PBSysRight_READ` and `PBSysRight_WRITE`. `PBSysChannel_DUPLEX` is implied if `readHandleOut` is NULL.

If the `PBSysChannel_MULTIPLE_WRITERS` flag is set, the returned handle will have `PBSysRight_DUPLICATE`. Similarly, if the `PBSysChannel_MULTIPLE_READERS` flag is set, a handle returned in `readHandleOut` will have `PBSysRight_DUPLICATE`.

- `readHandleOut`: If not NULL, a second handle is returned with `PBSysRight_READ`.
- `cap`: Initial capacity of the internal buffer, in number of entries. I.e. the total amount of memory allocated for the internal buffer is at least `entSize`*cap bytes.
- `maxCap`: Limits how much the internal buffer can grow. If `maxCap` is <= `cap`, a fixed size is used.
- Returns: A handle to the channel with `PBSysRight_WRITE`.
- Required rights: none

### `PBSysChannelRead`

```c
i32 PBSysChannelRead(PBSysHandle channel,
                     void*       dstEnts,
                     u32         dstEntSize,
                     u32         dstEntsCap,
                     u64         flags);
```

PBSysChannelRead reads up to `dstEntsCap` entries from a `channel`.

Panics if srcEntSize is different than the entSize the `channel` was created with.

- `dstEnts`: Must be an array of `dstEntsCap` number of entries, `dstEntSize` bytes each.
- `flags`: Should be 0.
- Returns: The number of entries read. 0 if there were no entries to be read or if `dstEntsCap` == 0. `PBSysErr_END` if the `channel` is closed.
- Required rights: `PBSysRight_READ`

### `PBSysChannelWrite`

```c
i32 PBSysChannelWrite(PBSysHandle channel,
                      const void* srcEnts,
                      u32         srcEntSize,
                      u32         srcEntsCap,
                      u64         flags);
```

PBSysChannelWrite writes up to `srcEntsCap` entries to a `channel`.

Panics if `srcEntSize` is different than the entSize the `channel` was created with.

- `srcEnts`: Must be an array of `srcEntsCap` number of entries, `srcEntSize` bytes each.
- `flags`: Should be 0.
- Returns: The number of entries written. 0 if the `channel` is full or `srcEntsCap` == 0. `PBSysErr_END` if the `channel` is closed for writing.
- Required rights: `PBSysRight_WRITE`

### `PBSysChannelDisableWrite`

```c
PBSysErr PBSysChannelDisableWrite(PBSysHandle channel);
```

PBSysChannelDisableWrite disables the ability to write to the `channel`, while reading remains possible. This is useful for "graceful shutdown" of channels; preventing new data from being produces while allowing queued data to be flushed.

- Required rights: `PBSysRight_WRITE`

### `PBSysClockMonotonic`

```c
PBSysTime PBSysClockMonotonic();
```

PBSysClockMonotonic returns the current system time

- Required rights: none

### `PBSysClockRead`

```c
PBSysDate PBSysClockRead(PBSysHandle clock);
```

PBSysClockRead returns the current "real" (calendar) time in UTC. On error, a `PBSysErr` is returned as a negative value. Thus, this function never returns a time value earlier than 1970-01-01 00:00:00.

- Required rights: `PBSysRight_READ`

### `PBSysClockReadInfo`

```c
PBSysErr PBSysClockReadInfo(PBSysHandle     clock,
                            PBSysClockInfo* info,
                            u32             infoSize);
```

PBSysClockReadInfo retrieves information about a `clock`

- Required rights: `PBSysRight_READ`

### `PBSysEventPoll`

```c
i32 PBSysEventPoll(PBSysEvent* events,
                   u32         eventsSize,
                   u64         deadline,
                   u64         deadlineLeeway);
```

PBSysEventPoll retrieves `events` from the runtime, suspending the calling thread if needed.

- `events`: Buffer to be populated with produced `events`.
- `eventsSize`: Total number of bytes available at `events`. Note that this is not the number of `PBSysEvent` structs but bytes of memory. The size of a `PBSysEvent` is variable. Generally this should be at least a kilobyte since IME input `events` may be arbitrarily large. In most cases single `events` are small; tens of bytes.
- `deadline`: When to time out. If `deadline` is U64_MAX, it will wait indefinitely until at least one event can be returned or an error occurs. If `deadline` is 0, this function only checks for available `events` without blocking.
- `deadlineLeeway`: Precision request in nanoseconds; how much `deadline` is willing to fluctuate.
- Returns: The number of `events` written (not the number of bytes.) 0 if `deadline` was reached, when `deadline` > 0. 0 if there were no `events` available, when `deadline` == 0 or eventsCap == 0. `PBSysErr_END` if the current thread is exiting (even pipeline shut down.) `PBSysErr_NO_MEM` if `eventsSize` is too small for a single event.
- Required rights: none

### `PBSysFileOpen`

```c
PBSysHandle PBSysFileOpen(PBSysHandle dir,
                          const u8*   path,
                          u32         pathLen,
                          u64         flags);
```

PBSysFileOpen opens a file or directory that's contained within a directory denoted by `dir`.

The effective rights given to the opened file must be the same or a subset of the rights given to the `fs` handle. I.e. on a read-only filesystem you cannot pass `PBSysFileOpenFlag_WRITE`.

The resulting handle is given `PBSysRight_TRANSFER` and `PBSysRight_DUPLICATE`, in addition to `PBSysRight_READ` and/or `PBSysRight_WRITE` as defined by `flags`.

- `dir`: Parent directory, an object of type `PBSysObject_File`
- `path`: Path as UTF-8 text
- `pathLen`: Size in bytes of `path`. Must be >0
- `flags`: Bits of `PBSysFileOpenFlags`
- Returns: `Handle` to a `PBSysObject_File` object that represents the item at `path`, or `PBSysErr` (negative value) on error
- Required rights: `PBSysRight_READ`

### `PBSysFileRead`

```c
i64 PBSysFileRead(PBSysHandle     file,
                  const PBSysBuf* bufs,
                  u32             bufCount,
                  u32             flags);
```

PBSysFileRead reads bytes from a `file` at its current read cursor into one or more buffers.

Note: Currently only synchronous reads are supported. Returns `PBSysErr_NOT_SUPPORTED` unless `PBSysFileReadFlag_SYNC` is set.

- `flags`: Bits of `PBSysFileReadFlags`
- Required rights: `PBSysRight_READ`

### `PBSysFileWrite`

```c
i64 PBSysFileWrite(PBSysHandle     file,
                   const PBSysBuf* bufs,
                   u32             bufCount,
                   u32             flags);
```

PBSysFileWrite writes bytes from one or more buffers to a `file` at the `file`'s current write cursor.

Note: Currently only synchronous writes are supported. Returns `PBSysErr_NOT_SUPPORTED` unless `PBSysFileWriteFlag_SYNC` is set.

- `flags`: Bits of `PBSysFileWriteFlags`
- Required rights: `PBSysRight_WRITE`

### `PBSysFileListOpen`

```c
PBSysHandle PBSysFileListOpen(PBSysHandle dir,
                              const u8*   path,
                              u32         pathLen,
                              u64         flags);
```

PBSysFileListOpen begins a list operation of the directory `dir`/`path`, or `dir` if `pathLen` is `0`. Call `PBSysFileListNext` to retrieve entries and `PBSysHandleClose` when done.

- `path`: Path as UTF-8 text
- `pathLen`: Size in bytes of `path`. May be 0 to mean "dir"
- `flags`: Unused. Pass 0.
- Returns: a handle to an object of type `PBSysObject_FileList`
- Required rights: none

### `PBSysFileListNext`

```c
i32 PBSysFileListNext(PBSysHandle         fileList,
                      u8*                 name,
                      u32                 nameCap,
                      PBSysFileListEntry* entry,
                      u32                 entrySize,
                      u64                 flags);
```

PBSysFileListNextName read the `name` of the next `entry` in a directory listing.

- `fileList`: `Handle` to object of type `PBSysObject_FileList`
- `name`: Buffer in which to write `name` of next `entry`
- `nameCap`: Capacity of `name`, in bytes
- `entry`: Optional buffer in which to write additional information about the next `entry`
- `entrySize`: Size in bytes of `entry`
- Returns: Total number of bytes written to `name` `PBSysErr_END` when the end of the list has been reached. `PBSysErr_BUFFER_TOO_SMALL` if `name` was too short, in which can you can try again with larger `nameCap` `PBSysErr` as a negative value on error.
- Required rights: `PBSysRight_READ`

### `PBSysGuiCursorStyleSet`

```c
PBSysErr PBSysGuiCursorStyleSet(PBSysHandle      gui,
                                u32              pointerId,
                                PBSysCursorStyle style,
                                PBSysHandle      image,
                                u64              flags);
```

PBSysGuiCursorStyleSet sets the appearance of specified pointer's cursor.

- `pointerId`: set to 0 to set cursor for all pointers, or a specific `pointerId` (e.g. from a `PBSysPointerEvent`) to set the cursor only for that pointer.
- `style` determines how the cursor is presented.
- `image` should be the handle of an `image` if `style` is `PBSysCursorStyle_IMAGE`, otherwise the `image` parameter is ignored and should be 0.
- `flags` are unused; pass 0.

- Required rights: none

### `PBSysHandleClose`

```c
PBSysErr PBSysHandleClose(PBSysHandle handle);
```

PBSysHandleClose closes a `handle`. The `handle` is invalid after this call.

- Required rights: none

### `PBSysHandleDuplicate`

```c
PBSysHandle PBSysHandleDuplicate(PBSysHandle     handle,
                                 PBSysRights     rights,
                                 PBSysHandleName name);
```

PBSysHandleDuplicate creates a new `handle` to the object referred to by `handle`. `rights` controls what `rights` are given and can only be same or less than the `rights` granted to `handle`. Use `PBSysRight_SAME_RIGHTS` for "same rights." Note: The new `handle` is unconditionally given `PBSysRight_TRANSFER`.

- Returns: A negative value as PBSysError on error.
- Required rights: `PBSysRight_DUPLICATE`

### `PBSysHandleList`

```c
i32 PBSysHandleList(PBSysHandleInfo* handles,
                    u32              handlesCap,
                    u32              handleSize,
                    u64              flags,
                    u64              predicate);
```

PBSysHandleList returns information about `handles` held by the calling thread. Writes up to `handlesCap` entries to `handles`.

`flags` are bits of `PBSysHandleListFlags`.

If `flags` contain a filter; a `PBSysHandleListFilter` value in the bits `PBSysHandleList_FILTER`, then `predicate` is a value for the filter. Only `handles` matching the filter are returned.

- Returns: The total number of `handles`, which might be more than `handlesCap`. <0 if an error occurred, as a `PBSysErr`.
- Required rights: none

### `PBSysNetSessionOpen`

```c
PBSysHandle PBSysNetSessionOpen(PBSysHandle                  net,
                                const u8*                    sessionId,
                                u32                          sessionIdLen,
                                const PBSysNetSessionConfig* config,
                                u32                          configSize);
```

PBSysNetSessionOpen opens a Playbit network session

- `net`: Networking capability (handle to an object of type `PBSysObject_Net`)
- `sessionId`: Session identifier, unique within app-id namespace
- `sessionIdLen`: Size in bytes of `sessionId`
- `config`: Configuration
- `configSize`: Size in bytes of struct in `config` parameter
- Returns: `Handle` to a `NetSession` object, or `PBSysErr` (negative value) on error. Opening a `NetSession` starts or attaches to the underlying AP connection asynchronously.
- Required rights: none

### `PBSysNetConnect`

```c
PBSysHandle PBSysNetConnect(PBSysHandle                  net,
                            const u8*                    uri,
                            u32                          uriLen,
                            const PBSysNetConnectConfig* config,
                            u32                          configSize);
```

PBSysNetConnect opens a stream connected to a network endpoint.

URIs have the form `protocol:node`, i.e.

    tcp:host:port  TCP/IP socket
    local:path     Local socket (aka UNIX socket)

The underlying implementation may not support the requested protocol.

The returned stream will have its `PBSysStreamSignal_WRITABLE` activated when the connection has been established.

- `net`: Networking capability (handle to an object of type `PBSysObject_Net`)
- `uri`: URI.
- `uriLen`: Size in bytes of `uri`
- `config`: Configuration
- `configSize`: Size in bytes of struct in `config` parameter
- Returns: `Handle` to a `NetSession` object on success, or `PBSysErr` (negative value) on error. `PBSysErr_NOT_SUPPORTED` if the protocol type requested in `uri` is not supported.
- Required rights: none

### `PBSysNetSessionId`

```c
PBSysErr PBSysNetSessionId(PBSysHandle netSession,
                           u8*         sessionIdBuf,
                           u32         sessionIdBufCap);
```

PBSysNetSessionId copies the session identifier bytes of a network session.

- `netSession`: Network session, handle to a `NetSession` object
- `sessionIdBuf`: Destination buffer for the session identifier bytes
- `sessionIdBufCap`: Size in bytes of `sessionIdBuf`
- Returns: 0 on success, `PBSysErr_BUFFER_TOO_SMALL` if `sessionIdBufCap` is too small, or `PBSysErr` on failure.
- Required rights: `PBSysRight_READ`

### `PBSysNetSessionOpenStream`

```c
PBSysHandle PBSysNetSessionOpenStream(PBSysHandle netSession,
                                      const u8*   channelId,
                                      u32         channelIdLen,
                                      u64         flags);
```

PBSysNetSessionOpenStream opens a stream for a channel in a network session.

- `netSession`: Network session, handle to a `NetSession` object
- `channelId`: `Channel` identifier, unique within the network session
- `channelIdLen`: Size in bytes of `channelId`
- `flags`: Reserved. Must be 0.
- Returns: `Handle` to a `Stream` object, or `PBSysErr` (negative value) on error. The stream may become writable later, after the underlying session is authenticated and ready.
- Required rights: none

### `PBSysObjectObserve`

```c
PBSysErr PBSysObjectObserve(PBSysHandle  handle,
                            PBSysSignals signals,
                            u32          flags);
```

PBSysObjectObserve configures signal observation of the object referred to by `handle`.

Signal observation is "level" triggered by default, meaning that whenever an observed signal becomes active, a `PBSysEventLegacy`.signal is produced, until you cancel observation by calling this function with `signals`=0. By setting the `PBSysObjectObserve_ONCE` flag, the behavior changes to be "edge" triggered, where one PBSysObjectObserve call yields just one signal event. If you want to keep observing an object after a signal event in "edge" triggered mode, you need to issue another call to PBSysObjectObserve. ONCE is manily useful for one-off observers of e.g. single-fire timers or threads.

Setting `signals` to 0 has the effect of canceling observation. If `PBSysObjectObserve_ADD` is set in `flags`, setting `signals` to 0 is an error (`PBSysErr_INVALID`).

This function may be called multiple times to modify what `signals` are observed.

- Required rights: `PBSysRight_OBSERVE`

### `PBSysObjectSignal`

```c
PBSysErr PBSysObjectSignal(PBSysHandle  handle,
                           PBSysSignals disableUserSignals,
                           PBSysSignals enableUserSignals,
                           PBSysSignals pulseUserSignals);
```

PBSysObjectSignal clear and/or sets user signals for `handle`.

First `disableUserSignals` are applied then `enableUserSignals`.

- Returns: `PBSysErr_INVALID` if any non-user (i.e. system) signals are included in the bitmasks.
- Required rights: none

### `PBSysStreamOpenPipePair`

```c
PBSysErr PBSysStreamOpenPipePair(PBSysHandle* handlesOut,
                                 u32          bufferSize,
                                 u64          flags);
```

PBSysStreamOpenPipePair creates two connected duplex byte streams.

Writes to one handle become readable from the other handle and vice versa.

- `handlesOut`: Receives the two created stream handles on success.
- `bufferSize`: Per-direction buffer capacity in bytes. 0 uses an implementation default.
- `flags`: Must be 0.
- Required rights: none

### `PBSysStreamRead`

```c
i64 PBSysStreamRead(PBSysHandle     stream,
                    const PBSysBuf* bufs,
                    u32             bufCount,
                    u32             flags);
```

PBSysStreamRead reads bytes from a `stream` into one or more buffers.

- `flags`: Unused. Pass 0
- Required rights: `PBSysRight_READ`

### `PBSysStreamWrite`

```c
i64 PBSysStreamWrite(PBSysHandle     stream,
                     const PBSysBuf* bufs,
                     u32             bufCount,
                     u32             flags);
```

PBSysStreamWrite writes bytes from one or more buffers to a `stream`.

- `flags`: Bits of `PBSysStreamWriteFlags`
- Required rights: `PBSysRight_WRITE`

### `PBSysStreamStatsRead`

```c
PBSysErr PBSysStreamStatsRead(PBSysHandle       stream,
                              PBSysStreamStats* stats,
                              u32               statsSize,
                              u64               flags);
```

PBSysStreamStatsRead retrieves statistics for a `stream`.

- `stats`: Storage location for results
- `statsSize`: Capacity of `stats` in bytes
- `flags`: Unused. Pass 0.
- Required rights: none

### `PBSysTextplanLayout`

```c
i64 PBSysTextplanLayout(PBSysHandle textPlan,
                        u32         flags,
                        i32         width,
                        i32         height);
```

PBSysTextplanLayout lays a text document into a rectangular bounding box.

`textPlan`: The text plan to contain the resulting layout.

`flags`: Flags bitwise OR-ed together controlling the text layout operation. The available `flags` are
- PBTextPlanLayout_PREFORMATTED = 1<<0: Prevents trimming of trailing/leading/duplicate whitespace.
- PBTextPlanLayout_ONE_LINE = 1<<1: When set: the text will be placed on a single line; newline characters are ignored; and PBTextPlanLayout_ALWAYS_SET_HEIGHT is implied. When clear, the text will be wrapped to multiple lines as necessary.
- PBTextPlanLayout_ALWAYS_SET_HEIGHT = 1<<2: Implied by PBTextPlanLayout_ONE_LINE. The computed `height` (see `PBSysTextplanGetSize`) will be set to the `height` of the single line, even if the input text is an empty string. Note that #defines are not provided yet for these `flags`, so you will need to enter the constant values manually.

`width`: The `width` of the rectangular bounding box in pixels. Set to 0 for infinite space (and thus preventing line wrapping or truncation).

`height`: The `height` of the rectangular bounding box in pixels. Set to 0 for infinite space.

If the system detects that the new bounding box will not affect the existing layout in the text plan, this function will do nothing.

This function performs text shaping and then places the resulting glyphs into lines.
If a line were to go off the right side of the box, it will either be truncated with an ellipsis character or wrap to a new line,
depending on whether PBTextPlanLayout_ONE_LINE is set.

Once this function has been called, you can use the other text plan functions.

- Required rights: `PBSysRight_WRITE`

### `PBSysTextplanGetSize`

```c
u64 PBSysTextplanGetSize(PBSysHandle textPlan);
```

PBSysTextplanGetSize: Get the size of a text plan's layout.

`textPlan`: The text plan object.

Return value: The width and height of the plan. The macros PBTextplanWidthOfSize and PBTextplanHeightOfSize can be used to extract the two values from the return value of the function.
The returned width is the width of the widest line in the plan in pixels.
The returned height is the distance from the top of the first line to the bottom of the last line in pixels.

This function gives no information about where text glyphs may actually be drawn.
Glyphs can extend outside the boundaries of the line on which they are placed.

You must call `PBSysTextplanLayout` before calling this function.

- Required rights: `PBSysRight_READ`

### `PBSysTextplanHitTest`

```c
u64 PBSysTextplanHitTest(PBSysHandle textPlan,
                         i32         x,
                         i32         y);
```

- Required rights: none

### `PBSysTextplanGetCaretBounds`

```c
u64 PBSysTextplanGetCaretBounds(PBSysHandle textPlan,
                                u64         caretTextIndex);
```

- Required rights: none

### `PBSysTextplanGetSelectionRects`

```c
u64 PBSysTextplanGetSelectionRects(PBSysHandle                 textPlan,
                                   u64                         selectionStart,
                                   u64                         selectionEnd,
                                   PBSysTextplanSelectionRect* rects,
                                   u32                         rectsCap,
                                   u32                         rectSize);
```

PBSysTextplanGetSelectionRects retrieves line-wise selection rectangles relative to the text plan
origin.

- `textPlan`: the text plan object
- `selectionStart`: one end of the selection range
- `selectionEnd`: the other end of the selection range
- `rects`: output buffer, or NULL to query the count only
- `rectsCap`: number of entries available in `rects`
- `rectSize`: size of one entry in `rects`, usually sizeof(`PBSysTextplanSelectionRect`)
- Returns: the total number of selection rectangles for the requested range
- Required rights: `PBSysRight_READ`

### `PBSysTextplanMoveSelectionToPoint`

```c
bool PBSysTextplanMoveSelectionToPoint(PBSysHandle             textPlan,
                                       u32                     mode,
                                       i32                     x,
                                       i32                     y,
                                       PBSysTextplanSelection* selection,
                                       u32                     selectionSize);
```

PBSysTextplanMoveSelectionToPoint updates a `selection` by hit-testing a point and applying
`selection`-adjustment flags.

- `textPlan`: the text plan object
- `mode`: a bitwise OR of PBSysTextplanSelectionAdjustment_* flags
- `x`: point `x` in px relative to the text plan origin
- `y`: point `y` in px relative to the text plan origin
- `selection`: in-out `selection` state containing anchor, caret, and lastDown
- `selectionSize`: size of *selection, usually sizeof(`PBSysTextplanSelection`)
- Returns: true if the `selection` changed
- Required rights: `PBSysRight_READ`

### `PBSysTextplanMoveSelection`

```c
bool PBSysTextplanMoveSelection(PBSysHandle             textPlan,
                                u32                     mode,
                                PBSysTextplanSelection* selection,
                                u32                     selectionSize);
```

PBSysTextplanMoveSelection updates a `selection` using `selection`-adjustment flags without hit
testing a point.

- `textPlan`: the text plan object
- `mode`: a bitwise OR of PBSysTextplanSelectionAdjustment_* flags
- `selection`: in-out `selection` state containing anchor, caret, and lastDown
- `selectionSize`: size of *selection, usually sizeof(`PBSysTextplanSelection`)
- Returns: true if the `selection` changed
- Required rights: `PBSysRight_READ`

### `PBSysTextplanMoveSelectionVertical`

```c
bool PBSysTextplanMoveSelectionVertical(PBSysHandle             textPlan,
                                        i32                     preferredX,
                                        bool                    upwards,
                                        bool                    extend,
                                        PBSysTextplanSelection* selection,
                                        u32                     selectionSize);
```

PBSysTextplanMoveSelectionVertical moves a `selection` up or down by one visual line while
preserving a preferred x position.

- `textPlan`: the text plan object
- `preferredX`: x in px relative to the text plan origin used to preserve column intent
- `upwards`: true to move up one visual line, false to move down
- `extend`: true to `extend` the current `selection` instead of collapsing to the moved caret
- `selection`: in-out `selection` state containing anchor, caret, and lastDown
- `selectionSize`: size of *selection, usually sizeof(`PBSysTextplanSelection`)
- Returns: true if the `selection` changed
- Required rights: `PBSysRight_READ`

### `PBSysTextureWrite`

```c
PBSysErr PBSysTextureWrite(PBSysHandle texture,
                           u32         originXInPx,
                           u32         originYInPx,
                           const void* pixels,
                           u64         pixelSize,
                           u32         widthInPx,
                           u32         heightInPx);
```

PBSysTextureWrite uploads pixel data to a region of a `texture`.
Pixels must be in the format the `texture` was created with (RGBA8: 4 bytes per pixel, row-major).

- `originXInPx`: x offset within the `texture`
- `originYInPx`: y offset within the `texture`
- `pixels`: pointer to pixel data
- `pixelCount`: number of bytes at `pixels` (must be >= `widthInPx` * `heightInPx` * 4)
- `widthInPx`: width of the upload region
- `heightInPx`: height of the upload region
- Required rights: `PBSysRight_WRITE`

### `PBSysThreadEnterMain`

```c
void PBSysThreadEnterMain(u64 flags);
```

PBSysThreadEnterMain

- `flags`: are bits of PBSysThread_
- Required rights: none

### `PBSysThreadStart`

```c
PBSysHandle PBSysThreadStart(PBSysHandle              parentThread,
                             u64                      flags,
                             const PBSysThreadConfig* config,
                             u64                      configSize);
```

PBSysThreadStart starts a new thread.

- Required rights: `PBSysRight_MANAGE_THREAD`

### `PBSysThreadExit`

```c
PBSysErr PBSysThreadExit(PBSysHandle thread,
                         i32         status);
```

PBSysThreadExit stops a `thread` and sets its exit `status`.

- Required rights: `PBSysRight_MANAGE_THREAD`

### `PBSysThreadExitStatus`

```c
i32 PBSysThreadExitStatus(PBSysHandle thread);
```

PBSysThreadExitStatus returns the exit status of `thread`.

- Returns: `PBSysErr` on error.
- Required rights: `PBSysRight_MANAGE_THREAD`

### `PBSysThreadExitProcess`

```c
PBSysErr PBSysThreadExitProcess(PBSysHandle thread,
                                i32         status);
```

PBSysThreadExitProcess terminated the process.

- Required rights: `PBSysRight_MANAGE_PROCESS`

### `PBSysThreadWrite`

```c
PBSysErr PBSysThreadWrite(PBSysHandle        thread,
                          const void*        data,
                          u32                dataSize,
                          const PBSysHandle* handles,
                          u32                handlesCount,
                          u64                flags);
```

PBSysThreadWrite sends a message to a `thread`. `data` is copied.

- `data`: to be written
- `dataSize`: is the number of bytes at `data`
- `handles`: to transfer ownership of to receiver `thread`
- `handlesCount`: is the number of `handles` at `handles`
- `flags`: are currently unused; pass 0.
- Required rights: `PBSysRight_WRITE`

### `PBSysThreadRead`

```c
PBSysErr PBSysThreadRead(void*        data,
                         u32*         dataSizeInOut,
                         PBSysHandle* handles,
                         u32*         handlesCountInOut,
                         u64          flags);
```

PBSysThreadRead receives a message sent to the calling thread.

Messages may contain both byte `data` and handle payloads and may only be read in their entirety. Partial reads are not possible.

- `data`: is a buffer to place read `data` into
- `dataSizeInOut`: in: capacity of `data`, out: bytes read
- `handles`: to accept ownership of, transferred from sender thread
- `handlesCountInOut`: in: capacity of `handles`, out: `handles` received
- `flags`: are currently unused; pass 0.
- Required rights: none

### `PBSysThreadLogWrite`

```c
PBSysErr PBSysThreadLogWrite(PBSysHandle     thread,
                             const PBSysBuf* bufs,
                             u32             bufCount,
                             u32             flags);
```

PBSysThreadLogWrite writes to the runtime log sink for a `thread`.

- Required rights: none

### `PBSysThreadWindowCreate`

```c
PBSysHandle PBSysThreadWindowCreate(PBSysHandle              thread,
                                    const PBSysWindowConfig* config,
                                    usize                    configSize);
```

PBSysThreadWindowCreate creates a window associated with a `thread`.

- Required rights: `PBSysRight_WRITE`

### `PBSysThreadNetConnect`

```c
PBSysHandle PBSysThreadNetConnect(PBSysHandle thread,
                                  u32         ipAddr,
                                  u16         tcpPort);
```

Note: Draft API; arguments will change

- Required rights: `PBSysRight_NETWORK`

### `PBSysThreadHostControllerConnect`

```c
PBSysHandle PBSysThreadHostControllerConnect(PBSysHandle thread);
```

Note: Draft API; arguments will change

- Required rights: none

### `PBSysWindowCreateTexture`

```c
PBSysHandle PBSysWindowCreateTexture(PBSysHandle                   window,
                                     PBSysTextureFormat            format,
                                     u32                           widthInPx,
                                     u32                           heightInPx,
                                     PBSysWindowCreateTextureFlags flags);
```

PBSysWindowCreateTexture creates an RGBA8 texture associated with a `window`.
The texture can be uploaded to via `PBSysTextureWrite` and set as the active texture
for shape draw calls via a TEXTURE_SET renderer instruction.

- `format`: must be `PBSysTextureFormat_RGBA8`
- `flags`: `PBSysWindowCreateTextureFlags` (e.g. STREAMING for frequently updated textures)
- Required rights: none

### `PBSysWindowCreateTextureFromData`

```c
PBSysHandle PBSysWindowCreateTextureFromData(PBSysHandle                   window,
                                             PBSysTextureFormat            format,
                                             const void*                   data,
                                             u64                           dataSize,
                                             PBSysWindowCreateTextureFlags flags);
```

PBSysWindowCreateTextureFromData decodes image `data` and creates a GPU texture in one step.
Supported formats: PNG, JPEG, WebP, GIF, BMP, TGA.
Pixels are always decoded to RGBA8. The `format` parameter must be `PBSysTextureFormat_RGBA8`.

- `data`: pointer to encoded image bytes (e.g. a PNG file loaded into memory)
- `dataSize`: number of bytes at `data`
- `flags`: `PBSysWindowCreateTextureFlags`
- Required rights: none

### `PBSysWindowInfoGet`

```c
PBSysErr PBSysWindowInfoGet(PBSysHandle      window,
                            PBSysWindowInfo* info,
                            u64              infoSize);
```

PBSysWindowInfoGet retrieves latest `window` metrics and timing hints.

- Required rights: `PBSysRight_READ`

### `PBSysWindowSetRect`

```c
PBSysErr PBSysWindowSetRect(PBSysHandle             window,
                            f32                     x,
                            f32                     y,
                            f32                     width,
                            f32                     height,
                            PBSysWindowSetRectFlags flags);
```

PBSysWindowSetRect sets the position and size of a `window`. The actual size of the `window` may be larger if the size is smaller than the minimum possible `window` size, according to the host OS.

`x` & `y` sets the position on screen of the top-left corner of the `window`, with a top-left origin. `x` and `y` are ignored if `PBSysWindowSetRectFlag_CENTER` is set.

- `x`: dp
- `y`: dp
- `width`: dp
- `height`: dp
- Required rights: `PBSysRight_WRITE`

### `PBSysWindowSetStyle`

```c
PBSysErr PBSysWindowSetStyle(PBSysHandle      window,
                             PBSysWindowStyle style,
                             u64              flags);
```

PBSysWindowSetStyle sets the `style` of a `window`.

- Required rights: `PBSysRight_WRITE`

### `PBSysWindowSetTitle`

```c
PBSysErr PBSysWindowSetTitle(PBSysHandle window,
                             const u8*   text,
                             u64         textLen);
```

PBSysWindowSetTitle sets the title of a `window`.

- `text`: UTF-8 bytes
- `textLen`: Number of bytes at `text`
- Required rights: `PBSysRight_WRITE`

### `PBSysWindowCopyTitle`

```c
i32 PBSysWindowCopyTitle(PBSysHandle window,
                         u8*         buf,
                         u32         bufCap,
                         u64         flags);
```

PBSysWindowCopyTitle retrieves the title of a `window`.

- `buf`: Destination to write UTF-8 bytes
- `bufCap`: Capacity of `buf`, in bytes
- Required rights: `PBSysRight_READ`

### `PBSysWindowSizeLimitsSet`

```c
PBSysErr PBSysWindowSizeLimitsSet(PBSysHandle window,
                                  f32         minWidth,
                                  f32         minHeight,
                                  f32         maxWidth,
                                  f32         maxHeight,
                                  u64         flags);
```

PBSysWindowSizeLimits sets lower and upper frame size limits.

Use negative numbers to keep values unchanged.

- Required rights: `PBSysRight_WRITE`

### `PBSysWindowFrameSyncEnable`

```c
PBSysErr PBSysWindowFrameSyncEnable(PBSysHandle window,
                                    u64         flags);
```

PBSysWindowFrameSyncEnable controls the production of FRAME_SYNC pulses.

- `flags`: should be 0 (disable) or 1 (enable).
- Required rights: none

### `PBSysWindowTextplanCreate`

```c
PBSysHandle PBSysWindowTextplanCreate(PBSysHandle window,
                                      const u8*   text,
                                      u64         textSize,
                                      u32         fontFamily,
                                      u32         size,
                                      u32         weight,
                                      u32         color);
```

PBSysWindowTextplanCreate creates a `text` plan object associated with a `window`.

TODO: Proper positioned attributes array.

- Required rights: none

### `PBSysWindowRendererPackageWrite`

```c
PBSysErr PBSysWindowRendererPackageWrite(PBSysHandle                       window,
                                         const PBSysWindowRendererPackage* package,
                                         usize                             packageSize);
```

PBSysWindowRendererPackageWrite submits renderer `package` data for a `window`.

- Required rights: `PBSysRight_WRITE`

### `PBSysWindowClipboardWriteText`

```c
PBSysErr PBSysWindowClipboardWriteText(PBSysHandle window,
                                       const u8*   text,
                                       u64         textSize);
```

PBSysWindowClipboardWriteText sets the `text` on the clipboard.

- Required rights: `PBSysRight_WRITE`

### `PBSysWindowClipboardReadText`

```c
i64 PBSysWindowClipboardReadText(PBSysHandle window,
                                 u8*         buffer,
                                 u64         bufferSize);
```

`PBSysWindowClipboardWriteText` reads the text from the clipboard.

- Required rights: `PBSysRight_READ`
