PC Screen Font:PSF 字体文件结构与在图形屏幕上显示的方法

来源:OSDev Wiki· 阅读原文 ↗

在每个 Linux 发行版中,都可以找到扩展名为 .psf 或 .psfu 的控制台字体文件。可以通过在终端中输入 whereis consolefonts 来定位它们。本文介绍如何在图形屏幕上显示这些字体,其优点是无需修改字体,而是直接使用 Linux 发行版随附的字体。另一个优点是 PSF 字体可以存储整个 Unicode 字符集,尽管 consolefonts 最多有 512 个字形。

PSF 有两个版本,PSF 1 和 PSF 2。每个版本都可以通过其魔数来检测。 本页假设使用的是 PSF 2 字体。

文件结构

PSF 文件由一个头部、字形的位图以及可选的 Unicode 字符转换表组成。

文件头部

它是文件开头的一个固定块。在继续解析字体文件之前,必须先检测版本。

#define PSF1_FONT_MAGIC 0x0436

/*
    For PSF1 glyph width is always = 8 bits
    and glyph height = characterSize
*/
typedef struct {
    uint16_t magic; // Magic bytes for identification.
    uint8_t fontMode; // PSF font mode.
    uint8_t characterSize; // PSF character size.
} PSF1_Header;


#define PSF_FONT_MAGIC 0x864ab572

/*
    PSF2
*/
typedef struct {
    uint32_t magic;         /* magic bytes to identify PSF */
    uint32_t version;       /* zero */
    uint32_t headersize;    /* offset of bitmaps in file, 32 */
    uint32_t flags;         /* 0 if there's no unicode table */
    uint32_t numglyph;      /* number of glyphs */
    uint32_t bytesperglyph; /* size of each glyph */
    uint32_t height;        /* height in pixels */
    uint32_t width;         /* width in pixels */
} PSF_font;

字形

每个字形都是一个位图,其编码方式与 VGA 字体 相同。对于 8x16 字体,每个字形长 16 字节,每个字节恰好编码字形的一行。

00000000b  byte  0
00000000b  byte  1
00000000b  byte  2
00010000b  byte  3
00111000b  byte  4
01101100b  byte  5
11000110b  byte  6
11000110b  byte  7
11111110b  byte  8
11000110b  byte  9
11000110b  byte 10
11000110b  byte 11
11000110b  byte 12
00000000b  byte 13
00000000b  byte 14
00000000b  byte 15

对于宽度不能被 8 整除的字形,会添加填充位,使该行在字节边界上可整除。 作为受 PC Screen Font - Wikipedia 启发的示例,下面的 psf 字形 O 是 12x12。由于 12 不能被 8 整除,因此添加 4 个填充位,使每行可被一个字节整除。

 Glyph Data  padding   
|-----------|----|
111111111111 0000
111111111111 0000
110000000011 0000
110000000011 0000
110000000011 0000
110000000011 0000
110000000011 0000
110000000011 0000
110000000011 0000
110000000011 0000
111111111111 0000
111111111111 0000

Unicode 表

如果 PSF 头部中的标志为 1,则表示该字体具有用于字形映射的 Unicode 表。没有这样的表时,Unicode 字符和字形的映射是相同的,因此第一个字形对应 Unicode 字符 0,第二个字形对应 Unicode 字符 1,依此类推。

该表如下:每个字形都有一个可变长度记录。这些记录与文本文件中的行非常相似,只是这里的行以 0xFF 字符结尾,而不是 '\n'(0x0A)。第 n 行描述第 n 个字形的映射。每行至少包含一个,但可能包含多个 UTF-8 字符序列。

处理 PSF

虽然有很多 PSF 编辑器,但大多数都已损坏或难以使用。因此建议改用两个 Perl 脚本:readpsf、writepsf。这些脚本可以将 PSF 转换为易于编辑的 ASCII 文本文件,或转换为可用任何图像编辑程序打开的位图图像。

加载字体

如 VGA 字体 中所述,有几种选择。为简单起见,在本示例中,字体将嵌入到内核可执行文件中。以下是将 PSF 转换为可与内核可执行文件链接的 ELF 的方法:

objcopy -O elf64-x86-64 -B i386 -I binary font.psf font.o
readelf -s font.o

Symbol table '.symtab' contains 5 entries:
   Num:    Value          Size Type    Bind   Vis      Ndx Name
     0: 0000000000000000     0 NOTYPE  LOCAL  DEFAULT  UND 
     1: 0000000000000000     0 SECTION LOCAL  DEFAULT    1 
     2: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT    1 _binary_font_psf_start
     3: 0000000000008020     0 NOTYPE  GLOBAL DEFAULT    1 _binary_font_psf_end
     4: 0000000000008020     0 NOTYPE  GLOBAL DEFAULT  ABS _binary_font_psf_size

生成的对象导出三个符号,可以像任何其他变量一样引用它们(例如在 C 中使用 extern)。

在使用字体之前,必须先解码 Unicode 表。这很棘手,需要动态内存分配(这里是 calloc()),但好消息是,如果 "第一个字形对应字符 0,第二个字形对应字符 1,等等" 的方案可以接受,那么这是可选的。

/* import the font contained in the object file created above */
extern char _binary_font_psf_start;
extern char _binary_font_psf_end;

uint16_t *unicode;

