Skip to content

niripy.models ⚓︎

Classes:

Name Description
ReplyError

Exception raised when an error occurs while processing a Niri reply.

ModelWithInstance

Base model for Niri objects that need access to the Instance.

ConfiguredPosition

A 2D [position][1] with integer coordinates.

KeyboardLayouts

Information about available [keyboard layouts][1].

Layer

Wayland [layer][1] shell layer types.

LayerSurfaceKeyboardInteractivity

[Layer surface keyboard interactivity][1] modes.

LayerSurface

A layer shell [surface][1] (e.g., panel, notification).

Transform

Image [transformation][1] operations.

LogicalOutput

[Logical output][1] configuration and transformations.

Mode

A display [mode][1] (resolution and refresh rate).

Output

A [monitor/output][1] device.

Overview

[Overview][1] mode state.

PickedColor

A [color][1] picked by the color picker tool.

Timestamp

A [timestamp][1] with second and nanosecond precision.

VrrToSet

[VRR][1] (Variable Refresh Rate) settings to apply.

WindowLayout

[Layout information][1] for a window in the tiling layout.

Window

A [Window][1] in the Niri compositor.

Workspace

A [workspace][1] (virtual desktop) in Niri.

OutputConfigChanged

[Output configuration][1] change states.

CastKind

Available [casting/screen capture][1] backends.

CastTarget

[Target][1] of a screen cast (what to record).

Cast

An active [screen cast][1] session.

Response

A [response][1] from a Niri IPC request.

Reply

A Niri IPC protocol [reply][1].

ReplyError ⚓︎

Bases: Exception

Exception raised when an error occurs while processing a Niri reply.

This exception is raised when: - Niri returns an error response - A reply cannot be unwrapped/parsed - A response doesn't contain expected fields

Example
>>> from niripy.models import Reply, ReplyError
>>> try:
...     reply = Reply.model_validate_json(error_response)
...     reply.unwrap()
... except ReplyError as e:
...     print(f"Niri error: {e}")

ModelWithInstance ⚓︎

Bases: BaseModel

Base model for Niri objects that need access to the Instance.

This is a Pydantic BaseModel that stores a reference to the Instance, allowing models to query related objects and state from Niri.

Attributes:

Name Type Description
_instance Instance

Reference to the connected Niri instance.

Note

When validating models that inherit from this, always pass context={'instance': instance} to model_validate().

Example
>>> from niripy.instances import Instance
>>> from niripy.models import Window
>>> instance = Instance()
>>> window_data = {"id": 1, "title": "Test", ...}
>>> window = Window.model_validate(window_data, context={'instance': instance})

Methods:

Name Description
model_post_init

Post-initialization hook to validate and store the instance context.

model_post_init ⚓︎

model_post_init(context: Any)

Post-initialization hook to validate and store the instance context.

Parameters:

Name Type Description Default

context ⚓︎

Any

Validation context. Must be a dict with 'instance' key.

required

Raises:

Type Description
AssertionError

If context doesn't contain the 'instance' key.

Source code in src/niripy/models.py
@override
def model_post_init(self, context: Any):
    """Post-initialization hook to validate and store the instance context.

    Args:
        context (Any): Validation context. Must be a dict with 'instance' key.

    Raises:
        AssertionError: If context doesn't contain the 'instance' key.
    """
    if not isinstance(context, dict) or "instance" not in context:
        raise AssertionError(
            "context['instance'] not defined: "  # pyright: ignore[reportImplicitStringConcatenation]
            "Make sure to validate with context={'instance': ...}. "
            "i.e. Model.model_validate(data, context={'instance': instance})"
        )
    self._instance = context["instance"]

ConfiguredPosition ⚓︎

Bases: BaseModel

A 2D position with integer coordinates.

Attributes:

Name Type Description
x int

X coordinate.

y int

Y coordinate.

KeyboardLayouts ⚓︎

Bases: BaseModel

Information about available keyboard layouts.

Attributes:

Name Type Description
names list[str]

List of available keyboard layout names.

current_idx int

Index of the currently active layout in the names list.

Layer ⚓︎

Bases: StrEnum

Wayland layer shell layer types.

