Add display rotation: Rot pill, chandra-ctl rotate, sensor auto-rotate
CI / test (push) Failing after 51s

- Rotate the display 0/90/180/270 degrees in the KMS host, with scanout and libinput touch/pointer coordinates transformed to match
- Add a touch "Rot" pill beside "KB": tap turns 90 CW, long-press or right-click flips 180
- Add `chandra-ctl rotate [cw|ccw|flip|0|90|180|270|status]`; CHANDRA_ROTATE sets the initial orientation
- Add session/chandra-auto-rotate, which follows iio-sensor-proxy orientation (disable with CHANDRA_AUTO_ROTATE=0)
- Advertise window_menu, maximize, fullscreen and minimize via xdg_toplevel.wm_capabilities (xdg_wm_base v5+)
- Add docs/handset.md covering handset touch, scaling, OSK and rotation
This commit is contained in:
nandi committed 2026-11-28 00:39:24 -08:00
1 parent 905dab8725
commit 2e00009c79
21 files changed
+636 -30

No files matched your search

+10
View File
@@ -328,6 +328,16 @@ pub fn run(args : Array[String]) -> Int {
NoChange => () NoChange => ()
} }
comp.step() comp.step()
match comp.take_pending_rotation() {
Some(rot) => {
let (nw, nh) = k.set_rotation(rot)
if nw > 0 && nh > 0 {
comp.apply_rotated_size(nw, nh)
need_present = true
}
}
None => ()
}
let f1 = @sys.monotonic_ms() let f1 = @sys.monotonic_ms()
k.set_cursor_shape(comp.desired_cursor()) k.set_cursor_shape(comp.desired_cursor())
// The host draws; only a changed desktop is sent, and the frame is shown by the host // The host draws; only a changed desktop is sent, and the frame is shown by the host
+9
View File
@@ -216,6 +216,15 @@ fn main {
for ev in k.take_input() { for ev in k.take_input() {
comp.handle_input(ev, now_ms) comp.handle_input(ev, now_ms)
} }
match comp.take_pending_rotation() {
Some(rot) => {
let (nw, nh) = k.set_rotation(rot)
if nw > 0 && nh > 0 {
comp.apply_rotated_size(nw, nh)
}
}
None => ()
}
k.set_cursor_shape(comp.desired_cursor()) k.set_cursor_shape(comp.desired_cursor())
if k.frame_ready() { if k.frame_ready() {
k.present(comp.present_to_gfx(gfx_ctx)) k.present(comp.present_to_gfx(gfx_ctx))
+72
View File
@@ -326,6 +326,9 @@ pub(all) struct ChandraCompositor {
mut osk_pressed : Int? mut osk_pressed : Int?
mut osk_hover : Int? mut osk_hover : Int?
mut osk_pointer_grab : Bool mut osk_pointer_grab : Bool
/// Output rotation (`0=0`, `1=90 CW`, `2=180 flip`, `3=270 CW`) and pending backend switch.
mut rotation : Int
mut pending_rotation : Int?
} }
///| ///|
@@ -475,6 +478,8 @@ pub fn ChandraCompositor::new(
osk_pressed: None, osk_pressed: None,
osk_hover: None, osk_hover: None,
osk_pointer_grab: false, osk_pointer_grab: false,
rotation: initial_rotation_from_env(),
pending_rotation: None,
} }
// Client popups (menus) are placed to stay on screen: the server asks for the output's // Client popups (menus) are placed to stay on screen: the server asks for the output's
// rectangle relative to the parent's content origin when it applies constraint adjustment. // rectangle relative to the parent's content origin when it applies constraint adjustment.
@@ -524,6 +529,72 @@ fn ChandraCompositor::recompute_work_area(self : ChandraCompositor) -> Unit {
self.damage.mark_full() self.damage.mark_full()
} }
///| Initial display rotation parsed from `CHANDRA_ROTATE` (`0|90|180|270` or `0..3`).
fn initial_rotation_from_env() -> Int {
match @sys.getenv("CHANDRA_ROTATE") {
"90" | "1" => 1
"180" | "2" => 2
"270" | "3" => 3
_ => 0
}
}
///| Queue a display rotation (`0=0`, `1=90 CW`, `2=180 flip`, `3=270 CW`). Applied by the
/// DRM/KMS host loop on the next iteration.
pub fn ChandraCompositor::request_rotation(self : ChandraCompositor, rot : Int) -> Unit {
let r = (rot % 4 + 4) % 4
self.pending_rotation = Some(r)
self.damage.mark_full()
}
///| Rotate the display 90 degrees clockwise.
pub fn ChandraCompositor::rotate_cw(self : ChandraCompositor) -> Unit {
self.request_rotation(self.rotation + 1)
}
///| Rotate the display 90 degrees counter-clockwise.
pub fn ChandraCompositor::rotate_ccw(self : ChandraCompositor) -> Unit {
self.request_rotation(self.rotation + 3)
}
///| Flip the display 180 degrees.
pub fn ChandraCompositor::rotate_flip(self : ChandraCompositor) -> Unit {
self.request_rotation(self.rotation + 2)
}
///| Current output rotation (`0=0`, `1=90`, `2=180`, `3=270`).
pub fn ChandraCompositor::current_rotation(self : ChandraCompositor) -> Int {
self.rotation
}
///| Consume any pending rotation request for the DRM backend.
pub fn ChandraCompositor::take_pending_rotation(self : ChandraCompositor) -> Int? {
match self.pending_rotation {
Some(r) => {
self.pending_rotation = None
self.rotation = r
Some(r)
}
None => None
}
}
///| Apply the new logical `(w, h)` reported by KMS after a rotation; forces a full redraw even
/// when dimensions match (such as a 180-degree flip).
pub fn ChandraCompositor::apply_rotated_size(self : ChandraCompositor, w : Int, h : Int) -> Unit {
if w > 0 && h > 0 && (w != self.output_w || h != self.output_h) {
self.resize(w, h)
}
self.last_frame = None
self.last_sig = None
self.frame_changed = true
self.damage.mark_full()
match self.emoji_ui {
Some(ui) => self.emoji_place(ui)
None => ()
}
}
///| The output changed size (the nested window was resized, maximized or made fullscreen): ///| The output changed size (the nested window was resized, maximized or made fullscreen):
/// lay the desktop out for the new size, so nothing is drawn past the edge and cropped away. /// lay the desktop out for the new size, so nothing is drawn past the edge and cropped away.
pub fn ChandraCompositor::resize(self : ChandraCompositor, w : Int, h : Int) -> Unit { pub fn ChandraCompositor::resize(self : ChandraCompositor, w : Int, h : Int) -> Unit {
@@ -963,6 +1034,7 @@ pub fn ChandraCompositor::step(self : ChandraCompositor) -> Unit {
/// a pending screenshot, a toast counting down): the main loop keeps its frame pace then instead /// a pending screenshot, a toast counting down): the main loop keeps its frame pace then instead
/// of sleeping until an fd wakes it. /// of sleeping until an fd wakes it.
pub fn ChandraCompositor::has_timed_work(self : ChandraCompositor) -> Bool { pub fn ChandraCompositor::has_timed_work(self : ChandraCompositor) -> Bool {
self.pending_rotation is Some(_) ||
self.rec is Some(_) || self.rec is Some(_) ||
self.shot_request is Some(_) || self.shot_request is Some(_) ||
self.rec_request is Some(_) || self.rec_request is Some(_) ||
+39
View File
@@ -213,6 +213,7 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin
"launch ID start desktop app ID (e.g. org.kde.kwi) as the dock does; a failed start shows its notice", "launch ID start desktop app ID (e.g. org.kde.kwi) as the dock does; a failed start shows its notice",
"windows each window: frame, layout, box, shadow, size limits; and what is under the pointer", "windows each window: frame, layout, box, shadow, size limits; and what is under the pointer",
"screenshot [PATH] save a full-screen PNG directly (without opening the editor)", "screenshot [PATH] save a full-screen PNG directly (without opening the editor)",
"rotate [cw|ccw|flip|0|90|180|270|status] rotate or flip the display",
"auth-demo [MODE] show the password dialog with a pretend check (password \"demo\"); MODE: " + "auth-demo [MODE] show the password dialog with a pretend check (password \"demo\"); MODE: " +
@polkit.demo_modes.join(", "), @polkit.demo_modes.join(", "),
"auth-status the password dialog's agent: running, registered, or why not", "auth-status the password dialog's agent: running, registered, or why not",
@@ -359,6 +360,44 @@ pub fn ChandraCompositor::control_command(self : ChandraCompositor, line : Strin
} }
} }
} }
"rotate" => {
let arg = if words.length() >= 2 { words[1] } else { "cw" }
if words.length() > 2 {
return (["error usage: rotate [cw|ccw|flip|0|90|180|270|status]"], false)
}
match arg {
"status" => (["ok " + (self.rotation * 90).to_string() + " " + self.output_w.to_string() + "x" + self.output_h.to_string()], true)
"cw" | "right" => {
self.rotate_cw()
(["ok rotate cw"], true)
}
"ccw" | "left" => {
self.rotate_ccw()
(["ok rotate ccw"], true)
}
"flip" => {
self.rotate_flip()
(["ok rotate flip"], true)
}
"0" | "normal" => {
self.request_rotation(0)
(["ok rotate 0"], true)
}
"90" | "1" => {
self.request_rotation(1)
(["ok rotate 90"], true)
}
"180" | "2" => {
self.request_rotation(2)
(["ok rotate 180"], true)
}
"270" | "3" => {
self.request_rotation(3)
(["ok rotate 270"], true)
}
_ => (["error usage: rotate [cw|ccw|flip|0|90|180|270|status]"], false)
}
}
other => (["error unknown command '" + other + "' (try: help)"], false) other => (["error unknown command '" + other + "' (try: help)"], false)
} }
} }
+61 -14
View File
@@ -118,6 +118,13 @@ pub fn ChandraCompositor::osk_toggle_rect(self : ChandraCompositor) -> @scene.Re
@scene.Rect::new(x, y, w, h) @scene.Rect::new(x, y, w, h)
} }
///| Compact "Rot" pill beside the "KB" pill: tap rotates 90 deg CW, long-press/right-click flips 180 deg.
pub fn ChandraCompositor::osk_rotate_rect(self : ChandraCompositor) -> @scene.Rect {
let kb = self.osk_toggle_rect()
let w = 44
@scene.Rect::new((kb.x - w - 6).max(4), kb.y, w, kb.h)
}
///| Show or hide the OSK, resizing `work_area` and lifting panel popups so focused content stays ///| Show or hide the OSK, resizing `work_area` and lifting panel popups so focused content stays
/// above the keyboard. /// above the keyboard.
fn ChandraCompositor::osk_set_visible(self : ChandraCompositor, want : Bool) -> Unit { fn ChandraCompositor::osk_set_visible(self : ChandraCompositor, want : Bool) -> Unit {
@@ -429,7 +436,7 @@ fn ChandraCompositor::osk_key_at(self : ChandraCompositor, x : Int, y : Int) ->
None None
} }
///| Whether `(x, y)` hits either the open OSK or its compact reopen pill. ///| Whether `(x, y)` hits either the open OSK or its compact corner pills ("Rot" / "KB").
fn ChandraCompositor::osk_hit_any(self : ChandraCompositor, x : Int, y : Int) -> Bool { fn ChandraCompositor::osk_hit_any(self : ChandraCompositor, x : Int, y : Int) -> Bool {
if !self.osk_enabled { if !self.osk_enabled {
return false return false
@@ -437,7 +444,8 @@ fn ChandraCompositor::osk_hit_any(self : ChandraCompositor, x : Int, y : Int) ->
if self.osk_visible { if self.osk_visible {
self.osk_rect().contains(x, y) self.osk_rect().contains(x, y)
} else { } else {
!self.kiosk_strict() && self.osk_toggle_rect().contains(x, y) !self.kiosk_strict() &&
(self.osk_toggle_rect().contains(x, y) || self.osk_rotate_rect().contains(x, y))
} }
} }
@@ -578,17 +586,32 @@ fn ChandraCompositor::osk_input(
} }
return false return false
} }
if !self.kiosk_strict() && self.osk_toggle_rect().contains(xi, yi) { if !self.kiosk_strict() {
if self.osk_hover != Some(-1) { let hover = if self.osk_toggle_rect().contains(xi, yi) {
self.osk_hover = Some(-1) Some(-1)
} else if self.osk_rotate_rect().contains(xi, yi) {
Some(-2)
} else {
None
}
match hover {
Some(id) => {
if self.osk_hover != Some(id) {
self.osk_hover = Some(id)
self.damage.mark_full() self.damage.mark_full()
} }
return true return true
} }
if self.osk_hover == Some(-1) { None =>
if self.osk_hover == Some(-1) || self.osk_hover == Some(-2) {
self.osk_hover = None self.osk_hover = None
self.damage.mark_full() self.damage.mark_full()
} }
}
if self.osk_pointer_grab {
return true
}
}
false false
} }
PointerButton(button, pressed) => { PointerButton(button, pressed) => {
@@ -606,6 +629,10 @@ fn ChandraCompositor::osk_input(
self.osk_manual_show = true self.osk_manual_show = true
self.osk_sync() self.osk_sync()
} }
Some(-2) =>
if !self.osk_visible && !self.kiosk_strict() && self.osk_rotate_rect().contains(xi, yi) {
self.rotate_cw()
}
Some(idx) => Some(idx) =>
if self.osk_visible && self.osk_key_at(xi, yi) == Some(idx) { if self.osk_visible && self.osk_key_at(xi, yi) == Some(idx) {
self.osk_activate_key(idx, time_ms) self.osk_activate_key(idx, time_ms)
@@ -623,14 +650,31 @@ fn ChandraCompositor::osk_input(
} }
return true return true
} }
if !self.osk_visible && !self.kiosk_strict() && self.osk_toggle_rect().contains(xi, yi) { if !self.osk_visible && !self.kiosk_strict() {
if button == 272U && pressed { let pill = if self.osk_toggle_rect().contains(xi, yi) {
Some(-1)
} else if self.osk_rotate_rect().contains(xi, yi) {
Some(-2)
} else {
None
}
match pill {
Some(id) => {
if pressed {
if button == 272U {
self.osk_pointer_grab = true self.osk_pointer_grab = true
self.osk_pressed = Some(-1) self.osk_pressed = Some(id)
self.damage.mark_full() self.damage.mark_full()
} else if button == 273U && id == -2 {
// Long-press / right-click on Rot flips 180 degrees.
self.rotate_flip()
}
} }
return true return true
} }
None => ()
}
}
false false
} }
Scroll(_, _, _) => { Scroll(_, _, _) => {
@@ -658,18 +702,21 @@ fn ChandraCompositor::osk_ops(self : ChandraCompositor) -> Array[@scene.DrawOp]
if self.kiosk_strict() { if self.kiosk_strict() {
return ops return ops
} }
let tr = self.osk_toggle_rect() let pills = [(self.osk_rotate_rect(), -2, "Rot"), (self.osk_toggle_rect(), -1, "KB")]
let bg = if self.osk_pressed == Some(-1) { for pill in pills {
let (tr, id, label) = pill
let bg = if self.osk_pressed == Some(id) {
pal.accent pal.accent
} else if self.osk_hover == Some(-1) { } else if self.osk_hover == Some(id) {
pal.surface_hover pal.surface_hover
} else { } else {
@scene.Rgba::new(pal.surface_popup.r.to_int(), pal.surface_popup.g.to_int(), pal.surface_popup.b.to_int(), 230) @scene.Rgba::new(pal.surface_popup.r.to_int(), pal.surface_popup.g.to_int(), pal.surface_popup.b.to_int(), 230)
} }
let fg = if self.osk_pressed == Some(-1) { pal.accent_foreground } else { pal.foreground } let fg = if self.osk_pressed == Some(id) { pal.accent_foreground } else { pal.foreground }
ops.push(@scene.DrawOp::FillRect(tr, bg, rad + 4)) ops.push(@scene.DrawOp::FillRect(tr, bg, rad + 4))
ops.push(@scene.DrawOp::StrokeRect(tr, pal.border, 1, rad + 4)) ops.push(@scene.DrawOp::StrokeRect(tr, pal.border, 1, rad + 4))
ops.push(@scene.DrawOp::Text(tr.x + tr.w / 2, tr.y + tr.h / 2, "KB", (fs - 2).max(10), fg, @scene.TextAlign::Center, true)) ops.push(@scene.DrawOp::Text(tr.x + tr.w / 2, tr.y + tr.h / 2, label, (fs - 2).max(10), fg, @scene.TextAlign::Center, true))
}
return ops return ops
} }
let r = self.osk_rect() let r = self.osk_rect()
+40
View File
@@ -137,3 +137,43 @@ test "OSK auto-opens on launcher popup, lifts popup above OSK, and types into se
assert_eq(comp.shell.launcher_state.query, "t") assert_eq(comp.shell.launcher_state.query, "t")
comp.close() comp.close()
} }
///|
test "Rot pill tap rotates CW, right-click flips 180 deg, and rotate control commands update size" {
let comp = osk_comp("rotate")
let rr = comp.osk_rotate_rect()
let rx = rr.x + rr.w / 2
let ry = rr.y + rr.h / 2
// Tap Rot pill -> queues 90 deg CW rotation.
click_at(comp, rx, ry, 10U)
assert_eq(comp.take_pending_rotation(), Some(1))
assert_eq(comp.current_rotation(), 1)
comp.apply_rotated_size(1170, 540)
assert_eq((comp.output_w, comp.output_h), (1170, 540))
// Right-click / long-press Rot pill -> queues 180 deg flip (1 -> 3 = 270 deg).
let rr2 = comp.osk_rotate_rect()
click_at(comp, rr2.x + rr2.w / 2, rr2.y + rr2.h / 2, 20U, btn=273U)
assert_eq(comp.take_pending_rotation(), Some(3))
assert_eq(comp.current_rotation(), 3)
// chandra-ctl rotate 0 / flip / status.
let (out0, ok0) = comp.control_command("rotate 0")
assert_true(ok0)
assert_eq(out0, ["ok rotate 0"])
assert_eq(comp.take_pending_rotation(), Some(0))
comp.apply_rotated_size(540, 1170)
let (out_flip, ok_flip) = comp.control_command("rotate flip")
assert_true(ok_flip)
assert_eq(out_flip, ["ok rotate flip"])
assert_eq(comp.take_pending_rotation(), Some(2))
comp.apply_rotated_size(540, 1170)
assert_true(comp.frame_changed)
let (out_st, ok_st) = comp.control_command("rotate status")
assert_true(ok_st)
assert_eq(out_st, ["ok 180 540x1170"])
comp.close()
}
+9
View File
@@ -51,12 +51,21 @@ extern "C" fn c_fd(i : Int) -> Int = "mp_kms_fd"
///| ///|
extern "C" fn c_set_power(on : Int) = "mp_kms_set_power" extern "C" fn c_set_power(on : Int) = "mp_kms_set_power"
///|
extern "C" fn c_set_rotation(rot : Int) -> Int = "mp_kms_set_rotation"
///| Turn the screen on or off (DPMS). While it is off no frame is shown (`frame_ready` is ///| Turn the screen on or off (DPMS). While it is off no frame is shown (`frame_ready` is
/// false); on shows the last frame again. /// false); on shows the last frame again.
pub fn Kms::set_power(_self : Kms, on : Bool) -> Unit { pub fn Kms::set_power(_self : Kms, on : Bool) -> Unit {
c_set_power(if on { 1 } else { 0 }) c_set_power(if on { 1 } else { 0 })
} }
///| Rotate the output (`0=0`, `1=90 CW`, `2=180`, `3=270 CW`); returns new logical `(w, h)`.
pub fn Kms::set_rotation(_self : Kms, rot : Int) -> (Int, Int) {
let p = c_set_rotation(rot)
((p >> 16) & 0xFFFF, p & 0xFFFF)
}
///| ///|
pub(all) struct Kms { pub(all) struct Kms {
width : Int width : Int
+132 -15
View File
@@ -147,10 +147,45 @@ static int g_flip_pending;
static int g_need_modeset; static int g_need_modeset;
static int g_width, g_height; static int g_width, g_height;
static int g_phys_w, g_phys_h; static int g_phys_w, g_phys_h;
static int g_base_w, g_base_h; /* unrotated logical size */
static int g_rot = 0; /* 0=0 deg, 1=90 deg CW, 2=180 deg flip, 3=270 deg CW */
static uint32_t g_mm_w, g_mm_h; static uint32_t g_mm_w, g_mm_h;
static int g_scale = 1; static int g_scale = 1;
static int g_blank; /* screen turned off (DPMS) by mp_kms_set_power */ static int g_blank; /* screen turned off (DPMS) by mp_kms_set_power */
static void logical_to_unrot(int x, int y, int *ux, int *uy) {
switch (g_rot) {
case 1: *ux = (g_base_w - 1) - y; *uy = x; break;
case 2: *ux = (g_base_w - 1) - x; *uy = (g_base_h - 1) - y; break;
case 3: *ux = y; *uy = (g_base_h - 1) - x; break;
default: *ux = x; *uy = y; break;
}
}
static void unrot_to_logical(int rx, int ry, int *x, int *y) {
if (rx < 0) rx = 0;
if (ry < 0) ry = 0;
if (g_base_w > 0 && rx >= g_base_w) rx = g_base_w - 1;
if (g_base_h > 0 && ry >= g_base_h) ry = g_base_h - 1;
switch (g_rot) {
case 1: *x = ry; *y = (g_base_w - 1) - rx; break;
case 2: *x = (g_base_w - 1) - rx; *y = (g_base_h - 1) - ry; break;
case 3: *x = (g_base_h - 1) - ry; *y = rx; break;
default: *x = rx; *y = ry; break;
}
}
static void apply_rotation_dims(int rot) {
g_rot = ((rot % 4) + 4) % 4;
if (g_rot == 1 || g_rot == 3) {
g_width = g_base_h;
g_height = g_base_w;
} else {
g_width = g_base_w;
g_height = g_base_h;
}
}
static int fb_create(struct fbuf *b, int w, int h) { static int fb_create(struct fbuf *b, int w, int h) {
struct drm_mode_create_dumb c = { .width = (uint32_t)w, .height = (uint32_t)h, .bpp = 32 }; struct drm_mode_create_dumb c = { .width = (uint32_t)w, .height = (uint32_t)h, .bpp = 32 };
if (drmIoctl(g_drm, DRM_IOCTL_MODE_CREATE_DUMB, &c) < 0) return -1; if (drmIoctl(g_drm, DRM_IOCTL_MODE_CREATE_DUMB, &c) < 0) return -1;
@@ -265,8 +300,12 @@ static void cursor_draw(int shape) {
static void cursor_apply(void) { static void cursor_apply(void) {
if (!g_cur_ready || !g_seat_enabled) return; if (!g_cur_ready || !g_seat_enabled) return;
int ux = g_px, uy = g_py;
if (g_rot != 0 && g_base_w > 0 && g_base_h > 0) {
logical_to_unrot(g_px, g_py, &ux, &uy);
}
drmModeSetCursor(g_drm, g_crtc, g_cur_buf.handle, CUR, CUR); drmModeSetCursor(g_drm, g_crtc, g_cur_buf.handle, CUR, CUR);
drmModeMoveCursor(g_drm, g_crtc, g_px * g_scale - g_hotx, g_py * g_scale - g_hoty); drmModeMoveCursor(g_drm, g_crtc, ux * g_scale - g_hotx, uy * g_scale - g_hoty);
} }
/* ---- touch long-press timer ---------------------------------------------- */ /* ---- touch long-press timer ---------------------------------------------- */
@@ -354,8 +393,9 @@ static void handle_li_event(struct libinput_event *ev) {
} }
case LIBINPUT_EVENT_POINTER_MOTION_ABSOLUTE: { case LIBINPUT_EVENT_POINTER_MOTION_ABSOLUTE: {
struct libinput_event_pointer *p = libinput_event_get_pointer_event(ev); struct libinput_event_pointer *p = libinput_event_get_pointer_event(ev);
g_px = (int)libinput_event_pointer_get_absolute_x_transformed(p, (uint32_t)g_width); int rx = (int)libinput_event_pointer_get_absolute_x_transformed(p, (uint32_t)g_base_w);
g_py = (int)libinput_event_pointer_get_absolute_y_transformed(p, (uint32_t)g_height); int ry = (int)libinput_event_pointer_get_absolute_y_transformed(p, (uint32_t)g_base_h);
unrot_to_logical(rx, ry, &g_px, &g_py);
clamp_pointer(); clamp_pointer();
q_push(EV_MOVE, g_px, g_py, 0, 0); q_push(EV_MOVE, g_px, g_py, 0, 0);
cursor_apply(); cursor_apply();
@@ -388,8 +428,9 @@ static void handle_li_event(struct libinput_event *ev) {
struct libinput_event_touch *t = libinput_event_get_touch_event(ev); struct libinput_event_touch *t = libinput_event_get_touch_event(ev);
if (g_touch_state == TOUCH_IDLE) { if (g_touch_state == TOUCH_IDLE) {
g_touch_slot = libinput_event_touch_get_seat_slot(t); g_touch_slot = libinput_event_touch_get_seat_slot(t);
g_px = (int)libinput_event_touch_get_x_transformed(t, (uint32_t)g_width); int rx = (int)libinput_event_touch_get_x_transformed(t, (uint32_t)g_base_w);
g_py = (int)libinput_event_touch_get_y_transformed(t, (uint32_t)g_height); int ry = (int)libinput_event_touch_get_y_transformed(t, (uint32_t)g_base_h);
unrot_to_logical(rx, ry, &g_px, &g_py);
clamp_pointer(); clamp_pointer();
g_touch_x0 = g_px; g_touch_x0 = g_px;
g_touch_y0 = g_py; g_touch_y0 = g_py;
@@ -403,8 +444,9 @@ static void handle_li_event(struct libinput_event *ev) {
case LIBINPUT_EVENT_TOUCH_MOTION: { case LIBINPUT_EVENT_TOUCH_MOTION: {
struct libinput_event_touch *t = libinput_event_get_touch_event(ev); struct libinput_event_touch *t = libinput_event_get_touch_event(ev);
if (g_touch_state != TOUCH_IDLE && libinput_event_touch_get_seat_slot(t) == g_touch_slot) { if (g_touch_state != TOUCH_IDLE && libinput_event_touch_get_seat_slot(t) == g_touch_slot) {
g_px = (int)libinput_event_touch_get_x_transformed(t, (uint32_t)g_width); int rx = (int)libinput_event_touch_get_x_transformed(t, (uint32_t)g_base_w);
g_py = (int)libinput_event_touch_get_y_transformed(t, (uint32_t)g_height); int ry = (int)libinput_event_touch_get_y_transformed(t, (uint32_t)g_base_h);
unrot_to_logical(rx, ry, &g_px, &g_py);
clamp_pointer(); clamp_pointer();
if (g_touch_state == TOUCH_PENDING) { if (g_touch_state == TOUCH_PENDING) {
int dx = g_px - g_touch_x0; int dx = g_px - g_touch_x0;
@@ -558,11 +600,19 @@ int32_t mp_kms_open(void) {
g_phys_w = g_mode.hdisplay; g_phys_w = g_mode.hdisplay;
g_phys_h = g_mode.vdisplay; g_phys_h = g_mode.vdisplay;
g_scale = pick_scale(g_phys_w, g_phys_h, g_mm_w, g_mm_h); g_scale = pick_scale(g_phys_w, g_phys_h, g_mm_w, g_mm_h);
g_width = g_phys_w / g_scale; g_base_w = g_phys_w / g_scale;
g_height = g_phys_h / g_scale; g_base_h = g_phys_h / g_scale;
if (g_scale > 1) { int init_rot = 0;
fprintf(stderr, "kms: output %dx%d scale %dx -> logical %dx%d\n", const char *renv = getenv("CHANDRA_ROTATE");
g_phys_w, g_phys_h, g_scale, g_width, g_height); if (renv && *renv) {
if (!strcmp(renv, "90") || !strcmp(renv, "1")) init_rot = 1;
else if (!strcmp(renv, "180") || !strcmp(renv, "2")) init_rot = 2;
else if (!strcmp(renv, "270") || !strcmp(renv, "3")) init_rot = 3;
}
apply_rotation_dims(init_rot);
if (g_scale > 1 || g_rot != 0) {
fprintf(stderr, "kms: output %dx%d scale %dx rot %d -> logical %dx%d\n",
g_phys_w, g_phys_h, g_scale, g_rot * 90, g_width, g_height);
} }
g_saved_crtc = drmModeGetCrtc(g_drm, g_crtc); g_saved_crtc = drmModeGetCrtc(g_drm, g_crtc);
@@ -603,8 +653,23 @@ int32_t mp_kms_open(void) {
MOONBIT_FFI_EXPORT int32_t mp_kms_width(void) { return g_width; } MOONBIT_FFI_EXPORT int32_t mp_kms_width(void) { return g_width; }
MOONBIT_FFI_EXPORT int32_t mp_kms_height(void) { return g_height; } MOONBIT_FFI_EXPORT int32_t mp_kms_height(void) { return g_height; }
MOONBIT_FFI_EXPORT int32_t mp_kms_rotation(void) { return g_rot; }
MOONBIT_FFI_EXPORT int32_t mp_kms_quit_requested(void) { return g_quit; } MOONBIT_FFI_EXPORT int32_t mp_kms_quit_requested(void) { return g_quit; }
/* Switch display rotation (0=0, 1=90 CW, 2=180, 3=270 CW). Returns (width << 16) | height. */
MOONBIT_FFI_EXPORT
int32_t mp_kms_set_rotation(int32_t rot) {
if (g_base_w <= 0 || g_base_h <= 0) return 0;
touch_cancel();
apply_rotation_dims(rot);
g_px = g_width / 2;
g_py = g_height / 2;
stale_add(0, 0, 1 << 16, 1 << 16);
cursor_apply();
fprintf(stderr, "kms: rotation %d deg -> logical %dx%d\n", g_rot * 90, g_width, g_height);
return ((g_width & 0xFFFF) << 16) | (g_height & 0xFFFF);
}
/* Service seat, DRM and input fds without blocking. Returns 1 while the seat is active. */ /* Service seat, DRM and input fds without blocking. Returns 1 while the seat is active. */
MOONBIT_FFI_EXPORT MOONBIT_FFI_EXPORT
int32_t mp_kms_poll(void) { int32_t mp_kms_poll(void) {
@@ -677,7 +742,8 @@ int32_t mp_kms_frame_ready(void) {
/* RGBA8888 rows -> the scanout buffer's XRGB8888 (B, G, R, X), one pixel as one 32-bit word. */ /* RGBA8888 rows -> the scanout buffer's XRGB8888 (B, G, R, X), one pixel as one 32-bit word. */
static void copy_rows(struct fbuf *b, const uint8_t *src, int w, int x0, int y0, int x1, int y1) { static void copy_rows(struct fbuf *b, const uint8_t *src, int w, int x0, int y0, int x1, int y1) {
if (g_scale <= 1) { int sc = g_scale > 1 ? g_scale : 1;
if (g_rot == 0 && sc == 1) {
for (int y = y0; y < y1; y++) { for (int y = y0; y < y1; y++) {
uint32_t *d = (uint32_t *)(b->map + (size_t)y * b->pitch); uint32_t *d = (uint32_t *)(b->map + (size_t)y * b->pitch);
const uint32_t *s = (const uint32_t *)(src + (size_t)y * (size_t)w * 4); const uint32_t *s = (const uint32_t *)(src + (size_t)y * (size_t)w * 4);
@@ -688,7 +754,7 @@ static void copy_rows(struct fbuf *b, const uint8_t *src, int w, int x0, int y0,
} }
return; return;
} }
int sc = g_scale; if (g_rot == 0) {
int px0 = x0 * sc; int px0 = x0 * sc;
int px1 = x1 * sc; int px1 = x1 * sc;
if (px1 > g_phys_w) px1 = g_phys_w; if (px1 > g_phys_w) px1 = g_phys_w;
@@ -712,6 +778,56 @@ static void copy_rows(struct fbuf *b, const uint8_t *src, int w, int x0, int y0,
memcpy(dy, (const uint8_t *)(d0 + px0), row_bytes); memcpy(dy, (const uint8_t *)(d0 + px0), row_bytes);
} }
} }
return;
}
if (g_rot == 2) {
int px0 = (g_base_w - x1) * sc;
int px1 = (g_base_w - x0) * sc;
if (px0 < 0) px0 = 0;
if (px1 > g_phys_w) px1 = g_phys_w;
if (px0 >= px1) return;
size_t row_bytes = (size_t)(px1 - px0) * 4;
for (int y = y0; y < y1; y++) {
int uy = (g_base_h - 1) - y;
int py0 = uy * sc;
if (py0 < 0 || py0 >= g_phys_h) continue;
uint32_t *d0 = (uint32_t *)(b->map + (size_t)py0 * b->pitch);
const uint32_t *s = (const uint32_t *)(src + (size_t)y * (size_t)w * 4);
for (int x = x0; x < x1; x++) {
uint32_t v = s[x];
uint32_t c = 0xff000000u | (v & 0x0000ff00u) | ((v >> 16) & 0xffu) | ((v & 0xffu) << 16);
int dx = ((g_base_w - 1) - x) * sc;
for (int k = 0; k < sc && dx + k < g_phys_w; k++) {
if (dx + k >= 0) d0[dx + k] = c;
}
}
for (int sy = 1; sy < sc && py0 + sy < g_phys_h; sy++) {
uint8_t *dy = b->map + (size_t)(py0 + sy) * b->pitch + (size_t)px0 * 4;
memcpy(dy, (const uint8_t *)(d0 + px0), row_bytes);
}
}
return;
}
/* 90 deg CW (g_rot == 1) and 270 deg CW (g_rot == 3). */
for (int y = y0; y < y1; y++) {
int ux = (g_rot == 1) ? ((g_base_w - 1) - y) : y;
int px = ux * sc;
if (px < 0 || px >= g_phys_w) continue;
const uint32_t *s = (const uint32_t *)(src + (size_t)y * (size_t)w * 4);
for (int x = x0; x < x1; x++) {
int uy = (g_rot == 1) ? x : ((g_base_h - 1) - x);
int py = uy * sc;
if (py < 0 || py >= g_phys_h) continue;
uint32_t v = s[x];
uint32_t c = 0xff000000u | (v & 0x0000ff00u) | ((v >> 16) & 0xffu) | ((v & 0xffu) << 16);
for (int sy = 0; sy < sc && py + sy < g_phys_h; sy++) {
uint32_t *d = (uint32_t *)(b->map + (size_t)(py + sy) * b->pitch);
for (int sx = 0; sx < sc && px + sx < g_phys_w; sx++) {
d[px + sx] = c;
}
}
}
}
} }
/* Present an RGBA8888 frame of w x h (must match the mode). */ /* Present an RGBA8888 frame of w x h (must match the mode). */
@@ -723,6 +839,7 @@ int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h);
MOONBIT_FFI_EXPORT MOONBIT_FFI_EXPORT
int32_t mp_kms_present_damage(moonbit_bytes_t pixels, int32_t w, int32_t h, int32_t dx, int32_t dy, int32_t dw, int32_t mp_kms_present_damage(moonbit_bytes_t pixels, int32_t w, int32_t h, int32_t dx, int32_t dy, int32_t dw,
int32_t dh) { int32_t dh) {
if (w != g_width || h != g_height) return 0;
int cw = w < g_width ? w : g_width; int cw = w < g_width ? w : g_width;
int ch = h < g_height ? h : g_height; int ch = h < g_height ? h : g_height;
int x0 = dx < 0 ? 0 : dx, y0 = dy < 0 ? 0 : dy; int x0 = dx < 0 ? 0 : dx, y0 = dy < 0 ? 0 : dy;
@@ -806,7 +923,7 @@ MOONBIT_FFI_EXPORT
void mp_kms_close(void) { void mp_kms_close(void) {
touch_cancel(); touch_cancel();
if (g_touch_timer >= 0) { close(g_touch_timer); g_touch_timer = -1; } if (g_touch_timer >= 0) { close(g_touch_timer); g_touch_timer = -1; }
g_phys_w = 0; g_phys_h = 0; g_mm_w = 0; g_mm_h = 0; g_scale = 1; g_phys_w = 0; g_phys_h = 0; g_base_w = 0; g_base_h = 0; g_rot = 0; g_mm_w = 0; g_mm_h = 0; g_scale = 1;
if (g_li) { libinput_unref(g_li); g_li = NULL; } if (g_li) { libinput_unref(g_li); g_li = NULL; }
if (g_udev) { udev_unref(g_udev); g_udev = NULL; } if (g_udev) { udev_unref(g_udev); g_udev = NULL; }
if (g_xkb_state) { xkb_state_unref(g_xkb_state); g_xkb_state = NULL; } if (g_xkb_state) { xkb_state_unref(g_xkb_state); g_xkb_state = NULL; }
+6
View File
@@ -53,6 +53,12 @@ pub fn Kms::set_power(_self : Kms, on : Bool) -> Unit {
@hostdisplay.set_power(on) @hostdisplay.set_power(on)
} }
///| Rotate the output (`0=0`, `1=90 CW`, `2=180`, `3=270 CW`); returns new logical `(w, h)`.
pub fn Kms::set_rotation(_self : Kms, rot : Int) -> (Int, Int) {
let p = @hostdisplay.set_rotation(rot.reinterpret_as_uint()).reinterpret_as_int()
((p >> 16) & 0xFFFF, p & 0xFFFF)
}
///| Show the cursor for a wp_cursor_shape_v1 value. ///| Show the cursor for a wp_cursor_shape_v1 value.
pub fn Kms::set_cursor_shape(_self : Kms, shape : UInt) -> Unit { pub fn Kms::set_cursor_shape(_self : Kms, shape : UInt) -> Unit {
@hostdisplay.set_cursor_shape(shape) @hostdisplay.set_cursor_shape(shape)
+18
View File
@@ -228,6 +228,8 @@ struct ClientConn {
pointer_ids : Array[UInt] pointer_ids : Array[UInt]
keyboard_ids : Array[UInt] keyboard_ids : Array[UInt]
mut seat_ver : UInt mut seat_ver : UInt
/// xdg_wm_base version the client bound (`wm_capabilities` arrived in v5).
mut xdg_ver : UInt
/// wl_data_device ids this client created (they receive selection events). /// wl_data_device ids this client created (they receive selection events).
data_devices : Array[UInt] data_devices : Array[UInt]
/// wl_data_source id -> mime types it offers. /// wl_data_source id -> mime types it offers.
@@ -269,6 +271,7 @@ fn ClientConn::new(client_id : UInt, fd : Int) -> ClientConn {
pointer_ids: [], pointer_ids: [],
keyboard_ids: [], keyboard_ids: [],
seat_ver: 1U, seat_ver: 1U,
xdg_ver: 1U,
data_devices: [], data_devices: [],
data_sources: {}, data_sources: {},
prim_devices: [], prim_devices: [],
@@ -673,6 +676,7 @@ fn WaylandServer::dispatch_msg(
emit_shm_formats(c, new_id) emit_shm_formats(c, new_id)
} else if iface == "xdg_wm_base" { } else if iface == "xdg_wm_base" {
c.objects.set(new_id, ObjXdgWmBase) c.objects.set(new_id, ObjXdgWmBase)
c.xdg_ver = ver
} else if iface == "zxdg_decoration_manager_v1" { } else if iface == "zxdg_decoration_manager_v1" {
c.objects.set(new_id, ObjDecoManager) c.objects.set(new_id, ObjDecoManager)
} else if iface == "org_kde_kwin_server_decoration_manager" { } else if iface == "org_kde_kwin_server_decoration_manager" {
@@ -1298,6 +1302,20 @@ fn WaylandServer::dispatch_msg(
wants_csd: false, wants_csd: false,
}) })
self.win_to_client.set(wid, c.client_id) self.win_to_client.set(wid, c.client_id)
if c.xdg_ver >= 5U {
// Advertise all standard window actions (window_menu, maximize, fullscreen, minimize)
// so GTK/Chromium CSD clients enable their Maximize button.
let caps : Array[Byte] = []
for cap in [1U, 2U, 3U, 4U] {
caps.push((cap & 0xFFU).to_byte())
caps.push(((cap >> 8) & 0xFFU).to_byte())
caps.push(((cap >> 16) & 0xFFU).to_byte())
caps.push(((cap >> 24) & 0xFFU).to_byte())
}
let wc = WireWriter::new()
wc.array(caps)
c.send_msg(wc.finish_msg(tl_id, 3U))
}
} else if opcode == 2U { } else if opcode == 2U {
// get_popup(id, parent: xdg_surface?, positioner) // get_popup(id, parent: xdg_surface?, positioner)
let pid = reader.u32() let pid = reader.u32()
+38
View File
@@ -0,0 +1,38 @@
# Handset & Touch Support
Chandra includes KMS/libinput/compositor adaptations tailored for mainline Linux smartphones (verified on OnePlus 6T `oneplus,fajita` at `1080x2340`).
## Display Scaling (`CHANDRA_SCALE`)
- Integer scaling lives in [`compositor/kms/kms_stub.c`](../compositor/kms/kms_stub.c).
- Setting `CHANDRA_SCALE=N` (or the default automatic `2x` scaling on dense portrait phone panels such as `1080x2340`) runs the compositor at a legible `540x1170` logical resolution while presenting `Nx` nearest pixels to hardware dumb buffers and cursor planes.
## Icon Desktop & Compact Panel
- **Icon desktop default:** Portrait handset layouts prioritize the touch-friendly icon desktop launcher aesthetic.
- **Compact panel layout:** Panel items (`launcher`, `dock`, `session-settings`, `network`, `battery`, `clock-digital`, `screenshot`) size compactly so all controls fit cleanly within `540px` portrait width without clipping, with fuel-gauge support (e.g. `bq27411-0`).
## Touch Input & On-Screen Keyboard
- **Long-press right-click:** In [`compositor/kms/kms_stub.c`](../compositor/kms/kms_stub.c), a stationary touch held for `500 ms` converts to a synthetic right-click (`BTN_RIGHT`) via a `timerfd`, allowing context menus and secondary actions without a mouse.
- **Built-in OSK:** [`compositor/host/osk.mbt`](../compositor/host/osk.mbt) provides a 5-row virtual keyboard that opens automatically when Wayland text input (`zwp_text_input_v3`) gains focus and can also be toggled manually from the bottom-right **`KB`** pill.
## Display Rotation, Flip, and Auto-Rotate
- **4-way transform (`0°`, `90° CW`, `180°`, `270° CW`):** Handled end-to-end across [`compositor/kms/kms_stub.c`](../compositor/kms/kms_stub.c), [`wit/host/display.wit`](../wit/host/display.wit), [`wasmhost/bin/display.mbt`](../wasmhost/bin/display.mbt), and the compositor event loop (`CHANDRA_ROTATE` sets the initial orientation). Both scanout rows and libinput touch/pointer coordinates transform to match the active orientation.
- **Touch `Rot` pill:** Sitting left of the `KB` pill in [`compositor/host/osk.mbt`](../compositor/host/osk.mbt):
- **Tap:** rotate `90°` clockwise (`0 -> 90 -> 180 -> 270 -> 0`).
- **Long-press / right-click:** flip `180°` (`0 <-> 180`, `90 <-> 270`).
- **CLI control:** `chandra-ctl rotate [cw|ccw|flip|0|90|180|270|status]` queries or changes rotation live (`0` portrait, `90` / `270` landscape, `180` inverted).
- **Sensor auto-rotate:** When running on the DRM backend (`chandra-session`) with `monitor-sensor` (`iio-sensor-proxy`) installed, [`session/chandra-auto-rotate`](../session/chandra-auto-rotate) runs inside the active `seat0` session and applies orientation change events (`normal -> 0`, `right-up -> 90`, `bottom-up -> 180`, `left-up -> 270`) without fighting manual `Rot` taps while stationary. Set `CHANDRA_AUTO_ROTATE=0` in the session environment to disable auto-rotate.
## Client-Side Window Controls (Chromium / GTK)
- [`compositor/wayland/server.mbt`](../compositor/wayland/server.mbt) emits `xdg_toplevel.wm_capabilities` (`window_menu`, `maximize`, `fullscreen`, `minimize`) for `xdg_wm_base` v5+ clients so client-decorated apps expose Maximize alongside Close.
- On GTK/Chromium setups where GNOME defaults (`org.gnome.desktop.wm.preferences button-layout`) omit maximize/minimize (e.g. `'appmenu:close'`), configure GTK and `gsettings`:
- `~/.config/gtk-3.0/settings.ini` and `~/.config/gtk-4.0/settings.ini`: `gtk-decoration-layout=:minimize,maximize,close`
- `gsettings set org.gnome.desktop.wm.preferences button-layout ':minimize,maximize,close'`
## Keyring Unlock
- [`session/chandra-session`](../session/chandra-session) starts `gnome-keyring-daemon --start --components=secrets` and unlocks an unencrypted default `login.keyring` at login over D-Bus (`org.freedesktop.Secret.Service.Unlock`) so apps such as Chromium store credentials without blocking prompts.
+3
View File
@@ -21,6 +21,9 @@ fn wasmImportSetCursorShape(p0 : Int) = "chandra:host/display@0.1.0" "set-curso
///| ///|
fn wasmImportSetPower(p0 : Int) = "chandra:host/display@0.1.0" "set-power" fn wasmImportSetPower(p0 : Int) = "chandra:host/display@0.1.0" "set-power"
///|
fn wasmImportSetRotation(p0 : Int) -> Int = "chandra:host/display@0.1.0" "set-rotation"
///| ///|
fn wasmImportTakeInput(p0 : Int) = "chandra:host/display@0.1.0" "take-input" fn wasmImportTakeInput(p0 : Int) = "chandra:host/display@0.1.0" "take-input"
@@ -35,6 +35,11 @@ fn wasmImportSetPower(p0 : Int) -> Unit {
abort("wasm-only host import") abort("wasm-only host import")
} }
///|
fn wasmImportSetRotation(p0 : Int) -> Int {
abort("wasm-only host import")
}
///| ///|
fn wasmImportTakeInput(p0 : Int) -> Unit { fn wasmImportTakeInput(p0 : Int) -> Unit {
abort("wasm-only host import") abort("wasm-only host import")
@@ -18,6 +18,8 @@ pub fn set_cursor_shape(UInt32) -> Unit
pub fn set_power(Bool) -> Unit pub fn set_power(Bool) -> Unit
pub fn set_rotation(UInt32) -> UInt32
pub fn take_input() -> Array[SeatEvent] pub fn take_input() -> Array[SeatEvent]
// Errors // Errors
+8
View File
@@ -103,6 +103,14 @@ pub fn set_power(on : Bool) -> Unit {
wasmImportSetPower((if on { 1 } else { 0 })); wasmImportSetPower((if on { 1 } else { 0 }));
}
///|
/// Rotate the output (0 = 0 deg, 1 = 90 deg CW, 2 = 180 deg flip, 3 = 270 deg CW).
/// Returns `(width << 16) | height` of the new logical output size.
pub fn set_rotation(rot : UInt) -> UInt {
(wasmImportSetRotation((rot).reinterpret_as_int())).reinterpret_as_uint()
} }
///| ///|
/// Input queued since the last call. /// Input queued since the last call.
+163
View File
@@ -0,0 +1,163 @@
#!/usr/bin/env python3
"""Auto-rotate the Chandra KMS display from iio-sensor-proxy accelerometer events."""
import argparse
import ctypes
import os
import signal
import subprocess
import sys
import time
CHANDRA_CTL = "/usr/local/bin/chandra-ctl"
ORIENTATION_TO_DEG = {
"normal": 0,
"right-up": 90,
"bottom-up": 180,
"left-up": 270,
}
PR_SET_PDEATHSIG = 1
def parse_orientation(line: str) -> int | None:
"""Return display rotation degrees (0/90/180/270) from a monitor-sensor line."""
text = line.strip()
if "Accelerometer orientation changed:" in text:
tail = text.split("Accelerometer orientation changed:", 1)[1].strip()
val = tail.split()[0] if tail else ""
return ORIENTATION_TO_DEG.get(val)
if "orientation:" in text:
part = text.split("orientation:", 1)[1].strip()
val = part.split(",", 1)[0].rstrip(")").strip()
return ORIENTATION_TO_DEG.get(val)
return None
def set_parent_death_signal() -> None:
"""Request SIGTERM from the kernel when the parent compositor process exits."""
try:
libc = ctypes.CDLL("libc.so.6")
libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0)
except OSError:
pass
def parent_alive(pid: int) -> bool:
"""Return True while the tracked parent PID still exists."""
try:
os.kill(pid, 0)
return True
except ProcessLookupError:
return False
except PermissionError:
return True
def wait_for_compositor(parent_pid: int, timeout_s: float = 15.0) -> bool:
"""Poll chandra-ctl ping until the compositor control socket responds or parent exits."""
deadline = time.monotonic() + timeout_s
while time.monotonic() < deadline:
if os.getppid() != parent_pid or not parent_alive(parent_pid):
return False
res = subprocess.run(
[CHANDRA_CTL, "ping"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
if res.returncode == 0:
return True
time.sleep(0.25)
return False
def current_rotation() -> int | None:
"""Query current display rotation degrees via chandra-ctl rotate status."""
res = subprocess.run(
[CHANDRA_CTL, "rotate", "status"],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
check=False,
)
if res.returncode != 0:
return None
parts = res.stdout.strip().split()
if len(parts) >= 2 and parts[0] == "ok":
try:
return int(parts[1])
except ValueError:
return None
return None
def apply_rotation(deg: int) -> bool:
"""Apply display rotation in degrees via chandra-ctl rotate."""
res = subprocess.run(
[CHANDRA_CTL, "rotate", str(deg)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
return res.returncode == 0
def main() -> int:
"""Watch monitor-sensor --accel and mirror orientation changes to Chandra."""
parser = argparse.ArgumentParser(description="Chandra auto-rotate daemon")
parser.add_argument("--parent-pid", type=int, default=os.getppid())
args = parser.parse_args()
parent_pid = args.parent_pid
set_parent_death_signal()
if os.getppid() != parent_pid:
return 0
if not wait_for_compositor(parent_pid):
return 0
proc = subprocess.Popen(
["monitor-sensor", "--accel"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
)
def stop_child(_signum: int, _frame: object) -> None:
if proc.poll() is None:
proc.terminate()
raise SystemExit(0)
signal.signal(signal.SIGTERM, stop_child)
signal.signal(signal.SIGINT, stop_child)
last_rot: int | None = None
try:
assert proc.stdout is not None
for line in proc.stdout:
if not parent_alive(parent_pid):
break
if "No accelerometer" in line or "Failed to claim accelerometer" in line:
print(f"chandra-auto-rotate: {line.strip()}", file=sys.stderr, flush=True)
break
deg = parse_orientation(line)
if deg is None or deg == last_rot:
continue
if last_rot is None and current_rotation() == deg:
last_rot = deg
continue
apply_rotation(deg)
last_rot = deg
finally:
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=2)
except subprocess.TimeoutExpired:
proc.kill()
return 0
if __name__ == "__main__":
raise SystemExit(main())
+2 -1
View File
@@ -10,6 +10,7 @@
chandra-ctl launch ID start desktop app ID (org.kde.kwi) as the dock does chandra-ctl launch ID start desktop app ID (org.kde.kwi) as the dock does
chandra-ctl windows how Chandra sees each window, and what is under the pointer chandra-ctl windows how Chandra sees each window, and what is under the pointer
chandra-ctl screenshot [PATH] save a full-screen PNG directly without opening the editor chandra-ctl screenshot [PATH] save a full-screen PNG directly without opening the editor
chandra-ctl rotate [ARG] rotate/flip display (cw, ccw, flip, 0, 90, 180, 270, status)
chandra-ctl auth-demo [MODE] show the password dialog with a pretend check (password "demo"); chandra-ctl auth-demo [MODE] show the password dialog with a pretend check (password "demo");
MODE: password, face, face-ok, die, slow, users (docs/auth-dialog.md) MODE: password, face, face-ok, die, slow, users (docs/auth-dialog.md)
chandra-ctl auth-status the password dialog's agent: registered with polkit, or why not chandra-ctl auth-status the password dialog's agent: registered with polkit, or why not
@@ -25,7 +26,7 @@ import os
import socket import socket
import sys import sys
USAGE = "usage: chandra-ctl [--socket PATH] [--quiet] {reload [NAME] | list | ping | shortcut ID | kiosk [lock|unlock|status] | launch ID | windows | screenshot [PATH] | auth-demo [MODE] | auth-status | help}" USAGE = "usage: chandra-ctl [--socket PATH] [--quiet] {reload [NAME] | list | ping | shortcut ID | kiosk [lock|unlock|status] | launch ID | windows | screenshot [PATH] | rotate [ARG] | auth-demo [MODE] | auth-status | help}"
def runtime_dir(): def runtime_dir():
+6
View File
@@ -241,5 +241,11 @@ for a in \
done done
export CHANDRA_POLKIT_FALLBACK="$fallback" export CHANDRA_POLKIT_FALLBACK="$fallback"
if [ "$backend" = --drm ] && [ "${CHANDRA_AUTO_ROTATE:-1}" != "0" ] &&
[ -x /usr/local/bin/chandra-auto-rotate ] && command -v monitor-sensor >/dev/null 2>&1; then
WAYLAND_DISPLAY="$(basename "$sock")" \
/usr/local/bin/chandra-auto-rotate --parent-pid "$$" >>"$log" 2>&1 &
fi
exec "$@" $backend --socket "$sock" \ exec "$@" $backend --socket "$sock" \
--theme "$share/config/themes/moon-night.json" >>"$log" 2>&1 --theme "$share/config/themes/moon-night.json" >>"$log" 2>&1
+3
View File
@@ -28,6 +28,7 @@ Installs:
starts it (docs/auth-dialog.md) starts it (docs/auth-dialog.md)
/usr/local/bin/chandra-ctl talk to the running session: `chandra-ctl reload` loads /usr/local/bin/chandra-ctl talk to the running session: `chandra-ctl reload` loads
the panel modules again (docs/reloading.md) the panel modules again (docs/reloading.md)
/usr/local/bin/chandra-auto-rotate DRM session accelerometer watcher (iio-sensor-proxy)
/usr/local/bin/chandra-kde-colors Dark mode for KDE/Qt apps: copies a color scheme into /usr/local/bin/chandra-kde-colors Dark mode for KDE/Qt apps: copies a color scheme into
kdeglobals (docs/dark-mode.md) kdeglobals (docs/dark-mode.md)
/usr/local/share/color-schemes/Chandra{Dark,Light}.colors KDE color schemes, used when Breeze's /usr/local/share/color-schemes/Chandra{Dark,Light}.colors KDE color schemes, used when Breeze's
@@ -64,6 +65,7 @@ targets = [
"/usr/local/bin/chandra-root", "/usr/local/bin/chandra-root",
"/usr/local/lib/chandra/chandra-polkit-agent", "/usr/local/lib/chandra/chandra-polkit-agent",
"/usr/local/bin/chandra-ctl", "/usr/local/bin/chandra-ctl",
"/usr/local/bin/chandra-auto-rotate",
"/usr/local/bin/chandra-kde-colors", "/usr/local/bin/chandra-kde-colors",
"/usr/local/share/color-schemes/ChandraDark.colors", "/usr/local/share/color-schemes/ChandraDark.colors",
"/usr/local/share/color-schemes/ChandraLight.colors", "/usr/local/share/color-schemes/ChandraLight.colors",
@@ -173,6 +175,7 @@ if linked:
else: else:
put(auth_agent, auth_agent_dst, 0o755) put(auth_agent, auth_agent_dst, 0o755)
install(os.path.join(root, "session/chandra-ctl"), "/usr/local/bin/chandra-ctl") install(os.path.join(root, "session/chandra-ctl"), "/usr/local/bin/chandra-ctl")
install(os.path.join(root, "session/chandra-auto-rotate"), "/usr/local/bin/chandra-auto-rotate")
install(os.path.join(root, "session/chandra-kde-colors"), "/usr/local/bin/chandra-kde-colors") install(os.path.join(root, "session/chandra-kde-colors"), "/usr/local/bin/chandra-kde-colors")
for f in ("ChandraDark.colors", "ChandraLight.colors"): for f in ("ChandraDark.colors", "ChandraLight.colors"):
put(os.path.join(root, "session/color-schemes", f), "/usr/local/share/color-schemes/" + f, 0o644) put(os.path.join(root, "session/color-schemes", f), "/usr/local/share/color-schemes/" + f, 0o644)
+7
View File
@@ -29,6 +29,9 @@ extern "C" fn mp_kms_set_cursor_shape(shape : Int) = "mp_kms_set_cursor_shape"
///| ///|
extern "C" fn mp_kms_set_power(on : Int) = "mp_kms_set_power" extern "C" fn mp_kms_set_power(on : Int) = "mp_kms_set_power"
///|
extern "C" fn mp_kms_set_rotation(rot : Int) -> Int = "mp_kms_set_rotation"
///| ///|
extern "C" fn mp_kms_next_event() -> Int = "mp_kms_next_event" extern "C" fn mp_kms_next_event() -> Int = "mp_kms_next_event"
@@ -192,6 +195,10 @@ fn display_funcs() -> Array[(String, (Array[@wt.Val]) -> Array[@wt.Val])] {
none none
}, },
), ),
(
"set-rotation",
a => [U32(mp_kms_set_rotation(a[0].to_int()).reinterpret_as_uint())],
),
("take-input", _ => [List(take_input())]), ("take-input", _ => [List(take_input())]),
( (
"close", "close",
+3
View File
@@ -28,6 +28,9 @@ interface display {
/// Turn the screen on or off (DPMS). While it is off no frame is shown (`frame-ready` is false); /// Turn the screen on or off (DPMS). While it is off no frame is shown (`frame-ready` is false);
/// turning it on shows the last frame again. /// turning it on shows the last frame again.
set-power: func(on: bool); set-power: func(on: bool);
/// Rotate the output (0 = 0 deg, 1 = 90 deg CW, 2 = 180 deg flip, 3 = 270 deg CW).
/// Returns `(width << 16) | height` of the new logical output size.
set-rotation: func(rot: u32) -> u32;
record pointer-pos { x: f64, y: f64 } record pointer-pos { x: f64, y: f64 }
/// A button or key as an evdev code, pressed or released. /// A button or key as an evdev code, pressed or released.