plymouth/scripts/keymap-render.py

100 lines
3.1 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/python3
# coding: utf-8
import cairo
import subprocess
import math
FONT_SIZE = 30
MARGIN = int(FONT_SIZE / 3)
def get_keymaps():
keymaps = subprocess.check_output(["localectl", "list-keymaps"]).decode("utf-8").strip().split()
# Note when changing this you MUST keep ply_keymap_normalize_keymap()
# from src/libply-splash-graphics/ply-keymap-icon.c in sync
def normalize_keymaps(keymap):
parts = keymap.replace("_", "-").replace(".", "-").split("-")
# Special case for dvorak, E.g. when mixing "us" and "us-dvorak"
# on machines returning "us" for both is not useful.
# Presumably users using dvorak now which variant they use
# so we just describe all dvorak layouts as "dvorak".
if "dvorak" in keymap:
return "dvorak"
# mac / sun keymaps are prefixes with mac / sun / sun[4-6]t
for prefix in ["mac", "sun" ]:
if keymap.startswith(prefix) and len(parts) > 1:
return parts[1]
return parts[0]
keymaps = list(map(normalize_keymaps ,keymaps))
#Remove duplicates
ret = []
for k in keymaps:
if k not in ret:
ret.append(k)
return ret
# Calculate size
sf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 1, 1)
ct = cairo.Context(sf)
ct.select_font_face("Cantarell", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
ct.set_font_size(FONT_SIZE)
max_height = 0.0
total_width = 0.0
for i in get_keymaps():
extents = ct.text_extents(i)
h = extents.height
if h > max_height:
max_height = h
total_width += extents.width
total_width += MARGIN * 2
ascent, descent, _h, _max_x, max_y = ct.font_extents()
# Create image
sf = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(total_width), int(max_height + MARGIN * 2))
ct = cairo.Context(sf)
ct.save()
ct.set_source_rgba(0, 0, 0, 0)
ct.set_operator (cairo.OPERATOR_SOURCE)
ct.paint()
ct.restore()
ct.select_font_face("Cantarell", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD)
ct.set_font_size(FONT_SIZE)
ct.set_source_rgba(0.75, 0.75, 0.75, 1.0)
ct.move_to(MARGIN, MARGIN + max_height - descent)
current_x, current_y = (MARGIN, MARGIN + max_height - descent)
metadata = []
for km in get_keymaps():
extents = ct.text_extents(km)
ct.show_text(km)
metadata.append((km, current_x, extents.width + MARGIN * 2))
current_x += extents.width + (MARGIN * 2)
ct.move_to(current_x, current_y)
sf.write_to_png("keymap-render.png")
print("/* This file is autogenerated by running:")
print(" * scripts/keymap-render.py > src/libply-splash-graphics/ply-keymap-metadata.h")
print(" */")
print("struct ply_keymap_metadata {")
print(" const char *name;")
print(" int offset;")
print(" int width;")
print("};")
print("")
print("static struct ply_keymap_metadata ply_keymap_metadata[] = {")
for i in metadata:
print((" { \"%s\", %d, %d }," % (i[0],i[1],i[2])))
print(" { NULL, } /* End of array marker */ ")
print("};")