###############################################################################
# This file is part of the ST-TouchGFX 4.9.3 distribution.
# Copyright (C) 2017 Draupner Graphics A/S <http://www.touchgfx.com>.
###############################################################################
# This is licensed software. Any use hereof is restricted by and subject to the
# applicable license terms. For further information see "About/Legal Notice"
# in ST-TouchGFX Designer or in your ST-TouchGFX installation directory.
###############################################################################
# Helper macros to convert spaces into question marks and back again
e := 
sp := $(e) $(e)
qs = $(subst ?,$(sp),$1)
sq = $(subst $(sp),?,$1)

# Get name of this Makefile (avoid getting word 0 and a starting space)
makefile_name := $(wordlist 1,1000,$(MAKEFILE_LIST))

# Get path of this Makefile
makefile_path := $(call qs,$(dir $(call sq,$(abspath $(call sq,$(makefile_name))))))

# Get path where the Application is
application_path := $(call qs,$(abspath $(call sq,$(makefile_path)../..)))

# Change makefile_name to a relative path
makefile_name := $(subst $(call sq,$(application_path))/,,$(call sq,$(abspath $(call sq,$(makefile_name)))))

# Get identification of this system
ifeq ($(OS),Windows_NT)
UNAME := MINGW32_NT-6.2
else
UNAME := $(shell uname -s)
endif

board_name := $(UNAME)

.PHONY: all clean assets

all assets: $(filter clean,$(MAKECMDGOALS))
all clean assets:
	@cd "$(application_path)" && $(MAKE) -r -f $(makefile_name) -s $(MFLAGS) _$@_

# Directories containing application-specific source and header files.
# Additional components can be added to this list. make will look for
# source files recursively in comp_name/src and setup an include directive
# for comp_name/include.
components := gui simulator generated/gui_generated

# Location of folder containing bmp/png files.
asset_images_input  := assets/images

# Location of folder to search for ttf font files
asset_fonts_input  := assets/fonts

# Location of folder where the texts.xlsx is placed
asset_texts_input  := assets/texts

build_root_path := build
object_output_path := $(build_root_path)/$(board_name)
binary_output_path := $(build_root_path)/bin

# Location of output folders where autogenerated code from assets is placed
asset_root_path := generated
asset_images_output := $(asset_root_path)/images
asset_fonts_output := $(asset_root_path)/fonts
asset_texts_output := $(asset_root_path)/texts

#include application specific configuration
-include config/gcc/app.mk

### END OF USER SECTION. THE FOLLOWING SHOULD NOT BE MODIFIED ###

ifeq ($(UNAME), Linux)
library_path := $(touchgfx_path)/lib/sdl2/linux64 $(touchgfx_path)/lib/linux
libraries := touchgfx SDL2 SDL2_image rt m pthread dl
libstart := -Wl,--start-group
libend := -Wl,--end-group
libextra :=
library_includes += $(touchgfx_path)/framework/include/platform/hal/simulator/sdl2/vendor
linker_options_local := -Xlinker -rpath -Xlinker $(abspath $(touchgfx_path)/lib/sdl2/linux64/)
resource_file :=
imageconvert_executable := $(touchgfx_path)/framework/tools/imageconvert/build/linux/imageconvert.out
fontconvert_executable := $(touchgfx_path)/framework/tools/fontconvert/build/linux/fontconvert.out
simulator_executable := simulator.out
linker_options += -static-libgcc -Xlinker --no-as-needed
else
sdl_library_path := $(touchgfx_path)/lib/sdl2/win32
library_path := $(sdl_library_path) $(touchgfx_path)/lib/win/mingw32
libraries := touchgfx SDL2 SDL2_image m pthread mingw32
libstart := -Wl,--start-group
libend := -Wl,--end-group
libextra := -Wl,--subsystem,windows
library_includes += $(touchgfx_path)/framework/include/platform/hal/simulator/sdl2/vendor
resource_file := simulator/touchgfx.res
imageconvert_executable := $(touchgfx_path)/framework/tools/imageconvert/build/win/imageconvert.out
fontconvert_executable := $(touchgfx_path)/framework/tools/fontconvert/build/win/fontconvert.out
simulator_executable := simulator.exe
$(resource_file): $(resource_file:%.res=%.rc) $(resource_file:%.res=%.ico)
	@echo Creating Windows resource file with program icon
	@windres $(resource_file:%.res=%.rc) -O coff -o $@
