-
Notifications
You must be signed in to change notification settings - Fork 4
/
CMakeLists.txt
457 lines (383 loc) · 17 KB
/
CMakeLists.txt
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
cmake_minimum_required(VERSION 3.21)
set_property(GLOBAL PROPERTY USE_FOLDERS ON)
project(embed LANGUAGES CXX)
# Options
option(B_EMBED_BUILD_EXAMPLES "Build battery::embed examples" ${PROJECT_IS_TOP_LEVEL})
option(B_PRODUCTION_MODE "Enable production mode and disable development tools such as hotreload" OFF)
option(B_EMBED_SILENCE_DEVMODE_WARNING "Disable the battery::embed devmode warning" OFF)
# Remember the binary dir for later
set(EMBED_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR}/embed CACHE INTERNAL "binary directory of the battery::embed library" FORCE)
# The template for how to generate the .cpp file
set(EMBED_SOURCE_FILE_TEMPLATE [==[
// File generated using battery::embed (https://github.com/batterycenter/embed)
// Embedded file: '${FILENAME}' as '${IDENTIFIER}'
// Filesize: ${FILESIZE} bytes
// DO NOT EDIT THIS FILE!!!
#include "battery/embed.hpp"
namespace b {
EmbedInternal::EmbeddedFile EmbedInternal::${IDENTIFIER} = {
std::string_view(
${GENERATED_BYTE_ARRAY},
${FILESIZE}
)
, "${FILENAME}"
#ifndef B_PRODUCTION_MODE
, "${FULL_PATH}"
#endif // !B_PRODUCTION_MODE
};
} // namespace b
]==])
file(WRITE ${EMBED_BINARY_DIR}/embed_source_file_template.cpp "${EMBED_SOURCE_FILE_TEMPLATE}")
# The single b::embed master source file which is compiled into the app
set(EMBED_MASTER_SOURCE_FILE [==[
// File generated using battery::embed (https://github.com/batterycenter/embed)
// DO NOT EDIT THIS FILE!!!
#include "battery/embed.hpp"
#if !defined(B_PRODUCTION_MODE) && !defined(B_OS_WEB)
#include <codecvt>
#include <thread>
#include <filesystem>
#include <fstream>
#include <mutex>
#include <unordered_map>
#include <optional>
#endif // !B_PRODUCTION_MODE and !B_OS_WEB
namespace b {
#if !defined(B_PRODUCTION_MODE) && !defined(B_OS_WEB)
// All this crazyness is necessary because we need to use std::string_view because of constexpr,
// and the string_view only points to a char array, so we need a string that outlives
// the string_view it is assigned to.
struct FileData {
std::string filename;
std::string newContent;
std::string filepath;
std::filesystem::file_time_type lastWriteTime;
std::function<void(const b::EmbedInternal::EmbeddedFile&)> callback;
};
static std::mutex embeddedFilesMapMutex;
static std::unordered_map<std::string,FileData> embeddedFiles;
#ifdef _WIN32
#ifdef __clang__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
static std::wstring embed_widen(const std::string& str) {
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
return converter.from_bytes(str);
}
#ifdef __clang__
#pragma GCC diagnostic pop
#endif
#endif // _WIN32
static std::optional<std::string> embed_read_file(const std::string_view& filename) {
#ifdef _WIN32
std::ifstream file(embed_widen(std::string(filename)).c_str(), std::ios::binary);
#else // _WIN32
std::ifstream file(std::string(filename), std::ios::binary);
#endif // _WIN32
if (file.fail()) {
return {};
}
return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
}
// Apple-Clang does not support std::jthread yet, hence we make our own version of jthread here:
class AutoThread {
public:
template<typename Tfunc>
AutoThread(Tfunc&& function)
: m_thread([&]() { function(m_shouldStop); })
{}
~AutoThread() {
m_shouldStop = true;
m_thread.join();
}
AutoThread(const AutoThread& other) = delete;
AutoThread(AutoThread&& other) = delete;
AutoThread& operator=(const AutoThread& other) = delete;
AutoThread& operator=(AutoThread&& other) = delete;
private:
std::thread m_thread;
std::atomic<bool> m_shouldStop = false;
};
// This is a global file watcher thread that is created at program start and automatically destroyed at program end
// All embedded files are hot-reloaded by this thread.
AutoThread embeddedFileWatcherThread = AutoThread([](std::atomic<bool>& shouldStop) {
while (!shouldStop) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::lock_guard<std::mutex> lock(embeddedFilesMapMutex);
for (auto& [key, filedata] : embeddedFiles) {
std::filesystem::path filepath(key);
std::error_code ec;
auto newWriteTime = std::filesystem::last_write_time(filepath, ec);
if (!ec) {
if (newWriteTime != filedata.lastWriteTime) {
filedata.lastWriteTime = newWriteTime;
auto fileresult = embed_read_file(key);
if (!fileresult) {
continue;
}
filedata.newContent = *fileresult;
EmbedInternal::EmbeddedFile newFile(filedata.newContent, filedata.filename, filedata.filepath);
filedata.callback(newFile);
}
}
}
}
});
#endif // !B_PRODUCTION_MODE and !B_OS_WEB
void EmbedInternal::EmbeddedFile::get(const std::function<void(const b::EmbedInternal::EmbeddedFile&)>& callback) {
#if defined(B_PRODUCTION_MODE) || defined(B_OS_WEB)
callback(*this);
#else // B_PRODUCTION_MODE or B_OS_WEB
auto fileresult = embed_read_file(m_fullFilepath);
if (fileresult) {
m_data = *fileresult;
}
callback(*this);
FileData fileData;
fileData.filename = m_filename;
fileData.newContent = m_data;
fileData.filepath = m_fullFilepath;
fileData.callback = callback;
fileData.lastWriteTime = std::filesystem::last_write_time(m_fullFilepath);
std::lock_guard<std::mutex> lock(embeddedFilesMapMutex);
embeddedFiles[std::string(m_fullFilepath)] = fileData;
#endif // B_PRODUCTION_MODE or B_OS_WEB
}
} // namespace b
]==])
file(WRITE ${EMBED_BINARY_DIR}/embed_impl.cpp "${EMBED_MASTER_SOURCE_FILE}")
# The common battery::embed header and source files
set(EMBED_HEADER_FILE [=[
// File generated by battery::embed
// DO NOT EDIT THIS FILE!!!
#ifndef BATTERY_EMBED_HPP
#define BATTERY_EMBED_HPP
#include <vector>
#include <string>
#include <string_view>
#include <stdexcept>
#include <sstream>
#include <functional>
#include <cstdint>
#include <algorithm>
#ifndef __cpp_constexpr_dynamic_alloc
# error "battery::embed requires C++20 (Your compiler does not provide __cpp_constexpr_dynamic_alloc, which is needed for battery::embed)"
#endif
namespace b {
struct EmbedInternal {
class EmbeddedFile {
public:
constexpr EmbeddedFile() = default;
constexpr EmbeddedFile(
const std::string_view& data,
const std::string_view& filename
#ifndef B_PRODUCTION_MODE
, const std::string_view& fullFilepath
#endif // !B_PRODUCTION_MODE
)
: m_data(data)
, m_filename(filename)
#ifndef B_PRODUCTION_MODE
, m_fullFilepath(fullFilepath)
#endif // !B_PRODUCTION_MODE
{}
[[nodiscard]] std::string str() const {
return m_data.data();
}
[[nodiscard]] const char* data() const {
return m_data.data();
}
[[nodiscard]] std::vector<uint8_t> vec() const {
return { m_data.begin(), m_data.end() };
}
[[nodiscard]] size_t length() const {
return m_data.size();
}
[[nodiscard]] size_t size() const {
return m_data.size();
}
operator std::string() const {
return str();
}
operator std::vector<uint8_t>() const {
return vec();
}
void get(const std::function<void(const b::EmbedInternal::EmbeddedFile&)>& callback);
private:
std::string_view m_data;
std::string_view m_filename;
#ifndef B_PRODUCTION_MODE
std::string_view m_fullFilepath;
#endif
}; // class EmbeddedFile
${EMBEDDED_FILES_DECLARATIONS}
}; // struct embedded_files
template<size_t N>
struct embed_string_literal {
constexpr embed_string_literal(const char (&str)[N]) {
std::copy_n(str, N, value);
}
constexpr bool operator!=(const embed_string_literal& other) const {
return std::equal(value, value + N, other.value);
}
[[nodiscard]] std::string str() const {
return std::string(value, N);
}
[[nodiscard]] constexpr bool _false() const {
return false;
}
char value[N];
};
template<size_t N, size_t M>
constexpr bool operator==(const embed_string_literal<N>& left, const char (&right)[M]) {
return std::equal(left.value, left.value + N, right);
}
template<embed_string_literal identifier>
constexpr EmbedInternal::EmbeddedFile embed() {
${EMBEDDED_FILES_RETURNS}{
static_assert(identifier._false(), "[b::embed<>] No such file or directory");
}
}
} // namespace b
inline std::ostream& operator<<(std::ostream& stream, const b::EmbedInternal::EmbeddedFile& file) {
stream << file.str();
return stream;
}
#endif // BATTERY_EMBED_HPP
]=])
file(WRITE ${EMBED_BINARY_DIR}/embed_header_file_template.hpp "${EMBED_HEADER_FILE}")
# The cmake script to embed the files. This is called later on-demand, in a separate process
set(EMBED_GENERATE_SCRIPT [=[
file(READ "${FULL_PATH}" GENERATED_BYTE_ARRAY HEX)
string(LENGTH "${GENERATED_BYTE_ARRAY}" FILESIZE)
math(EXPR FILESIZE "${FILESIZE} / 2")
string(REPEAT "[0-9a-f]" 32 PATTERN)
set(GENERATED_BYTE_ARRAY "\"${GENERATED_BYTE_ARRAY}")
string(REGEX REPLACE "${PATTERN}" "\\0\"\n \"" GENERATED_BYTE_ARRAY ${GENERATED_BYTE_ARRAY})
string(REGEX REPLACE "([0-9a-f][0-9a-f])" "\\\\x\\1" GENERATED_BYTE_ARRAY ${GENERATED_BYTE_ARRAY})
set(GENERATED_BYTE_ARRAY "${GENERATED_BYTE_ARRAY}\"")
configure_file(${INFILE} ${OUTFILE})
]=])
file(WRITE ${EMBED_BINARY_DIR}/generate.cmake ${EMBED_GENERATE_SCRIPT})
set(EMBED_IDENTIFIERS "" CACHE INTERNAL "list of all identifiers used by battery::embed")
set(EMBED_FILENAMES "" CACHE INTERNAL "list of all filenames used by battery::embed")
set(EMBED_TARGETS "" CACHE INTERNAL "list of all targets used by battery::embed")
# Defer the function call until the end of the configure step
cmake_language(DEFER DIRECTORY ${CMAKE_SOURCE_DIR} CALL _embed_generate_all_hpps())
function(_embed_generate_all_hpps)
message(STATUS "Generating b::embed() HPP files ...")
foreach (TARGET ${EMBED_TARGETS})
_embed_generate_hpp(${TARGET})
endforeach()
message(STATUS "Generating b::embed() HPP files ... Done")
endfunction(_embed_generate_all_hpps)
function(_embed_generate_hpp TARGET)
string(TOLOWER "${TARGET}" TARGET)
string(REGEX REPLACE "[^a-zA-Z0-9_]" "_" TARGET "${TARGET}")
if (NOT EMBED_IDENTIFIERS)
return()
endif()
set(EMBEDDED_FILES_DECLARATIONS "")
list(LENGTH EMBED_IDENTIFIERS num_identifiers)
foreach (IDENTIFIER IN LISTS EMBED_IDENTIFIERS)
if (IDENTIFIER MATCHES "^${TARGET}_")
set(EMBEDDED_FILES_DECLARATIONS "${EMBEDDED_FILES_DECLARATIONS}static EmbeddedFile ${IDENTIFIER};\n ")
endif()
endforeach()
set(EMBEDDED_FILES_RETURNS "")
math(EXPR num_identifiers "${num_identifiers} - 1")
foreach (INDEX RANGE ${num_identifiers})
list(GET EMBED_IDENTIFIERS ${INDEX} IDENTIFIER)
list(GET EMBED_FILENAMES ${INDEX} FILENAME)
if (IDENTIFIER MATCHES "^${TARGET}_")
set(EMBEDDED_FILES_RETURNS "${EMBEDDED_FILES_RETURNS}if constexpr (identifier == \"${FILENAME}\") { return EmbedInternal::${IDENTIFIER}; }\n else ")
endif()
endforeach()
file(READ ${EMBED_BINARY_DIR}/embed_header_file_template.hpp EMBED_HEADER_FILE)
string(CONFIGURE "${EMBED_HEADER_FILE}" EMBED_HEADER_FILE_GENERATED)
set(EMBED_HPP "${EMBED_BINARY_DIR}/autogen/${TARGET}/include/battery/embed.hpp")
file(WRITE "${EMBED_HPP}" "${EMBED_HEADER_FILE_GENERATED}")
endfunction(_embed_generate_hpp)
# Internal function for validating an identifier
function(embed_validate_identifier IDENTIFIER) # Validate the identifier against C variable naming rules
if (NOT IDENTIFIER MATCHES "^[a-zA-Z_][a-zA-Z0-9_]*$")
message(FATAL_ERROR "embed: Identifier contains invalid characters: '${IDENTIFIER}'")
endif()
endfunction()
# The main function for embedding files
function(b_embed TARGET FILENAME)
string(TOLOWER "${TARGET}" TARGET_ID)
string(REGEX REPLACE "[^a-zA-Z0-9_]" "_" TARGET_ID "${TARGET_ID}")
if (IS_ABSOLUTE "${FILENAME}")
message(FATAL_ERROR "embed: File name must be relative to the current source directory: '${FILENAME}'")
endif()
# Make the identifier
string(TOLOWER "${TARGET_ID}_${FILENAME}" IDENTIFIER)
string(REGEX REPLACE "[^a-zA-Z0-9_]" "_" IDENTIFIER "${IDENTIFIER}") # Replace all invalid characters with underscores
embed_validate_identifier("${IDENTIFIER}") # Validate the identifier against C variable naming rules
# Set up paths
get_filename_component(FULL_PATH "${FILENAME}" ABSOLUTE) # Make the file path absolute
set(CPP_FILE "${EMBED_BINARY_DIR}/autogen/${TARGET_ID}/src/${IDENTIFIER}.cpp")
# If identifier already in use
list(FIND EMBED_IDENTIFIERS ${IDENTIFIER} EMBED_USED_IDENTIFIERS_INDEX)
if (NOT EMBED_USED_IDENTIFIERS_INDEX EQUAL -1)
message(FATAL_ERROR "embed: Identifier already in use: '${IDENTIFIER}'")
endif()
set(EMBED_IDENTIFIERS ${EMBED_IDENTIFIERS} ${IDENTIFIER} CACHE INTERNAL "list of all identifiers used by the embed library")
set(EMBED_FILENAMES ${EMBED_FILENAMES} ${FILENAME} CACHE INTERNAL "list of all filenames used by the embed library")
set(EMBED_TARGETS ${EMBED_TARGETS} ${TARGET} CACHE INTERNAL "list of all targets used by the embed library")
# This action generates both files and is called on-demand whenever the resource file changes
set(EMBED_HPP "${EMBED_BINARY_DIR}/autogen/${TARGET_ID}/include/battery/embed.hpp")
set(EMBED_CPP_TEMPLATE "${EMBED_BINARY_DIR}/embed_source_file_template.cpp")
add_custom_command(
COMMAND ${CMAKE_COMMAND}
-DINFILE=${EMBED_CPP_TEMPLATE}
-DOUTFILE=${CPP_FILE}
-DFULL_PATH=${FULL_PATH}
-DIDENTIFIER=${IDENTIFIER}
-DFILENAME=${FILENAME}
-P "${EMBED_BINARY_DIR}/generate.cmake"
DEPENDS "${FULL_PATH}" "${EMBED_HPP}" "${EMBED_BINARY_DIR}/generate.cmake" "${EMBED_BINARY_DIR}/embed_source_file_template.cpp"
OUTPUT ${CPP_FILE}
VERBATIM
)
# Add the generated files to the target
target_include_directories(${TARGET} PUBLIC
$<BUILD_INTERFACE:${EMBED_BINARY_DIR}/autogen/${TARGET_ID}/include>
$<INSTALL_INTERFACE:>
)
target_sources(${TARGET} PRIVATE ${CPP_FILE} ${EMBED_BINARY_DIR}/embed_impl.cpp ${EMBED_HPP})
target_compile_definitions(${TARGET} PRIVATE _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING)
if (NOT B_PRODUCTION_MODE)
find_package(Threads REQUIRED)
target_link_libraries(${TARGET} PRIVATE Threads::Threads)
else ()
target_compile_definitions(${TARGET} PUBLIC B_PRODUCTION_MODE)
endif ()
if (MSVC)
target_sources(${TARGET} PRIVATE ${FULL_PATH})
source_group(TREE ${EMBED_BINARY_DIR}/autogen/${TARGET_ID}/src PREFIX "embed/autogen" FILES ${CPP_FILE})
source_group(TREE ${EMBED_BINARY_DIR} PREFIX "embed/autogen" FILES ${EMBED_BINARY_DIR}/embed_impl.cpp)
source_group(TREE ${EMBED_BINARY_DIR}/autogen/${TARGET_ID}/include/battery PREFIX "embed/autogen" FILES ${EMBED_HPP})
source_group(TREE "${CMAKE_CURRENT_SOURCE_DIR}" PREFIX "/embed" FILES ${FULL_PATH})
endif()
endfunction()
function(b_embed_proxy_target MAIN_TARGET PROXY_TARGET)
add_library(${PROXY_TARGET} STATIC)
target_compile_features(${PROXY_TARGET} PUBLIC cxx_std_20)
target_link_libraries(${MAIN_TARGET} PRIVATE ${PROXY_TARGET})
set_target_properties(${PROXY_TARGET} PROPERTIES FOLDER "embed-proxy-targets")
endfunction()
# Build all examples
if (B_EMBED_BUILD_EXAMPLES)
add_subdirectory(examples) # Set Example 'simple' as the default project in Visual Studio
set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT simple)
endif()
# Set the predefined targets folder for Visual Studio
if (PROJECT_IS_TOP_LEVEL)
set(PREDEFINED_TARGETS_FOLDER "CMakePredefinedTargets")
endif()
if (NOT B_EMBED_SILENCE_DEVMODE_WARNING AND NOT B_PRODUCTION_MODE)
message(WARNING "Battery::Embed is in development mode, enabling hotreload. Before deploying your application, use -DB_PRODUCTION_MODE=ON to strip all development features such as hotreload and absolute filepaths.")
endif ()