1
0
mirror of synced 2024-11-27 17:10:51 +01:00

Proper DPI scaling and basic custom font (#85)

* add glm to arch deps

After running got `None of the required 'glm' found`. This fixes that

* dist/fedora: Include file magic headers

Due to differences in package names between Deb based systems, Arch
Linux, and RPM based systems the package containing the development
headers for file were missing from the Fedora dependencies script.

This includes the package `file-devel`, which is the package which
resolves the issue.

In Fedora, one can identify the package providing a specific file using
the verb "whatprovides" with the command dnf, e.g.:

    [~]$ dnf whatprovides /usr/include/magic.h
    Last metadata expiration check: 4 days, 0:23:05 ago on Fri 04 Dec 2020 09:06:53 AM PST.
    file-devel-5.39-3.fc33.i686 : Libraries and header files for file development
    Repo        : fedora
    Matched from:
    Filename    : /usr/include/magic.h

    file-devel-5.39-3.fc33.x86_64 : Libraries and header files for file development
    Repo        : @System
    Matched from:
    Filename    : /usr/include/magic.h

    file-devel-5.39-3.fc33.x86_64 : Libraries and header files for file development
    Repo        : fedora
    Matched from:
    Filename    : /usr/include/magic.h

If one is unsure of the specific path, globbing may be used (but must be
quoted):

    dnf whatprovides "*/magic.h"

Resolves #48

* dist: Prevent already installed packages in ArchLinux and MSYS2.

Use --needed option with pacman to prevent it.

* Add script to install dependencies on Debian/Ubuntu.

Tested with Xubuntu 20.04 and Debian testing
(in today's Docker image bitnami/minideb).

Update README.md.

* ci: rework (#31)

* Support non standard LLVM library names (#86)

This fix openSUSE and Gentoo issue mentioned in https://github.com/WerWolv/ImHex/issues/37#issuecomment-739503138.

(tested on openSUSE tumbleweed via Docker)

I also took the liberty of renaming llvm_lib to llvm_demangle_lib to be more specific in the ``CMakeLists.txt``.

* Implement proper DPI handling

* Implement basic custom font support

* Fix building on windows

* Hopefully fix fonts on Windows

* Fix several scaling issues

* Replace font renderer with freetype

* Updated CI and dependency scripts

* Rebuild default font atlas

* Correct platform detection macro for mingw

* Fixed PKGBUILD

Co-authored-by: brockelmore <31553173+brockelmore@users.noreply.github.com>
Co-authored-by: Brian 'Redbeard' Harrington <redbeard@dead-city.org>
Co-authored-by: Biswapriyo Nath <nathbappai@gmail.com>
Co-authored-by: Stéphane Gourichon <stephane.gourichon@fidergo.fr>
Co-authored-by: umarcor <38422348+umarcor@users.noreply.github.com>
Co-authored-by: Mary <me@thog.eu>
Co-authored-by: WerWolv <werwolv98@gmail.com>
This commit is contained in:
averne 2020-12-11 14:24:42 +01:00 committed by GitHub
parent 9b853350f1
commit 56cca88fbd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 1016 additions and 248 deletions

View File

@ -1,172 +1,174 @@
name: Build
on:
push:
pull_request:
env:
BUILD_TYPE: Release
jobs:
lin:
runs-on: ubuntu-20.04
name: 🐧 Ubuntu 20.04
steps:
- name: 🧰 Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: ⬇️ Install dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
build-essential \
gcc-10 \
g++-10 \
pkg-config \
cmake \
make \
libglfw3-dev \
libglm-dev \
libmagic-dev \
libssl-dev \
libcapstone-dev \
llvm-dev \
nlohmann-json3-dev \
python3-dev \
- name: ✋ Build
run: |
mkdir build
cd build
CC=gcc-10 CXX=g++-10 cmake ..
make -j 4
win-manual:
runs-on: windows-latest
strategy:
fail-fast: false
matrix:
include:
- { msystem: MINGW64, arch: x86_64 }
#- { msystem: MINGW32, arch: i686 } # currently fail
name: 🟪 ${{ matrix.msystem }} · ${{ matrix.arch }} · manual
defaults:
run:
shell: msys2 {0}
env:
MINGW_INSTALLS: ${{ matrix.msystem }}
steps:
- name: 🧰 Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: 🟪 Setup MSYS2
uses: msys2/setup-msys2@v2
with:
msystem: ${{ matrix.msystem }}
update: true
install: >
mingw-w64-${{ matrix.arch }}-gcc
mingw-w64-${{ matrix.arch }}-cmake
mingw-w64-${{ matrix.arch }}-make
mingw-w64-${{ matrix.arch }}-capstone
mingw-w64-${{ matrix.arch }}-glfw
mingw-w64-${{ matrix.arch }}-glm
mingw-w64-${{ matrix.arch }}-file
mingw-w64-${{ matrix.arch }}-llvm
mingw-w64-${{ matrix.arch }}-nlohmann-json
mingw-w64-${{ matrix.arch }}-openssl
mingw-w64-${{ matrix.arch }}-polly
mingw-w64-${{ matrix.arch }}-python
- name: ✋ Build
run: |
mkdir build
cd build
cmake -G "MinGW Makefiles" ..
mingw32-make -j 4
win-makepkg:
runs-on: windows-latest
strategy:
fail-fast: false
matrix:
include:
- { msystem: MINGW64, arch: x86_64 }
#- { msystem: MINGW32, arch: i686 } # currently fail
name: 🟪 ${{ matrix.msystem }} · ${{ matrix.arch }} · makepkg
defaults:
run:
shell: msys2 {0}
steps:
- run: git config --global core.autocrlf input
shell: bash
- name: 🧰 Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: 🟪 Setup MSYS2
uses: msys2/setup-msys2@v2
with:
msystem: ${{ matrix.msystem }}
update: true
install: >
base-devel
mingw-w64-${{ matrix.arch }}-toolchain
- name: 🔧 Build
run: |
cd msys2
makepkg-mingw --noconfirm --noprogressbar -sCLf
env:
MINGW_INSTALLS: ${{ matrix.msystem }}
- name: '📤 Upload artifact: package'
uses: actions/upload-artifact@v2
with:
path: msys2/*.zst
win-test:
needs: win-makepkg
runs-on: windows-latest
strategy:
fail-fast: false
matrix:
include:
- { msystem: MINGW64, arch: x86_64 }
#- { msystem: MINGW32, arch: i686 } # currently fail
name: 🟪 ${{ matrix.msystem }} · ${{ matrix.arch }} · test
defaults:
run:
shell: msys2 {0}
steps:
- name: 🟪 Setup MSYS2
uses: msys2/setup-msys2@v2
with:
msystem: ${{ matrix.msystem }}
update: true
- name: '📥 Download artifacts'
uses: actions/download-artifact@v2
- name: ⚙️ Install
run: |
pacman -U --noconfirm --noprogressbar artifact/*.zst
- name: ▶️ Test
run: |
which ImHex
name: Build
on:
push:
pull_request:
env:
BUILD_TYPE: Release
jobs:
lin:
runs-on: ubuntu-20.04
name: 🐧 Ubuntu 20.04
steps:
- name: 🧰 Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: ⬇️ Install dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
build-essential \
gcc-10 \
g++-10 \
pkg-config \
cmake \
make \
libglfw3-dev \
libglm-dev \
libmagic-dev \
libssl-dev \
libcapstone-dev \
llvm-dev \
nlohmann-json3-dev \
python3-dev \
libfreetype-dev \
- name: ✋ Build
run: |
mkdir build
cd build
CC=gcc-10 CXX=g++-10 cmake ..
make -j 4
win-manual:
runs-on: windows-latest
strategy:
fail-fast: false
matrix:
include:
- { msystem: MINGW64, arch: x86_64 }
#- { msystem: MINGW32, arch: i686 } # currently fail
name: 🟪 ${{ matrix.msystem }} · ${{ matrix.arch }} · manual
defaults:
run:
shell: msys2 {0}
env:
MINGW_INSTALLS: ${{ matrix.msystem }}
steps:
- name: 🧰 Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: 🟪 Setup MSYS2
uses: msys2/setup-msys2@v2
with:
msystem: ${{ matrix.msystem }}
update: true
install: >
mingw-w64-${{ matrix.arch }}-gcc
mingw-w64-${{ matrix.arch }}-cmake
mingw-w64-${{ matrix.arch }}-make
mingw-w64-${{ matrix.arch }}-capstone
mingw-w64-${{ matrix.arch }}-glfw
mingw-w64-${{ matrix.arch }}-glm
mingw-w64-${{ matrix.arch }}-file
mingw-w64-${{ matrix.arch }}-llvm
mingw-w64-${{ matrix.arch }}-nlohmann-json
mingw-w64-${{ matrix.arch }}-openssl
mingw-w64-${{ matrix.arch }}-polly
mingw-w64-${{ matrix.arch }}-python
mingw-w64-${{ matrix.arch }}-freetype
- name: ✋ Build
run: |
mkdir build
cd build
cmake -G "MinGW Makefiles" ..
mingw32-make -j 4
win-makepkg:
runs-on: windows-latest
strategy:
fail-fast: false
matrix:
include:
- { msystem: MINGW64, arch: x86_64 }
#- { msystem: MINGW32, arch: i686 } # currently fail
name: 🟪 ${{ matrix.msystem }} · ${{ matrix.arch }} · makepkg
defaults:
run:
shell: msys2 {0}
steps:
- run: git config --global core.autocrlf input
shell: bash
- name: 🧰 Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: 🟪 Setup MSYS2
uses: msys2/setup-msys2@v2
with:
msystem: ${{ matrix.msystem }}
update: true
install: >
base-devel
mingw-w64-${{ matrix.arch }}-toolchain
- name: 🔧 Build
run: |
cd msys2
makepkg-mingw --noconfirm --noprogressbar -sCLf
env:
MINGW_INSTALLS: ${{ matrix.msystem }}
- name: '📤 Upload artifact: package'
uses: actions/upload-artifact@v2
with:
path: msys2/*.zst
win-test:
needs: win-makepkg
runs-on: windows-latest
strategy:
fail-fast: false
matrix:
include:
- { msystem: MINGW64, arch: x86_64 }
#- { msystem: MINGW32, arch: i686 } # currently fail
name: 🟪 ${{ matrix.msystem }} · ${{ matrix.arch }} · test
defaults:
run:
shell: msys2 {0}
steps:
- name: 🟪 Setup MSYS2
uses: msys2/setup-msys2@v2
with:
msystem: ${{ matrix.msystem }}
update: true
- name: '📥 Download artifacts'
uses: actions/download-artifact@v2
- name: ⚙️ Install
run: |
pacman -U --noconfirm --noprogressbar artifact/*.zst
- name: ▶️ Test
run: |
which ImHex

2
.gitignore vendored
View File

@ -1,3 +1,5 @@
.vscode/
cmake-build-debug/

View File

@ -15,6 +15,7 @@ pkg_search_module(CAPSTONE REQUIRED capstone)
find_package(OpenGL REQUIRED)
find_package(LLVM REQUIRED CONFIG)
find_package(nlohmann_json REQUIRED)
find_package(Freetype REQUIRED)
find_package(Python COMPONENTS Interpreter Development)
if(Python_VERSION LESS 3)
@ -83,6 +84,7 @@ add_executable(ImHex
libs/ImGui/source/imgui_draw.cpp
libs/ImGui/source/imgui_widgets.cpp
libs/ImGui/source/imgui_demo.cpp
libs/ImGui/source/imgui_freetype.cpp
libs/ImGui/source/imgui_impl_glfw.cpp
libs/ImGui/source/imgui_impl_opengl3.cpp
libs/ImGui/source/ImGuiFileBrowser.cpp
@ -94,11 +96,11 @@ add_executable(ImHex
target_link_directories(ImHex PRIVATE ${LLVM_LIBRARY_DIR})
if (WIN32)
target_link_libraries(ImHex libglfw3.a libgcc.a libstdc++.a libmagic.a libgnurx.a libtre.a libintl.a libiconv.a shlwapi.lib libcrypto.a libwinpthread.a libcapstone.a ${llvm_demangle_lib} ${Python_LIBRARIES} nlohmann_json::nlohmann_json)
target_link_libraries(ImHex libglfw3.a libgcc.a libstdc++.a libmagic.a libgnurx.a libtre.a libintl.a libiconv.a shlwapi.lib libcrypto.a libwinpthread.a libcapstone.a ${llvm_demangle_lib} ${Python_LIBRARIES} nlohmann_json::nlohmann_json Freetype::Freetype)
endif (WIN32)
if (UNIX)
target_link_libraries(ImHex libglfw.so libmagic.so libcrypto.so libdl.so libcapstone.so ${llvm_demangle_lib} ${Python_LIBRARIES} nlohmann_json::nlohmann_json)
target_link_libraries(ImHex libglfw.so libmagic.so libcrypto.so libdl.so libcapstone.so ${llvm_demangle_lib} ${Python_LIBRARIES} nlohmann_json::nlohmann_json Freetype::Freetype)
endif (UNIX)
install(TARGETS ImHex DESTINATION bin)

View File

@ -9,4 +9,5 @@ pacman -S --needed \
llvm-libs \
nlohmann-json \
glm \
python3
python3 \
freetype2

View File

@ -23,7 +23,8 @@ apt install \
llvm-dev \
libssl-dev \
libstdc++-10-dev \
python3-dev
python3-dev \
libfreetype-dev
echo "Please consider this before running cmake (useful on e.g. Ubuntu 20.04):"
echo "export CXX=g++-10"

View File

@ -11,4 +11,5 @@ dnf install \
llvm-devel \
mesa-libGL-devel \
openssl-devel \
python-devel
python-devel \
freetype-devel

View File

@ -12,4 +12,5 @@ pacman -S --needed \
mingw-w64-x86_64-nlohmann-json \
mingw-w64-x86_64-openssl \
mingw-w64-x86_64-polly \
mingw-w64-x86_64-python
mingw-w64-x86_64-python \
mingw-w64-x86_64-freetype

View File

@ -87,4 +87,15 @@ namespace hex {
static inline std::string s_errorMessage;
};
void confirmButtons(const char *textLeft, const char *textRight, auto leftButtonFn, auto rightButtonFn) {
auto width = ImGui::GetWindowWidth();
ImGui::SetCursorPosX(width / 9);
if (ImGui::Button(textLeft, ImVec2(width / 3, 0)))
leftButtonFn();
ImGui::SameLine();
ImGui::SetCursorPosX(width / 9 * 5);
if (ImGui::Button(textRight, ImVec2(width / 3, 0)))
rightButtonFn();
}
}

View File

@ -1,6 +1,7 @@
#pragma once
#include <concepts>
#include <filesystem>
#include <memory>
#include <vector>
@ -30,6 +31,8 @@ namespace hex {
friend void ImHexSettingsHandler_ApplyAll(ImGuiContext *ctx, ImGuiSettingsHandler *handler);
friend void ImHexSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf);
bool setFont(const std::filesystem::path &font_path);
private:
void frameBegin();
void frameEnd();

View File

@ -0,0 +1,36 @@
// dear imgui: wrapper to use FreeType (instead of stb_truetype)
// Get latest version at https://github.com/ocornut/imgui/tree/master/misc/freetype
// Original code by @Vuhdo (Aleksei Skriabin), maintained by @ocornut
#pragma once
#include "imgui.h" // IMGUI_API, ImFontAtlas
namespace ImGuiFreeType
{
// Hinting greatly impacts visuals (and glyph sizes).
// When disabled, FreeType generates blurrier glyphs, more or less matches the stb's output.
// The Default hinting mode usually looks good, but may distort glyphs in an unusual way.
// The Light hinting mode generates fuzzier glyphs but better matches Microsoft's rasterizer.
// You can set those flags on a per font basis in ImFontConfig::RasterizerFlags.
// Use the 'extra_flags' parameter of BuildFontAtlas() to force a flag on all your fonts.
enum RasterizerFlags
{
// By default, hinting is enabled and the font's native hinter is preferred over the auto-hinter.
NoHinting = 1 << 0, // Disable hinting. This generally generates 'blurrier' bitmap glyphs when the glyph are rendered in any of the anti-aliased modes.
NoAutoHint = 1 << 1, // Disable auto-hinter.
ForceAutoHint = 1 << 2, // Indicates that the auto-hinter is preferred over the font's native hinter.
LightHinting = 1 << 3, // A lighter hinting algorithm for gray-level modes. Many generated glyphs are fuzzier but better resemble their original shape. This is achieved by snapping glyphs to the pixel grid only vertically (Y-axis), as is done by Microsoft's ClearType and Adobe's proprietary font renderer. This preserves inter-glyph spacing in horizontal text.
MonoHinting = 1 << 4, // Strong hinting algorithm that should only be used for monochrome output.
Bold = 1 << 5, // Styling: Should we artificially embolden the font?
Oblique = 1 << 6, // Styling: Should we slant the font, emulating italic style?
Monochrome = 1 << 7 // Disable anti-aliasing. Combine this with MonoHinting for best results!
};
IMGUI_API bool BuildFontAtlas(ImFontAtlas* atlas, unsigned int extra_flags = 0);
// By default ImGuiFreeType will use IM_ALLOC()/IM_FREE().
// However, as FreeType does lots of allocations we provide a way for the user to redirect it to a separate memory heap if desired:
IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data = NULL);
}

View File

@ -550,7 +550,7 @@ struct MemoryEditor
ImGui::OpenPopup("options");
if (ImGui::BeginPopup("options")) {
ImGui::PushItemWidth(56);
ImGui::PushItemWidth(ImGui::CalcTextSize("00 cols").x * 1.1f);
if (ImGui::DragInt("##cols", &Cols, 0.2f, 4, 32, "%d cols")) { ContentsWidthChanged = true; if (Cols < 1) Cols = 1; }
ImGui::PopItemWidth();
ImGui::Checkbox("Show HexII", &OptShowHexII);

View File

@ -43,7 +43,6 @@ namespace imgui_addons
selected_ext_idx = 0;
ext_box_width = -1.0f;
col_width = 280.0f;
min_size = ImVec2(500,300);
invfile_modal_id = "Invalid File!";
repfile_modal_id = "Replace File?";
@ -109,11 +108,12 @@ namespace imgui_addons
bool ImGuiFileBrowser::showFileDialog(const std::string& label, const DialogMode mode, const ImVec2& sz_xy, const std::string& valid_types)
{
dialog_mode = mode;
ImGuiIO& io = ImGui::GetIO();
max_size.x = io.DisplaySize.x;
max_size.y = io.DisplaySize.y;
max_size = ImVec2( io.DisplaySize.x, io.DisplaySize.y);
min_size = ImVec2(0.5f * io.DisplaySize.x, 0.5f * io.DisplaySize.y);
ImGui::SetNextWindowSizeConstraints(min_size, max_size);
ImGui::SetNextWindowPos(io.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f,0.5f));
ImGui::SetNextWindowSize(ImVec2(std::max(sz_xy.x, min_size.x), std::max(sz_xy.y, min_size.y)), ImGuiCond_Appearing);

View File

@ -0,0 +1,680 @@
// dear imgui: wrapper to use FreeType (instead of stb_truetype)
// Get latest version at https://github.com/ocornut/imgui/tree/master/misc/freetype
// Original code by @vuhdo (Aleksei Skriabin). Improvements by @mikesart. Maintained and v0.60+ by @ocornut.
// Changelog:
// - v0.50: (2017/08/16) imported from https://github.com/Vuhdo/imgui_freetype into http://www.github.com/ocornut/imgui_club, updated for latest changes in ImFontAtlas, minor tweaks.
// - v0.51: (2017/08/26) cleanup, optimizations, support for ImFontConfig::RasterizerFlags, ImFontConfig::RasterizerMultiply.
// - v0.52: (2017/09/26) fixes for imgui internal changes.
// - v0.53: (2017/10/22) minor inconsequential change to match change in master (removed an unnecessary statement).
// - v0.54: (2018/01/22) fix for addition of ImFontAtlas::TexUvscale member.
// - v0.55: (2018/02/04) moved to main imgui repository (away from http://www.github.com/ocornut/imgui_club)
// - v0.56: (2018/06/08) added support for ImFontConfig::GlyphMinAdvanceX, GlyphMaxAdvanceX.
// - v0.60: (2019/01/10) re-factored to match big update in STB builder. fixed texture height waste. fixed redundant glyphs when merging. support for glyph padding.
// - v0.61: (2019/01/15) added support for imgui allocators + added FreeType only override function SetAllocatorFunctions().
// - v0.62: (2019/02/09) added RasterizerFlags::Monochrome flag to disable font anti-aliasing (combine with ::MonoHinting for best results!)
// - v0.63: (2020/06/04) fix for rare case where FT_Get_Char_Index() succeed but FT_Load_Glyph() fails.
// Gamma Correct Blending:
// FreeType assumes blending in linear space rather than gamma space.
// See https://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#FT_Render_Glyph
// For correct results you need to be using sRGB and convert to linear space in the pixel shader output.
// The default imgui styles will be impacted by this change (alpha values will need tweaking).
// FIXME: cfg.OversampleH, OversampleV are not supported (but perhaps not so necessary with this rasterizer).
#include "imgui_freetype.h"
#include "imgui_internal.h" // ImMin,ImMax,ImFontAtlasBuild*,
#include <stdint.h>
#include <ft2build.h>
#include FT_FREETYPE_H // <freetype/freetype.h>
#include FT_MODULE_H // <freetype/ftmodapi.h>
#include FT_GLYPH_H // <freetype/ftglyph.h>
#include FT_SYNTHESIS_H // <freetype/ftsynth.h>
#ifdef _MSC_VER
#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff)
#endif
#if defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#endif
namespace
{
// Glyph metrics:
// --------------
//
// xmin xmax
// | |
// |<-------- width -------->|
// | |
// | +-------------------------+----------------- ymax
// | | ggggggggg ggggg | ^ ^
// | | g:::::::::ggg::::g | | |
// | | g:::::::::::::::::g | | |
// | | g::::::ggggg::::::gg | | |
// | | g:::::g g:::::g | | |
// offsetX -|-------->| g:::::g g:::::g | offsetY |
// | | g:::::g g:::::g | | |
// | | g::::::g g:::::g | | |
// | | g:::::::ggggg:::::g | | |
// | | g::::::::::::::::g | | height
// | | gg::::::::::::::g | | |
// baseline ---*---------|---- gggggggg::::::g-----*-------- |
// / | | g:::::g | |
// origin | | gggggg g:::::g | |
// | | g:::::gg gg:::::g | |
// | | g::::::ggg:::::::g | |
// | | gg:::::::::::::g | |
// | | ggg::::::ggg | |
// | | gggggg | v
// | +-------------------------+----------------- ymin
// | |
// |------------- advanceX ----------->|
/// A structure that describe a glyph.
struct GlyphInfo
{
int Width; // Glyph's width in pixels.
int Height; // Glyph's height in pixels.
FT_Int OffsetX; // The distance from the origin ("pen position") to the left of the glyph.
FT_Int OffsetY; // The distance from the origin to the top of the glyph. This is usually a value < 0.
float AdvanceX; // The distance from the origin to the origin of the next glyph. This is usually a value > 0.
};
// Font parameters and metrics.
struct FontInfo
{
uint32_t PixelHeight; // Size this font was generated with.
float Ascender; // The pixel extents above the baseline in pixels (typically positive).
float Descender; // The extents below the baseline in pixels (typically negative).
float LineSpacing; // The baseline-to-baseline distance. Note that it usually is larger than the sum of the ascender and descender taken as absolute values. There is also no guarantee that no glyphs extend above or below subsequent baselines when using this distance. Think of it as a value the designer of the font finds appropriate.
float LineGap; // The spacing in pixels between one row's descent and the next row's ascent.
float MaxAdvanceWidth; // This field gives the maximum horizontal cursor advance for all glyphs in the font.
};
// FreeType glyph rasterizer.
// NB: No ctor/dtor, explicitly call Init()/Shutdown()
struct FreeTypeFont
{
bool InitFont(FT_Library ft_library, const ImFontConfig& cfg, unsigned int extra_user_flags); // Initialize from an external data buffer. Doesn't copy data, and you must ensure it stays valid up to this object lifetime.
void CloseFont();
void SetPixelHeight(int pixel_height); // Change font pixel size. All following calls to RasterizeGlyph() will use this size
const FT_Glyph_Metrics* LoadGlyph(uint32_t in_codepoint);
const FT_Bitmap* RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info);
void BlitGlyph(const FT_Bitmap* ft_bitmap, uint8_t* dst, uint32_t dst_pitch, unsigned char* multiply_table = NULL);
~FreeTypeFont() { CloseFont(); }
// [Internals]
FontInfo Info; // Font descriptor of the current font.
FT_Face Face;
unsigned int UserFlags; // = ImFontConfig::RasterizerFlags
FT_Int32 LoadFlags;
FT_Render_Mode RenderMode;
};
// From SDL_ttf: Handy routines for converting from fixed point
#define FT_CEIL(X) (((X + 63) & -64) / 64)
bool FreeTypeFont::InitFont(FT_Library ft_library, const ImFontConfig& cfg, unsigned int extra_user_flags)
{
FT_Error error = FT_New_Memory_Face(ft_library, (uint8_t*)cfg.FontData, (uint32_t)cfg.FontDataSize, (uint32_t)cfg.FontNo, &Face);
if (error != 0)
return false;
error = FT_Select_Charmap(Face, FT_ENCODING_UNICODE);
if (error != 0)
return false;
memset(&Info, 0, sizeof(Info));
SetPixelHeight((uint32_t)cfg.SizePixels);
// Convert to FreeType flags (NB: Bold and Oblique are processed separately)
UserFlags = cfg.RasterizerFlags | extra_user_flags;
LoadFlags = FT_LOAD_NO_BITMAP;
if (UserFlags & ImGuiFreeType::NoHinting)
LoadFlags |= FT_LOAD_NO_HINTING;
if (UserFlags & ImGuiFreeType::NoAutoHint)
LoadFlags |= FT_LOAD_NO_AUTOHINT;
if (UserFlags & ImGuiFreeType::ForceAutoHint)
LoadFlags |= FT_LOAD_FORCE_AUTOHINT;
if (UserFlags & ImGuiFreeType::LightHinting)
LoadFlags |= FT_LOAD_TARGET_LIGHT;
else if (UserFlags & ImGuiFreeType::MonoHinting)
LoadFlags |= FT_LOAD_TARGET_MONO;
else
LoadFlags |= FT_LOAD_TARGET_NORMAL;
if (UserFlags & ImGuiFreeType::Monochrome)
RenderMode = FT_RENDER_MODE_MONO;
else
RenderMode = FT_RENDER_MODE_NORMAL;
return true;
}
void FreeTypeFont::CloseFont()
{
if (Face)
{
FT_Done_Face(Face);
Face = NULL;
}
}
void FreeTypeFont::SetPixelHeight(int pixel_height)
{
// Vuhdo: I'm not sure how to deal with font sizes properly. As far as I understand, currently ImGui assumes that the 'pixel_height'
// is a maximum height of an any given glyph, i.e. it's the sum of font's ascender and descender. Seems strange to me.
// NB: FT_Set_Pixel_Sizes() doesn't seem to get us the same result.
FT_Size_RequestRec req;
req.type = FT_SIZE_REQUEST_TYPE_REAL_DIM;
req.width = 0;
req.height = (uint32_t)pixel_height * 64;
req.horiResolution = 0;
req.vertResolution = 0;
FT_Request_Size(Face, &req);
// Update font info
FT_Size_Metrics metrics = Face->size->metrics;
Info.PixelHeight = (uint32_t)pixel_height;
Info.Ascender = (float)FT_CEIL(metrics.ascender);
Info.Descender = (float)FT_CEIL(metrics.descender);
Info.LineSpacing = (float)FT_CEIL(metrics.height);
Info.LineGap = (float)FT_CEIL(metrics.height - metrics.ascender + metrics.descender);
Info.MaxAdvanceWidth = (float)FT_CEIL(metrics.max_advance);
}
const FT_Glyph_Metrics* FreeTypeFont::LoadGlyph(uint32_t codepoint)
{
uint32_t glyph_index = FT_Get_Char_Index(Face, codepoint);
if (glyph_index == 0)
return NULL;
FT_Error error = FT_Load_Glyph(Face, glyph_index, LoadFlags);
if (error)
return NULL;
// Need an outline for this to work
FT_GlyphSlot slot = Face->glyph;
IM_ASSERT(slot->format == FT_GLYPH_FORMAT_OUTLINE);
// Apply convenience transform (this is not picking from real "Bold"/"Italic" fonts! Merely applying FreeType helper transform. Oblique == Slanting)
if (UserFlags & ImGuiFreeType::Bold)
FT_GlyphSlot_Embolden(slot);
if (UserFlags & ImGuiFreeType::Oblique)
{
FT_GlyphSlot_Oblique(slot);
//FT_BBox bbox;
//FT_Outline_Get_BBox(&slot->outline, &bbox);
//slot->metrics.width = bbox.xMax - bbox.xMin;
//slot->metrics.height = bbox.yMax - bbox.yMin;
}
return &slot->metrics;
}
const FT_Bitmap* FreeTypeFont::RenderGlyphAndGetInfo(GlyphInfo* out_glyph_info)
{
FT_GlyphSlot slot = Face->glyph;
FT_Error error = FT_Render_Glyph(slot, RenderMode);
if (error != 0)
return NULL;
FT_Bitmap* ft_bitmap = &Face->glyph->bitmap;
out_glyph_info->Width = (int)ft_bitmap->width;
out_glyph_info->Height = (int)ft_bitmap->rows;
out_glyph_info->OffsetX = Face->glyph->bitmap_left;
out_glyph_info->OffsetY = -Face->glyph->bitmap_top;
out_glyph_info->AdvanceX = (float)FT_CEIL(slot->advance.x);
return ft_bitmap;
}
void FreeTypeFont::BlitGlyph(const FT_Bitmap* ft_bitmap, uint8_t* dst, uint32_t dst_pitch, unsigned char* multiply_table)
{
IM_ASSERT(ft_bitmap != NULL);
const uint32_t w = ft_bitmap->width;
const uint32_t h = ft_bitmap->rows;
const uint8_t* src = ft_bitmap->buffer;
const uint32_t src_pitch = ft_bitmap->pitch;
switch (ft_bitmap->pixel_mode)
{
case FT_PIXEL_MODE_GRAY: // Grayscale image, 1 byte per pixel.
{
if (multiply_table == NULL)
{
for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
memcpy(dst, src, w);
}
else
{
for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
for (uint32_t x = 0; x < w; x++)
dst[x] = multiply_table[src[x]];
}
break;
}
case FT_PIXEL_MODE_MONO: // Monochrome image, 1 bit per pixel. The bits in each byte are ordered from MSB to LSB.
{
uint8_t color0 = multiply_table ? multiply_table[0] : 0;
uint8_t color1 = multiply_table ? multiply_table[255] : 255;
for (uint32_t y = 0; y < h; y++, src += src_pitch, dst += dst_pitch)
{
uint8_t bits = 0;
const uint8_t* bits_ptr = src;
for (uint32_t x = 0; x < w; x++, bits <<= 1)
{
if ((x & 7) == 0)
bits = *bits_ptr++;
dst[x] = (bits & 0x80) ? color1 : color0;
}
}
break;
}
default:
IM_ASSERT(0 && "FreeTypeFont::BlitGlyph(): Unknown bitmap pixel mode!");
}
}
}
#ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)
#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
#define STBRP_ASSERT(x) do { IM_ASSERT(x); } while (0)
#define STBRP_STATIC
#define STB_RECT_PACK_IMPLEMENTATION
#endif
#ifdef IMGUI_STB_RECT_PACK_FILENAME
#include IMGUI_STB_RECT_PACK_FILENAME
#else
#include "imstb_rectpack.h"
#endif
#endif
struct ImFontBuildSrcGlyphFT
{
GlyphInfo Info;
uint32_t Codepoint;
unsigned char* BitmapData; // Point within one of the dst_tmp_bitmap_buffers[] array
};
struct ImFontBuildSrcDataFT
{
FreeTypeFont Font;
stbrp_rect* Rects; // Rectangle to pack. We first fill in their size and the packer will give us their position.
const ImWchar* SrcRanges; // Ranges as requested by user (user is allowed to request too much, e.g. 0x0020..0xFFFF)
int DstIndex; // Index into atlas->Fonts[] and dst_tmp_array[]
int GlyphsHighest; // Highest requested codepoint
int GlyphsCount; // Glyph count (excluding missing glyphs and glyphs already set by an earlier source font)
ImBitVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB)
ImVector<ImFontBuildSrcGlyphFT> GlyphsList;
};
// Temporary data for one destination ImFont* (multiple source fonts can be merged into one destination ImFont)
struct ImFontBuildDstDataFT
{
int SrcCount; // Number of source fonts targeting this destination font.
int GlyphsHighest;
int GlyphsCount;
ImBitVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font.
};
bool ImFontAtlasBuildWithFreeType(FT_Library ft_library, ImFontAtlas* atlas, unsigned int extra_flags)
{
IM_ASSERT(atlas->ConfigData.Size > 0);
ImFontAtlasBuildInit(atlas);
// Clear atlas
atlas->TexID = (ImTextureID)NULL;
atlas->TexWidth = atlas->TexHeight = 0;
atlas->TexUvScale = ImVec2(0.0f, 0.0f);
atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f);
atlas->ClearTexData();
// Temporary storage for building
ImVector<ImFontBuildSrcDataFT> src_tmp_array;
ImVector<ImFontBuildDstDataFT> dst_tmp_array;
src_tmp_array.resize(atlas->ConfigData.Size);
dst_tmp_array.resize(atlas->Fonts.Size);
memset((void*)src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes());
memset((void*)dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes());
// 1. Initialize font loading structure, check font data validity
for (int src_i = 0; src_i < atlas->ConfigData.Size; src_i++)
{
ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
ImFontConfig& cfg = atlas->ConfigData[src_i];
FreeTypeFont& font_face = src_tmp.Font;
IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == atlas));
// Find index from cfg.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices)
src_tmp.DstIndex = -1;
for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++)
if (cfg.DstFont == atlas->Fonts[output_i])
src_tmp.DstIndex = output_i;
IM_ASSERT(src_tmp.DstIndex != -1); // cfg.DstFont not pointing within atlas->Fonts[] array?
if (src_tmp.DstIndex == -1)
return false;
// Load font
if (!font_face.InitFont(ft_library, cfg, extra_flags))
return false;
// Measure highest codepoints
ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
src_tmp.SrcRanges = cfg.GlyphRanges ? cfg.GlyphRanges : atlas->GetGlyphRangesDefault();
for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]);
dst_tmp.SrcCount++;
dst_tmp.GlyphsHighest = ImMax(dst_tmp.GlyphsHighest, src_tmp.GlyphsHighest);
}
// 2. For every requested codepoint, check for their presence in the font data, and handle redundancy or overlaps between source fonts to avoid unused glyphs.
int total_glyphs_count = 0;
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
ImFontBuildDstDataFT& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
src_tmp.GlyphsSet.Create(src_tmp.GlyphsHighest + 1);
if (dst_tmp.GlyphsSet.Storage.empty())
dst_tmp.GlyphsSet.Create(dst_tmp.GlyphsHighest + 1);
for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
for (int codepoint = src_range[0]; codepoint <= (int)src_range[1]; codepoint++)
{
if (dst_tmp.GlyphsSet.TestBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option (e.g. MergeOverwrite)
continue;
uint32_t glyph_index = FT_Get_Char_Index(src_tmp.Font.Face, codepoint); // It is actually in the font? (FIXME-OPT: We are not storing the glyph_index..)
if (glyph_index == 0)
continue;
// Add to avail set/counters
src_tmp.GlyphsCount++;
dst_tmp.GlyphsCount++;
src_tmp.GlyphsSet.SetBit(codepoint);
dst_tmp.GlyphsSet.SetBit(codepoint);
total_glyphs_count++;
}
}
// 3. Unpack our bit map into a flat list (we now have all the Unicode points that we know are requested _and_ available _and_ not overlapping another)
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount);
IM_ASSERT(sizeof(src_tmp.GlyphsSet.Storage.Data[0]) == sizeof(ImU32));
const ImU32* it_begin = src_tmp.GlyphsSet.Storage.begin();
const ImU32* it_end = src_tmp.GlyphsSet.Storage.end();
for (const ImU32* it = it_begin; it < it_end; it++)
if (ImU32 entries_32 = *it)
for (ImU32 bit_n = 0; bit_n < 32; bit_n++)
if (entries_32 & ((ImU32)1 << bit_n))
{
ImFontBuildSrcGlyphFT src_glyph;
memset(&src_glyph, 0, sizeof(src_glyph));
src_glyph.Codepoint = (ImWchar)(((it - it_begin) << 5) + bit_n);
//src_glyph.GlyphIndex = 0; // FIXME-OPT: We had this info in the previous step and lost it..
src_tmp.GlyphsList.push_back(src_glyph);
}
src_tmp.GlyphsSet.Clear();
IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount);
}
for (int dst_i = 0; dst_i < dst_tmp_array.Size; dst_i++)
dst_tmp_array[dst_i].GlyphsSet.Clear();
dst_tmp_array.clear();
// Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0)
// (We technically don't need to zero-clear buf_rects, but let's do it for the sake of sanity)
ImVector<stbrp_rect> buf_rects;
buf_rects.resize(total_glyphs_count);
memset(buf_rects.Data, 0, (size_t)buf_rects.size_in_bytes());
// Allocate temporary rasterization data buffers.
// We could not find a way to retrieve accurate glyph size without rendering them.
// (e.g. slot->metrics->width not always matching bitmap->width, especially considering the Oblique transform)
// We allocate in chunks of 256 KB to not waste too much extra memory ahead. Hopefully users of FreeType won't find the temporary allocations.
const int BITMAP_BUFFERS_CHUNK_SIZE = 256 * 1024;
int buf_bitmap_current_used_bytes = 0;
ImVector<unsigned char*> buf_bitmap_buffers;
buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE));
// 4. Gather glyphs sizes so we can pack them in our virtual canvas.
// 8. Render/rasterize font characters into the texture
int total_surface = 0;
int buf_rects_out_n = 0;
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
ImFontConfig& cfg = atlas->ConfigData[src_i];
if (src_tmp.GlyphsCount == 0)
continue;
src_tmp.Rects = &buf_rects[buf_rects_out_n];
buf_rects_out_n += src_tmp.GlyphsCount;
// Compute multiply table if requested
const bool multiply_enabled = (cfg.RasterizerMultiply != 1.0f);
unsigned char multiply_table[256];
if (multiply_enabled)
ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply);
// Gather the sizes of all rectangles we will need to pack
const int padding = atlas->TexGlyphPadding;
for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++)
{
ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i];
const FT_Glyph_Metrics* metrics = src_tmp.Font.LoadGlyph(src_glyph.Codepoint);
if (metrics == NULL)
continue;
// Render glyph into a bitmap (currently held by FreeType)
const FT_Bitmap* ft_bitmap = src_tmp.Font.RenderGlyphAndGetInfo(&src_glyph.Info);
IM_ASSERT(ft_bitmap);
// Allocate new temporary chunk if needed
const int bitmap_size_in_bytes = src_glyph.Info.Width * src_glyph.Info.Height;
if (buf_bitmap_current_used_bytes + bitmap_size_in_bytes > BITMAP_BUFFERS_CHUNK_SIZE)
{
buf_bitmap_current_used_bytes = 0;
buf_bitmap_buffers.push_back((unsigned char*)IM_ALLOC(BITMAP_BUFFERS_CHUNK_SIZE));
}
// Blit rasterized pixels to our temporary buffer and keep a pointer to it.
src_glyph.BitmapData = buf_bitmap_buffers.back() + buf_bitmap_current_used_bytes;
buf_bitmap_current_used_bytes += bitmap_size_in_bytes;
src_tmp.Font.BlitGlyph(ft_bitmap, src_glyph.BitmapData, src_glyph.Info.Width * 1, multiply_enabled ? multiply_table : NULL);
src_tmp.Rects[glyph_i].w = (stbrp_coord)(src_glyph.Info.Width + padding);
src_tmp.Rects[glyph_i].h = (stbrp_coord)(src_glyph.Info.Height + padding);
total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h;
}
}
// We need a width for the skyline algorithm, any width!
// The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height.
// User can override TexDesiredWidth and TexGlyphPadding if they wish, otherwise we use a simple heuristic to select the width based on expected surface.
const int surface_sqrt = (int)ImSqrt((float)total_surface) + 1;
atlas->TexHeight = 0;
if (atlas->TexDesiredWidth > 0)
atlas->TexWidth = atlas->TexDesiredWidth;
else
atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 : (surface_sqrt >= 1024 * 0.7f) ? 1024 : 512;
// 5. Start packing
// Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values).
const int TEX_HEIGHT_MAX = 1024 * 32;
const int num_nodes_for_packing_algorithm = atlas->TexWidth - atlas->TexGlyphPadding;
ImVector<stbrp_node> pack_nodes;
pack_nodes.resize(num_nodes_for_packing_algorithm);
stbrp_context pack_context;
stbrp_init_target(&pack_context, atlas->TexWidth, TEX_HEIGHT_MAX, pack_nodes.Data, pack_nodes.Size);
ImFontAtlasBuildPackCustomRects(atlas, &pack_context);
// 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point.
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
if (src_tmp.GlyphsCount == 0)
continue;
stbrp_pack_rects(&pack_context, src_tmp.Rects, src_tmp.GlyphsCount);
// Extend texture height and mark missing glyphs as non-packed so we won't render them.
// FIXME: We are not handling packing failure here (would happen if we got off TEX_HEIGHT_MAX or if a single if larger than TexWidth?)
for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
if (src_tmp.Rects[glyph_i].was_packed)
atlas->TexHeight = ImMax(atlas->TexHeight, src_tmp.Rects[glyph_i].y + src_tmp.Rects[glyph_i].h);
}
// 7. Allocate texture
atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight);
atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight);
atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(atlas->TexWidth * atlas->TexHeight);
memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight);
// 8. Copy rasterized font characters back into the main texture
// 9. Setup ImFont and glyphs for runtime
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontBuildSrcDataFT& src_tmp = src_tmp_array[src_i];
if (src_tmp.GlyphsCount == 0)
continue;
// When merging fonts with MergeMode=true:
// - We can have multiple input fonts writing into a same destination font.
// - dst_font->ConfigData is != from cfg which is our source configuration.
ImFontConfig& cfg = atlas->ConfigData[src_i];
ImFont* dst_font = cfg.DstFont;
const float ascent = src_tmp.Font.Info.Ascender;
const float descent = src_tmp.Font.Info.Descender;
ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent);
const float font_off_x = cfg.GlyphOffset.x;
const float font_off_y = cfg.GlyphOffset.y + IM_ROUND(dst_font->Ascent);
const int padding = atlas->TexGlyphPadding;
for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
{
ImFontBuildSrcGlyphFT& src_glyph = src_tmp.GlyphsList[glyph_i];
stbrp_rect& pack_rect = src_tmp.Rects[glyph_i];
IM_ASSERT(pack_rect.was_packed);
if (pack_rect.w == 0 && pack_rect.h == 0)
continue;
GlyphInfo& info = src_glyph.Info;
IM_ASSERT(info.Width + padding <= pack_rect.w);
IM_ASSERT(info.Height + padding <= pack_rect.h);
const int tx = pack_rect.x + padding;
const int ty = pack_rect.y + padding;
// Blit from temporary buffer to final texture
size_t blit_src_stride = (size_t)src_glyph.Info.Width;
size_t blit_dst_stride = (size_t)atlas->TexWidth;
unsigned char* blit_src = src_glyph.BitmapData;
unsigned char* blit_dst = atlas->TexPixelsAlpha8 + (ty * blit_dst_stride) + tx;
for (int y = info.Height; y > 0; y--, blit_dst += blit_dst_stride, blit_src += blit_src_stride)
memcpy(blit_dst, blit_src, blit_src_stride);
// Register glyph
float x0 = info.OffsetX + font_off_x;
float y0 = info.OffsetY + font_off_y;
float x1 = x0 + info.Width;
float y1 = y0 + info.Height;
float u0 = (tx) / (float)atlas->TexWidth;
float v0 = (ty) / (float)atlas->TexHeight;
float u1 = (tx + info.Width) / (float)atlas->TexWidth;
float v1 = (ty + info.Height) / (float)atlas->TexHeight;
dst_font->AddGlyph(&cfg, (ImWchar)src_glyph.Codepoint, x0, y0, x1, y1, u0, v0, u1, v1, info.AdvanceX);
}
src_tmp.Rects = NULL;
}
// Cleanup
for (int buf_i = 0; buf_i < buf_bitmap_buffers.Size; buf_i++)
IM_FREE(buf_bitmap_buffers[buf_i]);
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
src_tmp_array[src_i].~ImFontBuildSrcDataFT();
ImFontAtlasBuildFinish(atlas);
return true;
}
// Default memory allocators
static void* ImFreeTypeDefaultAllocFunc(size_t size, void* user_data) { IM_UNUSED(user_data); return IM_ALLOC(size); }
static void ImFreeTypeDefaultFreeFunc(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_FREE(ptr); }
// Current memory allocators
static void* (*GImFreeTypeAllocFunc)(size_t size, void* user_data) = ImFreeTypeDefaultAllocFunc;
static void (*GImFreeTypeFreeFunc)(void* ptr, void* user_data) = ImFreeTypeDefaultFreeFunc;
static void* GImFreeTypeAllocatorUserData = NULL;
// FreeType memory allocation callbacks
static void* FreeType_Alloc(FT_Memory /*memory*/, long size)
{
return GImFreeTypeAllocFunc((size_t)size, GImFreeTypeAllocatorUserData);
}
static void FreeType_Free(FT_Memory /*memory*/, void* block)
{
GImFreeTypeFreeFunc(block, GImFreeTypeAllocatorUserData);
}
static void* FreeType_Realloc(FT_Memory /*memory*/, long cur_size, long new_size, void* block)
{
// Implement realloc() as we don't ask user to provide it.
if (block == NULL)
return GImFreeTypeAllocFunc((size_t)new_size, GImFreeTypeAllocatorUserData);
if (new_size == 0)
{
GImFreeTypeFreeFunc(block, GImFreeTypeAllocatorUserData);
return NULL;
}
if (new_size > cur_size)
{
void* new_block = GImFreeTypeAllocFunc((size_t)new_size, GImFreeTypeAllocatorUserData);
memcpy(new_block, block, (size_t)cur_size);
GImFreeTypeFreeFunc(block, GImFreeTypeAllocatorUserData);
return new_block;
}
return block;
}
bool ImGuiFreeType::BuildFontAtlas(ImFontAtlas* atlas, unsigned int extra_flags)
{
// FreeType memory management: https://www.freetype.org/freetype2/docs/design/design-4.html
FT_MemoryRec_ memory_rec = {};
memory_rec.user = NULL;
memory_rec.alloc = &FreeType_Alloc;
memory_rec.free = &FreeType_Free;
memory_rec.realloc = &FreeType_Realloc;
// https://www.freetype.org/freetype2/docs/reference/ft2-module_management.html#FT_New_Library
FT_Library ft_library;
FT_Error error = FT_New_Library(&memory_rec, &ft_library);
if (error != 0)
return false;
// If you don't call FT_Add_Default_Modules() the rest of code may work, but FreeType won't use our custom allocator.
FT_Add_Default_Modules(ft_library);
bool ret = ImFontAtlasBuildWithFreeType(ft_library, atlas, extra_flags);
FT_Done_Library(ft_library);
return ret;
}
void ImGuiFreeType::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
{
GImFreeTypeAllocFunc = alloc_func;
GImFreeTypeFreeFunc = free_func;
GImFreeTypeAllocatorUserData = user_data;
}

View File

@ -19,7 +19,8 @@ makedepends=("${MINGW_PACKAGE_PREFIX}-gcc"
"${MINGW_PACKAGE_PREFIX}-nlohmann-json"
"${MINGW_PACKAGE_PREFIX}-openssl"
"${MINGW_PACKAGE_PREFIX}-polly"
"${MINGW_PACKAGE_PREFIX}-python")
"${MINGW_PACKAGE_PREFIX}-python"
"${MINGW_PACKAGE_PREFIX}-freetype")
source=()
sha256sums=()

View File

@ -25,13 +25,11 @@ namespace hex {
ImGui::NewLine();
ImGui::PopStyleColor();
};
void ViewHelp::drawAboutPopup() {
ImGui::SetNextWindowSizeConstraints(ImVec2(450, 300), ImVec2(450, 300));
if (ImGui::BeginPopupModal("About", &this->m_aboutWindowOpen, ImGuiWindowFlags_NoResize)) {
if (ImGui::BeginPopupModal("About", &this->m_aboutWindowOpen, ImGuiWindowFlags_AlwaysAutoResize)) {
ImGui::Text("ImHex Hex Editor");
ImGui::Text("by WerWolv");
ImGui::Separator();
@ -44,7 +42,6 @@ namespace hex {
ImGui::Separator();
ImGui::Text("Libraries used");
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.2F, 0.2F, 0.2F, 0.3F));
ImGui::BeginChild("##scroll");
ImGui::NewLine();
ImGui::BulletText("ImGui by ocornut");
ImGui::BulletText("imgui_club by ocornut");
@ -59,7 +56,6 @@ namespace hex {
ImGui::BulletText("LLVM");
ImGui::BulletText("Python 3");
ImGui::EndChild();
ImGui::PopStyleColor();
ImGui::EndPopup();
}

View File

@ -135,32 +135,20 @@ namespace hex {
}
if (ImGui::BeginPopupModal("Save Changes", nullptr, ImGuiWindowFlags_NoResize)) {
constexpr auto Message = "You have unsaved changes made to your Project. Are you sure you want to exit?";
if (ImGui::BeginPopupModal("Save Changes", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
constexpr auto Message = "You have unsaved changes made to your Project.\nAre you sure you want to exit?";
ImGui::NewLine();
if (ImGui::BeginChild("##scrolling", ImVec2(300, 50))) {
ImGui::SetCursorPosX(10);
ImGui::TextWrapped("%s", Message);
ImGui::EndChild();
}
ImGui::SetCursorPosX(40);
if (ImGui::Button("Yes", ImVec2(100, 20)))
std::exit(0);
ImGui::SameLine();
ImGui::SetCursorPosX(160);
if (ImGui::Button("No", ImVec2(100, 20)))
ImGui::CloseCurrentPopup();
ImGui::TextUnformatted(Message);
ImGui::NewLine();
confirmButtons("Yes", "No", [] { std::exit(0); }, [] { ImGui::CloseCurrentPopup(); });
ImGui::EndPopup();
}
if (ImGui::BeginPopupModal("Load File with Loader Script", nullptr, ImGuiWindowFlags_NoResize)) {
if (ImGui::BeginPopupModal("Load File with Loader Script", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) {
constexpr auto Message = "Load a file using a Python loader script.";
ImGui::NewLine();
if (ImGui::BeginChild("##scrolling", ImVec2(500, 20))) {
ImGui::SetCursorPosX(10);
ImGui::TextWrapped("%s", Message);
ImGui::EndChild();
}
ImGui::SetCursorPosX(10);
ImGui::TextWrapped(Message);
ImGui::NewLine();
ImGui::InputText("##nolabel", this->m_loaderScriptScriptPath.data(), this->m_loaderScriptScriptPath.length(), ImGuiInputTextFlags_ReadOnly);
@ -182,22 +170,23 @@ namespace hex {
ImGui::NewLine();
ImGui::SetCursorPosX(40);
if (ImGui::Button("Load", ImVec2(100, 20))) {
if (!this->m_loaderScriptScriptPath.empty() && !this->m_loaderScriptFilePath.empty()) {
this->openFile(this->m_loaderScriptFilePath);
LoaderScript::setFilePath(this->m_loaderScriptFilePath);
LoaderScript::setDataProvider(this->m_dataProvider);
LoaderScript::processFile(this->m_loaderScriptScriptPath);
confirmButtons("Load", "Cancel",
[this] {
if (!this->m_loaderScriptScriptPath.empty() && !this->m_loaderScriptFilePath.empty()) {
this->openFile(this->m_loaderScriptFilePath);
LoaderScript::setFilePath(this->m_loaderScriptFilePath);
LoaderScript::setDataProvider(this->m_dataProvider);
LoaderScript::processFile(this->m_loaderScriptScriptPath);
ImGui::CloseCurrentPopup();
}
},
[] {
ImGui::CloseCurrentPopup();
}
}
ImGui::SameLine();
ImGui::SetCursorPosX(160);
if (ImGui::Button("Cancel", ImVec2(100, 20))) {
ImGui::CloseCurrentPopup();
}
);
ImGui::EndPopup();
}

View File

@ -1,11 +1,14 @@
#include "hex.hpp"
#include "window.hpp"
#include <iostream>
#include <numeric>
#include "imgui.h"
#include "imgui_internal.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include "imgui_freetype.h"
#include <glad/glad.h>
#include <GLFW/glfw3.h>
@ -21,36 +24,18 @@ namespace hex {
void ImHexSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler *handler, void *, const char* line) {
auto *window = reinterpret_cast<Window *>(handler->UserData);
float scale;
if (sscanf(line, "Scale=%f", &scale) == 1) { window->m_globalScale = scale; }
else if (sscanf(line, "FontScale=%f", &scale) == 1) { window->m_fontScale = scale; }
else {
for (auto &view : window->m_views) {
std::string format = view->getName() + "=%d";
sscanf(line, format.c_str(), &view->getWindowOpenState());
}
for (auto &view : window->m_views) {
std::string format = view->getName() + "=%d";
sscanf(line, format.c_str(), &view->getWindowOpenState());
}
}
void ImHexSettingsHandler_ApplyAll(ImGuiContext *ctx, ImGuiSettingsHandler *handler) {
auto *window = reinterpret_cast<Window *>(handler->UserData);
auto &style = ImGui::GetStyle();
auto &io = ImGui::GetIO();
if (window->m_globalScale != 0.0f)
style.ScaleAllSizes(window->m_globalScale);
if (window->m_fontScale != 0.0f)
io.FontGlobalScale = window->m_fontScale;
}
void ImHexSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf) {
auto *window = reinterpret_cast<Window *>(handler->UserData);
buf->reserve(buf->size() + 0x20); // Ballpark reserve
buf->appendf("[%s][General]\n", handler->TypeName);
buf->appendf("Scale=%.1f\n", window->m_globalScale);
buf->appendf("FontScale=%.1f\n", window->m_fontScale);
for (auto &view : window->m_views) {
buf->appendf("%s=%d\n", view->getName().c_str(), view->getWindowOpenState());
@ -99,6 +84,33 @@ namespace hex {
}
}
bool Window::setFont(const std::filesystem::path &path) {
if (!std::filesystem::exists(path))
return false;
auto &io = ImGui::GetIO();
// If we have a custom font, then rescaling is unnecessary and will make it blurry
io.FontGlobalScale = 1.0f;
// Load font data & build atlas
std::uint8_t *px;
int w, h;
io.Fonts->AddFontFromFileTTF(path.string().c_str(), std::floor(14.0f * this->m_fontScale)); // Needs conversion to char for Windows
ImGuiFreeType::BuildFontAtlas(io.Fonts, ImGuiFreeType::Monochrome);
io.Fonts->GetTexDataAsRGBA32(&px, &w, &h);
// Create new font atlas
GLuint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA8, GL_UNSIGNED_INT, px);
io.Fonts->SetTexID(reinterpret_cast<ImTextureID>(tex));
return true;
}
void Window::frameBegin() {
glfwPollEvents();
@ -206,12 +218,20 @@ namespace hex {
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
if (auto *monitor = glfwGetPrimaryMonitor(); monitor) {
float xscale, yscale;
glfwGetMonitorContentScale(monitor, &xscale, &yscale);
// In case the horizontal and vertical scale are different, fall back on the average
this->m_globalScale = this->m_fontScale = std::midpoint(xscale, yscale);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
this->m_window = glfwCreateWindow(1280, 720, "ImHex", nullptr, nullptr);
this->m_window = glfwCreateWindow(1280 * this->m_globalScale, 720 * this->m_globalScale, "ImHex", nullptr, nullptr);
if (this->m_window == nullptr)
@ -252,6 +272,29 @@ namespace hex {
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable | ImGuiConfigFlags_ViewportsEnable;
io.ConfigViewportsNoTaskBarIcon = true;
if (this->m_globalScale != 0.0f)
style.ScaleAllSizes(this->m_globalScale);
#ifdef __MINGW32__
std::filesystem::path resourcePath = std::filesystem::path(mainArgv[0]).parent_path();
#elif defined(__linux__)
std::filesystem::path resourcePath = "/usr/share/ImHex";
#else
std::filesystem::path resourcePath = "";
# warning "Unsupported OS for custom font support"
#endif
if (!resourcePath.empty() && this->setFont(resourcePath / "font.ttf"))
;
else if ((this->m_fontScale != 0.0f) && (this->m_fontScale != 1.0f)) {
io.Fonts->Clear();
ImFontConfig cfg;
cfg.OversampleH = cfg.OversampleV = 1, cfg.PixelSnapH = true;
cfg.SizePixels = 13.0f * this->m_fontScale;
io.Fonts->AddFontDefault(&cfg);
}
style.WindowMenuButtonPosition = ImGuiDir_None;
style.IndentSpacing = 10.0F;
@ -261,7 +304,6 @@ namespace hex {
handler.TypeHash = ImHashStr("ImHex");
handler.ReadOpenFn = ImHexSettingsHandler_ReadOpenFn;
handler.ReadLineFn = ImHexSettingsHandler_ReadLine;
handler.ApplyAllFn = ImHexSettingsHandler_ApplyAll;
handler.WriteAllFn = ImHexSettingsHandler_WriteAll;
handler.UserData = this;
ctx->SettingsHandlers.push_back(handler);