linker_options += -static-libgcc -static-libstdc++
endif

c_compiler           := g++
c_compiler_options   += -DSIMULATOR='' -g
cpp_compiler         := g++
cpp_compiler_options += -g -DSIMULATOR='' -DENABLE_LOG
linker               := g++

WARN = error all extra write-strings init-self cast-qual \
       pointer-arith strict-aliasing format=2 uninitialized \
       missing-declarations no-long-long no-unused-parameter \
       no-variadic-macros no-format-extra-args \
       no-conversion no-overloaded-virtual
CXXWARN = non-virtual-dtor ctor-dtor-privacy

c_compiler_options_local   += -pedantic $(addprefix -W,$(WARN))
cpp_compiler_options_local += -pedantic $(addprefix -W,$(WARN) $(CXXWARN))

#include everything + specific vendor folders
framework_includes := $(touchgfx_path)/framework/include

#only take in the source we want to build for this sim
framework_files := $(touchgfx_path)/framework/source/platform/driver/touch/SDL2TouchController.cpp
framework_source := $(touchgfx_path)/framework/source/platform/hal/simulator/sdl2

#this needs to change when assset include folder changes.
all_components := $(components) \
	$(asset_fonts_output) \
	$(asset_images_output) \
	$(asset_texts_output)

#keep framework include and source out of this
include_paths := $(library_includes) $(foreach comp, $(all_components), $(comp)/include) $(framework_includes)
source_paths = $(foreach comp, $(all_components), $(comp)/src) $(framework_source) simulator

