Day 45/100 100 Days of Code

Day 45/100 100 Days of Code

Rebuild Back Better

Today, I had trouble setting up CMake to add the assets to the .app container. After messing around with the code I found on Stack Overflow, I was able to fix it and add the font files to the project. The whole process was quite complicated though.

CMake Code

# Read more on adding files https://stackoverflow.com/questions/41121000/cmake-os-x-bundle-recursively-copy-directory-to-resources
# This gets the absolute path to the each .ttf file that exists in the fodler
file(GLOB_RECURSE FONT_SOURCES "fonts/*.ttf")

add_executable(${PROJECT_NAME} MACOSX_BUNDLE 
                # Source files
                ${FONT_SOURCES})

# Get each path
foreach(FONT_FILE ${FONT_SOURCES})
  # CMAKE_CURRENT_SOURCE_DIR is the absolute path to the top-level CMakeLists.txt file
  # The RELATIVE_PATH command removes the CMakeLists path from the 
  # FONT_FILE path and keep the relative path to the .ttf file
  # This means that the RES_PATH variable only has "fonts/name.ttf" now
  file(RELATIVE_PATH RES_PATH "${CMAKE_CURRENT_SOURCE_DIR}" ${FONT_FILE})

  # keep only the name of the folder
  # It removes the file name and keeps the directory
  # We need to do that to get the name of the folder only
  # The value of the NEW_FILE_PATH variable is fonts
  get_filename_component(NEW_FILE_PATH ${RES_PATH} DIRECTORY)

  # Add the file that is located at the end of the FONT_FILE path to the
  # fonts folder
  set_property(SOURCE ${FONT_FILE} PROPERTY MACOSX_PACKAGE_LOCATION "${NEW_FILE_PATH}")
endforeach(FONT_FILE)

Now everything works! However, I couldn't load the fonts even though the path was correct on the program's source file. This is an intricacy of MacOS .app bundle system. When I run the executable UNIX file the application launches and loads the fonts. This is not the case if I execute the .app file.

To fix this issue, I might have to use some Objective-C code.