summaryrefslogtreecommitdiff
path: root/Embed.cmake
blob: 9b50690594180a6a68db46f7130ca96f84325b02 (plain)
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
28
29
30
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
function (embed_getname output fn)
    get_filename_component (name ${fn} NAME_WE)
    string (REPLACE "-" "" name ${name})
    string (SUBSTRING ${name} 0 1 first)
    string (TOUPPER ${first} first)
    string (SUBSTRING ${name} 1 -1 remainder)
    set (name "${first}${remainder}")
    get_filename_component (ext ${fn} EXT)
    if (ext STREQUAL .ttf)
        set (resName "font")
    elseif (ext STREQUAL .png)
        set (resName "image")
    else ()
        set (resName "blob")
    endif ()        
    set (resName "${resName}${name}_Embedded" PARENT_SCOPE)
endfunction (embed_getname)

function (embed_write path name fnSource fnHeader)
    message (STATUS "${path}")
    file (READ ${path} fileData HEX)
    string (REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," cList ${fileData})
    string (REGEX REPLACE
        "(0x[0-9a-f][0-9a-f],0x[0-9a-f][0-9a-f],0x[0-9a-f][0-9a-f],0x[0-9a-f][0-9a-f],0x[0-9a-f][0-9a-f],0x[0-9a-f][0-9a-f],0x[0-9a-f][0-9a-f],0x[0-9a-f][0-9a-f],0x[0-9a-f][0-9a-f],0x[0-9a-f][0-9a-f],0x[0-9a-f][0-9a-f],0x[0-9a-f][0-9a-f],0x[0-9a-f][0-9a-f],0x[0-9a-f][0-9a-f],0x[0-9a-f][0-9a-f],0x[0-9a-f][0-9a-f],)"
        "\\1\n    " cList ${cList})
    string (LENGTH ${fileData} len)
    math (EXPR alen "${len} / 2")
    set (src "static const uint8_t bytes_${name}_[] = {\n")
    string (APPEND src "    ${cList}\n")
    string (APPEND src "};
static iBlockData data_${name}_ = {
    .refCount = 2, .data = iConstCast(char *, bytes_${name}_), .size = ${alen}, .allocSize = ${alen}
};
const iBlock ${name} = { &data_${name}_ };
")
    set (header "extern const iBlock ${name};\n")
    # Output the results.
    file (APPEND ${fnSource} "${src}")
    file (APPEND ${fnHeader} "${header}")
endfunction (embed_write)

function (embed_make)
    set (EMB_H ${CMAKE_CURRENT_BINARY_DIR}/embedded.h)
    set (EMB_C ${CMAKE_CURRENT_BINARY_DIR}/embedded.c)
    set (needGen NO)
    if (NOT EXISTS ${EMB_H} OR NOT EXISTS ${EMB_C})
        set (needGen YES)
    else ()
        file (TIMESTAMP ${EMB_H} genTime %s)
        foreach (resPath ${ARGV})
            set (fn "${CMAKE_CURRENT_LIST_DIR}/${resPath}")
            file (TIMESTAMP ${fn} resTime %s)
            if (${resTime} GREATER ${genTime})
                set (needGen YES)
            endif ()
        endforeach (resPath)
    endif ()
    if (needGen)
        file (WRITE ${EMB_H} "#include <the_Foundation/block.h>\n")
        file (WRITE ${EMB_C} "#include \"embedded.h\"\n")
        foreach (fn ${ARGV})
            embed_getname (resName ${fn})
            embed_write (${fn} ${resName} ${EMB_C} ${EMB_H})
        endforeach (fn)
    endif ()
endfunction (embed_make)