# Finds files that matches the specified pattern. The directory list
# is searched recursively. It is safe to invoke this function with an
# empty list of directories.
#
# Param $(1): List of directories to search
# Param $(2): The file pattern to search for
define find
	$(foreach dir,$(1),$(foreach d,$(wildcard $(dir)/*),\
		$(call find,$(d),$(2))) $(wildcard $(dir)/$(strip $(2))))
endef
unexport find

fontconvert_ttf_lower_files := $(call find, $(asset_fonts_input), *.ttf)
fontconvert_ttf_upper_files := $(call find, $(asset_fonts_input), *.TTF)
fontconvert_otf_lower_files := $(call find, $(asset_fonts_input), *.otf)
fontconvert_otf_upper_files := $(call find, $(asset_fonts_input), *.OTF)
fontconvert_bdf_lower_files := $(call find, $(asset_fonts_input), *.bdf)
fontconvert_bdf_upper_files := $(call find, $(asset_fonts_input), *.BDF)
fontconvert_font_files := $(fontconvert_ttf_lower_files) \
			  $(fontconvert_ttf_upper_files) \
			  $(fontconvert_otf_lower_files) \
			  $(fontconvert_otf_upper_files) \
			  $(fontconvert_bdf_lower_files) \
			  $(fontconvert_bdf_upper_files)

source_files := $(call find, $(source_paths),*.cpp) $(framework_files)
c_source_files := $(call find, $(source_paths),*.c)

object_files := $(source_files:$(touchgfx_path)/%.cpp=$(object_output_path)/touchgfx/%.o) $(c_source_files:$(touchgfx_path)/%.c=$(object_output_path)/touchgfx/%.o)
object_files := $(object_files:%.cpp=$(object_output_path)/%.o)
object_files := $(object_files:%.c=$(object_output_path)/%.o)
dependency_files := $(object_files:%.o=%.d)

textconvert_script_path := $(touchgfx_path)/framework/tools/textconvert
textconvert_executable := $(call find, $(textconvert_script_path), *.rb)

text_database := $(asset_texts_input)/texts.xlsx

.PHONY: _all_ _clean_ _assets_ generate_assets build_executable

# Force linking each time
.PHONY: $(binary_output_path)/$(simulator_executable)

_all_: generate_assets

generate_assets: _assets_
	@$(MAKE) -f $(makefile_name) -r -s $(MFLAGS) build_executable
build_executable: $(binary_output_path)/$(simulator_executable)

$(binary_output_path)/$(simulator_executable): $(object_files) $(resource_file)
	@echo Linking $(@)
	@mkdir -p $(@D)
	@mkdir -p $(object_output_path)
	@$(file >$(build_root_path)/objects.tmp) $(foreach F,$(object_files),$(file >>$(build_root_path)/objects.tmp,$F))
	@$(linker) \
		$(linker_options) $(linker_options_local) \
		$(patsubst %,-L%,$(library_path)) \
		@$(build_root_path)/objects.tmp -o $@ $(resource_file) \
		$(libstart) $(patsubst %,-l%,$(libraries)) $(libend) $(libextra)
	@rm -f $(build_root_path)/objects.tmp
ifeq ($(UNAME), Linux)
	@if [ -f simulator/landscape.png ]; then cp simulator/landscape.png $(binary_output_path); fi
	@if [ -f simulator/portrait.png ]; then cp simulator/portrait.png $(binary_output_path); fi
	@echo "To be able to run \"$(binary_output_path)/$(simulator_executable)\" type"
	@echo "     sudo ldconfig $(abspath $(touchgfx_path)/lib/sdl2/linux64)"
	@echo "at the command prompt at least once."
else
	@cp $(sdl_library_path)/SDL2.dll $(binary_output_path)
	@cp $(sdl_library_path)/SDL2_image.dll $(binary_output_path)
	@cp $(sdl_library_path)/libpng16-16.dll $(binary_output_path)
	@cp $(sdl_library_path)/zlib1.dll $(binary_output_path)
	@if [ -f simulator/landscape.png ]; then cp simulator/landscape.png $(binary_output_path); fi
	@if [ -f simulator/portrait.png ]; then cp simulator/portrait.png $(binary_output_path); fi
endif

$(object_output_path)/touchgfx/%.o: $(touchgfx_path)/%.cpp config/gcc/app.mk
	@echo Compiling $<
	@mkdir -p $(@D)
	@$(cpp_compiler) \
		-MMD -MP $(cpp_compiler_options) $(cpp_compiler_options_local) $(user_cflags) \
		$(patsubst %,-I%,$(include_paths)) \
		-c $< -o $@

$(object_output_path)/%.o: %.cpp config/gcc/app.mk
	@echo Compiling $<
	@mkdir -p $(@D)
	@$(cpp_compiler) \
		-MMD -MP $(cpp_compiler_options) $(cpp_compiler_options_local) $(user_cflags) \
		$(patsubst %,-I%,$(include_paths)) \
		-c $< -o $@

$(object_output_path)/%.o: %.c config/gcc/app.mk
	@echo Compiling $<
	@mkdir -p $(@D)
	@$(c_compiler) \
		-MMD -MP $(c_compiler_options) $(c_compiler_options_local) $(user_cflags) \
		$(patsubst %,-I%,$(include_paths)) \
		-c $< -o $@

ifeq ($(MAKECMDGOALS),build_executable)
$(firstword $(dependency_files)): config/gcc/app.mk
	@rm -rf $(object_output_path)
-include $(dependency_files)
endif

_assets_: BitmapDatabase $(asset_texts_output)/include/texts/TextKeysAndLanguages.hpp

alpha_dither ?= no
dither_algorith ?= 2
remap_identical_texts ?= yes

.PHONY: BitmapDatabase
BitmapDatabase:
	@echo Converting images
	@$(imageconvert_executable) -dither $(dither_algorithm) -alpha_dither $(alpha_dither) -opaque_image_format $(opaque_image_format) -non_opaque_image_format $(non_opaque_image_format) $(screen_orientation) -r $(asset_images_input) -w $(asset_images_output)

$(asset_texts_output)/include/texts/TextKeysAndLanguages.hpp: $(text_database) config/gcc/app.mk $(textconvert_executable) $(fontconvert_executable) $(fontconvert_font_files)
	@rm -f $(asset_fonts_output)/src/*
	@rm -f $(asset_fonts_output)/include/fonts/*
	@rm -f $(asset_fonts_output)/UnicodeList*.txt
	@rm -f $(asset_fonts_output)/CharSizes*.csv
	@mkdir -p $(asset_texts_output)/include/texts
	@ruby $(textconvert_script_path)/main.rb $(text_database) $(fontconvert_executable) $(asset_fonts_output) $(asset_texts_output) $(asset_fonts_input) . $(remap_identical_texts) $(text_data_format)

_clean_:
	@echo Cleaning
	@rm -rf $(build_root_path)
	# Do not remove gui_generated
	@rm -rf $(asset_images_output)
	@rm -rf $(asset_fonts_output)
	@rm -rf $(asset_texts_output)
	# Create directory to avoid error if it does not exist
	@mkdir -p $(asset_root_path)
	# Remove assets folder if it is empty (i.e. no gui_generated folder)
	@rmdir --ignore-fail-on-non-empty $(asset_root_path)