Represents the different zwlr_layer_shell layers for positioning surfaces.

Attributes:

Name Type Description
BACKGROUND

Background layer, below everything.

BOTTOM

Above background, below normal windows.

TOP

Above normal windows, below overlay.

OVERLAY

Top layer, above everything.

LayerSurfaceKeyboardInteractivity ⚓︎

Bases: StrEnum

Layer surface keyboard interactivity modes.

Defines the keyboard interactivity behavior for layer surfaces in Wayland, controlling how keyboard input is handled and routed to the surface.

Attributes:

Name Type Description
NONE

Keyboard input is not delivered to the layer surface.

EXCLUSIVE

The layer surface has exclusive keyboard focus and receives all keyboard input.

ON_DEMAND

Keyboard input is delivered to the layer surface only when explicitly requested.

LayerSurface ⚓︎

Bases: ModelWithInstance

A layer shell surface (e.g., panel, notification).

Represents a surface from the Wayland layer shell protocol.

Attributes:

Name Type Description
namespace str

The namespace/identifier of the surface.

output_name str

The name of the output this surface is on.

layer Layer

The layer this surface is placed in.

keyboard_interactivity LayerSurfaceKeyboardInteractivity

Keyboard interactivity mode for this surface.

output property ⚓︎

output: Output | None

Get the output this layer surface is displayed on.

Returns:

Type Description
Output | None

The output object, or None if not found.

Transform ⚓︎

Bases: StrEnum

Image transformation operations.

Represents various transformations that can be applied to images, including rotations and flips.

Attributes:

Name Type Description
NORMAL

No transformation applied.

ROTATE_90

Rotate image 90 degrees clockwise.

ROTATE_180

Rotate image 180 degrees.

ROTATE_270

Rotate image 270 degrees clockwise.

FLIPPED

Flip image horizontally.

FLIPPED_90

Flip image horizontally and rotate 90 degrees clockwise.

FLIPPED_180

Flip image horizontally and rotate 180 degrees.

FLIPPED_270

Flip image horizontally and rotate 270 degrees clockwise.

LogicalOutput ⚓︎

Bases: BaseModel

Logical output configuration and transformations.

Represents the logical position and scaling of an output in a multi-monitor setup.

Attributes:

Name Type Description
x int

Logical X position in pixels.

y int

Logical Y position in pixels.

width int

Logical width in pixels.

height int

Logical height in pixels.

scale float

Scale factor for DPI (e.g., 2.0 for 200%).

transform Transform

Rotation and/or flip transformation.

Mode ⚓︎

Bases: BaseModel

A display mode (resolution and refresh rate).

Attributes:

Name Type Description
width int

Resolution width in pixels.

height int

Resolution height in pixels.

refresh_rate int

Refresh rate in Hz.

is_preferred bool

Whether this is the preferred/native mode.

Output ⚓︎

Bases: ModelWithInstance

A monitor/output device.

Represents a connected display monitor with its capabilities and current state.

Attributes:

Name Type Description
name str

Output identifier (e.g., "HDMI-1", "DP-2").

make str

Manufacturer name.

model str

Model designation.

serial str | None

Serial number if available.

physical_size tuple[int, int]

Physical dimensions in millimeters (width, height).

modes list[Mode]

Available display modes.

current_mode int | None

Index of current mode in modes list, or None if custom.

is_custom_mode bool

Whether the current mode is custom/manual.

vrr_supported bool

Whether variable refresh rate is supported.

vrr_enabled bool

Whether VRR is currently enabled.

logical LogicalOutput | None

Logical position and scaling info.

workspaces property ⚓︎

workspaces: list[Workspace]

Get all workspaces on this output.

Returns:

Type Description
list[Workspace]

Workspaces displayed on this output.

layers property ⚓︎

layers: list[LayerSurface]

Get all layer surfaces on this output.

Returns:

Type Description
list[LayerSurface]

Layer surfaces (panels, notifications, etc.) on this output.

windows property ⚓︎

windows: list[Window]

Get all windows on workspaces on this output.

Returns:

Type Description
list[Window]

Windows from all workspaces on this output.

Overview ⚓︎

Bases: BaseModel

Overview mode state.

