fontconfig.py 2.66 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
# -*- coding: utf-8 -*-
#
# diffoscope: in-depth comparison of files, archives, and directories
#
# Copyright © 2017 Chris Lamb <lamby@debian.org>
#
# diffoscope is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# diffoscope is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with diffoscope.  If not, see <https://www.gnu.org/licenses/>.

import struct

from diffoscope.difference import Difference

from .utils.file import File


class FontconfigCacheFile(File):
28
    DESCRIPTION = "FreeDesktop Fontconfig cache files"
29 30
    FILE_TYPE_HEADER_PREFIX = struct.pack('<H', 0xFC04)
    FILE_EXTENSION_SUFFIX = '-le64.cache-4'
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

    def compare_details(self, other, source=None):
        return [Difference.from_text(
            describe_cache_file(self.path),
            describe_cache_file(other.path),
            self.path,
            other.path,
        )]


def describe_cache_file(filename):
    fmt = '<IIQQQQQQQ'
    fields = (
        'magic', 'version', 'size', 'dir', 'dirs', 'dirs_count', 'set',
        'checksum', 'checksum_nano',
    )

    with open(filename, 'rb') as f:
        data = struct.unpack(fmt, f.read(struct.calcsize(fmt)))
        kwargs = {x: y for x, y in zip(fields, data)}

        kwargs['dir_name'] = read_null_terminated_string(f, kwargs['dir'])

    return """
struct FcCache {{
    unsigned int    magic = 0x{magic:08X};  /* FC_CACHE_MAGIC_MMAP or FC_CACHE_ALLOC */
    int             version = {version};  /* FC_CACHE_VERSION_NUMBER */
    intptr_t        size = {size};  /* size of file */
    intptr_t        dir = 0x{dir};  /* offset to dir name ("{dir_name}") */
    intptr_t        dirs = 0x{dirs:08X};  /* offset to subdirs */
    int             dirs_count = {dirs_count};  /* number of subdir strings */
    intptr_t        set = 0x{set:08X};  /* offset to font set */
    int             checksum = {checksum};  /* checksum of directory state */
    int64_t         checksum_nano = {checksum_nano};  /* checksum of directory state */
}};
""".format(**kwargs)


def read_null_terminated_string(fileobj, offset=None):
    result = ''

    if offset is not None:
        fileobj.seek(offset)

    while True:
        x = fileobj.read(1).decode('ascii')
        if x in ('', '\0'):
            break
        result += x

    return result