void psf_init()
{
    uint16_t glyph = 0;
    /* cast the address to PSF header struct */
    PSF_font *font = (PSF_font*)&_binary_font_psf_start;
    /* is there a unicode table? */
    if (font->flags == 0) {
        unicode = NULL;
        return; 
    }

    /* get the offset of the table */
    char *s = (char *)(
    (unsigned char*)&_binary_font_psf_start +
      font->headersize +
      font->numglyph * font->bytesperglyph
    );
    /* allocate memory for translation table */
    unicode = calloc(USHRT_MAX, 2);
    while(s < (unsigned char*)&_binary_font_psf_end) {
        uint16_t uc = (uint16_t)((unsigned char *)s[0]);
        if(uc == 0xFF) {
            glyph++;
            s++;
            continue;
        } else if(uc & 128) {
            /* UTF-8 to unicode */
            if((uc & 32) == 0 ) {
                uc = ((s[0] & 0x1F)<<6)+(s[1] & 0x3F);
                s++;
            } else
            if((uc & 16) == 0 ) {
                uc = ((((s[0] & 0xF)<<6)+(s[1] & 0x3F))<<6)+(s[2] & 0x3F);
                s+=2;
            } else
            if((uc & 8) == 0 ) {
                uc = ((((((s[0] & 0x7)<<6)+(s[1] & 0x3F))<<6)+(s[2] & 0x3F))<<6)+(s[3] & 0x3F);
                s+=3;
            } else
                uc = 0;
        }
        /* save translation */
        unicode[uc] = glyph;
        s++;
    }
}

显示字符

假设线性帧缓冲区已正确设置,并且可以绘制像素。本示例使用 32 位 RGBA 格式,但可以轻松适配其他格式。

/* the linear framebuffer */
extern char *fb;
/* number of bytes in each line, it's possible it's not screen width * bytesperpixel! */
extern int scanline;
/* import the font contained in the object file created above */
extern char _binary_font_start[];

#define PIXEL uint32_t   /* pixel pointer */
 
void putchar(
    /* note that this is int, not char as it's a unicode character */
    unsigned short int c,
    /* cursor position on screen, in characters not in pixels */
    int cx, int cy,
    /* foreground and background colors, say 0xFFFFFF and 0x000000 */
    uint32_t fg, uint32_t bg)
{
    /* cast the address to PSF header struct */
    PSF_font *font = (PSF_font*)&_binary_font_psf_start;
    /* unicode translation */
    if(unicode != NULL) {
        c = unicode[c];
    }
    /* get the glyph for the character. If there's no
       glyph for a given character, we'll display the first glyph. */
    unsigned char *glyph =
     (unsigned char*)&_binary_font_psf_start +
     font->headersize +
     (c>0&&c<font->numglyph?c:0)*font->bytesperglyph;
    /* calculate the upper left corner on screen where we want to display.
       we only do this once, and adjust the offset later. This is faster. */
    int offs =
        (cy * font->height * scanline) +
        (cx * (font->width + 1) * sizeof(PIXEL));
    
    /* Calculate the number of bytes for a line in a glyph. If the
    glyph width isn't byte aligned, then it is rounded up to be byte aligned. */    
    uint32_t bytesPerGlyphLine = (width + 7) / 8;
    /* finally display pixels according to the bitmap */
    int x, y, line
    for(y = 0; y < font->height; y++){
        /* save the starting position of the line */
        line = offs;
        /* Calulate where the first byte for this line of the glyph is. */
        unsigned char* currentByte = glyph + (bytesPerGlyphLine * y);
        /* Start with a mask at this byte's MSB */
        uint8_t mask = 1<< 7;
        /* display a row */
        for(x = 0; x <font->width; x++){
            *((PIXEL*)(fb + line)) = (*currentByte & mask) ? fg : bg;
            mask >>= 1;
            if (mask == 0){
                /* We have read this byte of the glyph.
                Reset mask and move to next byte */
                mask = 1<<7;
                currentByte += 1;
            }
            /* adjust to the next pixel in framebuffer */
            line += sizeof(PIXEL);
        }
        /* adjust to the next line in framebuffer */
        offs  += scanline;
    }
}

使用此代码,可以在线性帧缓冲区上显示字符串。请注意,此代码并非最优,仅用于演示目的,但它是一个良好的起点。

使用宽度 + 1 计算偏移量是必要的,以保持屏幕上字形之间有一个像素的距离。否则某些字体会变得难以阅读。这也是原始 VGA 硬件 所做的,它使用 8x16 字体,但实际上将它们显示为 9x16。在使用掩码进行 AND 之前转换字形是必要的,以支持宽度达 32 像素的字体。

使用 8 像素宽度需要 unsigned char,而 9 像素则需要 unsigned short。这样,即使在编译时不知道所需大小(因为它取决于加载的字体),也可以使用相同的代码。

可能很想用数组替换 PIXEL 和 line,但这在所有硬件上都不起作用,因为 scanline 是以字节为单位给出的,而且没有人真正说过它必须是 PIXEL 的倍数(可能性很小,但有可能)。

另请参阅

外部链接

来源与翻译说明

本文根据原文快照翻译,保留原有代码、数值、技术限定及历史背景。原文中的命令与运行结果不代表本站已实际执行验证。

原文:PC Screen Font;离线修订号:30385。

原作者:OSDev Wiki 社区贡献者。原文及引用资料的版权与许可声明继续适用:版权声明 许可说明

评论

暂无评论