Attributes:

Name Type Description
is_open bool

Whether the overview is currently open/visible.

PickedColor ⚓︎

Bases: BaseModel

A color picked by the color picker tool.

Attributes:

Name Type Description
rgb tuple[float, float, float]

RGB color values (typically 0-1 range).

Note

This model is not fully tested yet.

Timestamp ⚓︎

Bases: BaseModel

A timestamp with second and nanosecond precision.

Attributes:

Name Type Description
seconds int

Number of seconds.

nanoseconds int

Nanosecond component (0-999,999,999).

VrrToSet ⚓︎

Bases: BaseModel

VRR (Variable Refresh Rate) settings to apply.

Attributes:

Name Type Description
vrr bool

Whether to enable VRR.

on_demand bool

If true, VRR is only active during updates (power saving mode).

WindowLayout ⚓︎

Bases: BaseModel

Layout information for a window in the tiling layout.

Contains positioning and sizing data for a window within Niri's tiling system.

Attributes:

Name Type Description
pos_in_scrolling_layout tuple[int, int] | None

Position in scrolling layout.

tile_size tuple[float, float]

Size of the tile (width, height).

window_size tuple[int, int]

Actual window size in pixels (width, height).

tile_pos_in_workspace_view tuple[float, float] | None

Tile position in workspace view.

window_offset_in_tile tuple[float, float]

Offset of window content within its tile.

Window ⚓︎

Bases: ModelWithInstance

A Window in the Niri compositor.

Represents an open window with its state, position, and metadata.

Attributes:

Name Type Description
id int

Unique window identifier.

title str | None

Window title if available.

app_id str | None

Application ID (from desktop file).

pid int | None

Process ID if available.

workspace_id int | None

ID of workspace containing this window.

is_focused bool

Whether this window has keyboard focus.

is_floating bool

Whether the window is floating (not tiled).

is_urgent bool

Whether the window has an urgent flag set.

layout WindowLayout

Tiling layout information.

focus_timestamp Timestamp | None

When this window was last focused.

workspace property ⚓︎

workspace: Workspace | None

Get the workspace containing this window.

Returns:

Type Description
Workspace | None

The workspace, or None if not in any workspace.

Workspace ⚓︎

Bases: ModelWithInstance

A workspace (virtual desktop) in Niri.

Represents a workspace that contains windows and is assigned to an output.

Attributes:

Name Type Description
id int

Unique workspace identifier.

idx int

Index/order of this workspace.

name str | None

User-friendly workspace name if set.

output_name str | None

Name of the output this workspace is on.

is_urgent bool

Whether the workspace has an urgent flag set.

is_active bool

Whether this workspace is active (visible).

is_focused bool

Whether this workspace has keyboard focus.

active_window_id int | None

ID of the currently focused window.

output property ⚓︎

output: Output | None

Get the output this workspace is displayed on.

Returns:

Type Description
Output | None

The output, or None if not assigned.

active_window property ⚓︎

active_window: Window | None

Get the currently focused window in this workspace.

Returns:

Type Description
Window | None

The active window, or None if no window is focused.

windows property ⚓︎

windows: list[Window]

Get all windows in this workspace.

Returns:

Type Description
list[Window]

All windows currently in this workspace.

OutputConfigChanged ⚓︎

Bases: StrEnum

Output configuration change states.

Attributes:

Name Type Description
APPLIED

Indicates that the output configuration change was successfully applied.

OUTPUT_WAS_MISSING

Indicates that the output configuration change occurred because the output was previously missing.

CastKind ⚓︎

Bases: StrEnum

Available casting/screen capture backends.

Attributes:

Name Type Description
PIPEWIRE

PipeWire audio/video server backend for screen casting.

WLR_SCREENCOPY

Wlroots screencopy protocol backend for screen capture.

CastTarget ⚓︎

Bases: BaseModel

Target of a screen cast (what to record).

One of the three fields should be set to indicate the cast target.

Attributes:

Name Type Description
nothing dict[str, str] | None

No specific target (background, etc.).

output dict[str, str] | None

Cast a specific output/monitor.

window dict[str, int] | None

Cast a specific window.

Cast ⚓︎

