chamesle

chamesle.org: the site of Chamesle, a small Linux distribution
git clone https://github.com/tortr-rs/chamesle
Log | Files | Refs | README

generate_keyboard_layout.py (14841B)


      1 #!/usr/bin/python3
      2 
      3 import subprocess
      4 import sys
      5 from PIL import Image, ImageDraw, ImageFont
      6 
      7 FONT_NAME = "/usr/share/live-installer/GoNotoCurrent-Regular.ttf"
      8 
      9 LARGE_FONT_SIZE = 14
     10 REG_FONT_SIZE = 12
     11 META_FONT_SIZE = 18
     12 
     13 WIDTH = 640
     14 HEIGHT = 178
     15 
     16 key_color = (0x58, 0x58, 0x58)
     17 meta_key_color = (0x50, 0x50, 0x50)
     18 border_color = (0x99, 0x99, 0x99)
     19 primary_text_color = (0xff, 0xff, 0xff)
     20 secondary_text_color = (0x9e, 0xde, 0xff)
     21 
     22 CAP_FONT_OFFSET_X = 6
     23 CAP_FONT_OFFSET_Y = 3
     24 REG_FONT_OFFSET_X = 6
     25 REG_FONT_OFFSET_Y = 19
     26 CTRL_FONT_OFFSET_X = 23
     27 CTRL_FONT_OFFSET_Y = 19
     28 
     29 UNICODE_RETURN = "\u21B5" # ⏎
     30 
     31 # Dead key mappings
     32 DEAD_KEYS = {
     33     "dead_circumflex": "\u005E",    # ^ (Circumflex Accent)
     34     "dead_acute": "\u00B4",         # ´ (Acute Accent)
     35     "dead_grave": "\u0060",         # ` (Grave Accent)
     36     "dead_tilde": "\u007E",         # ~ (Tilde)
     37     "dead_diaeresis": "\u00A8",     # ¨ (Diaeresis/Umlaut)
     38     "dead_cedilla": "\u00B8",       # ¸ (Cedilla)
     39     "dead_macron": "\u00AF",        # ¯ (Macron)
     40     "dead_breve": "\u02D8",         # ˘ (Breve)
     41     "dead_abovedot": "\u02D9",      # ˙ (Dot Above)
     42     "dead_ogonek": "\u02DB",        # ˛ (Ogonek)
     43     "dead_caron": "\u02C7",         # ˇ (Caron/Hacek)
     44     "dead_doubleacute": "\u02DD",   # ˝ (Double Acute)
     45     "dead_abovering": "\u02DA",     # ˚ (Ring Above)
     46     "dead_iota": "\u037A",          # ͺ (Greek Iota Subscript)
     47     "dead_greek": "\u037E",         # ; (Greek Question Mark, often for Greek tone)
     48     "dead_semivoiced_sound": "\u309A",  # ゚ (Katakana Semivoiced Sound)
     49     "dead_voiced_sound": "\u3099"   # ゛ (Katakana Voiced Sound)
     50 }
     51 
     52 # U+ , or +U+ ... to string
     53 def fromUnicodeString(raw):
     54     if raw[0:2] == "U+":
     55         return chr(int(raw[2:], 16))
     56     elif raw[0:2] == "+U":
     57         return chr(int(raw[3:], 16))
     58     elif raw in DEAD_KEYS:
     59         return DEAD_KEYS[raw]
     60     elif raw.startswith("dead_"):
     61         return ""
     62     elif raw.startswith("KP_"):
     63         return ""
     64     elif raw in ["Delete", "Shift", "Return", "Caps_Lock", "Left", "Right", "Alt", "Control"]:
     65         return ""
     66     return raw
     67 
     68 class KeyboardRenderer:
     69     # Keyboard layouts
     70     kb_104 = {
     71         "extended_return": False,
     72         "keys": [
     73         (0x29, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd),
     74         (0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x2b),
     75         (0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28),
     76         (0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35),
     77         ()]
     78     }
     79 
     80     kb_105 = {
     81         "extended_return": True,
     82         "keys": [
     83         (0x29, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd),
     84         (0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b),
     85         (0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x2b),
     86         (0x55, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35),
     87         ()]
     88     }
     89 
     90     kb_106 = {
     91         "extended_return": True,
     92         "keys": [
     93         (0x29, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe),
     94         (0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b),
     95         (0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29),
     96         (0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36),
     97         ()]
     98     }
     99 
    100     def __init__(self, layout, variant, scale, filename):
    101         self.codes = []
    102         self.layout = layout
    103         self.variant = variant
    104         self.scale = scale
    105         self.kb = None
    106         self.width = WIDTH
    107         self.height = HEIGHT
    108         self.filename = filename
    109         self.space = 6
    110         self.usable_width = self.width - 6
    111         self.key_w = round((self.usable_width - 14 * self.space) / 15)
    112 
    113         try:
    114             self.large_font = ImageFont.truetype(FONT_NAME, LARGE_FONT_SIZE * self.scale)
    115             self.regular_font = ImageFont.truetype(FONT_NAME, REG_FONT_SIZE * self.scale)
    116             self.meta_font = ImageFont.truetype(FONT_NAME, META_FONT_SIZE * self.scale)
    117         except IOError:
    118             print("Error: Could not load fonts!")
    119             sys.exit(1)
    120 
    121         self.loadCodes()
    122         self.loadInfo()
    123         self.render()
    124 
    125     def loadInfo(self):
    126         kbl_104 = ["us", "th"]
    127         kbl_106 = ["jp"]
    128 
    129         # most keyboards are 105 key so default to that
    130         if self.layout in kbl_104:
    131             self.kb = self.kb_104
    132         elif self.layout in kbl_106:
    133             self.kb = self.kb_106
    134         elif self.kb != self.kb_105:
    135             self.kb = self.kb_105
    136 
    137     def regular_text(self, index):
    138         return self.codes[index - 1][0]
    139 
    140     def shift_text(self, index):
    141         return self.codes[index - 1][1]
    142 
    143     def ctrl_text(self, index):
    144         return self.codes[index - 1][2]
    145 
    146     def alt_text(self, index):
    147         return self.codes[index - 1][3]
    148 
    149     def loadCodes(self):
    150         if self.layout is None:
    151             return
    152 
    153         variantParam = ""
    154         if self.variant is not None and self.variant != "None":
    155             variantParam = "-variant %s" % self.variant
    156 
    157         cmd = "ckbcomp -model pc106 -layout %s %s -compact" % (self.layout, variantParam)
    158 
    159         pipe = subprocess.Popen(cmd, shell=True, encoding='utf-8', errors='ignore', stdout=subprocess.PIPE, stderr=None)
    160         cfile = pipe.communicate()[0]
    161 
    162         # clear the current codes
    163         del self.codes[:]
    164 
    165         for l in cfile.split('\n'):
    166             if l[:7] != "keycode":
    167                 continue
    168 
    169             codes = l.split('=')[1].strip().split(' ')
    170 
    171             plain = fromUnicodeString(codes[0])
    172             shift = fromUnicodeString(codes[1])
    173             ctrl = fromUnicodeString(codes[2])
    174             alt = fromUnicodeString(codes[3])
    175 
    176             if ctrl == plain:
    177                 ctrl = ""
    178 
    179             if alt == plain:
    180                 alt = ""
    181 
    182             self.codes.append((plain, shift, ctrl, alt))
    183 
    184     def rounded_rectangle(self, draw, xy, radius, fill, outline=None, width=1):
    185         x1, y1, x2, y2 = xy
    186         r = radius
    187         draw.ellipse((x1, y1, x1 + r*2, y1 + r*2), fill=fill, outline=outline, width=width)
    188         draw.ellipse((x2 - r*2, y1, x2, y1 + r*2), fill=fill, outline=outline, width=width)
    189         draw.ellipse((x1, y2 - r*2, x1 + r*2, y2), fill=fill, outline=outline, width=width)
    190         draw.ellipse((x2 - r*2, y2 - r*2, x2, y2), fill=fill, outline=outline, width=width)
    191         draw.rectangle((x1 + r, y1, x2 - r, y2), fill=fill, outline=outline, width=0)
    192         draw.rectangle((x1, y1 + r, x2, y2 - r), fill=fill, outline=outline, width=0)
    193         if outline:
    194             draw.line((x1 + r, y1, x2 - r, y1), fill=outline, width=width)
    195             draw.line((x1 + r, y2, x2 - r, y2), fill=outline, width=width)
    196             draw.line((x1, y1 + r, x1, y2 - r), fill=outline, width=width)
    197             draw.line((x2, y1 + r, x2, y2 - r), fill=outline, width=width)
    198 
    199     def render(self):
    200         width = self.width * self.scale
    201         height = self.height * self.scale
    202         key_w = self.key_w * self.scale
    203         space = self.space * self.scale
    204 
    205         # Create a transparent image
    206         img = Image.new('RGBA', (width, height), (255, 255, 255, 0))
    207         draw = ImageDraw.Draw(img)
    208 
    209         rx = 3 * self.scale  # Corner radius
    210 
    211         def draw_row(row_index, row, sx, sy, last_end=False):
    212             x = sx
    213             y = sy
    214             keys = row
    215             rw = self.usable_width * self.scale - sx
    216             i = 0
    217 
    218             for k in keys:
    219                 rect_width = key_w
    220 
    221                 if i == len(keys) - 1 and last_end:
    222                     rect_width = rw
    223 
    224                 # Draw key
    225                 self.rounded_rectangle(draw, (x, y, x + rect_width, y + key_w), rx,
    226                                       fill=key_color, outline=border_color, width=1)
    227 
    228 
    229                 shift_text = self.shift_text(k)
    230                 regular_text = self.regular_text(k)
    231                 ctrl_text = self.ctrl_text(k)
    232                 if shift_text == regular_text or shift_text == regular_text.upper():
    233                     # Draw shift text (center)
    234                     bbox = draw.textbbox((0, 0), shift_text, font=self.large_font)
    235                     text_x = x + key_w // 2 - bbox[2] // 2
    236                     text_y = y + key_w // 2 - bbox[3] // 2
    237                     draw.text((text_x, text_y), shift_text, font=self.large_font, fill=primary_text_color)
    238                 else:
    239                     # Draw shift text (top)
    240                     text_x = x + CAP_FONT_OFFSET_X * self.scale
    241                     text_y = y + CAP_FONT_OFFSET_Y * self.scale
    242                     draw.text((text_x, text_y), shift_text, font=self.regular_font, fill=primary_text_color)
    243 
    244                     # Draw regular text (bottom)
    245                     text_x = x + REG_FONT_OFFSET_X * self.scale
    246                     text_y = y + REG_FONT_OFFSET_Y * self.scale
    247                     draw.text((text_x, text_y), regular_text, font=self.regular_font, fill=primary_text_color)
    248 
    249                     # Control text
    250                     ctrl_text = self.ctrl_text(k)
    251                     if ctrl_text and row_index == 0:
    252                         ctrl_bbox = draw.textbbox((0, 0), ctrl_text, font=self.regular_font)
    253                         text_x = x + CTRL_FONT_OFFSET_X * self.scale
    254                         text_y = y + CTRL_FONT_OFFSET_Y * self.scale
    255                         draw.text((text_x, text_y), ctrl_text, font=self.regular_font, fill=secondary_text_color)
    256 
    257                 rw = rw - space - key_w
    258                 x = x + space + key_w
    259                 i = i + 1
    260 
    261             return (x, rw)
    262 
    263         x = 6 * self.scale
    264         y = 6 * self.scale
    265 
    266         keys = self.kb["keys"]
    267         ext_return = self.kb["extended_return"]
    268 
    269         first_key_w = 0
    270 
    271         rows = 4
    272         remaining_x = [0, 0, 0, 0]
    273         remaining_widths = [0, 0, 0, 0]
    274 
    275         left_keys = []
    276         left_keys.append(0) # not used..
    277         left_keys.append("\u21E5") # ⇥
    278         left_keys.append("\u21EA") # ⇪
    279         left_keys.append("\u21E7") # ⇧
    280 
    281         right_keys = []
    282         right_keys.append("←") # backspace
    283         right_keys.append(0) # not used..
    284         right_keys.append(0) # not used..
    285         right_keys.append("\u21E7") # ⇧
    286 
    287         for i in range(0, rows):
    288             if first_key_w > 0:
    289                 first_key_w = first_key_w * 1.375
    290 
    291                 if self.kb == self.kb_105 and i == 3:
    292                     first_key_w = key_w * 1.275
    293 
    294                 # Draw first key
    295                 self.rounded_rectangle(draw, (6 * self.scale, y, 6 * self.scale + first_key_w, y + key_w),
    296                                       rx, fill=meta_key_color, outline=border_color, width=1)
    297 
    298                 # Draw regular text (bottom)
    299                 regular_text = left_keys[i]
    300                 bbox = draw.textbbox((0, 0), regular_text, font=self.meta_font)
    301                 text_x = x + REG_FONT_OFFSET_X * self.scale
    302                 text_y = y + key_w // 2 - bbox[3] // 2
    303                 draw.text((text_x, text_y), regular_text, font=self.meta_font, fill=secondary_text_color)
    304 
    305                 x = 6 * self.scale + first_key_w + space
    306             else:
    307                 first_key_w = key_w
    308 
    309             x, rw = draw_row(i, keys[i], x, y, i == 1 and not ext_return)
    310 
    311             remaining_x[i] = x
    312             remaining_widths[i] = rw
    313 
    314             if i != 1 and i != 2:
    315                 # Draw remaining keys
    316                 self.rounded_rectangle(draw, (x, y, x + rw, y + key_w),
    317                                       rx, fill=meta_key_color, outline=border_color, width=1)
    318 
    319                 # Draw regular text (bottom)
    320                 regular_text = right_keys[i]
    321                 bbox = draw.textbbox((0, 0), regular_text, font=self.meta_font)
    322                 text_x = x + REG_FONT_OFFSET_X * self.scale
    323                 text_y = y + key_w // 2 - bbox[3] // 2
    324                 draw.text((text_x, text_y), regular_text, font=self.meta_font, fill=secondary_text_color)
    325 
    326             x = 6 * self.scale
    327             y = y + space + key_w
    328 
    329         if ext_return:
    330             # Draw extended return key
    331             x1 = remaining_x[1]
    332             y1 = 6 * self.scale + key_w * 1 + space * 1
    333             w1 = remaining_widths[1]
    334             x2 = remaining_x[2]
    335             y2 = 6 * self.scale + key_w * 2 + space * 2
    336 
    337             # Create a polygon for the extended return key
    338             # This is a simplified approach that doesn't perfectly match the rounded corners
    339             # of the original, but it's close enough
    340             poly = [
    341                 (x1, y1 + rx),                # Start from left side
    342                 (x1 + rx, y1),                # Top left corner
    343                 (x1 + w1 - rx, y1),           # Top right corner (almost)
    344                 (x1 + w1, y1 + rx),           # Top right corner
    345                 (x1 + w1, y2 + key_w - rx),   # Bottom right corner (almost)
    346                 (x1 + w1 - rx, y2 + key_w),   # Bottom right corner
    347                 (x2 + rx, y2 + key_w),        # Bottom left of the second part
    348                 (x2, y2 + key_w - rx),        # Bottom left corner
    349                 (x2, y1 + key_w),             # Middle left edge
    350                 (x1 + rx, y1 + key_w),        # Bottom of top part
    351                 (x1, y1 + key_w - rx)         # Bottom left corner of top part
    352             ]
    353 
    354             draw.polygon(poly, fill=meta_key_color, outline=border_color)
    355             # Draw regular text (bottom)
    356             regular_text = UNICODE_RETURN
    357             bbox = draw.textbbox((0, 0), regular_text, font=self.meta_font)
    358             text_x = x1 + REG_FONT_OFFSET_X * self.scale
    359             text_y = y1 + 12 * self.scale
    360             draw.text((text_x, text_y), regular_text, font=self.meta_font, fill=secondary_text_color)
    361 
    362         else:
    363             # Draw regular return key
    364             x = remaining_x[2]
    365             y = 6 * self.scale + key_w * 2 + space * 2
    366             self.rounded_rectangle(draw, (x, y, x + remaining_widths[2], y + key_w),
    367                                   rx, fill=key_color, outline=border_color, width=1)
    368 
    369             # Draw regular text (bottom)
    370             regular_text = UNICODE_RETURN
    371             bbox = draw.textbbox((0, 0), regular_text, font=self.meta_font)
    372             text_x = x + REG_FONT_OFFSET_X * self.scale
    373             text_y = y + key_w // 2 - bbox[3] // 2
    374             draw.text((text_x, text_y), regular_text, font=self.meta_font, fill=secondary_text_color)
    375 
    376 
    377         # Save to file
    378         img.save(filename, "PNG")
    379 
    380 # Command line usage
    381 if __name__ == "__main__":
    382     layout = sys.argv[1]
    383     variant = sys.argv[2]
    384     filename = sys.argv[3]
    385     scale = 1
    386     if len(sys.argv) > 4 and sys.argv[4] == "hidpi":
    387         scale = 2
    388         print("Keyboard layout being generated for hidpi")
    389 
    390     kb = KeyboardRenderer(layout, variant, scale, filename)