HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
initialize.hpp
1// Copyright Take Vos 2023.
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
4
5#pragma once
6
7#include "terminate.hpp"
8#if HI_OPERATING_SYSTEM == HI_OS_WINDOWS
9#include "console_win32.hpp"
10#endif
11#include "debugger_intf.hpp"
12#include <atomic>
13#include <chrono>
14#include <thread>
15#include <cstdint>
16#include <cstddef>
17
22hi_export_module(hikogui.utility.initialize);
23
24hi_export namespace hi {
25inline namespace v1 {
26namespace detail {
27
28enum class initialize_state_type {
29 uninitialized,
30 running,
31 finished,
32};
33
34inline thread_local uint16_t initialize_thread_id_dummy;
35
39[[nodiscard]] inline uintptr_t initialize_thread_id() noexcept
40{
41 // The following is guaranteed:
42 // - 0: An address can never be a nullptr.
43 // - 1: initialize_thread_id_dummy is a uint16_t which is aligned to a multiple of two.
44 return std::bit_cast<uintptr_t>(std::addressof(initialize_thread_id_dummy));
45}
46
47inline std::atomic<uintptr_t> initialize_state = 0;
48
49}
50
58inline void initialize() noexcept
59{
60 using namespace std::literals;
61
62 uintptr_t expected = 0;
63 if (detail::initialize_state.compare_exchange_strong(expected, detail::initialize_thread_id(), std::memory_order::acquire)) {
64 // Make sure stdin, stdout, stderr are attached to a console and that
65 // std::print() works properly.
67
68 // Install the terminate handle to make pretty error messages for
69 // end users.
70 //old_terminate_handler = std::set_terminate(hi::terminate_handler);
71
72 // Install the handler for break-points and other traps.
73 // Which will optionally start the just-in-time debugger, or call
74 // std::terminate() with an appropriate error.
75 //enable_debugger();
76
77 // Mark initialization as "finished".
78 detail::initialize_state.store(1, std::memory_order::release);
79
80 } else if (expected == detail::initialize_thread_id()) {
81 set_debug_message("hi::initialize() re-enterred from same thread.");
83
84 } else {
85 // We can not use std::mutex before main().
86 // Wait until initialization on the other thread is finished.
87 while (detail::initialize_state.load(std::memory_order::acquire) != 1) {
89 }
90 }
91}
92
93} // namespace v1
94}
Utilities for throwing exceptions and terminating the application.
The HikoGUI namespace.
Definition array_generic.hpp:21
The HikoGUI API version 1.
Definition array_generic.hpp:22
void start_console() noexcept
Start the console.
Definition console_win32.hpp:21
void initialize() noexcept
Initialize base functionality of HikoGUI.
Definition initialize.hpp:58
constexpr Out load(In const *src) noexcept
Unaligned Load of a numeric value from an array.
Definition endian.hpp:80
T addressof(T... args)
T sleep_for(T... args)
T terminate(T... args)