Bases: BaseModel

An active screen cast session.

Represents a screen capture/recording session.

Attributes:

Name Type Description
stream_id int

Stream identifier.

session_id int

Session identifier.

kind CastKind

The casting protocol used.

target CastTarget

What is being cast (output/window/etc).

is_dynamic_target bool

Whether the target can change during cast.

is_active bool

Whether the cast is currently active.

pid int | None

Process ID of the casting application.

pw_node_id int | None

PipeWire node ID if using PipeWire.

Note

Screen casting is not fully tested yet.

Response ⚓︎

Bases: BaseModel

A response from a Niri IPC request.

Contains the result of a request, with one of the fields populated depending on the request type.

Attributes:

Name Type Description
handled bool | None

Whether an action was handled.

version str | None

Niri version string.

outputs dict[str, Output] | None

Map of output names to Output objects.

workspaces list[Workspace] | None

List of all workspaces.

windows list[Window] | None

List of all windows.

layers list[LayerSurface] | None

List of layer surfaces.

keyboard_layouts KeyboardLayouts | None

Available keyboard layouts.

focused_output Output | None

The currently focused output.

focused_window Window | None

The currently focused window.

picked_window Window | None

Window selected by pick-window action.

picked_color PickedColor | None

Color selected by pick-color action.

output_config_changed OutputConfigChanged | None

Status of output config change.

overview_state Overview | None

Overview mode state.

casts list[Cast] | None

List of active screen casts.

Methods:

Name Description
unwrap

Extract the meaningful field from the response.

unwrap ⚓︎

unwrap() -> Any

Extract the meaningful field from the response.

Returns the first non-None field from the response. Useful for extracting the actual response value after validation.

Returns:

Type Description
Any

The first non-None response field.

Raises:

Type Description
ReplyError

If all fields are None.

Example
>>> reply = Reply.model_validate_json(json_data, context={'instance': instance})
>>> response = reply.unwrap()
>>> windows = response.unwrap()  # Extract the actual data
Source code in src/niripy/models.py
def unwrap(self) -> Any:
    """Extract the meaningful field from the response.

    Returns the first non-None field from the response. Useful for extracting
    the actual response value after validation.

    Returns:
        The first non-None response field.

    Raises:
        ReplyError: If all fields are None.

    Example:
        ```py
        >>> reply = Reply.model_validate_json(json_data, context={'instance': instance})
        >>> response = reply.unwrap()
        >>> windows = response.unwrap()  # Extract the actual data
        ```
    """
    for value in self.model_dump().values():
        if value is not None:
            return value
    raise ReplyError("Response does not contain any known fields.")

Reply ⚓︎

Bases: BaseModel

A Niri IPC protocol reply.

Wraps a Response with success/error indication. Either ok or err will be set, never both.

Attributes:

Name Type Description
ok Response | None

The response data if the request succeeded.

err str | None

Error message if the request failed.

Example
>>> from niripy.instances import Instance
>>> instance = Instance()
>>> json_data = instance.socket.send_command({"Outputs": {}})
>>> reply = Reply.model_validate_json(json_data, context={'instance': instance})
>>> response = reply.unwrap()  # Raises ReplyError if err is set
>>> windows = response.unwrap()  # Extract the actual data

Methods:

Name Description
unwrap

Extract the response or raise an error.

unwrap ⚓︎

unwrap() -> Response

Extract the response or raise an error.

Returns:

Type Description
Response

The ok response if present.

Raises:

Type Description
ReplyError

If the reply contains an error.

Example
>>> reply = Reply.model_validate_json(data, context={'instance': instance})
>>> response = reply.unwrap()  # Raises if err is set
Source code in src/niripy/models.py
def unwrap(self) -> Response:
    """Extract the response or raise an error.

    Returns:
        The ok response if present.

    Raises:
        ReplyError: If the reply contains an error.

    Example:
        ```py
        >>> reply = Reply.model_validate_json(data, context={'instance': instance})
        >>> response = reply.unwrap()  # Raises if err is set
        ```
    """
    if self.err is not None:
        raise ReplyError(f"Niri replied with error: {self.err}")
    assert self.ok is not None
    return self.ok