feat: Add an option to add the remaining spool weight to the title-bar (fixed) (#1662)

---------

Co-authored-by: Alfredo Monclus <alfredomonclus@gmail.com>
This commit is contained in:
locki-czandAlfredo Monclus authored and Alfredo Monclus committed 2026-04-19 15:01:41 -03:00
1 parent 0568319100
commit 2c693ddf16
6 files changed
+197 -8

No files matched your search

+7 -2
View File
@@ -70,7 +70,7 @@ moonraker_port: 7125
# moonraker_ssl: False # moonraker_ssl: False
# If you're using the route_prefix option in your moonraker config, specify it here. # If you're using the route_prefix option in your moonraker config, specify it here.
# This can be useful for running multiple printers behind a path-based reverse proxy. # This can be useful for running multiple printers behind a path-based reverse proxy.
# Most installs will not need this. # Most installs will not need this.
# moonraker_path: printer1 # moonraker_path: printer1
# Moonraker API key if this host is not connecting from a trusted client IP # Moonraker API key if this host is not connecting from a trusted client IP
# moonraker_api_key: False # moonraker_api_key: False
@@ -87,12 +87,17 @@ moonraker_port: 7125
# Define what items should be shown in titlebar besides the extruder and bed # Define what items should be shown in titlebar besides the extruder and bed
# the name must be the same as defined in the klipper config # the name must be the same as defined in the klipper config
# valid options are temperature_sensors or temperature_fans, or heater_generic # valid options are temperature_sensors or temperature_fans, or heater_generic
# titlebar_items: chamber, MCU, Pi # There is a special item named "spool" that depends on Spoolman data provided through Moonraker
# titlebar_items: chamber, MCU, Pi, spool
# The style of the user defined items in the titlebar # The style of the user defined items in the titlebar
# Can be 'full' indicating that the full name is shown, 'short' for the first letter, or None (default) for no name # Can be 'full' indicating that the full name is shown, 'short' for the first letter, or None (default) for no name
# titlebar_name_type: None # titlebar_name_type: None
# Low limit for remaining spool weight in the title bar, in grams.
# When the active spool drops below this value, the spool icon and weight turn red.
# spool_low_limit: 20
# Z probe calibrate position # Z probe calibrate position
# By default it tries to guess the correct location # By default it tries to guess the correct location
# it will try using zero reference position, safe_z, mesh midddle, middle of axis length, etc # it will try using zero reference position, safe_z, mesh midddle, middle of axis length, etc
+1 -1
View File
@@ -195,7 +195,7 @@ class KlipperScreenConfig:
) )
numbers = ( numbers = (
'moonraker_port', 'move_speed_xy', 'move_speed_z', 'screw_rotation', 'moonraker_port', 'move_speed_xy', 'move_speed_z', 'screw_rotation',
'calibrate_x_position', 'calibrate_y_position', 'calibrate_x_position', 'calibrate_y_position', 'spool_low_limit',
) )
elif section.startswith('preheat '): elif section.startswith('preheat '):
strs = ('gcode', '') strs = ('gcode', '')
+11
View File
@@ -27,6 +27,9 @@ class Printer:
self.cameras = [] self.cameras = []
self.available_commands = {} self.available_commands = {}
self.spoolman = False self.spoolman = False
self.active_spool_id = None
self.active_spool = None
self.active_spool_checked = False
self.temp_devices = self.sensors = None self.temp_devices = self.sensors = None
self.system_info = {} self.system_info = {}
self.warnings = [] self.warnings = []
@@ -48,6 +51,9 @@ class Printer:
self.stop_tempstore_updates() self.stop_tempstore_updates()
self.system_info.clear() self.system_info.clear()
self.warnings = [] self.warnings = []
self.active_spool_id = None
self.active_spool = None
self.active_spool_checked = False
for x in self.config.keys(): for x in self.config.keys():
# Support for hiding devices by name # Support for hiding devices by name
@@ -420,3 +426,8 @@ class Printer:
def enable_spoolman(self): def enable_spoolman(self):
logging.info("Enabling Spoolman") logging.info("Enabling Spoolman")
self.spoolman = True self.spoolman = True
def set_active_spool(self, spool_id=None, spool=None, checked=True):
self.active_spool_id = spool_id
self.active_spool = spool
self.active_spool_checked = checked
+171 -5
View File
@@ -1,15 +1,19 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import logging import logging
import os
import pathlib
import gi import gi
gi.require_version("Gtk", "3.0") gi.require_version("Gtk", "3.0")
from gi.repository import GLib, Gtk, Pango from gi.repository import Gio, GLib, Gtk, Pango, GdkPixbuf
from jinja2 import Environment from jinja2 import Environment
from datetime import datetime from datetime import datetime
from math import log from math import log
from ks_includes.screen_panel import ScreenPanel from ks_includes.screen_panel import ScreenPanel
SPOOL_ID_UNSET = object()
try: try:
import psutil import psutil
psutil_available = True psutil_available = True
@@ -26,8 +30,12 @@ class BasePanel(ScreenPanel):
self.time_format = self._config.get_main_config().getboolean("24htime", True) self.time_format = self._config.get_main_config().getboolean("24htime", True)
self.time_update = None self.time_update = None
self.battery_update = None self.battery_update = None
self.spoolman_update = None
self.titlebar_items = [] self.titlebar_items = []
self.titlebar_name_type = None self.titlebar_name_type = None
self.show_spoolman_in_title = False
self.spoolman_low_limit = 20
self.spoolman_current_color = None
self.current_extruder = None self.current_extruder = None
self.last_usage_report = datetime.now() self.last_usage_report = datetime.now()
self.usage_report = 0 self.usage_report = 0
@@ -104,6 +112,15 @@ class BasePanel(ScreenPanel):
for widget in self.control['battery_box']: for widget in self.control['battery_box']:
widget.show() widget.show()
self.labels['spoolman_icon'] = Gtk.Image()
self.labels['spoolman_weight'] = Gtk.Label()
self.control['spoolman_box'] = Gtk.Box()
self.control['spoolman_box'].set_no_show_all(True)
self.control['spoolman_box'].pack_start(self.labels['spoolman_icon'], False, False, 7)
self.control['spoolman_box'].pack_start(self.labels['spoolman_weight'], False, False, 0)
self.labels['spoolman_icon'].show()
self.labels['spoolman_weight'].show()
self.titlebar = Gtk.Box(spacing=5, valign=Gtk.Align.CENTER) self.titlebar = Gtk.Box(spacing=5, valign=Gtk.Align.CENTER)
self.titlebar.get_style_context().add_class("title_bar") self.titlebar.get_style_context().add_class("title_bar")
self.titlebar.add(self.control['temp_box']) self.titlebar.add(self.control['temp_box'])
@@ -157,9 +174,48 @@ class BasePanel(ScreenPanel):
self.battery_icons = self.load_battery_icons() self.battery_icons = self.load_battery_icons()
self.battery_percentage() self.battery_percentage()
def get_spoolman_icon_pixbuf(self, color):
klipperscreendir = pathlib.Path(__file__).parent.resolve().parent
icon_path = os.path.join(klipperscreendir, "styles", self._screen.theme, "images", "spool.svg")
icon_size = self._gtk.img_scale * self.bts * .9
if not os.path.isfile(icon_path):
icon_path = os.path.join(klipperscreendir, "styles", "spool.svg")
try:
svg = pathlib.Path(icon_path).read_text(encoding="utf-8")
svg = svg.replace("var(--filament-color)", f"#{color}")
stream = Gio.MemoryInputStream.new_from_data(svg.encode(), None)
pixbuf = GdkPixbuf.Pixbuf.new_from_stream_at_scale(
stream,
-1,
icon_size,
True,
None,
)
stream.close_async(2)
return pixbuf
except Exception as e:
logging.error(f"Couldn't load spoolman icon: {e}")
return self._gtk.PixbufFromIcon("spool", icon_size, icon_size)
def get_active_spoolman_color(self):
default_color = "000000"
if (
self._printer is None
or not self._printer.active_spool
or "filament" not in self._printer.active_spool
or not self._printer.active_spool["filament"]
):
return default_color
filament = self._printer.active_spool["filament"]
color = filament.get("color_hex")
if isinstance(color, str):
return color.strip().lstrip("#") or default_color
return default_color
def show_heaters(self, show=True): def show_heaters(self, show=True):
for child in self.control['temp_box'].get_children(): for child in self.control['temp_box'].get_children():
self.control['temp_box'].remove(child) self.control['temp_box'].remove(child)
self.control['spoolman_box'].hide()
if self._printer is None or not show: if self._printer is None or not show:
return return
try: try:
@@ -193,13 +249,17 @@ class BasePanel(ScreenPanel):
elif device.startswith("heater"): elif device.startswith("heater"):
self.control['temp_box'].add(self.labels[f"{device}_box"]) self.control['temp_box'].add(self.labels[f"{device}_box"])
n += 1 n += 1
for device in devices: for item in self.titlebar_items:
# Users can fill the bar if they want # Users can fill the bar if they want
if n >= nlimit + 1: if n >= nlimit + 1:
break break
name = device.split()[1] if len(device.split()) > 1 else device if item == "spool" and self._printer.spoolman:
for item in self.titlebar_items: self.control['temp_box'].add(self.control['spoolman_box'])
if name == item: n += 1
continue
for device in devices:
name = device.split()[1] if len(device.split()) > 1 else device
if name == item and self.labels[f"{device}_box"].get_parent() is None:
self.control['temp_box'].add(self.labels[f"{device}_box"]) self.control['temp_box'].add(self.labels[f"{device}_box"])
n += 1 n += 1
break break
@@ -234,6 +294,10 @@ class BasePanel(ScreenPanel):
if self.battery_update is None: if self.battery_update is None:
self.battery_update = GLib.timeout_add_seconds(60, self.battery_percentage) self.battery_update = GLib.timeout_add_seconds(60, self.battery_percentage)
def set_spoolman_refresh(self):
if not self.spoolman_update:
self.spoolman_update = GLib.timeout_add_seconds(60, self.fetch_spoolman)
def add_content(self, panel): def add_content(self, panel):
printing = self._printer and self._printer.state in {"printing", "paused"} printing = self._printer and self._printer.state in {"printing", "paused"}
connected = self._printer and self._printer.state not in {'disconnected', 'startup', 'shutdown', 'error'} connected = self._printer and self._printer.state not in {'disconnected', 'startup', 'shutdown', 'error'}
@@ -242,6 +306,7 @@ class BasePanel(ScreenPanel):
self.control['shutdown'].set_visible(not printing) self.control['shutdown'].set_visible(not printing)
self.show_shortcut(connected and printer_select) self.show_shortcut(connected and printer_select)
self.show_heaters(connected and printer_select) self.show_heaters(connected and printer_select)
self.refresh_spoolman_weight(connected and printer_select)
self.show_printer_select(len(self._config.get_printers()) > 1) self.show_printer_select(len(self._config.get_printers()) > 1)
for control in ('back', 'home'): for control in ('back', 'home'):
self.set_control_sensitive(len(self._screen._cur_panels) > 1, control=control) self.set_control_sensitive(len(self._screen._cur_panels) > 1, control=control)
@@ -249,6 +314,85 @@ class BasePanel(ScreenPanel):
self.set_title(panel.title) self.set_title(panel.title)
self.content.add(panel.content) self.content.add(panel.content)
def update_spoolman_alert_visuals(self, alert):
if alert:
self.labels['spoolman_weight'].get_style_context().add_class("spoolman_low")
else:
self.labels['spoolman_weight'].get_style_context().remove_class("spoolman_low")
def update_spoolman_weight_label(self):
if (
self._printer is None
or not self.show_spoolman_in_title
):
self.control['spoolman_box'].hide()
return
if (
not self._printer.spoolman
or not self._printer.active_spool
or "remaining_weight" not in self._printer.active_spool
or self._printer.active_spool["remaining_weight"] is None
):
self.update_spoolman_alert_visuals(False)
self.labels['spoolman_weight'].set_label("?")
self.control['spoolman_box'].show()
return
remaining_weight = self._printer.active_spool["remaining_weight"]
self.labels['spoolman_weight'].set_label(f'{round(remaining_weight):.0f} g')
self.update_spoolman_alert_visuals(remaining_weight < self.spoolman_low_limit)
self.control['spoolman_box'].show()
def refresh_spoolman_weight(self, show=True, spool_id=SPOOL_ID_UNSET, force=False):
if (
self._printer is None
or not self._printer.spoolman
or not self.show_spoolman_in_title
or not show
):
self.control['spoolman_box'].hide()
return
if (
not force
and spool_id is SPOOL_ID_UNSET
and self._printer.active_spool_checked
):
self.update_spoolman_weight_label()
return
def reset_spool_ui(sid=None, checked=False):
self._printer.set_active_spool(spool_id=sid, checked=checked)
self.update_spoolman_weight_label()
if spool_id is SPOOL_ID_UNSET:
result = self._screen.apiclient.send_request("server/spoolman/spool_id")
if not result or not result.get("spool_id"):
logging.error("Error trying to fetch active spool id")
reset_spool_ui(checked=False)
return
spool_id = result["spool_id"]
spool_resp = self._screen.apiclient.post_request("server/spoolman/proxy", json={
"request_method": "GET",
"path": f"/v1/spool/{spool_id}",
})
if not spool_resp or "result" not in spool_resp:
logging.error("Error trying to fetch active spool information")
reset_spool_ui(sid=spool_id, checked=False)
return
self._printer.set_active_spool(spool_id=spool_id, spool=spool_resp["result"])
self.update_spoolman_weight_label()
color = self.get_active_spoolman_color()
if color != self.spoolman_current_color:
self.labels['spoolman_icon'].set_from_pixbuf(self.get_spoolman_icon_pixbuf(color))
self.spoolman_current_color = color
def fetch_spoolman(self):
printing = self._printer.state in {"printing", "paused"}
printer_select = 'printer_select' in self._screen._cur_panels
if printer_select or not printing:
return False
self.refresh_spoolman_weight(force=True)
return True
def back(self, widget=None): def back(self, widget=None):
if self.current_panel is None: if self.current_panel is None:
return return
@@ -259,6 +403,19 @@ class BasePanel(ScreenPanel):
self._screen._menu_go_back() self._screen._menu_go_back()
def process_update(self, action, data): def process_update(self, action, data):
if action == "notify_active_spool_set":
has_spool_id = isinstance(data, dict) and "spool_id" in data
if not has_spool_id and self._printer is not None:
# Force a refetch when the event arrives without an explicit spool_id
# so the titlebar doesn't keep showing a stale cached spool.
self._printer.set_active_spool(checked=False)
spool_id = data.get("spool_id") if has_spool_id else SPOOL_ID_UNSET
self.refresh_spoolman_weight(
self._printer is not None
and self._printer.state not in {'disconnected', 'startup', 'shutdown', 'error'},
spool_id=spool_id
)
return
if action == "notify_proc_stat_update": if action == "notify_proc_stat_update":
cpu = data["system_cpu_usage"]["cpu"] cpu = data["system_cpu_usage"]["cpu"]
memory = (data["system_memory"]["used"] / data["system_memory"]["total"]) * 100 memory = (data["system_memory"]["used"] / data["system_memory"]["total"]) * 100
@@ -428,6 +585,15 @@ class BasePanel(ScreenPanel):
logging.info(f"Titlebar name type: {self.titlebar_name_type} items: {self.titlebar_items}") logging.info(f"Titlebar name type: {self.titlebar_name_type} items: {self.titlebar_items}")
else: else:
self.titlebar_items = [] self.titlebar_items = []
self.show_spoolman_in_title = "spool" in self.titlebar_items
self.spoolman_low_limit = self.ks_printer_cfg.getfloat("spool_low_limit", fallback=20)
else:
self.titlebar_items = []
self.show_spoolman_in_title = False
self.spoolman_low_limit = 20
self.refresh_spoolman_weight(
self._printer is not None and self._printer.state not in {'disconnected', 'startup', 'shutdown', 'error'}
)
def show_update_dialog(self): def show_update_dialog(self):
if self.update_dialog is not None: if self.update_dialog is not None:
+3
View File
@@ -778,6 +778,8 @@ class KlipperScreen(Gtk.Window):
def state_printing(self): def state_printing(self):
self.show_panel("job_status", remove_all=True) self.show_panel("job_status", remove_all=True)
if self.printer.spoolman:
self.base_panel.set_spoolman_refresh()
def state_ready(self, wait=True): def state_ready(self, wait=True):
# Do not return to main menu if completing a job, timeouts/user input will return # Do not return to main menu if completing a job, timeouts/user input will return
@@ -1108,6 +1110,7 @@ class KlipperScreen(Gtk.Window):
self.printer.configure_cameras(cameras['webcams']) self.printer.configure_cameras(cameras['webcams'])
if "spoolman" in self.server_info["components"]: if "spoolman" in self.server_info["components"]:
self.printer.enable_spoolman() self.printer.enable_spoolman()
self.base_panel.refresh_spoolman_weight()
def init_klipper(self): def init_klipper(self):
if self.reinit_count > self.max_retries or 'printer_select' in self._cur_panels: if self.reinit_count > self.max_retries or 'printer_select' in self._cur_panels:
+4
View File
@@ -290,6 +290,10 @@ trough {
min-height: 2em; min-height: 2em;
} }
.spoolman_low {
color: @warning;
}
.content { .content {
margin: 0 .1em; margin: 0 .1em;
} }