diff --git a/cfg/language.ini b/cfg/language.ini index bf1f8a06..3d14720a 100644 --- a/cfg/language.ini +++ b/cfg/language.ini @@ -323,7 +323,7 @@ LANG_0321 = Save two models, empty worldspawn and target model.\n LANG_0322 = Remove all unused map data #1.\n LANG_0323 = Copy temporary model to worldspawn.\n LANG_0324 = Remove temporary func_wall.\n -LANG_0325 = Validate model...\n +LANG_0325 = Move model to zero origin\n LANG_0326 = Remove unused wad files.\n LANG_0327 = Remove all unused map data #2.\n LANG_0328 = Regenerated hulls 1-3 on model {}\n @@ -641,12 +641,12 @@ LANG_0641 = PRESS ME TO DECAL LANG_0642 = TEST VIS DATA[CLIPNODES] LANG_0643 = MARK ALL VISIBLED CLIPNODES FACES FROM CAMERA POS LANG_0644 = TEST PVS VIS DATA -LANG_0645 = TEST VIS DATA[HIGHFACES] +LANG_0645 = TEST VIS DATA[FACES] LANG_0646 = MARK ALL VISIBLED AND INVISIBLED FACES FROM CAMERA POS LANG_0647 = Model 1 ##mdl1 LANG_0648 = Model 2 ##mdl1 -LANG_0649 = Swap two models -LANG_0650 = SWAP TWO MODELS, USEFUL FOR EDITING WITH SAVE CRC +LANG_0649 = Swap models +LANG_0650 = Swap two models in map.\nEnter model id above. LANG_0651 = Texture browser LANG_0652 = Internal LANG_0653 = Internal Names @@ -1045,7 +1045,7 @@ LANG_1047 = Bad face index\n LANG_1048 = ERROR: Unexpected end of class header (line {}) in FGD {}\n LANG_1049 = No map selecetd\n LANG_1050 = No face selected\n -LANG_1051 = Can't validate map\n +LANG_1051 = Validate failed! Map has errors!\n LANG_1052 = Import entities from: {}\n LANG_1053 = Writing {}\n LANG_1054 = Execute 'duplicate' for {} models.\n diff --git a/cfg/language_ru.ini b/cfg/language_ru.ini index 1882e8c9..ce8ab364 100644 --- a/cfg/language_ru.ini +++ b/cfg/language_ru.ini @@ -323,7 +323,7 @@ LANG_0321 = Сохраняются 2 модели, пустой worldspawn и ц LANG_0322 = Удаляются все неиспользуемые данные карты #1.\n LANG_0323 = Временная модель копируется на worldspawn.\n LANG_0324 = Удаляется временный func_wall.\n -LANG_0325 = Валидизируется модель...\n +LANG_0325 = Перемещение модели в нулевые координаты\n LANG_0326 = Удаляются неиспользуемые WAD-файлы.\n LANG_0327 = Удаляются все неиспользуемые данные карты #2.\n LANG_0328 = Хуллы 1-3 модели {} регенерированы\n @@ -641,12 +641,12 @@ LANG_0641 = Тест деколей (WIP) LANG_0642 = Тест VIS-данных [клипноды] LANG_0643 = Пометить все клипноды, видимые с текущей точки обзора камеры. LANG_0644 = Тест VIS-данных PVS -LANG_0645 = Тест VIS-данных [верхние фейсы] +LANG_0645 = Тест VIS-данных [фейсы] LANG_0646 = Пометить все фейсы, видимые и не видимые с текущей точки обзора камеры. LANG_0647 = Модель 1 ##mdl1 LANG_0648 = Модель 2 ##mdl1 -LANG_0649 = Свопнуть 2 модели -LANG_0650 = Своп двух моделей, в целях правки с сохранением CRC +LANG_0649 = Поменять местами +LANG_0650 = Поменять местами две модели в карте\nВведите номера моделей выше. LANG_0651 = Браузер текстур LANG_0652 = Вшитые LANG_0653 = Используемые @@ -1045,7 +1045,7 @@ LANG_1047 = Некорректный индекс фейса\n LANG_1048 = ОШИБКА: неожиданный конец заголовка класса (строка {}) в FGD {}\n LANG_1049 = Карта не выбрана\n LANG_1050 = Фейсы не выбраны\n -LANG_1051 = Невозможно валидизировать карту\n +LANG_1051 = Проверка карты провалена! Обнаружены ошибки.\n LANG_1052 = Импорт сущностей из: {}\n LANG_1053 = Сохранение {}\n LANG_1054 = Применяется 'дублирование' к {} моделям.\n @@ -1064,6 +1064,7 @@ LANG_1069 = Клипноды LANG_1070 = Текстуры в WAD-файлах LANG_1071 = Вшитые текстуры [HL1] LANG_1072 = Вшитые текстуры [QUAKE/HL1+XASH] +LANG_1073 = Вставить LANG_1074 = Ctrl+V LANG_1075 = Вставить в исходном месте LANG_1076 = Экспорт браш-модели diff --git a/fmt/.github/workflows/lint.yml b/fmt/.github/workflows/lint.yml new file mode 100644 index 00000000..b906fac2 --- /dev/null +++ b/fmt/.github/workflows/lint.yml @@ -0,0 +1,26 @@ +name: lint + +on: + pull_request: + paths: + - '**.h' + - '**.cc' + +permissions: + contents: read + +jobs: + format_code: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install clang-format + uses: aminya/setup-cpp@v1 + with: + clangformat: 17.0.5 + + - name: Run clang-format + run: | + find include src -name '*.h' -o -name '*.cc' | xargs clang-format -i -style=file -fallback-style=none + git diff --exit-code diff --git a/fmt/CMakeLists.txt b/fmt/CMakeLists.txt index 639c44f4..4b928ae3 100644 --- a/fmt/CMakeLists.txt +++ b/fmt/CMakeLists.txt @@ -283,7 +283,7 @@ if (FMT_OS) endif () add_module_library(fmt src/fmt.cc FALLBACK - ${FMT_SOURCES} ${FMT_HEADERS} README.rst ChangeLog.md + ${FMT_SOURCES} ${FMT_HEADERS} README.md ChangeLog.md IF FMT_MODULE) add_library(fmt::fmt ALIAS fmt) if (FMT_MODULE) @@ -448,6 +448,6 @@ if (FMT_MASTER_PROJECT AND EXISTS ${gitignore}) set(CPACK_SOURCE_IGNORE_FILES ${ignored_files}) set(CPACK_SOURCE_PACKAGE_FILE_NAME fmt-${FMT_VERSION}) set(CPACK_PACKAGE_NAME fmt) - set(CPACK_RESOURCE_FILE_README ${PROJECT_SOURCE_DIR}/README.rst) + set(CPACK_RESOURCE_FILE_README ${PROJECT_SOURCE_DIR}/README.md) include(CPack) endif () diff --git a/fmt/ChangeLog.rst b/fmt/ChangeLog.rst deleted file mode 100644 index 4ebc5c73..00000000 --- a/fmt/ChangeLog.rst +++ /dev/null @@ -1,5255 +0,0 @@ -9.1.0 - 2022-08-27 ------------------- - -* ``fmt::formatted_size`` now works at compile time - (`#3026 `_). For example - (`godbolt `__): - - .. code:: c++ - - #include - - int main() { - using namespace fmt::literals; - constexpr size_t n = fmt::formatted_size("{}"_cf, 42); - fmt::print("{}\n", n); // prints 2 - } - - Thanks `@marksantaniello (Mark Santaniello) - `_. - -* Fixed handling of invalid UTF-8 - (`#3038 `_, - `#3044 `_, - `#3056 `_). - Thanks `@phprus (Vladislav Shchapov) `_ and - `@skeeto (Christopher Wellons) `_. - -* Improved Unicode support in ``ostream`` overloads of ``print`` - (`#2994 `_, - `#3001 `_, - `#3025 `_). - Thanks `@dimztimz (Dimitrij Mijoski) `_. - -* Fixed handling of the sign specifier in localized formatting on systems with - 32-bit ``wchar_t`` (`#3041 `_). - -* Added support for wide streams to ``fmt::streamed`` - (`#2994 `_). - Thanks `@phprus (Vladislav Shchapov) `_. - -* Added the ``n`` specifier that disables the output of delimiters when - formatting ranges (`#2981 `_, - `#2983 `_). - For example (`godbolt `__): - - .. code:: c++ - - #include - #include - - int main() { - auto v = std::vector{1, 2, 3}; - fmt::print("{:n}\n", v); // prints 1, 2, 3 - } - - Thanks `@BRevzin (Barry Revzin) `_. - -* Worked around problematic ``std::string_view`` constructors introduced in - C++23 (`#3030 `_, - `#3050 `_). - Thanks `@strega-nil-ms (nicole mazzuca) `_. - -* Improve handling (exclusion) of recursive ranges - (`#2968 `_, - `#2974 `_). - Thanks `@Dani-Hub (Daniel Krügler) `_. - -* Improved error reporting in format string compilation - (`#3055 `_). - -* Improved the implementation of - `Dragonbox `_, the algorithm used for - the default floating-point formatting - (`#2984 `_). - Thanks `@jk-jeon (Junekey Jeon) `_. - -* Fixed issues with floating-point formatting on exotic platforms. - -* Improved the implementation of chrono formatting - (`#3010 `_). - Thanks `@phprus (Vladislav Shchapov) `_. - -* Improved documentation - (`#2966 `_, - `#3009 `_, - `#3020 `_, - `#3037 `_). - Thanks `@mwinterb `_, - `@jcelerier (Jean-Michaël Celerier) `_ - and `@remiburtin (Rémi Burtin) `_. - -* Improved build configuration - (`#2991 `_, - `#2995 `_, - `#3004 `_, - `#3007 `_, - `#3040 `_). - Thanks `@dimztimz (Dimitrij Mijoski) `_ and - `@hwhsu1231 (Haowei Hsu) `_. - -* Fixed various warnings and compilation issues - (`#2969 `_, - `#2971 `_, - `#2975 `_, - `#2982 `_, - `#2985 `_, - `#2988 `_, - `#3000 `_, - `#3006 `_, - `#3014 `_, - `#3015 `_, - `#3021 `_, - `#3023 `_, - `#3024 `_, - `#3029 `_, - `#3043 `_, - `#3052 `_, - `#3053 `_, - `#3054 `_). - Thanks `@h-friederich (Hannes Friederich) `_, - `@dimztimz (Dimitrij Mijoski) `_, - `@olupton (Olli Lupton) `_, - `@bernhardmgruber (Bernhard Manfred Gruber) - `_, - `@phprus (Vladislav Shchapov) `_. - -9.0.0 - 2022-07-04 ------------------- - -* Switched to the internal floating point formatter for all decimal presentation - formats. In particular this results in consistent rounding on all platforms - and removing the ``s[n]printf`` fallback for decimal FP formatting. - -* Compile-time floating point formatting no longer requires the header-only - mode. For example (`godbolt `__): - - .. code:: c++ - - #include - #include - - consteval auto compile_time_dtoa(double value) -> std::array { - auto result = std::array(); - fmt::format_to(result.data(), FMT_COMPILE("{}"), value); - return result; - } - - constexpr auto answer = compile_time_dtoa(0.42); - - works with the default settings. - -* Improved the implementation of - `Dragonbox `_, the algorithm used for - the default floating-point formatting - (`#2713 `_, - `#2750 `_). - Thanks `@jk-jeon (Junekey Jeon) `_. - -* Made ``fmt::to_string`` work with ``__float128``. This uses the internal - FP formatter and works even on system without ``__float128`` support in - ``[s]printf``. - -* Disabled automatic ``std::ostream`` insertion operator (``operator<<``) - discovery when ``fmt/ostream.h`` is included to prevent ODR violations. - You can get the old behavior by defining ``FMT_DEPRECATED_OSTREAM`` but this - will be removed in the next major release. Use ``fmt::streamed`` or - ``fmt::ostream_formatter`` to enable formatting via ``std::ostream`` instead. - -* Added ``fmt::ostream_formatter`` that can be used to write ``formatter`` - specializations that perform formatting via ``std::ostream``. - For example (`godbolt `__): - - .. code:: c++ - - #include - - struct date { - int year, month, day; - - friend std::ostream& operator<<(std::ostream& os, const date& d) { - return os << d.year << '-' << d.month << '-' << d.day; - } - }; - - template <> struct fmt::formatter : ostream_formatter {}; - - std::string s = fmt::format("The date is {}", date{2012, 12, 9}); - // s == "The date is 2012-12-9" - -* Added the ``fmt::streamed`` function that takes an object and formats it - via ``std::ostream``. - For example (`godbolt `__): - - .. code:: c++ - - #include - #include - - int main() { - fmt::print("Current thread id: {}\n", - fmt::streamed(std::this_thread::get_id())); - } - - Note that ``fmt/std.h`` provides a ``formatter`` specialization for - ``std::thread::id`` so you don't need to format it via ``std::ostream``. - -* Deprecated implicit conversions of unscoped enums to integers for consistency - with scoped enums. - -* Added an argument-dependent lookup based ``format_as`` extension API to - simplify formatting of enums. - -* Added experimental ``std::variant`` formatting support - (`#2941 `_). - For example (`godbolt `__): - - .. code:: c++ - - #include - #include - - int main() { - auto v = std::variant(42); - fmt::print("{}\n", v); - } - - prints:: - - variant(42) - - Thanks `@jehelset `_. - -* Added experimental ``std::filesystem::path`` formatting support - (`#2865 `_, - `#2902 `_, - `#2917 `_, - `#2918 `_). - For example (`godbolt `__): - - .. code:: c++ - - #include - #include - - int main() { - fmt::print("There is no place like {}.", std::filesystem::path("/home")); - } - - prints:: - - There is no place like "/home". - - Thanks `@phprus (Vladislav Shchapov) `_. - -* Added a ``std::thread::id`` formatter to ``fmt/std.h``. - For example (`godbolt `__): - - .. code:: c++ - - #include - #include - - int main() { - fmt::print("Current thread id: {}\n", std::this_thread::get_id()); - } - -* Added ``fmt::styled`` that applies a text style to an individual argument - (`#2793 `_). - For example (`godbolt `__): - - .. code:: c++ - - #include - #include - - int main() { - auto now = std::chrono::system_clock::now(); - fmt::print( - "[{}] {}: {}\n", - fmt::styled(now, fmt::emphasis::bold), - fmt::styled("error", fg(fmt::color::red)), - "something went wrong"); - } - - prints - - .. image:: https://user-images.githubusercontent.com/576385/ - 175071215-12809244-dab0-4005-96d8-7cd911c964d5.png - - Thanks `@rbrugo (Riccardo Brugo) `_. - -* Made ``fmt::print`` overload for text styles correctly handle UTF-8 - (`#2681 `_, - `#2701 `_). - Thanks `@AlexGuteniev (Alex Guteniev) `_. - -* Fixed Unicode handling when writing to an ostream. - -* Added support for nested specifiers to range formatting - (`#2673 `_). - For example (`godbolt `__): - - .. code:: c++ - - #include - #include - - int main() { - fmt::print("{::#x}\n", std::vector{10, 20, 30}); - } - - prints ``[0xa, 0x14, 0x1e]``. - - Thanks `@BRevzin (Barry Revzin) `_. - -* Implemented escaping of wide strings in ranges - (`#2904 `_). - Thanks `@phprus (Vladislav Shchapov) `_. - -* Added support for ranges with ``begin`` / ``end`` found via the - argument-dependent lookup - (`#2807 `_). - Thanks `@rbrugo (Riccardo Brugo) `_. - -* Fixed formatting of certain kinds of ranges of ranges - (`#2787 `_). - Thanks `@BRevzin (Barry Revzin) `_. - -* Fixed handling of maps with element types other than ``std::pair`` - (`#2944 `_). - Thanks `@BrukerJWD (Jonathan W) `_. - -* Made tuple formatter enabled only if elements are formattable - (`#2939 `_, - `#2940 `_). - Thanks `@jehelset `_. - -* Made ``fmt::join`` compatible with format string compilation - (`#2719 `_, - `#2720 `_). - Thanks `@phprus (Vladislav Shchapov) `_. - -* Made compile-time checks work with named arguments of custom types and - ``std::ostream`` ``print`` overloads - (`#2816 `_, - `#2817 `_, - `#2819 `_). - Thanks `@timsong-cpp `_. - -* Removed ``make_args_checked`` because it is no longer needed for compile-time - checks (`#2760 `_). - Thanks `@phprus (Vladislav Shchapov) `_. - -* Removed the following deprecated APIs: ``_format``, ``arg_join``, - the ``format_to`` overload that takes a memory buffer, - ``[v]fprintf`` that takes an ``ostream``. - -* Removed the deprecated implicit conversion of ``[const] signed char*`` and - ``[const] unsigned char*`` to C strings. - -* Removed the deprecated ``fmt/locale.h``. - -* Replaced the deprecated ``fileno()`` with ``descriptor()`` in - ``buffered_file``. - -* Moved ``to_string_view`` to the ``detail`` namespace since it's an - implementation detail. - -* Made access mode of a created file consistent with ``fopen`` by setting - ``S_IWGRP`` and ``S_IWOTH`` - (`#2733 `_). - Thanks `@arogge (Andreas Rogge) `_. - -* Removed a redundant buffer resize when formatting to ``std::ostream`` - (`#2842 `_, - `#2843 `_). - Thanks `@jcelerier (Jean-Michaël Celerier) `_. - -* Made precision computation for strings consistent with width - (`#2888 `_). - -* Fixed handling of locale separators in floating point formatting - (`#2830 `_). - -* Made sign specifiers work with ``__int128_t`` - (`#2773 `_). - -* Improved support for systems such as CHERI with extra data stored in pointers - (`#2932 `_). - Thanks `@davidchisnall (David Chisnall) `_. - -* Improved documentation - (`#2706 `_, - `#2712 `_, - `#2789 `_, - `#2803 `_, - `#2805 `_, - `#2815 `_, - `#2924 `_). - Thanks `@BRevzin (Barry Revzin) `_, - `@Pokechu22 `_, - `@setoye (Alta) `_, - `@rtobar `_, - `@rbrugo (Riccardo Brugo) `_, - `@anoonD (cre) `_, - `@leha-bot (Alex) `_. - -* Improved build configuration - (`#2766 `_, - `#2772 `_, - `#2836 `_, - `#2852 `_, - `#2907 `_, - `#2913 `_, - `#2914 `_). - Thanks `@kambala-decapitator (Andrey Filipenkov) - `_, - `@mattiasljungstrom (Mattias Ljungström) - `_, - `@kieselnb (Nick Kiesel) `_, - `@nathannaveen `_, - `@Vertexwahn `_. - -* Fixed various warnings and compilation issues - (`#2408 `_, - `#2507 `_, - `#2697 `_, - `#2715 `_, - `#2717 `_, - `#2722 `_, - `#2724 `_, - `#2725 `_, - `#2726 `_, - `#2728 `_, - `#2732 `_, - `#2738 `_, - `#2742 `_, - `#2744 `_, - `#2745 `_, - `#2746 `_, - `#2754 `_, - `#2755 `_, - `#2757 `_, - `#2758 `_, - `#2761 `_, - `#2762 `_, - `#2763 `_, - `#2765 `_, - `#2769 `_, - `#2770 `_, - `#2771 `_, - `#2777 `_, - `#2779 `_, - `#2782 `_, - `#2783 `_, - `#2794 `_, - `#2796 `_, - `#2797 `_, - `#2801 `_, - `#2802 `_, - `#2808 `_, - `#2818 `_, - `#2819 `_, - `#2829 `_, - `#2835 `_, - `#2848 `_, - `#2860 `_, - `#2861 `_, - `#2882 `_, - `#2886 `_, - `#2891 `_, - `#2892 `_, - `#2895 `_, - `#2896 `_, - `#2903 `_, - `#2906 `_, - `#2908 `_, - `#2909 `_, - `#2920 `_, - `#2922 `_, - `#2927 `_, - `#2929 `_, - `#2936 `_, - `#2937 `_, - `#2938 `_, - `#2951 `_, - `#2954 `_, - `#2957 `_, - `#2958 `_, - `#2960 `_). - Thanks `@matrackif `_ - `@Tobi823 (Tobias Hellmann) `_, - `@ivan-volnov (Ivan Volnov) `_, - `@VasiliPupkin256 `_, - `@federico-busato (Federico) `_, - `@barcharcraz (Charlie Barto) `_, - `@jk-jeon (Junekey Jeon) `_, - `@HazardyKnusperkeks (Björn Schäpers) - `_, - `@dalboris (Boris Dalstein) `_, - `@seanm (Sean McBride) `_, - `@gsjaardema (Greg Sjaardema) `_, - `@timsong-cpp `_, - `@seanm (Sean McBride) `_, - `@frithrah `_, - `@chronoxor (Ivan Shynkarenka) `_, - `@Agga `_, - `@madmaxoft (Mattes D) `_, - `@JurajX (Juraj) `_, - `@phprus (Vladislav Shchapov) `_, - `@Dani-Hub (Daniel Krügler) `_. - -8.1.1 - 2022-01-06 ------------------- - -* Restored ABI compatibility with version 8.0.x - (`#2695 `_, - `#2696 `_). - Thanks `@saraedum (Julian Rüth) `_. - -* Fixed chrono formatting on big endian systems - (`#2698 `_, - `#2699 `_). - Thanks `@phprus (Vladislav Shchapov) `_ and - `@xvitaly (Vitaly Zaitsev) `_. - -* Fixed a linkage error with mingw - (`#2691 `_, - `#2692 `_). - Thanks `@rbberger (Richard Berger) `_. - -8.1.0 - 2022-01-02 ------------------- - -* Optimized chrono formatting - (`#2500 `_, - `#2537 `_, - `#2541 `_, - `#2544 `_, - `#2550 `_, - `#2551 `_, - `#2576 `_, - `#2577 `_, - `#2586 `_, - `#2591 `_, - `#2594 `_, - `#2602 `_, - `#2617 `_, - `#2628 `_, - `#2633 `_, - `#2670 `_, - `#2671 `_). - - Processing of some specifiers such as ``%z`` and ``%Y`` is now up to 10-20 - times faster, for example on GCC 11 with libstdc++:: - - ---------------------------------------------------------------------------- - Benchmark Before After - ---------------------------------------------------------------------------- - FMTFormatter_z 261 ns 26.3 ns - FMTFormatterCompile_z 246 ns 11.6 ns - FMTFormatter_Y 263 ns 26.1 ns - FMTFormatterCompile_Y 244 ns 10.5 ns - ---------------------------------------------------------------------------- - - Thanks `@phprus (Vladislav Shchapov) `_ and - `@toughengineer (Pavel Novikov) `_. - -* Implemented subsecond formatting for chrono durations - (`#2623 `_). - For example (`godbolt `__): - - .. code:: c++ - - #include - - int main() { - fmt::print("{:%S}", std::chrono::milliseconds(1234)); - } - - prints "01.234". - - Thanks `@matrackif `_. - -* Fixed handling of precision 0 when formatting chrono durations - (`#2587 `_, - `#2588 `_). - Thanks `@lukester1975 `_. - -* Fixed an overflow on invalid inputs in the ``tm`` formatter - (`#2564 `_). - Thanks `@phprus (Vladislav Shchapov) `_. - -* Added ``fmt::group_digits`` that formats integers with a non-localized digit - separator (comma) for groups of three digits. - For example (`godbolt `__): - - .. code:: c++ - - #include - - int main() { - fmt::print("{} dollars", fmt::group_digits(1000000)); - } - - prints "1,000,000 dollars". - -* Added support for faint, conceal, reverse and blink text styles - (`#2394 `_): - - https://user-images.githubusercontent.com/576385/147710227-c68f5317-f8fa-42c3-9123-7c4ba3c398cb.mp4 - - Thanks `@benit8 (Benoît Lormeau) `_ and - `@data-man (Dmitry Atamanov) `_. - -* Added experimental support for compile-time floating point formatting - (`#2426 `_, - `#2470 `_). - It is currently limited to the header-only mode. - Thanks `@alexezeder (Alexey Ochapov) `_. - -* Added UDL-based named argument support to compile-time format string checks - (`#2640 `_, - `#2649 `_). - For example (`godbolt `__): - - .. code:: c++ - - #include - - int main() { - using namespace fmt::literals; - fmt::print("{answer:s}", "answer"_a=42); - } - - gives a compile-time error on compilers with C++20 ``consteval`` and non-type - template parameter support (gcc 10+) because ``s`` is not a valid format - specifier for an integer. - - Thanks `@alexezeder (Alexey Ochapov) `_. - -* Implemented escaping of string range elements. - For example (`godbolt `__): - - .. code:: c++ - - #include - #include - - int main() { - fmt::print("{}", std::vector{"\naan"}); - } - - is now printed as:: - - ["\naan"] - - instead of:: - - [" - aan"] - -* Added an experimental ``?`` specifier for escaping strings. - (`#2674 `_). - Thanks `@BRevzin (Barry Revzin) `_. - -* Switched to JSON-like representation of maps and sets for consistency with - Python's ``str.format``. - For example (`godbolt `__): - - .. code:: c++ - - #include - #include - - int main() { - fmt::print("{}", std::map{{"answer", 42}}); - } - - is now printed as:: - - {"answer": 42} - -* Extended ``fmt::join`` to support C++20-only ranges - (`#2549 `_). - Thanks `@BRevzin (Barry Revzin) `_. - -* Optimized handling of non-const-iterable ranges and implemented initial - support for non-const-formattable types. - -* Disabled implicit conversions of scoped enums to integers that was - accidentally introduced in earlier versions - (`#1841 `_). - -* Deprecated implicit conversion of ``[const] signed char*`` and - ``[const] unsigned char*`` to C strings. - -* Deprecated ``_format``, a legacy UDL-based format API - (`#2646 `_). - Thanks `@alexezeder (Alexey Ochapov) `_. - -* Marked ``format``, ``formatted_size`` and ``to_string`` as ``[[nodiscard]]`` - (`#2612 `_). - `@0x8000-0000 (Florin Iucha) `_. - -* Added missing diagnostic when trying to format function and member pointers - as well as objects convertible to pointers which is explicitly disallowed - (`#2598 `_, - `#2609 `_, - `#2610 `_). - Thanks `@AlexGuteniev (Alex Guteniev) `_. - -* Optimized writing to a contiguous buffer with ``format_to_n`` - (`#2489 `_). - Thanks `@Roman-Koshelev `_. - -* Optimized writing to non-``char`` buffers - (`#2477 `_). - Thanks `@Roman-Koshelev `_. - -* Decimal point is now localized when using the ``L`` specifier. - -* Improved floating point formatter implementation - (`#2498 `_, - `#2499 `_). - Thanks `@Roman-Koshelev `_. - -* Fixed handling of very large precision in fixed format - (`#2616 `_). - -* Made a table of cached powers used in FP formatting static - (`#2509 `_). - Thanks `@jk-jeon (Junekey Jeon) `_. - -* Resolved a lookup ambiguity with C++20 format-related functions due to ADL - (`#2639 `_, - `#2641 `_). - Thanks `@mkurdej (Marek Kurdej) `_. - -* Removed unnecessary inline namespace qualification - (`#2642 `_, - `#2643 `_). - Thanks `@mkurdej (Marek Kurdej) `_. - -* Implemented argument forwarding in ``format_to_n`` - (`#2462 `_, - `#2463 `_). - Thanks `@owent (WenTao Ou) `_. - -* Fixed handling of implicit conversions in ``fmt::to_string`` and format string - compilation (`#2565 `_). - -* Changed the default access mode of files created by ``fmt::output_file`` to - ``-rw-r--r--`` for consistency with ``fopen`` - (`#2530 `_). - -* Make ``fmt::ostream::flush`` public - (`#2435 `_). - -* Improved C++14/17 attribute detection - (`#2615 `_). - Thanks `@AlexGuteniev (Alex Guteniev) `_. - -* Improved ``consteval`` detection for MSVC - (`#2559 `_). - Thanks `@DanielaE (Daniela Engert) `_. - -* Improved documentation - (`#2406 `_, - `#2446 `_, - `#2493 `_, - `#2513 `_, - `#2515 `_, - `#2522 `_, - `#2562 `_, - `#2575 `_, - `#2606 `_, - `#2620 `_, - `#2676 `_). - Thanks `@sobolevn (Nikita Sobolev) `_, - `@UnePierre (Max FERGER) `_, - `@zhsj `_, - `@phprus (Vladislav Shchapov) `_, - `@ericcurtin (Eric Curtin) `_, - `@Lounarok `_. - -* Improved fuzzers and added a fuzzer for chrono timepoint formatting - (`#2461 `_, - `#2469 `_). - `@pauldreik (Paul Dreik) `_, - -* Added the ``FMT_SYSTEM_HEADERS`` CMake option setting which marks {fmt}'s - headers as system. It can be used to suppress warnings - (`#2644 `_, - `#2651 `_). - Thanks `@alexezeder (Alexey Ochapov) `_. - -* Added the Bazel build system support - (`#2505 `_, - `#2516 `_). - Thanks `@Vertexwahn `_. - -* Improved build configuration and tests - (`#2437 `_, - `#2558 `_, - `#2648 `_, - `#2650 `_, - `#2663 `_, - `#2677 `_). - Thanks `@DanielaE (Daniela Engert) `_, - `@alexezeder (Alexey Ochapov) `_, - `@phprus (Vladislav Shchapov) `_. - -* Fixed various warnings and compilation issues - (`#2353 `_, - `#2356 `_, - `#2399 `_, - `#2408 `_, - `#2414 `_, - `#2427 `_, - `#2432 `_, - `#2442 `_, - `#2434 `_, - `#2439 `_, - `#2447 `_, - `#2450 `_, - `#2455 `_, - `#2465 `_, - `#2472 `_, - `#2474 `_, - `#2476 `_, - `#2478 `_, - `#2479 `_, - `#2481 `_, - `#2482 `_, - `#2483 `_, - `#2490 `_, - `#2491 `_, - `#2510 `_, - `#2518 `_, - `#2528 `_, - `#2529 `_, - `#2539 `_, - `#2540 `_, - `#2545 `_, - `#2555 `_, - `#2557 `_, - `#2570 `_, - `#2573 `_, - `#2582 `_, - `#2605 `_, - `#2611 `_, - `#2647 `_, - `#2627 `_, - `#2630 `_, - `#2635 `_, - `#2638 `_, - `#2653 `_, - `#2654 `_, - `#2661 `_, - `#2664 `_, - `#2684 `_). - Thanks `@DanielaE (Daniela Engert) `_, - `@mwinterb `_, - `@cdacamar (Cameron DaCamara) `_, - `@TrebledJ (Johnathan) `_, - `@bodomartin (brm) `_, - `@cquammen (Cory Quammen) `_, - `@white238 (Chris White) `_, - `@mmarkeloff (Max) `_, - `@palacaze (Pierre-Antoine Lacaze) `_, - `@jcelerier (Jean-Michaël Celerier) `_, - `@mborn-adi (Mathias Born) `_, - `@BrukerJWD (Jonathan W) `_, - `@spyridon97 (Spiros Tsalikis) `_, - `@phprus (Vladislav Shchapov) `_, - `@oliverlee (Oliver Lee) `_, - `@joshessman-llnl (Josh Essman) `_, - `@akohlmey (Axel Kohlmeyer) `_, - `@timkalu `_, - `@olupton (Olli Lupton) `_, - `@Acretock `_, - `@alexezeder (Alexey Ochapov) `_, - `@andrewcorrigan (Andrew Corrigan) `_, - `@lucpelletier `_, - `@HazardyKnusperkeks (Björn Schäpers) - `_. - -8.0.1 - 2021-07-02 ------------------- - -* Fixed the version number in the inline namespace - (`#2374 `_). - -* Added a missing presentation type check for ``std::string`` - (`#2402 `_). - -* Fixed a linkage error when mixing code built with clang and gcc - (`#2377 `_). - -* Fixed documentation issues - (`#2396 `_, - `#2403 `_, - `#2406 `_). - Thanks `@mkurdej (Marek Kurdej) `_. - -* Removed dead code in FP formatter ( - `#2398 `_). - Thanks `@javierhonduco (Javier Honduvilla Coto) - `_. - -* Fixed various warnings and compilation issues - (`#2351 `_, - `#2359 `_, - `#2365 `_, - `#2368 `_, - `#2370 `_, - `#2376 `_, - `#2381 `_, - `#2382 `_, - `#2386 `_, - `#2389 `_, - `#2395 `_, - `#2397 `_, - `#2400 `_, - `#2401 `_, - `#2407 `_). - Thanks `@zx2c4 (Jason A. Donenfeld) `_, - `@AidanSun05 (Aidan Sun) `_, - `@mattiasljungstrom (Mattias Ljungström) - `_, - `@joemmett (Jonathan Emmett) `_, - `@erengy (Eren Okka) `_, - `@patlkli (Patrick Geltinger) `_, - `@gsjaardema (Greg Sjaardema) `_, - `@phprus (Vladislav Shchapov) `_. - -8.0.0 - 2021-06-21 ------------------- - -* Enabled compile-time format string checks by default. - For example (`godbolt `__): - - .. code:: c++ - - #include - - int main() { - fmt::print("{:d}", "I am not a number"); - } - - gives a compile-time error on compilers with C++20 ``consteval`` support - (gcc 10+, clang 11+) because ``d`` is not a valid format specifier for a - string. - - To pass a runtime string wrap it in ``fmt::runtime``: - - .. code:: c++ - - fmt::print(fmt::runtime("{:d}"), "I am not a number"); - -* Added compile-time formatting - (`#2019 `_, - `#2044 `_, - `#2056 `_, - `#2072 `_, - `#2075 `_, - `#2078 `_, - `#2129 `_, - `#2326 `_). - For example (`godbolt `__): - - .. code:: c++ - - #include - - consteval auto compile_time_itoa(int value) -> std::array { - auto result = std::array(); - fmt::format_to(result.data(), FMT_COMPILE("{}"), value); - return result; - } - - constexpr auto answer = compile_time_itoa(42); - - Most of the formatting functionality is available at compile time with a - notable exception of floating-point numbers and pointers. - Thanks `@alexezeder (Alexey Ochapov) `_. - -* Optimized handling of format specifiers during format string compilation. - For example, hexadecimal formatting (``"{:x}"``) is now 3-7x faster than - before when using ``format_to`` with format string compilation and a - stack-allocated buffer (`#1944 `_). - - Before (7.1.3):: - - ---------------------------------------------------------------------------- - Benchmark Time CPU Iterations - ---------------------------------------------------------------------------- - FMTCompileOld/0 15.5 ns 15.5 ns 43302898 - FMTCompileOld/42 16.6 ns 16.6 ns 43278267 - FMTCompileOld/273123 18.7 ns 18.6 ns 37035861 - FMTCompileOld/9223372036854775807 19.4 ns 19.4 ns 35243000 - ---------------------------------------------------------------------------- - - After (8.x):: - - ---------------------------------------------------------------------------- - Benchmark Time CPU Iterations - ---------------------------------------------------------------------------- - FMTCompileNew/0 1.99 ns 1.99 ns 360523686 - FMTCompileNew/42 2.33 ns 2.33 ns 279865664 - FMTCompileNew/273123 3.72 ns 3.71 ns 190230315 - FMTCompileNew/9223372036854775807 5.28 ns 5.26 ns 130711631 - ---------------------------------------------------------------------------- - - It is even faster than ``std::to_chars`` from libc++ compiled with clang on - macOS:: - - ---------------------------------------------------------------------------- - Benchmark Time CPU Iterations - ---------------------------------------------------------------------------- - ToChars/0 4.42 ns 4.41 ns 160196630 - ToChars/42 5.00 ns 4.98 ns 140735201 - ToChars/273123 7.26 ns 7.24 ns 95784130 - ToChars/9223372036854775807 8.77 ns 8.75 ns 75872534 - ---------------------------------------------------------------------------- - - In other cases, especially involving ``std::string`` construction, the - speed up is usually lower because handling format specifiers takes a smaller - fraction of the total time. - -* Added the ``_cf`` user-defined literal to represent a compiled format string. - It can be used instead of the ``FMT_COMPILE`` macro - (`#2043 `_, - `#2242 `_): - - .. code:: c++ - - #include - - using namespace fmt::literals; - auto s = fmt::format(FMT_COMPILE("{}"), 42); // 🙁 not modern - auto s = fmt::format("{}"_cf, 42); // 🙂 modern as hell - - It requires compiler support for class types in non-type template parameters - (a C++20 feature) which is available in GCC 9.3+. - Thanks `@alexezeder (Alexey Ochapov) `_. - -* Format string compilation now requires ``format`` functions of ``formatter`` - specializations for user-defined types to be ``const``: - - .. code:: c++ - - template <> struct fmt::formatter: formatter { - template - auto format(my_type obj, FormatContext& ctx) const { // Note const here. - // ... - } - }; - -* Added UDL-based named argument support to format string compilation - (`#2243 `_, - `#2281 `_). For example: - - .. code:: c++ - - #include - - using namespace fmt::literals; - auto s = fmt::format(FMT_COMPILE("{answer}"), "answer"_a = 42); - - Here the argument named "answer" is resolved at compile time with no - runtime overhead. - Thanks `@alexezeder (Alexey Ochapov) `_. - -* Added format string compilation support to ``fmt::print`` - (`#2280 `_, - `#2304 `_). - Thanks `@alexezeder (Alexey Ochapov) `_. - -* Added initial support for compiling {fmt} as a C++20 module - (`#2235 `_, - `#2240 `_, - `#2260 `_, - `#2282 `_, - `#2283 `_, - `#2288 `_, - `#2298 `_, - `#2306 `_, - `#2307 `_, - `#2309 `_, - `#2318 `_, - `#2324 `_, - `#2332 `_, - `#2340 `_). - Thanks `@DanielaE (Daniela Engert) `_. - -* Made symbols private by default reducing shared library size - (`#2301 `_). For example there was - a ~15% reported reduction on one platform. - Thanks `@sergiud (Sergiu Deitsch) `_. - -* Optimized includes making the result of preprocessing ``fmt/format.h`` - ~20% smaller with libstdc++/C++20 and slightly improving build times - (`#1998 `_). - -* Added support of ranges with non-const ``begin`` / ``end`` - (`#1953 `_). - Thanks `@kitegi (sarah) `_. - -* Added support of ``std::byte`` and other formattable types to ``fmt::join`` - (`#1981 `_, - `#2040 `_, - `#2050 `_, - `#2262 `_). For example: - - .. code:: c++ - - #include - #include - #include - - int main() { - auto bytes = std::vector{std::byte(4), std::byte(2)}; - fmt::print("{}", fmt::join(bytes, "")); - } - - prints "42". - - Thanks `@kamibo (Camille Bordignon) `_. - -* Implemented the default format for ``std::chrono::system_clock`` - (`#2319 `_, - `#2345 `_). For example: - - .. code:: c++ - - #include - - int main() { - fmt::print("{}", std::chrono::system_clock::now()); - } - - prints "2021-06-18 15:22:00" (the output depends on the current date and - time). Thanks `@sunmy2019 `_. - -* Made more chrono specifiers locale independent by default. Use the ``'L'`` - specifier to get localized formatting. For example: - - .. code:: c++ - - #include - - int main() { - std::locale::global(std::locale("ru_RU.UTF-8")); - auto monday = std::chrono::weekday(1); - fmt::print("{}\n", monday); // prints "Mon" - fmt::print("{:L}\n", monday); // prints "пн" - } - -* Improved locale handling in chrono formatting - (`#2337 `_, - `#2349 `_, - `#2350 `_). - Thanks `@phprus (Vladislav Shchapov) `_. - -* Deprecated ``fmt/locale.h`` moving the formatting functions that take a - locale to ``fmt/format.h`` (``char``) and ``fmt/xchar`` (other overloads). - This doesn't introduce a dependency on ```` so there is virtually no - compile time effect. - -* Deprecated an undocumented ``format_to`` overload that takes - ``basic_memory_buffer``. - -* Made parameter order in ``vformat_to`` consistent with ``format_to`` - (`#2327 `_). - -* Added support for time points with arbitrary durations - (`#2208 `_). For example: - - .. code:: c++ - - #include - - int main() { - using tp = std::chrono::time_point< - std::chrono::system_clock, std::chrono::seconds>; - fmt::print("{:%S}", tp(std::chrono::seconds(42))); - } - - prints "42". - -* Formatting floating-point numbers no longer produces trailing zeros by default - for consistency with ``std::format``. For example: - - .. code:: c++ - - #include - - int main() { - fmt::print("{0:.3}", 1.1); - } - - prints "1.1". Use the ``'#'`` specifier to keep trailing zeros. - -* Dropped a limit on the number of elements in a range and replaced ``{}`` with - ``[]`` as range delimiters for consistency with Python's ``str.format``. - -* The ``'L'`` specifier for locale-specific numeric formatting can now be - combined with presentation specifiers as in ``std::format``. For example: - - .. code:: c++ - - #include - #include - - int main() { - std::locale::global(std::locale("fr_FR.UTF-8")); - fmt::print("{0:.2Lf}", 0.42); - } - - prints "0,42". The deprecated ``'n'`` specifier has been removed. - -* Made the ``0`` specifier ignored for infinity and NaN - (`#2305 `_, - `#2310 `_). - Thanks `@Liedtke (Matthias Liedtke) `_. - -* Made the hexfloat formatting use the right alignment by default - (`#2308 `_, - `#2317 `_). - Thanks `@Liedtke (Matthias Liedtke) `_. - -* Removed the deprecated numeric alignment (``'='``). Use the ``'0'`` specifier - instead. - -* Removed the deprecated ``fmt/posix.h`` header that has been replaced with - ``fmt/os.h``. - -* Removed the deprecated ``format_to_n_context``, ``format_to_n_args`` and - ``make_format_to_n_args``. They have been replaced with ``format_context``, - ``format_args` and ``make_format_args`` respectively. - -* Moved ``wchar_t``-specific functions and types to ``fmt/xchar.h``. - You can define ``FMT_DEPRECATED_INCLUDE_XCHAR`` to automatically include - ``fmt/xchar.h`` from ``fmt/format.h`` but this will be disabled in the next - major release. - -* Fixed handling of the ``'+'`` specifier in localized formatting - (`#2133 `_). - -* Added support for the ``'s'`` format specifier that gives textual - representation of ``bool`` - (`#2094 `_, - `#2109 `_). For example: - - .. code:: c++ - - #include - - int main() { - fmt::print("{:s}", true); - } - - prints "true". - Thanks `@powercoderlol (Ivan Polyakov) `_. - -* Made ``fmt::ptr`` work with function pointers - (`#2131 `_). For example: - - .. code:: c++ - - #include - - int main() { - fmt::print("My main: {}\n", fmt::ptr(main)); - } - - Thanks `@mikecrowe (Mike Crowe) `_. - -* The undocumented support for specializing ``formatter`` for pointer types - has been removed. - -* Fixed ``fmt::formatted_size`` with format string compilation - (`#2141 `_, - `#2161 `_). - Thanks `@alexezeder (Alexey Ochapov) `_. - -* Fixed handling of empty format strings during format string compilation - (`#2042 `_): - - .. code:: c++ - - auto s = fmt::format(FMT_COMPILE("")); - - Thanks `@alexezeder (Alexey Ochapov) `_. - -* Fixed handling of enums in ``fmt::to_string`` - (`#2036 `_). - -* Improved width computation - (`#2033 `_, - `#2091 `_). For example: - - .. code:: c++ - - #include - - int main() { - fmt::print("{:-<10}{}\n", "你好", "世界"); - fmt::print("{:-<10}{}\n", "hello", "world"); - } - - prints - - .. image:: https://user-images.githubusercontent.com/576385/ - 119840373-cea3ca80-beb9-11eb-91e0-54266c48e181.png - - on a modern terminal. - -* The experimental fast output stream (``fmt::ostream``) is now truncated by - default for consistency with ``fopen`` - (`#2018 `_). For example: - - .. code:: c++ - - #include - - int main() { - fmt::ostream out1 = fmt::output_file("guide"); - out1.print("Zaphod"); - out1.close(); - fmt::ostream out2 = fmt::output_file("guide"); - out2.print("Ford"); - } - - writes "Ford" to the file "guide". To preserve the old file content if any - pass ``fmt::file::WRONLY | fmt::file::CREATE`` flags to ``fmt::output_file``. - -* Fixed moving of ``fmt::ostream`` that holds buffered data - (`#2197 `_, - `#2198 `_). - Thanks `@vtta `_. - -* Replaced the ``fmt::system_error`` exception with a function of the same - name that constructs ``std::system_error`` - (`#2266 `_). - -* Replaced the ``fmt::windows_error`` exception with a function of the same - name that constructs ``std::system_error`` with the category returned by - ``fmt::system_category()`` - (`#2274 `_, - `#2275 `_). - The latter is similar to ``std::sytem_category`` but correctly handles UTF-8. - Thanks `@phprus (Vladislav Shchapov) `_. - -* Replaced ``fmt::error_code`` with ``std::error_code`` and made it formattable - (`#2269 `_, - `#2270 `_, - `#2273 `_). - Thanks `@phprus (Vladislav Shchapov) `_. - -* Added speech synthesis support - (`#2206 `_). - -* Made ``format_to`` work with a memory buffer that has a custom allocator - (`#2300 `_). - Thanks `@voxmea `_. - -* Added ``Allocator::max_size`` support to ``basic_memory_buffer``. - (`#1960 `_). - Thanks `@phprus (Vladislav Shchapov) `_. - -* Added wide string support to ``fmt::join`` - (`#2236 `_). - Thanks `@crbrz `_. - -* Made iterators passed to ``formatter`` specializations via a format context - satisfy C++20 ``std::output_iterator`` requirements - (`#2156 `_, - `#2158 `_, - `#2195 `_, - `#2204 `_). - Thanks `@randomnetcat (Jason Cobb) `_. - -* Optimized the ``printf`` implementation - (`#1982 `_, - `#1984 `_, - `#2016 `_, - `#2164 `_). - Thanks `@rimathia `_ and - `@moiwi `_. - -* Improved detection of ``constexpr`` ``char_traits`` - (`#2246 `_, - `#2257 `_). - Thanks `@phprus (Vladislav Shchapov) `_. - -* Fixed writing to ``stdout`` when it is redirected to ``NUL`` on Windows - (`#2080 `_). - -* Fixed exception propagation from iterators - (`#2097 `_). - -* Improved ``strftime`` error handling - (`#2238 `_, - `#2244 `_). - Thanks `@yumeyao `_. - -* Stopped using deprecated GCC UDL template extension. - -* Added ``fmt/args.h`` to the install target - (`#2096 `_). - -* Error messages are now passed to assert when exceptions are disabled - (`#2145 `_). - Thanks `@NobodyXu (Jiahao XU) `_. - -* Added the ``FMT_MASTER_PROJECT`` CMake option to control build and install - targets when {fmt} is included via ``add_subdirectory`` - (`#2098 `_, - `#2100 `_). - Thanks `@randomizedthinking `_. - -* Improved build configuration - (`#2026 `_, - `#2122 `_). - Thanks `@luncliff (Park DongHa) `_ and - `@ibaned (Dan Ibanez) `_. - -* Fixed various warnings and compilation issues - (`#1947 `_, - `#1959 `_, - `#1963 `_, - `#1965 `_, - `#1966 `_, - `#1974 `_, - `#1975 `_, - `#1990 `_, - `#2000 `_, - `#2001 `_, - `#2002 `_, - `#2004 `_, - `#2006 `_, - `#2009 `_, - `#2010 `_, - `#2038 `_, - `#2039 `_, - `#2047 `_, - `#2053 `_, - `#2059 `_, - `#2065 `_, - `#2067 `_, - `#2068 `_, - `#2073 `_, - `#2103 `_, - `#2105 `_, - `#2106 `_, - `#2107 `_, - `#2116 `_, - `#2117 `_, - `#2118 `_, - `#2119 `_, - `#2127 `_, - `#2128 `_, - `#2140 `_, - `#2142 `_, - `#2143 `_, - `#2144 `_, - `#2147 `_, - `#2148 `_, - `#2149 `_, - `#2152 `_, - `#2160 `_, - `#2170 `_, - `#2175 `_, - `#2176 `_, - `#2177 `_, - `#2178 `_, - `#2179 `_, - `#2180 `_, - `#2181 `_, - `#2183 `_, - `#2184 `_, - `#2185 `_, - `#2186 `_, - `#2187 `_, - `#2190 `_, - `#2192 `_, - `#2194 `_, - `#2205 `_, - `#2210 `_, - `#2211 `_, - `#2215 `_, - `#2216 `_, - `#2218 `_, - `#2220 `_, - `#2228 `_, - `#2229 `_, - `#2230 `_, - `#2233 `_, - `#2239 `_, - `#2248 `_, - `#2252 `_, - `#2253 `_, - `#2255 `_, - `#2261 `_, - `#2278 `_, - `#2284 `_, - `#2287 `_, - `#2289 `_, - `#2290 `_, - `#2293 `_, - `#2295 `_, - `#2296 `_, - `#2297 `_, - `#2311 `_, - `#2313 `_, - `#2315 `_, - `#2320 `_, - `#2321 `_, - `#2323 `_, - `#2328 `_, - `#2329 `_, - `#2333 `_, - `#2338 `_, - `#2341 `_). - Thanks `@darklukee `_, - `@fagg (Ashton Fagg) `_, - `@killerbot242 (Lieven de Cock) `_, - `@jgopel (Jonathan Gopel) `_, - `@yeswalrus (Walter Gray) `_, - `@Finkman `_, - `@HazardyKnusperkeks (Björn Schäpers) `_, - `@dkavolis (Daumantas Kavolis) `_, - `@concatime (Issam Maghni) `_, - `@chronoxor (Ivan Shynkarenka) `_, - `@summivox (Yin Zhong) `_, - `@yNeo `_, - `@Apache-HB (Elliot) `_, - `@alexezeder (Alexey Ochapov) `_, - `@toojays (John Steele Scott) `_, - `@Brainy0207 `_, - `@vadz (VZ) `_, - `@imsherlock (Ryan Sherlock) `_, - `@phprus (Vladislav Shchapov) `_, - `@white238 (Chris White) `_, - `@yafshar (Yaser Afshar) `_, - `@BillyDonahue (Billy Donahue) `_, - `@jstaahl `_, - `@denchat `_, - `@DanielaE (Daniela Engert) `_, - `@ilyakurdyukov (Ilya Kurdyukov) `_, - `@ilmai `_, - `@JessyDL (Jessy De Lannoit) `_, - `@sergiud (Sergiu Deitsch) `_, - `@mwinterb `_, - `@sven-herrmann `_, - `@jmelas (John Melas) `_, - `@twoixter (Jose Miguel Pérez) `_, - `@crbrz `_, - `@upsj (Tobias Ribizel) `_. - -* Improved documentation - (`#1986 `_, - `#2051 `_, - `#2057 `_, - `#2081 `_, - `#2084 `_, - `#2312 `_). - Thanks `@imba-tjd (谭九鼎) `_, - `@0x416c69 (AlιAѕѕaѕѕιN) `_, - `@mordante `_. - -* Continuous integration and test improvements - (`#1969 `_, - `#1991 `_, - `#2020 `_, - `#2110 `_, - `#2114 `_, - `#2196 `_, - `#2217 `_, - `#2247 `_, - `#2256 `_, - `#2336 `_, - `#2346 `_). - Thanks `@jgopel (Jonathan Gopel) `_, - `@alexezeder (Alexey Ochapov) `_ and - `@DanielaE (Daniela Engert) `_. - -7.1.3 - 2020-11-24 ------------------- - -* Fixed handling of buffer boundaries in ``format_to_n`` - (`#1996 `_, - `#2029 `_). - -* Fixed linkage errors when linking with a shared library - (`#2011 `_). - -* Reintroduced ostream support to range formatters - (`#2014 `_). - -* Worked around an issue with mixing std versions in gcc - (`#2017 `_). - -7.1.2 - 2020-11-04 ------------------- - -* Fixed floating point formatting with large precision - (`#1976 `_). - -7.1.1 - 2020-11-01 ------------------- - -* Fixed ABI compatibility with 7.0.x - (`#1961 `_). - -* Added the ``FMT_ARM_ABI_COMPATIBILITY`` macro to work around ABI - incompatibility between GCC and Clang on ARM - (`#1919 `_). - -* Worked around a SFINAE bug in GCC 8 - (`#1957 `_). - -* Fixed linkage errors when building with GCC's LTO - (`#1955 `_). - -* Fixed a compilation error when building without ``__builtin_clz`` or equivalent - (`#1968 `_). - Thanks `@tohammer (Tobias Hammer) `_. - -* Fixed a sign conversion warning - (`#1964 `_). - Thanks `@OptoCloud `_. - -7.1.0 - 2020-10-25 ------------------- - -* Switched from `Grisu3 - `_ - to `Dragonbox `_ for the default - floating-point formatting which gives the shortest decimal representation - with round-trip guarantee and correct rounding - (`#1882 `_, - `#1887 `_, - `#1894 `_). This makes {fmt} up to - 20-30x faster than common implementations of ``std::ostringstream`` and - ``sprintf`` on `dtoa-benchmark `_ - and faster than double-conversion and Ryū: - - .. image:: https://user-images.githubusercontent.com/576385/ - 95684665-11719600-0ba8-11eb-8e5b-972ff4e49428.png - - It is possible to get even better performance at the cost of larger binary - size by compiling with the ``FMT_USE_FULL_CACHE_DRAGONBOX`` macro set to 1. - - Thanks `@jk-jeon (Junekey Jeon) `_. - -* Added an experimental unsynchronized file output API which, together with - `format string compilation `_, - can give `5-9 times speed up compared to fprintf - `_ - on common platforms (`godbolt `__): - - .. code:: c++ - - #include - - int main() { - auto f = fmt::output_file("guide"); - f.print("The answer is {}.", 42); - } - -* Added a formatter for ``std::chrono::time_point`` - (`#1819 `_, - `#1837 `_). For example - (`godbolt `__): - - .. code:: c++ - - #include - - int main() { - auto now = std::chrono::system_clock::now(); - fmt::print("The time is {:%H:%M:%S}.\n", now); - } - - Thanks `@adamburgess (Adam Burgess) `_. - -* Added support for ranges with non-const ``begin``/``end`` to ``fmt::join`` - (`#1784 `_, - `#1786 `_). For example - (`godbolt `__): - - .. code:: c++ - - #include - #include - - int main() { - using std::literals::string_literals::operator""s; - auto strs = std::array{"a"s, "bb"s, "ccc"s}; - auto range = strs | ranges::views::filter( - [] (const std::string &x) { return x.size() != 2; } - ); - fmt::print("{}\n", fmt::join(range, "")); - } - - prints "accc". - - Thanks `@tonyelewis (Tony E Lewis) `_. - -* Added a ``memory_buffer::append`` overload that takes a range - (`#1806 `_). - Thanks `@BRevzin (Barry Revzin) `_. - -* Improved handling of single code units in ``FMT_COMPILE``. For example: - - .. code:: c++ - - #include - - char* f(char* buf) { - return fmt::format_to(buf, FMT_COMPILE("x{}"), 42); - } - - compiles to just (`godbolt `__): - - .. code:: asm - - _Z1fPc: - movb $120, (%rdi) - xorl %edx, %edx - cmpl $42, _ZN3fmt2v76detail10basic_dataIvE23zero_or_powers_of_10_32E+8(%rip) - movl $3, %eax - seta %dl - subl %edx, %eax - movzwl _ZN3fmt2v76detail10basic_dataIvE6digitsE+84(%rip), %edx - cltq - addq %rdi, %rax - movw %dx, -2(%rax) - ret - - Here a single ``mov`` instruction writes ``'x'`` (``$120``) to the output - buffer. - -* Added dynamic width support to format string compilation - (`#1809 `_). - -* Improved error reporting for unformattable types: now you'll get the type name - directly in the error message instead of the note: - - .. code:: c++ - - #include - - struct how_about_no {}; - - int main() { - fmt::print("{}", how_about_no()); - } - - Error (`godbolt `__): - - ``fmt/core.h:1438:3: error: static_assert failed due to requirement - 'fmt::v7::formattable()' "Cannot format an argument. - To make type T formattable provide a formatter specialization: - https://fmt.dev/latest/api.html#udt" - ...`` - -* Added the `make_args_checked `_ - function template that allows you to write formatting functions with - compile-time format string checks and avoid binary code bloat - (`godbolt `__): - - .. code:: c++ - - void vlog(const char* file, int line, fmt::string_view format, - fmt::format_args args) { - fmt::print("{}: {}: ", file, line); - fmt::vprint(format, args); - } - - template - void log(const char* file, int line, const S& format, Args&&... args) { - vlog(file, line, format, - fmt::make_args_checked(format, args...)); - } - - #define MY_LOG(format, ...) \ - log(__FILE__, __LINE__, FMT_STRING(format), __VA_ARGS__) - - MY_LOG("invalid squishiness: {}", 42); - -* Replaced ``snprintf`` fallback with a faster internal IEEE 754 ``float`` and - ``double`` formatter for arbitrary precision. For example - (`godbolt `__): - - .. code:: c++ - - #include - - int main() { - fmt::print("{:.500}\n", 4.9406564584124654E-324); - } - - prints - - ``4.9406564584124654417656879286822137236505980261432476442558568250067550727020875186529983636163599237979656469544571773092665671035593979639877479601078187812630071319031140452784581716784898210368871863605699873072305000638740915356498438731247339727316961514003171538539807412623856559117102665855668676818703956031062493194527159149245532930545654440112748012970999954193198940908041656332452475714786901472678015935523861155013480352649347201937902681071074917033322268447533357208324319360923829e-324``. - -* Made ``format_to_n`` and ``formatted_size`` part of the `core API - `__ - (`godbolt `__): - - .. code:: c++ - - #include - - int main() { - char buffer[10]; - auto result = fmt::format_to_n(buffer, sizeof(buffer), "{}", 42); - } - -* Added ``fmt::format_to_n`` overload with format string compilation - (`#1764 `_, - `#1767 `_, - `#1869 `_). For example - (`godbolt `__): - - .. code:: c++ - - #include - - int main() { - char buffer[8]; - fmt::format_to_n(buffer, sizeof(buffer), FMT_COMPILE("{}"), 42); - } - - Thanks `@Kurkin (Dmitry Kurkin) `_, - `@alexezeder (Alexey Ochapov) `_. - -* Added ``fmt::format_to`` overload that take ``text_style`` - (`#1593 `_, - `#1842 `_, - `#1843 `_). For example - (`godbolt `__): - - .. code:: c++ - - #include - - int main() { - std::string out; - fmt::format_to(std::back_inserter(out), - fmt::emphasis::bold | fg(fmt::color::red), - "The answer is {}.", 42); - } - - Thanks `@Naios (Denis Blank) `_. - -* Made the ``'#'`` specifier emit trailing zeros in addition to the decimal - point (`#1797 `_). For example - (`godbolt `__): - - .. code:: c++ - - #include - - int main() { - fmt::print("{:#.2g}", 0.5); - } - - prints ``0.50``. - -* Changed the default floating point format to not include ``.0`` for - consistency with ``std::format`` and ``std::to_chars`` - (`#1893 `_, - `#1943 `_). It is possible to get - the decimal point and trailing zero with the ``#`` specifier. - -* Fixed an issue with floating-point formatting that could result in addition of - a non-significant trailing zero in rare cases e.g. ``1.00e-34`` instead of - ``1.0e-34`` (`#1873 `_, - `#1917 `_). - -* Made ``fmt::to_string`` fallback on ``ostream`` insertion operator if - the ``formatter`` specialization is not provided - (`#1815 `_, - `#1829 `_). - Thanks `@alexezeder (Alexey Ochapov) `_. - -* Added support for the append mode to the experimental file API and - improved ``fcntl.h`` detection. - (`#1847 `_, - `#1848 `_). - Thanks `@t-wiser `_. - -* Fixed handling of types that have both an implicit conversion operator and - an overloaded ``ostream`` insertion operator - (`#1766 `_). - -* Fixed a slicing issue in an internal iterator type - (`#1822 `_). - Thanks `@BRevzin (Barry Revzin) `_. - -* Fixed an issue in locale-specific integer formatting - (`#1927 `_). - -* Fixed handling of exotic code unit types - (`#1870 `_, - `#1932 `_). - -* Improved ``FMT_ALWAYS_INLINE`` - (`#1878 `_). - Thanks `@jk-jeon (Junekey Jeon) `_. - -* Removed dependency on ``windows.h`` - (`#1900 `_). - Thanks `@bernd5 (Bernd Baumanns) `_. - -* Optimized counting of decimal digits on MSVC - (`#1890 `_). - Thanks `@mwinterb `_. - -* Improved documentation - (`#1772 `_, - `#1775 `_, - `#1792 `_, - `#1838 `_, - `#1888 `_, - `#1918 `_, - `#1939 `_). - Thanks `@leolchat (Léonard Gérard) `_, - `@pepsiman (Malcolm Parsons) `_, - `@Klaim (Joël Lamotte) `_, - `@ravijanjam (Ravi J) `_, - `@francesco-st `_, - `@udnaan (Adnan) `_. - -* Added the ``FMT_REDUCE_INT_INSTANTIATIONS`` CMake option that reduces the - binary code size at the cost of some integer formatting performance. This can - be useful for extremely memory-constrained embedded systems - (`#1778 `_, - `#1781 `_). - Thanks `@kammce (Khalil Estell) `_. - -* Added the ``FMT_USE_INLINE_NAMESPACES`` macro to control usage of inline - namespaces (`#1945 `_). - Thanks `@darklukee `_. - -* Improved build configuration - (`#1760 `_, - `#1770 `_, - `#1779 `_, - `#1783 `_, - `#1823 `_). - Thanks `@dvetutnev (Dmitriy Vetutnev) `_, - `@xvitaly (Vitaly Zaitsev) `_, - `@tambry (Raul Tambre) `_, - `@medithe `_, - `@martinwuehrer (Martin Wührer) `_. - -* Fixed various warnings and compilation issues - (`#1790 `_, - `#1802 `_, - `#1808 `_, - `#1810 `_, - `#1811 `_, - `#1812 `_, - `#1814 `_, - `#1816 `_, - `#1817 `_, - `#1818 `_, - `#1825 `_, - `#1836 `_, - `#1855 `_, - `#1856 `_, - `#1860 `_, - `#1877 `_, - `#1879 `_, - `#1880 `_, - `#1896 `_, - `#1897 `_, - `#1898 `_, - `#1904 `_, - `#1908 `_, - `#1911 `_, - `#1912 `_, - `#1928 `_, - `#1929 `_, - `#1935 `_, - `#1937 `_, - `#1942 `_, - `#1949 `_). - Thanks `@TheQwertiest `_, - `@medithe `_, - `@martinwuehrer (Martin Wührer) `_, - `@n16h7hunt3r `_, - `@Othereum (Seokjin Lee) `_, - `@gsjaardema (Greg Sjaardema) `_, - `@AlexanderLanin (Alexander Lanin) `_, - `@gcerretani (Giovanni Cerretani) `_, - `@chronoxor (Ivan Shynkarenka) `_, - `@noizefloor (Jan Schwers) `_, - `@akohlmey (Axel Kohlmeyer) `_, - `@jk-jeon (Junekey Jeon) `_, - `@rimathia `_, - `@rglarix (Riccardo Ghetta (larix)) `_, - `@moiwi `_, - `@heckad (Kazantcev Andrey) `_, - `@MarcDirven `_. - `@BartSiwek (Bart Siwek) `_, - `@darklukee `_. - -7.0.3 - 2020-08-06 ------------------- - -* Worked around broken ``numeric_limits`` for 128-bit integers - (`#1787 `_). - -* Added error reporting on missing named arguments - (`#1796 `_). - -* Stopped using 128-bit integers with clang-cl - (`#1800 `_). - Thanks `@Kingcom `_. - -* Fixed issues in locale-specific integer formatting - (`#1782 `_, - `#1801 `_). - -7.0.2 - 2020-07-29 ------------------- - -* Worked around broken ``numeric_limits`` for 128-bit integers - (`#1725 `_). - -* Fixed compatibility with CMake 3.4 - (`#1779 `_). - -* Fixed handling of digit separators in locale-specific formatting - (`#1782 `_). - -7.0.1 - 2020-07-07 ------------------- - -* Updated the inline version namespace name. - -* Worked around a gcc bug in mangling of alias templates - (`#1753 `_). - -* Fixed a linkage error on Windows - (`#1757 `_). - Thanks `@Kurkin (Dmitry Kurkin) `_. - -* Fixed minor issues with the documentation. - -7.0.0 - 2020-07-05 ------------------- - -* Reduced the library size. For example, on macOS a stripped test binary - statically linked with {fmt} `shrank from ~368k to less than 100k - `_. - -* Added a simpler and more efficient `format string compilation API - `_: - - .. code:: c++ - - #include - - // Converts 42 into std::string using the most efficient method and no - // runtime format string processing. - std::string s = fmt::format(FMT_COMPILE("{}"), 42); - - The old ``fmt::compile`` API is now deprecated. - -* Optimized integer formatting: ``format_to`` with format string compilation - and a stack-allocated buffer is now `faster than to_chars on both - libc++ and libstdc++ - `_. - -* Optimized handling of small format strings. For example, - - .. code:: c++ - - fmt::format("Result: {}: ({},{},{},{})", str1, str2, str3, str4, str5) - - is now ~40% faster (`#1685 `_). - -* Applied extern templates to improve compile times when using the core API - and ``fmt/format.h`` (`#1452 `_). - For example, on macOS with clang the compile time of a test translation unit - dropped from 2.3s to 0.3s with ``-O2`` and from 0.6s to 0.3s with the default - settings (``-O0``). - - Before (``-O2``):: - - % time c++ -c test.cc -I include -std=c++17 -O2 - c++ -c test.cc -I include -std=c++17 -O2 2.22s user 0.08s system 99% cpu 2.311 total - - After (``-O2``):: - - % time c++ -c test.cc -I include -std=c++17 -O2 - c++ -c test.cc -I include -std=c++17 -O2 0.26s user 0.04s system 98% cpu 0.303 total - - Before (default):: - - % time c++ -c test.cc -I include -std=c++17 - c++ -c test.cc -I include -std=c++17 0.53s user 0.06s system 98% cpu 0.601 total - - After (default):: - - % time c++ -c test.cc -I include -std=c++17 - c++ -c test.cc -I include -std=c++17 0.24s user 0.06s system 98% cpu 0.301 total - - It is still recommended to use ``fmt/core.h`` instead of ``fmt/format.h`` but - the compile time difference is now smaller. Thanks - `@alex3d `_ for the suggestion. - -* Named arguments are now stored on stack (no dynamic memory allocations) and - the compiled code is more compact and efficient. For example - - .. code:: c++ - - #include - - int main() { - fmt::print("The answer is {answer}\n", fmt::arg("answer", 42)); - } - - compiles to just (`godbolt `__) - - .. code:: asm - - .LC0: - .string "answer" - .LC1: - .string "The answer is {answer}\n" - main: - sub rsp, 56 - mov edi, OFFSET FLAT:.LC1 - mov esi, 23 - movabs rdx, 4611686018427387905 - lea rax, [rsp+32] - lea rcx, [rsp+16] - mov QWORD PTR [rsp+8], 1 - mov QWORD PTR [rsp], rax - mov DWORD PTR [rsp+16], 42 - mov QWORD PTR [rsp+32], OFFSET FLAT:.LC0 - mov DWORD PTR [rsp+40], 0 - call fmt::v6::vprint(fmt::v6::basic_string_view, - fmt::v6::format_args) - xor eax, eax - add rsp, 56 - ret - - .L.str.1: - .asciz "answer" - -* Implemented compile-time checks for dynamic width and precision - (`#1614 `_): - - .. code:: c++ - - #include - - int main() { - fmt::print(FMT_STRING("{0:{1}}"), 42); - } - - now gives a compilation error because argument 1 doesn't exist:: - - In file included from test.cc:1: - include/fmt/format.h:2726:27: error: constexpr variable 'invalid_format' must be - initialized by a constant expression - FMT_CONSTEXPR_DECL bool invalid_format = - ^ - ... - include/fmt/core.h:569:26: note: in call to - '&checker(s, {}).context_->on_error(&"argument not found"[0])' - if (id >= num_args_) on_error("argument not found"); - ^ - -* Added sentinel support to ``fmt::join`` - (`#1689 `_) - - .. code:: c++ - - struct zstring_sentinel {}; - bool operator==(const char* p, zstring_sentinel) { return *p == '\0'; } - bool operator!=(const char* p, zstring_sentinel) { return *p != '\0'; } - - struct zstring { - const char* p; - const char* begin() const { return p; } - zstring_sentinel end() const { return {}; } - }; - - auto s = fmt::format("{}", fmt::join(zstring{"hello"}, "_")); - // s == "h_e_l_l_o" - - Thanks `@BRevzin (Barry Revzin) `_. - -* Added support for named arguments, ``clear`` and ``reserve`` to - ``dynamic_format_arg_store`` - (`#1655 `_, - `#1663 `_, - `#1674 `_, - `#1677 `_). - Thanks `@vsolontsov-ll (Vladimir Solontsov) - `_. - -* Added support for the ``'c'`` format specifier to integral types for - compatibility with ``std::format`` - (`#1652 `_). - -* Replaced the ``'n'`` format specifier with ``'L'`` for compatibility with - ``std::format`` (`#1624 `_). - The ``'n'`` specifier can be enabled via the ``FMT_DEPRECATED_N_SPECIFIER`` - macro. - -* The ``'='`` format specifier is now disabled by default for compatibility with - ``std::format``. It can be enabled via the ``FMT_DEPRECATED_NUMERIC_ALIGN`` - macro. - -* Removed the following deprecated APIs: - - * ``FMT_STRING_ALIAS`` and ``fmt`` macros - replaced by ``FMT_STRING`` - * ``fmt::basic_string_view::char_type`` - replaced by - ``fmt::basic_string_view::value_type`` - * ``convert_to_int`` - * ``format_arg_store::types`` - * ``*parse_context`` - replaced by ``*format_parse_context`` - * ``FMT_DEPRECATED_INCLUDE_OS`` - * ``FMT_DEPRECATED_PERCENT`` - incompatible with ``std::format`` - * ``*writer`` - replaced by compiled format API - -* Renamed the ``internal`` namespace to ``detail`` - (`#1538 `_). The former is still - provided as an alias if the ``FMT_USE_INTERNAL`` macro is defined. - -* Improved compatibility between ``fmt::printf`` with the standard specs - (`#1595 `_, - `#1682 `_, - `#1683 `_, - `#1687 `_, - `#1699 `_). - Thanks `@rimathia `_. - -* Fixed handling of ``operator<<`` overloads that use ``copyfmt`` - (`#1666 `_). - -* Added the ``FMT_OS`` CMake option to control inclusion of OS-specific APIs - in the fmt target. This can be useful for embedded platforms - (`#1654 `_, - `#1656 `_). - Thanks `@kwesolowski (Krzysztof Wesolowski) - `_. - -* Replaced ``FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION`` with the ``FMT_FUZZ`` - macro to prevent interferring with fuzzing of projects using {fmt} - (`#1650 `_). - Thanks `@asraa (Asra Ali) `_. - -* Fixed compatibility with emscripten - (`#1636 `_, - `#1637 `_). - Thanks `@ArthurSonzogni (Arthur Sonzogni) - `_. - -* Improved documentation - (`#704 `_, - `#1643 `_, - `#1660 `_, - `#1681 `_, - `#1691 `_, - `#1706 `_, - `#1714 `_, - `#1721 `_, - `#1739 `_, - `#1740 `_, - `#1741 `_, - `#1751 `_). - Thanks `@senior7515 (Alexander Gallego) `_, - `@lsr0 (Lindsay Roberts) `_, - `@puetzk (Kevin Puetz) `_, - `@fpelliccioni (Fernando Pelliccioni) `_, - Alexey Kuzmenko, `@jelly (jelle van der Waa) `_, - `@claremacrae (Clare Macrae) `_, - `@jiapengwen (文佳鹏) `_, - `@gsjaardema (Greg Sjaardema) `_, - `@alexey-milovidov `_. - -* Implemented various build configuration fixes and improvements - (`#1603 `_, - `#1657 `_, - `#1702 `_, - `#1728 `_). - Thanks `@scramsby (Scott Ramsby) `_, - `@jtojnar (Jan Tojnar) `_, - `@orivej (Orivej Desh) `_, - `@flagarde `_. - -* Fixed various warnings and compilation issues - (`#1616 `_, - `#1620 `_, - `#1622 `_, - `#1625 `_, - `#1627 `_, - `#1628 `_, - `#1629 `_, - `#1631 `_, - `#1633 `_, - `#1649 `_, - `#1658 `_, - `#1661 `_, - `#1667 `_, - `#1668 `_, - `#1669 `_, - `#1692 `_, - `#1696 `_, - `#1697 `_, - `#1707 `_, - `#1712 `_, - `#1716 `_, - `#1722 `_, - `#1724 `_, - `#1729 `_, - `#1738 `_, - `#1742 `_, - `#1743 `_, - `#1744 `_, - `#1747 `_, - `#1750 `_). - Thanks `@gsjaardema (Greg Sjaardema) `_, - `@gabime (Gabi Melman) `_, - `@johnor (Johan) `_, - `@Kurkin (Dmitry Kurkin) `_, - `@invexed (James Beach) `_, - `@peterbell10 `_, - `@daixtrose (Markus Werle) `_, - `@petrutlucian94 (Lucian Petrut) `_, - `@Neargye (Daniil Goncharov) `_, - `@ambitslix (Attila M. Szilagyi) `_, - `@gabime (Gabi Melman) `_, - `@erthink (Leonid Yuriev) `_, - `@tohammer (Tobias Hammer) `_, - `@0x8000-0000 (Florin Iucha) `_. - -6.2.1 - 2020-05-09 ------------------- - -* Fixed ostream support in ``sprintf`` - (`#1631 `_). - -* Fixed type detection when using implicit conversion to ``string_view`` and - ostream ``operator<<`` inconsistently - (`#1662 `_). - -6.2.0 - 2020-04-05 ------------------- - -* Improved error reporting when trying to format an object of a non-formattable - type: - - .. code:: c++ - - fmt::format("{}", S()); - - now gives:: - - include/fmt/core.h:1015:5: error: static_assert failed due to requirement - 'formattable' "Cannot format argument. To make type T formattable provide a - formatter specialization: - https://fmt.dev/latest/api.html#formatting-user-defined-types" - static_assert( - ^ - ... - note: in instantiation of function template specialization - 'fmt::v6::format' requested here - fmt::format("{}", S()); - ^ - - if ``S`` is not formattable. - -* Reduced the library size by ~10%. - -* Always print decimal point if ``#`` is specified - (`#1476 `_, - `#1498 `_): - - .. code:: c++ - - fmt::print("{:#.0f}", 42.0); - - now prints ``42.`` - -* Implemented the ``'L'`` specifier for locale-specific numeric formatting to - improve compatibility with ``std::format``. The ``'n'`` specifier is now - deprecated and will be removed in the next major release. - -* Moved OS-specific APIs such as ``windows_error`` from ``fmt/format.h`` to - ``fmt/os.h``. You can define ``FMT_DEPRECATED_INCLUDE_OS`` to automatically - include ``fmt/os.h`` from ``fmt/format.h`` for compatibility but this will be - disabled in the next major release. - -* Added precision overflow detection in floating-point formatting. - -* Implemented detection of invalid use of ``fmt::arg``. - -* Used ``type_identity`` to block unnecessary template argument deduction. - Thanks Tim Song. - -* Improved UTF-8 handling - (`#1109 `_): - - .. code:: c++ - - fmt::print("┌{0:─^{2}}┐\n" - "│{1: ^{2}}│\n" - "└{0:─^{2}}┘\n", "", "Привет, мир!", 20); - - now prints:: - - ┌────────────────────┐ - │ Привет, мир! │ - └────────────────────┘ - - on systems that support Unicode. - -* Added experimental dynamic argument storage - (`#1170 `_, - `#1584 `_): - - .. code:: c++ - - fmt::dynamic_format_arg_store store; - store.push_back("answer"); - store.push_back(42); - fmt::vprint("The {} is {}.\n", store); - - prints:: - - The answer is 42. - - Thanks `@vsolontsov-ll (Vladimir Solontsov) - `_. - -* Made ``fmt::join`` accept ``initializer_list`` - (`#1591 `_). - Thanks `@Rapotkinnik (Nikolay Rapotkin) `_. - -* Fixed handling of empty tuples - (`#1588 `_). - -* Fixed handling of output iterators in ``format_to_n`` - (`#1506 `_). - -* Fixed formatting of ``std::chrono::duration`` types to wide output - (`#1533 `_). - Thanks `@zeffy (pilao) `_. - -* Added const ``begin`` and ``end`` overload to buffers - (`#1553 `_). - Thanks `@dominicpoeschko `_. - -* Added the ability to disable floating-point formatting via ``FMT_USE_FLOAT``, - ``FMT_USE_DOUBLE`` and ``FMT_USE_LONG_DOUBLE`` macros for extremely - memory-constrained embedded system - (`#1590 `_). - Thanks `@albaguirre (Alberto Aguirre) `_. - -* Made ``FMT_STRING`` work with ``constexpr`` ``string_view`` - (`#1589 `_). - Thanks `@scramsby (Scott Ramsby) `_. - -* Implemented a minor optimization in the format string parser - (`#1560 `_). - Thanks `@IkarusDeveloper `_. - -* Improved attribute detection - (`#1469 `_, - `#1475 `_, - `#1576 `_). - Thanks `@federico-busato (Federico) `_, - `@chronoxor (Ivan Shynkarenka) `_, - `@refnum `_. - -* Improved documentation - (`#1481 `_, - `#1523 `_). - Thanks `@JackBoosY (Jack·Boos·Yu) `_, - `@imba-tjd (谭九鼎) `_. - -* Fixed symbol visibility on Linux when compiling with ``-fvisibility=hidden`` - (`#1535 `_). - Thanks `@milianw (Milian Wolff) `_. - -* Implemented various build configuration fixes and improvements - (`#1264 `_, - `#1460 `_, - `#1534 `_, - `#1536 `_, - `#1545 `_, - `#1546 `_, - `#1566 `_, - `#1582 `_, - `#1597 `_, - `#1598 `_). - Thanks `@ambitslix (Attila M. Szilagyi) `_, - `@jwillikers (Jordan Williams) `_, - `@stac47 (Laurent Stacul) `_. - -* Fixed various warnings and compilation issues - (`#1433 `_, - `#1461 `_, - `#1470 `_, - `#1480 `_, - `#1485 `_, - `#1492 `_, - `#1493 `_, - `#1504 `_, - `#1505 `_, - `#1512 `_, - `#1515 `_, - `#1516 `_, - `#1518 `_, - `#1519 `_, - `#1520 `_, - `#1521 `_, - `#1522 `_, - `#1524 `_, - `#1530 `_, - `#1531 `_, - `#1532 `_, - `#1539 `_, - `#1547 `_, - `#1548 `_, - `#1554 `_, - `#1567 `_, - `#1568 `_, - `#1569 `_, - `#1571 `_, - `#1573 `_, - `#1575 `_, - `#1581 `_, - `#1583 `_, - `#1586 `_, - `#1587 `_, - `#1594 `_, - `#1596 `_, - `#1604 `_, - `#1606 `_, - `#1607 `_, - `#1609 `_). - Thanks `@marti4d (Chris Martin) `_, - `@iPherian `_, - `@parkertomatoes `_, - `@gsjaardema (Greg Sjaardema) `_, - `@chronoxor (Ivan Shynkarenka) `_, - `@DanielaE (Daniela Engert) `_, - `@torsten48 `_, - `@tohammer (Tobias Hammer) `_, - `@lefticus (Jason Turner) `_, - `@ryusakki (Haise) `_, - `@adnsv (Alex Denisov) `_, - `@fghzxm `_, - `@refnum `_, - `@pramodk (Pramod Kumbhar) `_, - `@Spirrwell `_, - `@scramsby (Scott Ramsby) `_. - -6.1.2 - 2019-12-11 ------------------- - -* Fixed ABI compatibility with ``libfmt.so.6.0.0`` - (`#1471 `_). - -* Fixed handling types convertible to ``std::string_view`` - (`#1451 `_). - Thanks `@denizevrenci (Deniz Evrenci) `_. - -* Made CUDA test an opt-in enabled via the ``FMT_CUDA_TEST`` CMake option. - -* Fixed sign conversion warnings - (`#1440 `_). - Thanks `@0x8000-0000 (Florin Iucha) `_. - -6.1.1 - 2019-12-04 ------------------- - -* Fixed shared library build on Windows - (`#1443 `_, - `#1445 `_, - `#1446 `_, - `#1450 `_). - Thanks `@egorpugin (Egor Pugin) `_, - `@bbolli (Beat Bolli) `_. - -* Added a missing decimal point in exponent notation with trailing zeros. - -* Removed deprecated ``format_arg_store::TYPES``. - -6.1.0 - 2019-12-01 ------------------- - -* {fmt} now formats IEEE 754 ``float`` and ``double`` using the shortest decimal - representation with correct rounding by default: - - .. code:: c++ - - #include - #include - - int main() { - fmt::print("{}", M_PI); - } - - prints ``3.141592653589793``. - -* Made the fast binary to decimal floating-point formatter the default, - simplified it and improved performance. {fmt} is now 15 times faster than - libc++'s ``std::ostringstream``, 11 times faster than ``printf`` and 10% - faster than double-conversion on `dtoa-benchmark - `_: - - ================== ========= ======= - Function Time (ns) Speedup - ================== ========= ======= - ostringstream 1,346.30 1.00x - ostrstream 1,195.74 1.13x - sprintf 995.08 1.35x - doubleconv 99.10 13.59x - fmt 88.34 15.24x - ================== ========= ======= - - .. image:: https://user-images.githubusercontent.com/576385/ - 69767160-cdaca400-112f-11ea-9fc5-347c9f83caad.png - -* {fmt} no longer converts ``float`` arguments to ``double``. In particular this - improves the default (shortest) representation of floats and makes - ``fmt::format`` consistent with ``std::format`` specs - (`#1336 `_, - `#1353 `_, - `#1360 `_, - `#1361 `_): - - .. code:: c++ - - fmt::print("{}", 0.1f); - - prints ``0.1`` instead of ``0.10000000149011612``. - - Thanks `@orivej (Orivej Desh) `_. - -* Made floating-point formatting output consistent with ``printf``/iostreams - (`#1376 `_, - `#1417 `_). - -* Added support for 128-bit integers - (`#1287 `_): - - .. code:: c++ - - fmt::print("{}", std::numeric_limits<__int128_t>::max()); - - prints ``170141183460469231731687303715884105727``. - - Thanks `@denizevrenci (Deniz Evrenci) `_. - -* The overload of ``print`` that takes ``text_style`` is now atomic, i.e. the - output from different threads doesn't interleave - (`#1351 `_). - Thanks `@tankiJong (Tanki Zhang) `_. - -* Made compile time in the header-only mode ~20% faster by reducing the number - of template instantiations. ``wchar_t`` overload of ``vprint`` was moved from - ``fmt/core.h`` to ``fmt/format.h``. - -* Added an overload of ``fmt::join`` that works with tuples - (`#1322 `_, - `#1330 `_): - - .. code:: c++ - - #include - #include - - int main() { - std::tuple t{'a', 1, 2.0f}; - fmt::print("{}", t); - } - - prints ``('a', 1, 2.0)``. - - Thanks `@jeremyong (Jeremy Ong) `_. - -* Changed formatting of octal zero with prefix from "00" to "0": - - .. code:: c++ - - fmt::print("{:#o}", 0); - - prints ``0``. - -* The locale is now passed to ostream insertion (``<<``) operators - (`#1406 `_): - - .. code:: c++ - - #include - #include - - struct S { - double value; - }; - - std::ostream& operator<<(std::ostream& os, S s) { - return os << s.value; - } - - int main() { - auto s = fmt::format(std::locale("fr_FR.UTF-8"), "{}", S{0.42}); - // s == "0,42" - } - - Thanks `@dlaugt (Daniel Laügt) `_. - -* Locale-specific number formatting now uses grouping - (`#1393 `_ - `#1394 `_). - Thanks `@skrdaniel `_. - -* Fixed handling of types with deleted implicit rvalue conversion to - ``const char**`` (`#1421 `_): - - .. code:: c++ - - struct mystring { - operator const char*() const&; - operator const char*() &; - operator const char*() const&& = delete; - operator const char*() && = delete; - }; - mystring str; - fmt::print("{}", str); // now compiles - -* Enums are now mapped to correct underlying types instead of ``int`` - (`#1286 `_). - Thanks `@agmt (Egor Seredin) `_. - -* Enum classes are no longer implicitly converted to ``int`` - (`#1424 `_). - -* Added ``basic_format_parse_context`` for consistency with C++20 - ``std::format`` and deprecated ``basic_parse_context``. - -* Fixed handling of UTF-8 in precision - (`#1389 `_, - `#1390 `_). - Thanks `@tajtiattila (Attila Tajti) `_. - -* {fmt} can now be installed on Linux, macOS and Windows with - `Conda `__ using its - `conda-forge `__ - `package `__ - (`#1410 `_):: - - conda install -c conda-forge fmt - - Thanks `@tdegeus (Tom de Geus) `_. - -* Added a CUDA test (`#1285 `_, - `#1317 `_). - Thanks `@luncliff (Park DongHa) `_ and - `@risa2000 `_. - -* Improved documentation (`#1276 `_, - `#1291 `_, - `#1296 `_, - `#1315 `_, - `#1332 `_, - `#1337 `_, - `#1395 `_ - `#1418 `_). - Thanks - `@waywardmonkeys (Bruce Mitchener) `_, - `@pauldreik (Paul Dreik) `_, - `@jackoalan (Jack Andersen) `_. - -* Various code improvements - (`#1358 `_, - `#1407 `_). - Thanks `@orivej (Orivej Desh) `_, - `@dpacbach (David P. Sicilia) `_, - -* Fixed compile-time format string checks for user-defined types - (`#1292 `_). - -* Worked around a false positive in ``unsigned-integer-overflow`` sanitizer - (`#1377 `_). - -* Fixed various warnings and compilation issues - (`#1273 `_, - `#1278 `_, - `#1280 `_, - `#1281 `_, - `#1288 `_, - `#1290 `_, - `#1301 `_, - `#1305 `_, - `#1306 `_, - `#1309 `_, - `#1312 `_, - `#1313 `_, - `#1316 `_, - `#1319 `_, - `#1320 `_, - `#1326 `_, - `#1328 `_, - `#1344 `_, - `#1345 `_, - `#1347 `_, - `#1349 `_, - `#1354 `_, - `#1362 `_, - `#1366 `_, - `#1364 `_, - `#1370 `_, - `#1371 `_, - `#1385 `_, - `#1388 `_, - `#1397 `_, - `#1414 `_, - `#1416 `_, - `#1422 `_ - `#1427 `_, - `#1431 `_, - `#1433 `_). - Thanks `@hhb `_, - `@gsjaardema (Greg Sjaardema) `_, - `@gabime (Gabi Melman) `_, - `@neheb (Rosen Penev) `_, - `@vedranmiletic (Vedran Miletić) `_, - `@dkavolis (Daumantas Kavolis) `_, - `@mwinterb `_, - `@orivej (Orivej Desh) `_, - `@denizevrenci (Deniz Evrenci) `_ - `@leonklingele `_, - `@chronoxor (Ivan Shynkarenka) `_, - `@kent-tri `_, - `@0x8000-0000 (Florin Iucha) `_, - `@marti4d (Chris Martin) `_. - -6.0.0 - 2019-08-26 ------------------- - -* Switched to the `MIT license - `_ - with an optional exception that allows distributing binary code without - attribution. - -* Floating-point formatting is now locale-independent by default: - - .. code:: c++ - - #include - #include - - int main() { - std::locale::global(std::locale("ru_RU.UTF-8")); - fmt::print("value = {}", 4.2); - } - - prints "value = 4.2" regardless of the locale. - - For locale-specific formatting use the ``n`` specifier: - - .. code:: c++ - - std::locale::global(std::locale("ru_RU.UTF-8")); - fmt::print("value = {:n}", 4.2); - - prints "value = 4,2". - -* Added an experimental Grisu floating-point formatting algorithm - implementation (disabled by default). To enable it compile with the - ``FMT_USE_GRISU`` macro defined to 1: - - .. code:: c++ - - #define FMT_USE_GRISU 1 - #include - - auto s = fmt::format("{}", 4.2); // formats 4.2 using Grisu - - With Grisu enabled, {fmt} is 13x faster than ``std::ostringstream`` (libc++) - and 10x faster than ``sprintf`` on `dtoa-benchmark - `_ (`full results - `_): - - .. image:: https://user-images.githubusercontent.com/576385/ - 54883977-9fe8c000-4e28-11e9-8bde-272d122e7c52.jpg - -* Separated formatting and parsing contexts for consistency with - `C++20 std::format `_, removing the - undocumented ``basic_format_context::parse_context()`` function. - -* Added `oss-fuzz `_ support - (`#1199 `_). - Thanks `@pauldreik (Paul Dreik) `_. - -* ``formatter`` specializations now always take precedence over ``operator<<`` - (`#952 `_): - - .. code:: c++ - - #include - #include - - struct S {}; - - std::ostream& operator<<(std::ostream& os, S) { - return os << 1; - } - - template <> - struct fmt::formatter : fmt::formatter { - auto format(S, format_context& ctx) { - return formatter::format(2, ctx); - } - }; - - int main() { - std::cout << S() << "\n"; // prints 1 using operator<< - fmt::print("{}\n", S()); // prints 2 using formatter - } - -* Introduced the experimental ``fmt::compile`` function that does format string - compilation (`#618 `_, - `#1169 `_, - `#1171 `_): - - .. code:: c++ - - #include - - auto f = fmt::compile("{}"); - std::string s = fmt::format(f, 42); // can be called multiple times to - // format different values - // s == "42" - - It moves the cost of parsing a format string outside of the format function - which can be beneficial when identically formatting many objects of the same - types. Thanks `@stryku (Mateusz Janek) `_. - -* Added experimental ``%`` format specifier that formats floating-point values - as percentages (`#1060 `_, - `#1069 `_, - `#1071 `_): - - .. code:: c++ - - auto s = fmt::format("{:.1%}", 0.42); // s == "42.0%" - - Thanks `@gawain-bolton (Gawain Bolton) `_. - -* Implemented precision for floating-point durations - (`#1004 `_, - `#1012 `_): - - .. code:: c++ - - auto s = fmt::format("{:.1}", std::chrono::duration(1.234)); - // s == 1.2s - - Thanks `@DanielaE (Daniela Engert) `_. - -* Implemented ``chrono`` format specifiers ``%Q`` and ``%q`` that give the value - and the unit respectively (`#1019 `_): - - .. code:: c++ - - auto value = fmt::format("{:%Q}", 42s); // value == "42" - auto unit = fmt::format("{:%q}", 42s); // unit == "s" - - Thanks `@DanielaE (Daniela Engert) `_. - -* Fixed handling of dynamic width in chrono formatter: - - .. code:: c++ - - auto s = fmt::format("{0:{1}%H:%M:%S}", std::chrono::seconds(12345), 12); - // ^ width argument index ^ width - // s == "03:25:45 " - - Thanks Howard Hinnant. - -* Removed deprecated ``fmt/time.h``. Use ``fmt/chrono.h`` instead. - -* Added ``fmt::format`` and ``fmt::vformat`` overloads that take ``text_style`` - (`#993 `_, - `#994 `_): - - .. code:: c++ - - #include - - std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red), - "The answer is {}.", 42); - - Thanks `@Naios (Denis Blank) `_. - -* Removed the deprecated color API (``print_colored``). Use the new API, namely - ``print`` overloads that take ``text_style`` instead. - -* Made ``std::unique_ptr`` and ``std::shared_ptr`` formattable as pointers via - ``fmt::ptr`` (`#1121 `_): - - .. code:: c++ - - std::unique_ptr p = ...; - fmt::print("{}", fmt::ptr(p)); // prints p as a pointer - - Thanks `@sighingnow (Tao He) `_. - -* Made ``print`` and ``vprint`` report I/O errors - (`#1098 `_, - `#1099 `_). - Thanks `@BillyDonahue (Billy Donahue) `_. - -* Marked deprecated APIs with the ``[[deprecated]]`` attribute and removed - internal uses of deprecated APIs - (`#1022 `_). - Thanks `@eliaskosunen (Elias Kosunen) `_. - -* Modernized the codebase using more C++11 features and removing workarounds. - Most importantly, ``buffer_context`` is now an alias template, so - use ``buffer_context`` instead of ``buffer_context::type``. - These features require GCC 4.8 or later. - -* ``formatter`` specializations now always take precedence over implicit - conversions to ``int`` and the undocumented ``convert_to_int`` trait - is now deprecated. - -* Moved the undocumented ``basic_writer``, ``writer``, and ``wwriter`` types - to the ``internal`` namespace. - -* Removed deprecated ``basic_format_context::begin()``. Use ``out()`` instead. - -* Disallowed passing the result of ``join`` as an lvalue to prevent misuse. - -* Refactored the undocumented structs that represent parsed format specifiers - to simplify the API and allow multibyte fill. - -* Moved SFINAE to template parameters to reduce symbol sizes. - -* Switched to ``fputws`` for writing wide strings so that it's no longer - required to call ``_setmode`` on Windows - (`#1229 `_, - `#1243 `_). - Thanks `@jackoalan (Jack Andersen) `_. - -* Improved literal-based API - (`#1254 `_). - Thanks `@sylveon (Charles Milette) `_. - -* Added support for exotic platforms without ``uintptr_t`` such as IBM i - (AS/400) which has 128-bit pointers and only 64-bit integers - (`#1059 `_). - -* Added `Sublime Text syntax highlighting config - `_ - (`#1037 `_). - Thanks `@Kronuz (Germán Méndez Bravo) `_. - -* Added the ``FMT_ENFORCE_COMPILE_STRING`` macro to enforce the use of - compile-time format strings - (`#1231 `_). - Thanks `@jackoalan (Jack Andersen) `_. - -* Stopped setting ``CMAKE_BUILD_TYPE`` if {fmt} is a subproject - (`#1081 `_). - -* Various build improvements - (`#1039 `_, - `#1078 `_, - `#1091 `_, - `#1103 `_, - `#1177 `_). - Thanks `@luncliff (Park DongHa) `_, - `@jasonszang (Jason Shuo Zang) `_, - `@olafhering (Olaf Hering) `_, - `@Lecetem `_, - `@pauldreik (Paul Dreik) `_. - -* Improved documentation - (`#1049 `_, - `#1051 `_, - `#1083 `_, - `#1113 `_, - `#1114 `_, - `#1146 `_, - `#1180 `_, - `#1250 `_, - `#1252 `_, - `#1265 `_). - Thanks `@mikelui (Michael Lui) `_, - `@foonathan (Jonathan Müller) `_, - `@BillyDonahue (Billy Donahue) `_, - `@jwakely (Jonathan Wakely) `_, - `@kaisbe (Kais Ben Salah) `_, - `@sdebionne (Samuel Debionne) `_. - -* Fixed ambiguous formatter specialization in ``fmt/ranges.h`` - (`#1123 `_). - -* Fixed formatting of a non-empty ``std::filesystem::path`` which is an - infinitely deep range of its components - (`#1268 `_). - -* Fixed handling of general output iterators when formatting characters - (`#1056 `_, - `#1058 `_). - Thanks `@abolz (Alexander Bolz) `_. - -* Fixed handling of output iterators in ``formatter`` specialization for - ranges (`#1064 `_). - -* Fixed handling of exotic character types - (`#1188 `_). - -* Made chrono formatting work with exceptions disabled - (`#1062 `_). - -* Fixed DLL visibility issues - (`#1134 `_, - `#1147 `_). - Thanks `@denchat `_. - -* Disabled the use of UDL template extension on GCC 9 - (`#1148 `_). - -* Removed misplaced ``format`` compile-time checks from ``printf`` - (`#1173 `_). - -* Fixed issues in the experimental floating-point formatter - (`#1072 `_, - `#1129 `_, - `#1153 `_, - `#1155 `_, - `#1210 `_, - `#1222 `_). - Thanks `@alabuzhev (Alex Alabuzhev) `_. - -* Fixed bugs discovered by fuzzing or during fuzzing integration - (`#1124 `_, - `#1127 `_, - `#1132 `_, - `#1135 `_, - `#1136 `_, - `#1141 `_, - `#1142 `_, - `#1178 `_, - `#1179 `_, - `#1194 `_). - Thanks `@pauldreik (Paul Dreik) `_. - -* Fixed building tests on FreeBSD and Hurd - (`#1043 `_). - Thanks `@jackyf (Eugene V. Lyubimkin) `_. - -* Fixed various warnings and compilation issues - (`#998 `_, - `#1006 `_, - `#1008 `_, - `#1011 `_, - `#1025 `_, - `#1027 `_, - `#1028 `_, - `#1029 `_, - `#1030 `_, - `#1031 `_, - `#1054 `_, - `#1063 `_, - `#1068 `_, - `#1074 `_, - `#1075 `_, - `#1079 `_, - `#1086 `_, - `#1088 `_, - `#1089 `_, - `#1094 `_, - `#1101 `_, - `#1102 `_, - `#1105 `_, - `#1107 `_, - `#1115 `_, - `#1117 `_, - `#1118 `_, - `#1120 `_, - `#1123 `_, - `#1139 `_, - `#1140 `_, - `#1143 `_, - `#1144 `_, - `#1150 `_, - `#1151 `_, - `#1152 `_, - `#1154 `_, - `#1156 `_, - `#1159 `_, - `#1175 `_, - `#1181 `_, - `#1186 `_, - `#1187 `_, - `#1191 `_, - `#1197 `_, - `#1200 `_, - `#1203 `_, - `#1205 `_, - `#1206 `_, - `#1213 `_, - `#1214 `_, - `#1217 `_, - `#1228 `_, - `#1230 `_, - `#1232 `_, - `#1235 `_, - `#1236 `_, - `#1240 `_). - Thanks `@DanielaE (Daniela Engert) `_, - `@mwinterb `_, - `@eliaskosunen (Elias Kosunen) `_, - `@morinmorin `_, - `@ricco19 (Brian Ricciardelli) `_, - `@waywardmonkeys (Bruce Mitchener) `_, - `@chronoxor (Ivan Shynkarenka) `_, - `@remyabel `_, - `@pauldreik (Paul Dreik) `_, - `@gsjaardema (Greg Sjaardema) `_, - `@rcane (Ronny Krüger) `_, - `@mocabe `_, - `@denchat `_, - `@cjdb (Christopher Di Bella) `_, - `@HazardyKnusperkeks (Björn Schäpers) `_, - `@vedranmiletic (Vedran Miletić) `_, - `@jackoalan (Jack Andersen) `_, - `@DaanDeMeyer (Daan De Meyer) `_, - `@starkmapper (Mark Stapper) `_. - -5.3.0 - 2018-12-28 ------------------- - -* Introduced experimental chrono formatting support: - - .. code:: c++ - - #include - - int main() { - using namespace std::literals::chrono_literals; - fmt::print("Default format: {} {}\n", 42s, 100ms); - fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s); - } - - prints:: - - Default format: 42s 100ms - strftime-like format: 03:15:30 - -* Added experimental support for emphasis (bold, italic, underline, - strikethrough), colored output to a file stream, and improved colored - formatting API - (`#961 `_, - `#967 `_, - `#973 `_): - - .. code:: c++ - - #include - - int main() { - print(fg(fmt::color::crimson) | fmt::emphasis::bold, - "Hello, {}!\n", "world"); - print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) | - fmt::emphasis::underline, "Hello, {}!\n", "мир"); - print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, - "Hello, {}!\n", "世界"); - } - - prints the following on modern terminals with RGB color support: - - .. image:: https://user-images.githubusercontent.com/576385/ - 50405788-b66e7500-076e-11e9-9592-7324d1f951d8.png - - Thanks `@Rakete1111 (Nicolas) `_. - -* Added support for 4-bit terminal colors - (`#968 `_, - `#974 `_) - - .. code:: c++ - - #include - - int main() { - print(fg(fmt::terminal_color::red), "stop\n"); - } - - Note that these colors vary by terminal: - - .. image:: https://user-images.githubusercontent.com/576385/ - 50405925-dbfc7e00-0770-11e9-9b85-333fab0af9ac.png - - Thanks `@Rakete1111 (Nicolas) `_. - -* Parameterized formatting functions on the type of the format string - (`#880 `_, - `#881 `_, - `#883 `_, - `#885 `_, - `#897 `_, - `#920 `_). - Any object of type ``S`` that has an overloaded ``to_string_view(const S&)`` - returning ``fmt::string_view`` can be used as a format string: - - .. code:: c++ - - namespace my_ns { - inline string_view to_string_view(const my_string& s) { - return {s.data(), s.length()}; - } - } - - std::string message = fmt::format(my_string("The answer is {}."), 42); - - Thanks `@DanielaE (Daniela Engert) `_. - -* Made ``std::string_view`` work as a format string - (`#898 `_): - - .. code:: c++ - - auto message = fmt::format(std::string_view("The answer is {}."), 42); - - Thanks `@DanielaE (Daniela Engert) `_. - -* Added wide string support to compile-time format string checks - (`#924 `_): - - .. code:: c++ - - print(fmt(L"{:f}"), 42); // compile-time error: invalid type specifier - - Thanks `@XZiar `_. - -* Made colored print functions work with wide strings - (`#867 `_): - - .. code:: c++ - - #include - - int main() { - print(fg(fmt::color::red), L"{}\n", 42); - } - - Thanks `@DanielaE (Daniela Engert) `_. - -* Introduced experimental Unicode support - (`#628 `_, - `#891 `_): - - .. code:: c++ - - using namespace fmt::literals; - auto s = fmt::format("{:*^5}"_u, "🤡"_u); // s == "**🤡**"_u - -* Improved locale support: - - .. code:: c++ - - #include - - struct numpunct : std::numpunct { - protected: - char do_thousands_sep() const override { return '~'; } - }; - - std::locale loc; - auto s = fmt::format(std::locale(loc, new numpunct()), "{:n}", 1234567); - // s == "1~234~567" - -* Constrained formatting functions on proper iterator types - (`#921 `_). - Thanks `@DanielaE (Daniela Engert) `_. - -* Added ``make_printf_args`` and ``make_wprintf_args`` functions - (`#934 `_). - Thanks `@tnovotny `_. - -* Deprecated ``fmt::visit``, ``parse_context``, and ``wparse_context``. - Use ``fmt::visit_format_arg``, ``format_parse_context``, and - ``wformat_parse_context`` instead. - -* Removed undocumented ``basic_fixed_buffer`` which has been superseded by the - iterator-based API - (`#873 `_, - `#902 `_). - Thanks `@superfunc (hollywood programmer) `_. - -* Disallowed repeated leading zeros in an argument ID: - - .. code:: c++ - - fmt::print("{000}", 42); // error - -* Reintroduced support for gcc 4.4. - -* Fixed compilation on platforms with exotic ``double`` - (`#878 `_). - -* Improved documentation - (`#164 `_, - `#877 `_, - `#901 `_, - `#906 `_, - `#979 `_). - Thanks `@kookjr (Mathew Cucuzella) `_, - `@DarkDimius (Dmitry Petrashko) `_, - `@HecticSerenity `_. - -* Added pkgconfig support which makes it easier to consume the library from - meson and other build systems - (`#916 `_). - Thanks `@colemickens (Cole Mickens) `_. - -* Various build improvements - (`#909 `_, - `#926 `_, - `#937 `_, - `#953 `_, - `#959 `_). - Thanks `@tchaikov (Kefu Chai) `_, - `@luncliff (Park DongHa) `_, - `@AndreasSchoenle (Andreas Schönle) `_, - `@hotwatermorning `_, - `@Zefz (JohanJansen) `_. - -* Improved ``string_view`` construction performance - (`#914 `_). - Thanks `@gabime (Gabi Melman) `_. - -* Fixed non-matching char types - (`#895 `_). - Thanks `@DanielaE (Daniela Engert) `_. - -* Fixed ``format_to_n`` with ``std::back_insert_iterator`` - (`#913 `_). - Thanks `@DanielaE (Daniela Engert) `_. - -* Fixed locale-dependent formatting - (`#905 `_). - -* Fixed various compiler warnings and errors - (`#882 `_, - `#886 `_, - `#933 `_, - `#941 `_, - `#931 `_, - `#943 `_, - `#954 `_, - `#956 `_, - `#962 `_, - `#965 `_, - `#977 `_, - `#983 `_, - `#989 `_). - Thanks `@Luthaf (Guillaume Fraux) `_, - `@stevenhoving (Steven Hoving) `_, - `@christinaa (Kristina Brooks) `_, - `@lgritz (Larry Gritz) `_, - `@DanielaE (Daniela Engert) `_, - `@0x8000-0000 (Sign Bit) `_, - `@liuping1997 `_. - -5.2.1 - 2018-09-21 ------------------- - -* Fixed ``visit`` lookup issues on gcc 7 & 8 - (`#870 `_). - Thanks `@medithe `_. - -* Fixed linkage errors on older gcc. - -* Prevented ``fmt/range.h`` from specializing ``fmt::basic_string_view`` - (`#865 `_, - `#868 `_). - Thanks `@hhggit (dual) `_. - -* Improved error message when formatting unknown types - (`#872 `_). - Thanks `@foonathan (Jonathan Müller) `_, - -* Disabled templated user-defined literals when compiled under nvcc - (`#875 `_). - Thanks `@CandyGumdrop (Candy Gumdrop) `_, - -* Fixed ``format_to`` formatting to ``wmemory_buffer`` - (`#874 `_). - -5.2.0 - 2018-09-13 ------------------- - -* Optimized format string parsing and argument processing which resulted in up - to 5x speed up on long format strings and significant performance boost on - various benchmarks. For example, version 5.2 is 2.22x faster than 5.1 on - decimal integer formatting with ``format_to`` (macOS, clang-902.0.39.2): - - ================== ======= ======= - Method Time, s Speedup - ================== ======= ======= - fmt::format 5.1 0.58 - fmt::format 5.2 0.35 1.66x - fmt::format_to 5.1 0.51 - fmt::format_to 5.2 0.23 2.22x - sprintf 0.71 - std::to_string 1.01 - std::stringstream 1.73 - ================== ======= ======= - -* Changed the ``fmt`` macro from opt-out to opt-in to prevent name collisions. - To enable it define the ``FMT_STRING_ALIAS`` macro to 1 before including - ``fmt/format.h``: - - .. code:: c++ - - #define FMT_STRING_ALIAS 1 - #include - std::string answer = format(fmt("{}"), 42); - -* Added compile-time format string checks to ``format_to`` overload that takes - ``fmt::memory_buffer`` (`#783 `_): - - .. code:: c++ - - fmt::memory_buffer buf; - // Compile-time error: invalid type specifier. - fmt::format_to(buf, fmt("{:d}"), "foo"); - -* Moved experimental color support to ``fmt/color.h`` and enabled the - new API by default. The old API can be enabled by defining the - ``FMT_DEPRECATED_COLORS`` macro. - -* Added formatting support for types explicitly convertible to - ``fmt::string_view``: - - .. code:: c++ - - struct foo { - explicit operator fmt::string_view() const { return "foo"; } - }; - auto s = format("{}", foo()); - - In particular, this makes formatting function work with - ``folly::StringPiece``. - -* Implemented preliminary support for ``char*_t`` by replacing the ``format`` - function overloads with a single function template parameterized on the string - type. - -* Added support for dynamic argument lists - (`#814 `_, - `#819 `_). - Thanks `@MikePopoloski (Michael Popoloski) - `_. - -* Reduced executable size overhead for embedded targets using newlib nano by - making locale dependency optional - (`#839 `_). - Thanks `@teajay-fr (Thomas Benard) `_. - -* Keep ``noexcept`` specifier when exceptions are disabled - (`#801 `_, - `#810 `_). - Thanks `@qis (Alexej Harm) `_. - -* Fixed formatting of user-defined types providing ``operator<<`` with - ``format_to_n`` - (`#806 `_). - Thanks `@mkurdej (Marek Kurdej) `_. - -* Fixed dynamic linkage of new symbols - (`#808 `_). - -* Fixed global initialization issue - (`#807 `_): - - .. code:: c++ - - // This works on compilers with constexpr support. - static const std::string answer = fmt::format("{}", 42); - -* Fixed various compiler warnings and errors - (`#804 `_, - `#809 `_, - `#811 `_, - `#822 `_, - `#827 `_, - `#830 `_, - `#838 `_, - `#843 `_, - `#844 `_, - `#851 `_, - `#852 `_, - `#854 `_). - Thanks `@henryiii (Henry Schreiner) `_, - `@medithe `_, and - `@eliasdaler (Elias Daler) `_. - -5.1.0 - 2018-07-05 ------------------- - -* Added experimental support for RGB color output enabled with - the ``FMT_EXTENDED_COLORS`` macro: - - .. code:: c++ - - #define FMT_EXTENDED_COLORS - #define FMT_HEADER_ONLY // or compile fmt with FMT_EXTENDED_COLORS defined - #include - - fmt::print(fmt::color::steel_blue, "Some beautiful text"); - - The old API (the ``print_colored`` and ``vprint_colored`` functions and the - ``color`` enum) is now deprecated. - (`#762 `_ - `#767 `_). - thanks `@Remotion (Remo) `_. - -* Added quotes to strings in ranges and tuples - (`#766 `_). - Thanks `@Remotion (Remo) `_. - -* Made ``format_to`` work with ``basic_memory_buffer`` - (`#776 `_). - -* Added ``vformat_to_n`` and ``wchar_t`` overload of ``format_to_n`` - (`#764 `_, - `#769 `_). - -* Made ``is_range`` and ``is_tuple_like`` part of public (experimental) API - to allow specialization for user-defined types - (`#751 `_, - `#759 `_). - Thanks `@drrlvn (Dror Levin) `_. - -* Added more compilers to continuous integration and increased ``FMT_PEDANTIC`` - warning levels - (`#736 `_). - Thanks `@eliaskosunen (Elias Kosunen) `_. - -* Fixed compilation with MSVC 2013. - -* Fixed handling of user-defined types in ``format_to`` - (`#793 `_). - -* Forced linking of inline ``vformat`` functions into the library - (`#795 `_). - -* Fixed incorrect call to on_align in ``'{:}='`` - (`#750 `_). - -* Fixed floating-point formatting to a non-back_insert_iterator with sign & - numeric alignment specified - (`#756 `_). - -* Fixed formatting to an array with ``format_to_n`` - (`#778 `_). - -* Fixed formatting of more than 15 named arguments - (`#754 `_). - -* Fixed handling of compile-time strings when including ``fmt/ostream.h``. - (`#768 `_). - -* Fixed various compiler warnings and errors - (`#742 `_, - `#748 `_, - `#752 `_, - `#770 `_, - `#775 `_, - `#779 `_, - `#780 `_, - `#790 `_, - `#792 `_, - `#800 `_). - Thanks `@Remotion (Remo) `_, - `@gabime (Gabi Melman) `_, - `@foonathan (Jonathan Müller) `_, - `@Dark-Passenger (Dhruv Paranjape) `_, and - `@0x8000-0000 (Sign Bit) `_. - -5.0.0 - 2018-05-21 ------------------- - -* Added a requirement for partial C++11 support, most importantly variadic - templates and type traits, and dropped ``FMT_VARIADIC_*`` emulation macros. - Variadic templates are available since GCC 4.4, Clang 2.9 and MSVC 18.0 (2013). - For older compilers use {fmt} `version 4.x - `_ which continues to be - maintained and works with C++98 compilers. - -* Renamed symbols to follow standard C++ naming conventions and proposed a subset - of the library for standardization in `P0645R2 Text Formatting - `_. - -* Implemented ``constexpr`` parsing of format strings and `compile-time format - string checks - `_. For - example - - .. code:: c++ - - #include - - std::string s = format(fmt("{:d}"), "foo"); - - gives a compile-time error because ``d`` is an invalid specifier for strings - (`godbolt `__):: - - ... - :4:19: note: in instantiation of function template specialization 'fmt::v5::format' requested here - std::string s = format(fmt("{:d}"), "foo"); - ^ - format.h:1337:13: note: non-constexpr function 'on_error' cannot be used in a constant expression - handler.on_error("invalid type specifier"); - - Compile-time checks require relaxed ``constexpr`` (C++14 feature) support. If - the latter is not available, checks will be performed at runtime. - -* Separated format string parsing and formatting in the extension API to enable - compile-time format string processing. For example - - .. code:: c++ - - struct Answer {}; - - namespace fmt { - template <> - struct formatter { - constexpr auto parse(parse_context& ctx) { - auto it = ctx.begin(); - spec = *it; - if (spec != 'd' && spec != 's') - throw format_error("invalid specifier"); - return ++it; - } - - template - auto format(Answer, FormatContext& ctx) { - return spec == 's' ? - format_to(ctx.begin(), "{}", "fourty-two") : - format_to(ctx.begin(), "{}", 42); - } - - char spec = 0; - }; - } - - std::string s = format(fmt("{:x}"), Answer()); - - gives a compile-time error due to invalid format specifier (`godbolt - `__):: - - ... - :12:45: error: expression '' is not a constant expression - throw format_error("invalid specifier"); - -* Added `iterator support - `_: - - .. code:: c++ - - #include - #include - - std::vector out; - fmt::format_to(std::back_inserter(out), "{}", 42); - -* Added the `format_to_n - `_ - function that restricts the output to the specified number of characters - (`#298 `_): - - .. code:: c++ - - char out[4]; - fmt::format_to_n(out, sizeof(out), "{}", 12345); - // out == "1234" (without terminating '\0') - -* Added the `formatted_size - `_ - function for computing the output size: - - .. code:: c++ - - #include - - auto size = fmt::formatted_size("{}", 12345); // size == 5 - -* Improved compile times by reducing dependencies on standard headers and - providing a lightweight `core API `_: - - .. code:: c++ - - #include - - fmt::print("The answer is {}.", 42); - - See `Compile time and code bloat - `_. - -* Added the `make_format_args - `_ - function for capturing formatting arguments: - - .. code:: c++ - - // Prints formatted error message. - void vreport_error(const char *format, fmt::format_args args) { - fmt::print("Error: "); - fmt::vprint(format, args); - } - template - void report_error(const char *format, const Args & ... args) { - vreport_error(format, fmt::make_format_args(args...)); - } - -* Added the ``make_printf_args`` function for capturing ``printf`` arguments - (`#687 `_, - `#694 `_). - Thanks `@Kronuz (Germán Méndez Bravo) `_. - -* Added prefix ``v`` to non-variadic functions taking ``format_args`` to - distinguish them from variadic ones: - - .. code:: c++ - - std::string vformat(string_view format_str, format_args args); - - template - std::string format(string_view format_str, const Args & ... args); - -* Added experimental support for formatting ranges, containers and tuple-like - types in ``fmt/ranges.h`` (`#735 `_): - - .. code:: c++ - - #include - - std::vector v = {1, 2, 3}; - fmt::print("{}", v); // prints {1, 2, 3} - - Thanks `@Remotion (Remo) `_. - -* Implemented ``wchar_t`` date and time formatting - (`#712 `_): - - .. code:: c++ - - #include - - std::time_t t = std::time(nullptr); - auto s = fmt::format(L"The date is {:%Y-%m-%d}.", *std::localtime(&t)); - - Thanks `@DanielaE (Daniela Engert) `_. - -* Provided more wide string overloads - (`#724 `_). - Thanks `@DanielaE (Daniela Engert) `_. - -* Switched from a custom null-terminated string view class to ``string_view`` - in the format API and provided ``fmt::string_view`` which implements a subset - of ``std::string_view`` API for pre-C++17 systems. - -* Added support for ``std::experimental::string_view`` - (`#607 `_): - - .. code:: c++ - - #include - #include - - fmt::print("{}", std::experimental::string_view("foo")); - - Thanks `@virgiliofornazin (Virgilio Alexandre Fornazin) - `__. - -* Allowed mixing named and automatic arguments: - - .. code:: c++ - - fmt::format("{} {two}", 1, fmt::arg("two", 2)); - -* Removed the write API in favor of the `format API - `_ with compile-time handling of - format strings. - -* Disallowed formatting of multibyte strings into a wide character target - (`#606 `_). - -* Improved documentation - (`#515 `_, - `#614 `_, - `#617 `_, - `#661 `_, - `#680 `_). - Thanks `@ibell (Ian Bell) `_, - `@mihaitodor (Mihai Todor) `_, and - `@johnthagen `_. - -* Implemented more efficient handling of large number of format arguments. - -* Introduced an inline namespace for symbol versioning. - -* Added debug postfix ``d`` to the ``fmt`` library name - (`#636 `_). - -* Removed unnecessary ``fmt/`` prefix in includes - (`#397 `_). - Thanks `@chronoxor (Ivan Shynkarenka) `_. - -* Moved ``fmt/*.h`` to ``include/fmt/*.h`` to prevent irrelevant files and - directories appearing on the include search paths when fmt is used as a - subproject and moved source files to the ``src`` directory. - -* Added qmake project file ``support/fmt.pro`` - (`#641 `_). - Thanks `@cowo78 (Giuseppe Corbelli) `_. - -* Added Gradle build file ``support/build.gradle`` - (`#649 `_). - Thanks `@luncliff (Park DongHa) `_. - -* Removed ``FMT_CPPFORMAT`` CMake option. - -* Fixed a name conflict with the macro ``CHAR_WIDTH`` in glibc - (`#616 `_). - Thanks `@aroig (Abdó Roig-Maranges) `_. - -* Fixed handling of nested braces in ``fmt::join`` - (`#638 `_). - -* Added ``SOURCELINK_SUFFIX`` for compatibility with Sphinx 1.5 - (`#497 `_). - Thanks `@ginggs (Graham Inggs) `_. - -* Added a missing ``inline`` in the header-only mode - (`#626 `_). - Thanks `@aroig (Abdó Roig-Maranges) `_. - -* Fixed various compiler warnings - (`#640 `_, - `#656 `_, - `#679 `_, - `#681 `_, - `#705 `__, - `#715 `_, - `#717 `_, - `#720 `_, - `#723 `_, - `#726 `_, - `#730 `_, - `#739 `_). - Thanks `@peterbell10 `_, - `@LarsGullik `_, - `@foonathan (Jonathan Müller) `_, - `@eliaskosunen (Elias Kosunen) `_, - `@christianparpart (Christian Parpart) `_, - `@DanielaE (Daniela Engert) `_, - and `@mwinterb `_. - -* Worked around an MSVC bug and fixed several warnings - (`#653 `_). - Thanks `@alabuzhev (Alex Alabuzhev) `_. - -* Worked around GCC bug 67371 - (`#682 `_). - -* Fixed compilation with ``-fno-exceptions`` - (`#655 `_). - Thanks `@chenxiaolong (Andrew Gunnerson) `_. - -* Made ``constexpr remove_prefix`` gcc version check tighter - (`#648 `_). - -* Renamed internal type enum constants to prevent collision with poorly written - C libraries (`#644 `_). - -* Added detection of ``wostream operator<<`` - (`#650 `_). - -* Fixed compilation on OpenBSD - (`#660 `_). - Thanks `@hubslave `_. - -* Fixed compilation on FreeBSD 12 - (`#732 `_). - Thanks `@dankm `_. - -* Fixed compilation when there is a mismatch between ``-std`` options between - the library and user code - (`#664 `_). - -* Fixed compilation with GCC 7 and ``-std=c++11`` - (`#734 `_). - -* Improved generated binary code on GCC 7 and older - (`#668 `_). - -* Fixed handling of numeric alignment with no width - (`#675 `_). - -* Fixed handling of empty strings in UTF8/16 converters - (`#676 `_). - Thanks `@vgalka-sl (Vasili Galka) `_. - -* Fixed formatting of an empty ``string_view`` - (`#689 `_). - -* Fixed detection of ``string_view`` on libc++ - (`#686 `_). - -* Fixed DLL issues (`#696 `_). - Thanks `@sebkoenig `_. - -* Fixed compile checks for mixing narrow and wide strings - (`#690 `_). - -* Disabled unsafe implicit conversion to ``std::string`` - (`#729 `_). - -* Fixed handling of reused format specs (as in ``fmt::join``) for pointers - (`#725 `_). - Thanks `@mwinterb `_. - -* Fixed installation of ``fmt/ranges.h`` - (`#738 `_). - Thanks `@sv1990 `_. - -4.1.0 - 2017-12-20 ------------------- - -* Added ``fmt::to_wstring()`` in addition to ``fmt::to_string()`` - (`#559 `_). - Thanks `@alabuzhev (Alex Alabuzhev) `_. - -* Added support for C++17 ``std::string_view`` - (`#571 `_ and - `#578 `_). - Thanks `@thelostt (Mário Feroldi) `_ and - `@mwinterb `_. - -* Enabled stream exceptions to catch errors - (`#581 `_). - Thanks `@crusader-mike `_. - -* Allowed formatting of class hierarchies with ``fmt::format_arg()`` - (`#547 `_). - Thanks `@rollbear (Björn Fahller) `_. - -* Removed limitations on character types - (`#563 `_). - Thanks `@Yelnats321 (Elnar Dakeshov) `_. - -* Conditionally enabled use of ``std::allocator_traits`` - (`#583 `_). - Thanks `@mwinterb `_. - -* Added support for ``const`` variadic member function emulation with - ``FMT_VARIADIC_CONST`` (`#591 `_). - Thanks `@ludekvodicka (Ludek Vodicka) `_. - -* Various bugfixes: bad overflow check, unsupported implicit type conversion - when determining formatting function, test segfaults - (`#551 `_), ill-formed macros - (`#542 `_) and ambiguous overloads - (`#580 `_). - Thanks `@xylosper (Byoung-young Lee) `_. - -* Prevented warnings on MSVC (`#605 `_, - `#602 `_, and - `#545 `_), - clang (`#582 `_), - GCC (`#573 `_), - various conversion warnings (`#609 `_, - `#567 `_, - `#553 `_ and - `#553 `_), and added ``override`` and - ``[[noreturn]]`` (`#549 `_ and - `#555 `_). - Thanks `@alabuzhev (Alex Alabuzhev) `_, - `@virgiliofornazin (Virgilio Alexandre Fornazin) - `_, - `@alexanderbock (Alexander Bock) `_, - `@yumetodo `_, - `@VaderY (Császár Mátyás) `_, - `@jpcima (JP Cimalando) `_, - `@thelostt (Mário Feroldi) `_, and - `@Manu343726 (Manu Sánchez) `_. - -* Improved CMake: Used ``GNUInstallDirs`` to set installation location - (`#610 `_) and fixed warnings - (`#536 `_ and - `#556 `_). - Thanks `@mikecrowe (Mike Crowe) `_, - `@evgen231 `_ and - `@henryiii (Henry Schreiner) `_. - -4.0.0 - 2017-06-27 ------------------- - -* Removed old compatibility headers ``cppformat/*.h`` and CMake options - (`#527 `_). - Thanks `@maddinat0r (Alex Martin) `_. - -* Added ``string.h`` containing ``fmt::to_string()`` as alternative to - ``std::to_string()`` as well as other string writer functionality - (`#326 `_ and - `#441 `_): - - .. code:: c++ - - #include "fmt/string.h" - - std::string answer = fmt::to_string(42); - - Thanks to `@glebov-andrey (Andrey Glebov) - `_. - -* Moved ``fmt::printf()`` to new ``printf.h`` header and allowed ``%s`` as - generic specifier (`#453 `_), - made ``%.f`` more conformant to regular ``printf()`` - (`#490 `_), added custom writer - support (`#476 `_) and implemented - missing custom argument formatting - (`#339 `_ and - `#340 `_): - - .. code:: c++ - - #include "fmt/printf.h" - - // %s format specifier can be used with any argument type. - fmt::printf("%s", 42); - - Thanks `@mojoBrendan `_, - `@manylegged (Arthur Danskin) `_ and - `@spacemoose (Glen Stark) `_. - See also `#360 `_, - `#335 `_ and - `#331 `_. - -* Added ``container.h`` containing a ``BasicContainerWriter`` - to write to containers like ``std::vector`` - (`#450 `_). - Thanks `@polyvertex (Jean-Charles Lefebvre) `_. - -* Added ``fmt::join()`` function that takes a range and formats - its elements separated by a given string - (`#466 `_): - - .. code:: c++ - - #include "fmt/format.h" - - std::vector v = {1.2, 3.4, 5.6}; - // Prints "(+01.20, +03.40, +05.60)". - fmt::print("({:+06.2f})", fmt::join(v.begin(), v.end(), ", ")); - - Thanks `@olivier80 `_. - -* Added support for custom formatting specifications to simplify customization - of built-in formatting (`#444 `_). - Thanks `@polyvertex (Jean-Charles Lefebvre) `_. - See also `#439 `_. - -* Added ``fmt::format_system_error()`` for error code formatting - (`#323 `_ and - `#526 `_). - Thanks `@maddinat0r (Alex Martin) `_. - -* Added thread-safe ``fmt::localtime()`` and ``fmt::gmtime()`` - as replacement for the standard version to ``time.h`` - (`#396 `_). - Thanks `@codicodi `_. - -* Internal improvements to ``NamedArg`` and ``ArgLists`` - (`#389 `_ and - `#390 `_). - Thanks `@chronoxor `_. - -* Fixed crash due to bug in ``FormatBuf`` - (`#493 `_). - Thanks `@effzeh `_. See also - `#480 `_ and - `#491 `_. - -* Fixed handling of wide strings in ``fmt::StringWriter``. - -* Improved compiler error messages - (`#357 `_). - -* Fixed various warnings and issues with various compilers - (`#494 `_, - `#499 `_, - `#483 `_, - `#485 `_, - `#482 `_, - `#475 `_, - `#473 `_ and - `#414 `_). - Thanks `@chronoxor `_, - `@zhaohuaxishi `_, - `@pkestene (Pierre Kestener) `_, - `@dschmidt (Dominik Schmidt) `_ and - `@0x414c (Alexey Gorishny) `_ . - -* Improved CMake: targets are now namespaced - (`#511 `_ and - `#513 `_), supported header-only - ``printf.h`` (`#354 `_), fixed issue - with minimal supported library subset - (`#418 `_, - `#419 `_ and - `#420 `_). - Thanks `@bjoernthiel (Bjoern Thiel) `_, - `@niosHD (Mario Werner) `_, - `@LogicalKnight (Sean LK) `_ and - `@alabuzhev (Alex Alabuzhev) `_. - -* Improved documentation. Thanks to - `@pwm1234 (Phil) `_ for - `#393 `_. - -3.0.2 - 2017-06-14 ------------------- - -* Added ``FMT_VERSION`` macro - (`#411 `_). - -* Used ``FMT_NULL`` instead of literal ``0`` - (`#409 `_). - Thanks `@alabuzhev (Alex Alabuzhev) `_. - -* Added extern templates for ``format_float`` - (`#413 `_). - -* Fixed implicit conversion issue - (`#507 `_). - -* Fixed signbit detection (`#423 `_). - -* Fixed naming collision (`#425 `_). - -* Fixed missing intrinsic for C++/CLI - (`#457 `_). - Thanks `@calumr (Calum Robinson) `_ - -* Fixed Android detection (`#458 `_). - Thanks `@Gachapen (Magnus Bjerke Vik) `_. - -* Use lean ``windows.h`` if not in header-only mode - (`#503 `_). - Thanks `@Quentin01 (Quentin Buathier) `_. - -* Fixed issue with CMake exporting C++11 flag - (`#445 `_). - Thanks `@EricWF (Eric) `_. - -* Fixed issue with nvcc and MSVC compiler bug and MinGW - (`#505 `_). - -* Fixed DLL issues (`#469 `_ and - `#502 `_). - Thanks `@richardeakin (Richard Eakin) `_ and - `@AndreasSchoenle (Andreas Schönle) `_. - -* Fixed test compilation under FreeBSD - (`#433 `_). - -* Fixed various warnings (`#403 `_, - `#410 `_ and - `#510 `_). - Thanks `@Lecetem `_, - `@chenhayat (Chen Hayat) `_ and - `@trozen `_. - -* Worked around a broken ``__builtin_clz`` in clang with MS codegen - (`#519 `_). - -* Removed redundant include - (`#479 `_). - -* Fixed documentation issues. - -3.0.1 - 2016-11-01 ------------------- -* Fixed handling of thousands separator - (`#353 `_). - -* Fixed handling of ``unsigned char`` strings - (`#373 `_). - -* Corrected buffer growth when formatting time - (`#367 `_). - -* Removed warnings under MSVC and clang - (`#318 `_, - `#250 `_, also merged - `#385 `_ and - `#361 `_). - Thanks `@jcelerier (Jean-Michaël Celerier) `_ - and `@nmoehrle (Nils Moehrle) `_. - -* Fixed compilation issues under Android - (`#327 `_, - `#345 `_ and - `#381 `_), - FreeBSD (`#358 `_), - Cygwin (`#388 `_), - MinGW (`#355 `_) as well as other - issues (`#350 `_, - `#366 `_, - `#348 `_, - `#402 `_, - `#405 `_). - Thanks to `@dpantele (Dmitry) `_, - `@hghwng (Hugh Wang) `_, - `@arvedarved (Tilman Keskinöz) `_, - `@LogicalKnight (Sean) `_ and - `@JanHellwig (Jan Hellwig) `_. - -* Fixed some documentation issues and extended specification - (`#320 `_, - `#333 `_, - `#347 `_, - `#362 `_). - Thanks to `@smellman (Taro Matsuzawa aka. btm) - `_. - -3.0.0 - 2016-05-07 ------------------- - -* The project has been renamed from C++ Format (cppformat) to fmt for - consistency with the used namespace and macro prefix - (`#307 `_). - Library headers are now located in the ``fmt`` directory: - - .. code:: c++ - - #include "fmt/format.h" - - Including ``format.h`` from the ``cppformat`` directory is deprecated - but works via a proxy header which will be removed in the next major version. - - The documentation is now available at https://fmt.dev. - -* Added support for `strftime `_-like - `date and time formatting `_ - (`#283 `_): - - .. code:: c++ - - #include "fmt/time.h" - - std::time_t t = std::time(nullptr); - // Prints "The date is 2016-04-29." (with the current date) - fmt::print("The date is {:%Y-%m-%d}.", *std::localtime(&t)); - -* ``std::ostream`` support including formatting of user-defined types that provide - overloaded ``operator<<`` has been moved to ``fmt/ostream.h``: - - .. code:: c++ - - #include "fmt/ostream.h" - - class Date { - int year_, month_, day_; - public: - Date(int year, int month, int day) : year_(year), month_(month), day_(day) {} - - friend std::ostream &operator<<(std::ostream &os, const Date &d) { - return os << d.year_ << '-' << d.month_ << '-' << d.day_; - } - }; - - std::string s = fmt::format("The date is {}", Date(2012, 12, 9)); - // s == "The date is 2012-12-9" - -* Added support for `custom argument formatters - `_ - (`#235 `_). - -* Added support for locale-specific integer formatting with the ``n`` specifier - (`#305 `_): - - .. code:: c++ - - std::setlocale(LC_ALL, "en_US.utf8"); - fmt::print("cppformat: {:n}\n", 1234567); // prints 1,234,567 - -* Sign is now preserved when formatting an integer with an incorrect ``printf`` - format specifier (`#265 `_): - - .. code:: c++ - - fmt::printf("%lld", -42); // prints -42 - - Note that it would be an undefined behavior in ``std::printf``. - -* Length modifiers such as ``ll`` are now optional in printf formatting - functions and the correct type is determined automatically - (`#255 `_): - - .. code:: c++ - - fmt::printf("%d", std::numeric_limits::max()); - - Note that it would be an undefined behavior in ``std::printf``. - -* Added initial support for custom formatters - (`#231 `_). - -* Fixed detection of user-defined literal support on Intel C++ compiler - (`#311 `_, - `#312 `_). - Thanks to `@dean0x7d (Dean Moldovan) `_ and - `@speth (Ray Speth) `_. - -* Reduced compile time - (`#243 `_, - `#249 `_, - `#317 `_): - - .. image:: https://cloud.githubusercontent.com/assets/4831417/11614060/ - b9e826d2-9c36-11e5-8666-d4131bf503ef.png - - .. image:: https://cloud.githubusercontent.com/assets/4831417/11614080/ - 6ac903cc-9c37-11e5-8165-26df6efae364.png - - Thanks to `@dean0x7d (Dean Moldovan) `_. - -* Compile test fixes (`#313 `_). - Thanks to `@dean0x7d (Dean Moldovan) `_. - -* Documentation fixes (`#239 `_, - `#248 `_, - `#252 `_, - `#258 `_, - `#260 `_, - `#301 `_, - `#309 `_). - Thanks to `@ReadmeCritic `_ - `@Gachapen (Magnus Bjerke Vik) `_ and - `@jwilk (Jakub Wilk) `_. - -* Fixed compiler and sanitizer warnings - (`#244 `_, - `#256 `_, - `#259 `_, - `#263 `_, - `#274 `_, - `#277 `_, - `#286 `_, - `#291 `_, - `#296 `_, - `#308 `_) - Thanks to `@mwinterb `_, - `@pweiskircher (Patrik Weiskircher) `_, - `@Naios `_. - -* Improved compatibility with Windows Store apps - (`#280 `_, - `#285 `_) - Thanks to `@mwinterb `_. - -* Added tests of compatibility with older C++ standards - (`#273 `_). - Thanks to `@niosHD `_. - -* Fixed Android build (`#271 `_). - Thanks to `@newnon `_. - -* Changed ``ArgMap`` to be backed by a vector instead of a map. - (`#261 `_, - `#262 `_). - Thanks to `@mwinterb `_. - -* Added ``fprintf`` overload that writes to a ``std::ostream`` - (`#251 `_). - Thanks to `nickhutchinson (Nicholas Hutchinson) `_. - -* Export symbols when building a Windows DLL - (`#245 `_). - Thanks to `macdems (Maciek Dems) `_. - -* Fixed compilation on Cygwin (`#304 `_). - -* Implemented a workaround for a bug in Apple LLVM version 4.2 of clang - (`#276 `_). - -* Implemented a workaround for Google Test bug - `#705 `_ on gcc 6 - (`#268 `_). - Thanks to `octoploid `_. - -* Removed Biicode support because the latter has been discontinued. - -2.1.1 - 2016-04-11 ------------------- - -* The install location for generated CMake files is now configurable via - the ``FMT_CMAKE_DIR`` CMake variable - (`#299 `_). - Thanks to `@niosHD `_. - -* Documentation fixes (`#252 `_). - -2.1.0 - 2016-03-21 ------------------- - -* Project layout and build system improvements - (`#267 `_): - - * The code have been moved to the ``cppformat`` directory. - Including ``format.h`` from the top-level directory is deprecated - but works via a proxy header which will be removed in the next - major version. - - * C++ Format CMake targets now have proper interface definitions. - - * Installed version of the library now supports the header-only - configuration. - - * Targets ``doc``, ``install``, and ``test`` are now disabled if C++ Format - is included as a CMake subproject. They can be enabled by setting - ``FMT_DOC``, ``FMT_INSTALL``, and ``FMT_TEST`` in the parent project. - - Thanks to `@niosHD `_. - -2.0.1 - 2016-03-13 ------------------- - -* Improved CMake find and package support - (`#264 `_). - Thanks to `@niosHD `_. - -* Fix compile error with Android NDK and mingw32 - (`#241 `_). - Thanks to `@Gachapen (Magnus Bjerke Vik) `_. - -* Documentation fixes - (`#248 `_, - `#260 `_). - -2.0.0 - 2015-12-01 ------------------- - -General -~~~~~~~ - -* [Breaking] Named arguments - (`#169 `_, - `#173 `_, - `#174 `_): - - .. code:: c++ - - fmt::print("The answer is {answer}.", fmt::arg("answer", 42)); - - Thanks to `@jamboree `_. - -* [Experimental] User-defined literals for format and named arguments - (`#204 `_, - `#206 `_, - `#207 `_): - - .. code:: c++ - - using namespace fmt::literals; - fmt::print("The answer is {answer}.", "answer"_a=42); - - Thanks to `@dean0x7d (Dean Moldovan) `_. - -* [Breaking] Formatting of more than 16 arguments is now supported when using - variadic templates - (`#141 `_). - Thanks to `@Shauren `_. - -* Runtime width specification - (`#168 `_): - - .. code:: c++ - - fmt::format("{0:{1}}", 42, 5); // gives " 42" - - Thanks to `@jamboree `_. - -* [Breaking] Enums are now formatted with an overloaded ``std::ostream`` insertion - operator (``operator<<``) if available - (`#232 `_). - -* [Breaking] Changed default ``bool`` format to textual, "true" or "false" - (`#170 `_): - - .. code:: c++ - - fmt::print("{}", true); // prints "true" - - To print ``bool`` as a number use numeric format specifier such as ``d``: - - .. code:: c++ - - fmt::print("{:d}", true); // prints "1" - -* ``fmt::printf`` and ``fmt::sprintf`` now support formatting of ``bool`` with the - ``%s`` specifier giving textual output, "true" or "false" - (`#223 `_): - - .. code:: c++ - - fmt::printf("%s", true); // prints "true" - - Thanks to `@LarsGullik `_. - -* [Breaking] ``signed char`` and ``unsigned char`` are now formatted as integers by default - (`#217 `_). - -* [Breaking] Pointers to C strings can now be formatted with the ``p`` specifier - (`#223 `_): - - .. code:: c++ - - fmt::print("{:p}", "test"); // prints pointer value - - Thanks to `@LarsGullik `_. - -* [Breaking] ``fmt::printf`` and ``fmt::sprintf`` now print null pointers as ``(nil)`` - and null strings as ``(null)`` for consistency with glibc - (`#226 `_). - Thanks to `@LarsGullik `_. - -* [Breaking] ``fmt::(s)printf`` now supports formatting of objects of user-defined types - that provide an overloaded ``std::ostream`` insertion operator (``operator<<``) - (`#201 `_): - - .. code:: c++ - - fmt::printf("The date is %s", Date(2012, 12, 9)); - -* [Breaking] The ``Buffer`` template is now part of the public API and can be used - to implement custom memory buffers - (`#140 `_). - Thanks to `@polyvertex (Jean-Charles Lefebvre) `_. - -* [Breaking] Improved compatibility between ``BasicStringRef`` and - `std::experimental::basic_string_view - `_ - (`#100 `_, - `#159 `_, - `#183 `_): - - - Comparison operators now compare string content, not pointers - - ``BasicStringRef::c_str`` replaced by ``BasicStringRef::data`` - - ``BasicStringRef`` is no longer assumed to be null-terminated - - References to null-terminated strings are now represented by a new class, - ``BasicCStringRef``. - -* Dependency on pthreads introduced by Google Test is now optional - (`#185 `_). - -* New CMake options ``FMT_DOC``, ``FMT_INSTALL`` and ``FMT_TEST`` to control - generation of ``doc``, ``install`` and ``test`` targets respectively, on by default - (`#197 `_, - `#198 `_, - `#200 `_). - Thanks to `@maddinat0r (Alex Martin) `_. - -* ``noexcept`` is now used when compiling with MSVC2015 - (`#215 `_). - Thanks to `@dmkrepo (Dmitriy) `_. - -* Added an option to disable use of ``windows.h`` when ``FMT_USE_WINDOWS_H`` - is defined as 0 before including ``format.h`` - (`#171 `_). - Thanks to `@alfps (Alf P. Steinbach) `_. - -* [Breaking] ``windows.h`` is now included with ``NOMINMAX`` unless - ``FMT_WIN_MINMAX`` is defined. This is done to prevent breaking code using - ``std::min`` and ``std::max`` and only affects the header-only configuration - (`#152 `_, - `#153 `_, - `#154 `_). - Thanks to `@DevO2012 `_. - -* Improved support for custom character types - (`#171 `_). - Thanks to `@alfps (Alf P. Steinbach) `_. - -* Added an option to disable use of IOStreams when ``FMT_USE_IOSTREAMS`` - is defined as 0 before including ``format.h`` - (`#205 `_, - `#208 `_). - Thanks to `@JodiTheTigger `_. - -* Improved detection of ``isnan``, ``isinf`` and ``signbit``. - -Optimization -~~~~~~~~~~~~ - -* Made formatting of user-defined types more efficient with a custom stream buffer - (`#92 `_, - `#230 `_). - Thanks to `@NotImplemented `_. - -* Further improved performance of ``fmt::Writer`` on integer formatting - and fixed a minor regression. Now it is ~7% faster than ``karma::generate`` - on Karma's benchmark - (`#186 `_). - -* [Breaking] Reduced `compiled code size - `_ - (`#143 `_, - `#149 `_). - -Distribution -~~~~~~~~~~~~ - -* [Breaking] Headers are now installed in - ``${CMAKE_INSTALL_PREFIX}/include/cppformat`` - (`#178 `_). - Thanks to `@jackyf (Eugene V. Lyubimkin) `_. - -* [Breaking] Changed the library name from ``format`` to ``cppformat`` - for consistency with the project name and to avoid potential conflicts - (`#178 `_). - Thanks to `@jackyf (Eugene V. Lyubimkin) `_. - -* C++ Format is now available in `Debian `_ GNU/Linux - (`stretch `_, - `sid `_) and - derived distributions such as - `Ubuntu `_ 15.10 and later - (`#155 `_):: - - $ sudo apt-get install libcppformat1-dev - - Thanks to `@jackyf (Eugene V. Lyubimkin) `_. - -* `Packages for Fedora and RHEL `_ - are now available. Thanks to Dave Johansen. - -* C++ Format can now be installed via `Homebrew `_ on OS X - (`#157 `_):: - - $ brew install cppformat - - Thanks to `@ortho `_, Anatoliy Bulukin. - -Documentation -~~~~~~~~~~~~~ - -* Migrated from ReadTheDocs to GitHub Pages for better responsiveness - and reliability - (`#128 `_). - New documentation address is http://cppformat.github.io/. - - -* Added `Building the documentation - `_ - section to the documentation. - -* Documentation build script is now compatible with Python 3 and newer pip versions. - (`#189 `_, - `#209 `_). - Thanks to `@JodiTheTigger `_ and - `@xentec `_. - -* Documentation fixes and improvements - (`#36 `_, - `#75 `_, - `#125 `_, - `#160 `_, - `#161 `_, - `#162 `_, - `#165 `_, - `#210 `_). - Thanks to `@syohex (Syohei YOSHIDA) `_ and - bug reporters. - -* Fixed out-of-tree documentation build - (`#177 `_). - Thanks to `@jackyf (Eugene V. Lyubimkin) `_. - -Fixes -~~~~~ - -* Fixed ``initializer_list`` detection - (`#136 `_). - Thanks to `@Gachapen (Magnus Bjerke Vik) `_. - -* [Breaking] Fixed formatting of enums with numeric format specifiers in - ``fmt::(s)printf`` - (`#131 `_, - `#139 `_): - - .. code:: c++ - - enum { ANSWER = 42 }; - fmt::printf("%d", ANSWER); - - Thanks to `@Naios `_. - -* Improved compatibility with old versions of MinGW - (`#129 `_, - `#130 `_, - `#132 `_). - Thanks to `@cstamford (Christopher Stamford) `_. - -* Fixed a compile error on MSVC with disabled exceptions - (`#144 `_). - -* Added a workaround for broken implementation of variadic templates in MSVC2012 - (`#148 `_). - -* Placed the anonymous namespace within ``fmt`` namespace for the header-only - configuration - (`#171 `_). - Thanks to `@alfps (Alf P. Steinbach) `_. - -* Fixed issues reported by Coverity Scan - (`#187 `_, - `#192 `_). - -* Implemented a workaround for a name lookup bug in MSVC2010 - (`#188 `_). - -* Fixed compiler warnings - (`#95 `_, - `#96 `_, - `#114 `_, - `#135 `_, - `#142 `_, - `#145 `_, - `#146 `_, - `#158 `_, - `#163 `_, - `#175 `_, - `#190 `_, - `#191 `_, - `#194 `_, - `#196 `_, - `#216 `_, - `#218 `_, - `#220 `_, - `#229 `_, - `#233 `_, - `#234 `_, - `#236 `_, - `#281 `_, - `#289 `_). - Thanks to `@seanmiddleditch (Sean Middleditch) `_, - `@dixlorenz (Dix Lorenz) `_, - `@CarterLi (李通洲) `_, - `@Naios `_, - `@fmatthew5876 (Matthew Fioravante) `_, - `@LevskiWeng (Levski Weng) `_, - `@rpopescu `_, - `@gabime (Gabi Melman) `_, - `@cubicool (Jeremy Moles) `_, - `@jkflying (Julian Kent) `_, - `@LogicalKnight (Sean L) `_, - `@inguin (Ingo van Lil) `_ and - `@Jopie64 (Johan) `_. - -* Fixed portability issues (mostly causing test failures) on ARM, ppc64, ppc64le, - s390x and SunOS 5.11 i386 - (`#138 `_, - `#179 `_, - `#180 `_, - `#202 `_, - `#225 `_, - `Red Hat Bugzilla Bug 1260297 `_). - Thanks to `@Naios `_, - `@jackyf (Eugene V. Lyubimkin) `_ and Dave Johansen. - -* Fixed a name conflict with macro ``free`` defined in - ``crtdbg.h`` when ``_CRTDBG_MAP_ALLOC`` is set - (`#211 `_). - -* Fixed shared library build on OS X - (`#212 `_). - Thanks to `@dean0x7d (Dean Moldovan) `_. - -* Fixed an overload conflict on MSVC when ``/Zc:wchar_t-`` option is specified - (`#214 `_). - Thanks to `@slavanap (Vyacheslav Napadovsky) `_. - -* Improved compatibility with MSVC 2008 - (`#236 `_). - Thanks to `@Jopie64 (Johan) `_. - -* Improved compatibility with bcc32 - (`#227 `_). - -* Fixed ``static_assert`` detection on Clang - (`#228 `_). - Thanks to `@dean0x7d (Dean Moldovan) `_. - -1.1.0 - 2015-03-06 ------------------- - -* Added ``BasicArrayWriter``, a class template that provides operations for - formatting and writing data into a fixed-size array - (`#105 `_ and - `#122 `_): - - .. code:: c++ - - char buffer[100]; - fmt::ArrayWriter w(buffer); - w.write("The answer is {}", 42); - -* Added `0 A.D. `_ and `PenUltima Online (POL) - `_ to the list of notable projects using C++ Format. - -* C++ Format now uses MSVC intrinsics for better formatting performance - (`#115 `_, - `#116 `_, - `#118 `_ and - `#121 `_). - Previously these optimizations where only used on GCC and Clang. - Thanks to `@CarterLi `_ and - `@objectx `_. - -* CMake install target (`#119 `_). - Thanks to `@TrentHouliston `_. - - You can now install C++ Format with ``make install`` command. - -* Improved `Biicode `_ support - (`#98 `_ and - `#104 `_). Thanks to - `@MariadeAnton `_ and - `@franramirez688 `_. - -* Improved support for building with `Android NDK - `_ - (`#107 `_). - Thanks to `@newnon `_. - - The `android-ndk-example `_ - repository provides and example of using C++ Format with Android NDK: - - .. image:: https://raw.githubusercontent.com/fmtlib/android-ndk-example/ - master/screenshot.png - -* Improved documentation of ``SystemError`` and ``WindowsError`` - (`#54 `_). - -* Various code improvements - (`#110 `_, - `#111 `_ - `#112 `_). - Thanks to `@CarterLi `_. - -* Improved compile-time errors when formatting wide into narrow strings - (`#117 `_). - -* Fixed ``BasicWriter::write`` without formatting arguments when C++11 support - is disabled (`#109 `_). - -* Fixed header-only build on OS X with GCC 4.9 - (`#124 `_). - -* Fixed packaging issues (`#94 `_). - -* Added `changelog `_ - (`#103 `_). - -1.0.0 - 2015-02-05 ------------------- - -* Add support for a header-only configuration when ``FMT_HEADER_ONLY`` is - defined before including ``format.h``: - - .. code:: c++ - - #define FMT_HEADER_ONLY - #include "format.h" - -* Compute string length in the constructor of ``BasicStringRef`` - instead of the ``size`` method - (`#79 `_). - This eliminates size computation for string literals on reasonable optimizing - compilers. - -* Fix formatting of types with overloaded ``operator <<`` for ``std::wostream`` - (`#86 `_): - - .. code:: c++ - - fmt::format(L"The date is {0}", Date(2012, 12, 9)); - -* Fix linkage of tests on Arch Linux - (`#89 `_). - -* Allow precision specifier for non-float arguments - (`#90 `_): - - .. code:: c++ - - fmt::print("{:.3}\n", "Carpet"); // prints "Car" - -* Fix build on Android NDK - (`#93 `_) - -* Improvements to documentation build procedure. - -* Remove ``FMT_SHARED`` CMake variable in favor of standard `BUILD_SHARED_LIBS - `_. - -* Fix error handling in ``fmt::fprintf``. - -* Fix a number of warnings. - -0.12.0 - 2014-10-25 -------------------- - -* [Breaking] Improved separation between formatting and buffer management. - ``Writer`` is now a base class that cannot be instantiated directly. - The new ``MemoryWriter`` class implements the default buffer management - with small allocations done on stack. So ``fmt::Writer`` should be replaced - with ``fmt::MemoryWriter`` in variable declarations. - - Old code: - - .. code:: c++ - - fmt::Writer w; - - New code: - - .. code:: c++ - - fmt::MemoryWriter w; - - If you pass ``fmt::Writer`` by reference, you can continue to do so: - - .. code:: c++ - - void f(fmt::Writer &w); - - This doesn't affect the formatting API. - -* Support for custom memory allocators - (`#69 `_) - -* Formatting functions now accept `signed char` and `unsigned char` strings as - arguments (`#73 `_): - - .. code:: c++ - - auto s = format("GLSL version: {}", glGetString(GL_VERSION)); - -* Reduced code bloat. According to the new `benchmark results - `_, - cppformat is close to ``printf`` and by the order of magnitude better than - Boost Format in terms of compiled code size. - -* Improved appearance of the documentation on mobile by using the `Sphinx - Bootstrap theme `_: - - .. |old| image:: https://cloud.githubusercontent.com/assets/576385/4792130/ - cd256436-5de3-11e4-9a62-c077d0c2b003.png - - .. |new| image:: https://cloud.githubusercontent.com/assets/576385/4792131/ - cd29896c-5de3-11e4-8f59-cac952942bf0.png - - +-------+-------+ - | Old | New | - +-------+-------+ - | |old| | |new| | - +-------+-------+ - -0.11.0 - 2014-08-21 -------------------- - -* Safe printf implementation with a POSIX extension for positional arguments: - - .. code:: c++ - - fmt::printf("Elapsed time: %.2f seconds", 1.23); - fmt::printf("%1$s, %3$d %2$s", weekday, month, day); - -* Arguments of ``char`` type can now be formatted as integers - (Issue `#55 `_): - - .. code:: c++ - - fmt::format("0x{0:02X}", 'a'); - -* Deprecated parts of the API removed. - -* The library is now built and tested on MinGW with Appveyor in addition to - existing test platforms Linux/GCC, OS X/Clang, Windows/MSVC. - -0.10.0 - 2014-07-01 -------------------- - -**Improved API** - -* All formatting methods are now implemented as variadic functions instead - of using ``operator<<`` for feeding arbitrary arguments into a temporary - formatter object. This works both with C++11 where variadic templates are - used and with older standards where variadic functions are emulated by - providing lightweight wrapper functions defined with the ``FMT_VARIADIC`` - macro. You can use this macro for defining your own portable variadic - functions: - - .. code:: c++ - - void report_error(const char *format, const fmt::ArgList &args) { - fmt::print("Error: {}"); - fmt::print(format, args); - } - FMT_VARIADIC(void, report_error, const char *) - - report_error("file not found: {}", path); - - Apart from a more natural syntax, this also improves performance as there - is no need to construct temporary formatter objects and control arguments' - lifetimes. Because the wrapper functions are very lightweight, this doesn't - cause code bloat even in pre-C++11 mode. - -* Simplified common case of formatting an ``std::string``. Now it requires a - single function call: - - .. code:: c++ - - std::string s = format("The answer is {}.", 42); - - Previously it required 2 function calls: - - .. code:: c++ - - std::string s = str(Format("The answer is {}.") << 42); - - Instead of unsafe ``c_str`` function, ``fmt::Writer`` should be used directly - to bypass creation of ``std::string``: - - .. code:: c++ - - fmt::Writer w; - w.write("The answer is {}.", 42); - w.c_str(); // returns a C string - - This doesn't do dynamic memory allocation for small strings and is less error - prone as the lifetime of the string is the same as for ``std::string::c_str`` - which is well understood (hopefully). - -* Improved consistency in naming functions that are a part of the public API. - Now all public functions are lowercase following the standard library - conventions. Previously it was a combination of lowercase and - CapitalizedWords. - Issue `#50 `_. - -* Old functions are marked as deprecated and will be removed in the next - release. - -**Other Changes** - -* Experimental support for printf format specifications (work in progress): - - .. code:: c++ - - fmt::printf("The answer is %d.", 42); - std::string s = fmt::sprintf("Look, a %s!", "string"); - -* Support for hexadecimal floating point format specifiers ``a`` and ``A``: - - .. code:: c++ - - print("{:a}", -42.0); // Prints -0x1.5p+5 - print("{:A}", -42.0); // Prints -0X1.5P+5 - -* CMake option ``FMT_SHARED`` that specifies whether to build format as a - shared library (off by default). - -0.9.0 - 2014-05-13 ------------------- - -* More efficient implementation of variadic formatting functions. - -* ``Writer::Format`` now has a variadic overload: - - .. code:: c++ - - Writer out; - out.Format("Look, I'm {}!", "variadic"); - -* For efficiency and consistency with other overloads, variadic overload of - the ``Format`` function now returns ``Writer`` instead of ``std::string``. - Use the ``str`` function to convert it to ``std::string``: - - .. code:: c++ - - std::string s = str(Format("Look, I'm {}!", "variadic")); - -* Replaced formatter actions with output sinks: ``NoAction`` -> ``NullSink``, - ``Write`` -> ``FileSink``, ``ColorWriter`` -> ``ANSITerminalSink``. - This improves naming consistency and shouldn't affect client code unless - these classes are used directly which should be rarely needed. - -* Added ``ThrowSystemError`` function that formats a message and throws - ``SystemError`` containing the formatted message and system-specific error - description. For example, the following code - - .. code:: c++ - - FILE *f = fopen(filename, "r"); - if (!f) - ThrowSystemError(errno, "Failed to open file '{}'") << filename; - - will throw ``SystemError`` exception with description - "Failed to open file '': No such file or directory" if file - doesn't exist. - -* Support for AppVeyor continuous integration platform. - -* ``Format`` now throws ``SystemError`` in case of I/O errors. - -* Improve test infrastructure. Print functions are now tested by redirecting - the output to a pipe. - -0.8.0 - 2014-04-14 ------------------- - -* Initial release diff --git a/fmt/LICENSE.rst b/fmt/LICENSE.rst deleted file mode 100644 index f0ec3db4..00000000 --- a/fmt/LICENSE.rst +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 - present, Victor Zverovich - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - ---- Optional exception to the license --- - -As an exception, if, as a result of your compiling your source code, portions -of this Software are embedded into a machine-executable object form of such -source code, you may redistribute such embedded portions in such object form -without including the above copyright and permission notices. diff --git a/fmt/README.md b/fmt/README.md new file mode 100644 index 00000000..697a6efa --- /dev/null +++ b/fmt/README.md @@ -0,0 +1,490 @@ +{fmt} + +[![image](https://github.com/fmtlib/fmt/workflows/linux/badge.svg)](https://github.com/fmtlib/fmt/actions?query=workflow%3Alinux) +[![image](https://github.com/fmtlib/fmt/workflows/macos/badge.svg)](https://github.com/fmtlib/fmt/actions?query=workflow%3Amacos) +[![image](https://github.com/fmtlib/fmt/workflows/windows/badge.svg)](https://github.com/fmtlib/fmt/actions?query=workflow%3Awindows) +[![fmt is continuously fuzzed at oss-fuzz](https://oss-fuzz-build-logs.storage.googleapis.com/badges/fmt.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?\%0Acolspec=ID%20Type%20Component%20Status%20Proj%20Reported%20Owner%20\%0ASummary&q=proj%3Dfmt&can=1) +[![Ask questions at StackOverflow with the tag fmt](https://img.shields.io/badge/stackoverflow-fmt-blue.svg)](https://stackoverflow.com/questions/tagged/fmt) +[![image](https://api.securityscorecards.dev/projects/github.com/fmtlib/fmt/badge)](https://securityscorecards.dev/viewer/?uri=github.com/fmtlib/fmt) + +**{fmt}** is an open-source formatting library providing a fast and safe +alternative to C stdio and C++ iostreams. + +If you like this project, please consider donating to one of the funds +that help victims of the war in Ukraine: . + +[Documentation](https://fmt.dev) + +[Cheat Sheets](https://hackingcpp.com/cpp/libs/fmt.html) + +Q&A: ask questions on [StackOverflow with the tag +fmt](https://stackoverflow.com/questions/tagged/fmt). + +Try {fmt} in [Compiler Explorer](https://godbolt.org/z/Eq5763). + +# Features + +- Simple [format API](https://fmt.dev/latest/api.html) with positional + arguments for localization +- Implementation of [C++20 + std::format](https://en.cppreference.com/w/cpp/utility/format) and + [C++23 std::print](https://en.cppreference.com/w/cpp/io/print) +- [Format string syntax](https://fmt.dev/latest/syntax.html) similar + to Python\'s + [format](https://docs.python.org/3/library/stdtypes.html#str.format) +- Fast IEEE 754 floating-point formatter with correct rounding, + shortness and round-trip guarantees using the + [Dragonbox](https://github.com/jk-jeon/dragonbox) algorithm +- Portable Unicode support +- Safe [printf + implementation](https://fmt.dev/latest/api.html#printf-formatting) + including the POSIX extension for positional arguments +- Extensibility: [support for user-defined + types](https://fmt.dev/latest/api.html#formatting-user-defined-types) +- High performance: faster than common standard library + implementations of `(s)printf`, iostreams, `to_string` and + `to_chars`, see [Speed tests](#speed-tests) and [Converting a + hundred million integers to strings per + second](http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html) +- Small code size both in terms of source code with the minimum + configuration consisting of just three files, `core.h`, `format.h` + and `format-inl.h`, and compiled code; see [Compile time and code + bloat](#compile-time-and-code-bloat) +- Reliability: the library has an extensive set of + [tests](https://github.com/fmtlib/fmt/tree/master/test) and is + [continuously fuzzed](https://bugs.chromium.org/p/oss-fuzz/issues/list?colspec=ID%20Type%20Component%20Status%20Proj%20Reported%20Owner%20Summary&q=proj%3Dfmt&can=1) +- Safety: the library is fully type-safe, errors in format strings can + be reported at compile time, automatic memory management prevents + buffer overflow errors +- Ease of use: small self-contained code base, no external + dependencies, permissive MIT + [license](https://github.com/fmtlib/fmt/blob/master/LICENSE.rst) +- [Portability](https://fmt.dev/latest/index.html#portability) with + consistent output across platforms and support for older compilers +- Clean warning-free codebase even on high warning levels such as + `-Wall -Wextra -pedantic` +- Locale independence by default +- Optional header-only configuration enabled with the + `FMT_HEADER_ONLY` macro + +See the [documentation](https://fmt.dev) for more details. + +# Examples + +**Print to stdout** ([run](https://godbolt.org/z/Tevcjh)) + +``` c++ +#include + +int main() { + fmt::print("Hello, world!\n"); +} +``` + +**Format a string** ([run](https://godbolt.org/z/oK8h33)) + +``` c++ +std::string s = fmt::format("The answer is {}.", 42); +// s == "The answer is 42." +``` + +**Format a string using positional arguments** +([run](https://godbolt.org/z/Yn7Txe)) + +``` c++ +std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy"); +// s == "I'd rather be happy than right." +``` + +**Print chrono durations** ([run](https://godbolt.org/z/K8s4Mc)) + +``` c++ +#include + +int main() { + using namespace std::literals::chrono_literals; + fmt::print("Default format: {} {}\n", 42s, 100ms); + fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s); +} +``` + +Output: + + Default format: 42s 100ms + strftime-like format: 03:15:30 + +**Print a container** ([run](https://godbolt.org/z/MxM1YqjE7)) + +``` c++ +#include +#include + +int main() { + std::vector v = {1, 2, 3}; + fmt::print("{}\n", v); +} +``` + +Output: + + [1, 2, 3] + +**Check a format string at compile time** + +``` c++ +std::string s = fmt::format("{:d}", "I am not a number"); +``` + +This gives a compile-time error in C++20 because `d` is an invalid +format specifier for a string. + +**Write a file from a single thread** + +``` c++ +#include + +int main() { + auto out = fmt::output_file("guide.txt"); + out.print("Don't {}", "Panic"); +} +``` + +This can be [5 to 9 times faster than +fprintf](http://www.zverovich.net/2020/08/04/optimal-file-buffer-size.html). + +**Print with colors and text styles** + +``` c++ +#include + +int main() { + fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold, + "Hello, {}!\n", "world"); + fmt::print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) | + fmt::emphasis::underline, "Olá, {}!\n", "Mundo"); + fmt::print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, + "你好{}!\n", "世界"); +} +``` + +Output on a modern terminal with Unicode support: + +![image](https://github.com/fmtlib/fmt/assets/%0A576385/2a93c904-d6fa-4aa6-b453-2618e1c327d7) + +# Benchmarks + +## Speed tests + +| Library | Method | Run Time, s | +|-------------------|---------------|-------------| +| libc | printf | 0.91 | +| libc++ | std::ostream | 2.49 | +| {fmt} 9.1 | fmt::print | 0.74 | +| Boost Format 1.80 | boost::format | 6.26 | +| Folly Format | folly::format | 1.87 | + +{fmt} is the fastest of the benchmarked methods, \~20% faster than +`printf`. + +The above results were generated by building `tinyformat_test.cpp` on +macOS 12.6.1 with `clang++ -O3 -DNDEBUG -DSPEED_TEST -DHAVE_FORMAT`, and +taking the best of three runs. In the test, the format string +`"%0.10f:%04d:%+g:%s:%p:%c:%%\n"` or equivalent is filled 2,000,000 +times with output sent to `/dev/null`; for further details refer to the +[source](https://github.com/fmtlib/format-benchmark/blob/master/src/tinyformat-test.cc). + +{fmt} is up to 20-30x faster than `std::ostringstream` and `sprintf` on +IEEE754 `float` and `double` formatting +([dtoa-benchmark](https://github.com/fmtlib/dtoa-benchmark)) and faster +than [double-conversion](https://github.com/google/double-conversion) +and [ryu](https://github.com/ulfjack/ryu): + +[![image](https://user-images.githubusercontent.com/576385/95684665-11719600-0ba8-11eb-8e5b-972ff4e49428.png)](https://fmt.dev/unknown_mac64_clang12.0.html) + +## Compile time and code bloat + +The script +[bloat-test.py](https://github.com/fmtlib/format-benchmark/blob/master/bloat-test.py) +from [format-benchmark](https://github.com/fmtlib/format-benchmark) +tests compile time and code bloat for nontrivial projects. It generates +100 translation units and uses `printf()` or its alternative five times +in each to simulate a medium-sized project. The resulting executable +size and compile time (Apple LLVM version 8.1.0 (clang-802.0.42), macOS +Sierra, best of three) is shown in the following tables. + +**Optimized build (-O3)** + +| Method | Compile Time, s | Executable size, KiB | Stripped size, KiB | +|---------------|-----------------|----------------------|--------------------| +| printf | 2.6 | 29 | 26 | +| printf+string | 16.4 | 29 | 26 | +| iostreams | 31.1 | 59 | 55 | +| {fmt} | 19.0 | 37 | 34 | +| Boost Format | 91.9 | 226 | 203 | +| Folly Format | 115.7 | 101 | 88 | + +As you can see, {fmt} has 60% less overhead in terms of resulting binary +code size compared to iostreams and comes pretty close to `printf`. +Boost Format and Folly Format have the largest overheads. + +`printf+string` is the same as `printf` but with an extra `` +include to measure the overhead of the latter. + +**Non-optimized build** + +| Method | Compile Time, s | Executable size, KiB | Stripped size, KiB | +|---------------|-----------------|----------------------|--------------------| +| printf | 2.2 | 33 | 30 | +| printf+string | 16.0 | 33 | 30 | +| iostreams | 28.3 | 56 | 52 | +| {fmt} | 18.2 | 59 | 50 | +| Boost Format | 54.1 | 365 | 303 | +| Folly Format | 79.9 | 445 | 430 | + +`libc`, `lib(std)c++`, and `libfmt` are all linked as shared libraries +to compare formatting function overhead only. Boost Format is a +header-only library so it doesn\'t provide any linkage options. + +## Running the tests + +Please refer to [Building the +library](https://fmt.dev/latest/usage.html#building-the-library) for +instructions on how to build the library and run the unit tests. + +Benchmarks reside in a separate repository, +[format-benchmarks](https://github.com/fmtlib/format-benchmark), so to +run the benchmarks you first need to clone this repository and generate +Makefiles with CMake: + + $ git clone --recursive https://github.com/fmtlib/format-benchmark.git + $ cd format-benchmark + $ cmake . + +Then you can run the speed test: + + $ make speed-test + +or the bloat test: + + $ make bloat-test + +# Migrating code + +[clang-tidy](https://clang.llvm.org/extra/clang-tidy/) v17 (not yet +released) provides the +[modernize-use-std-print](https://clang.llvm.org/extra/clang-tidy/checks/modernize/use-std-print.html) +check that is capable of converting occurrences of `printf` and +`fprintf` to `fmt::print` if configured to do so. (By default it +converts to `std::print`.) + +# Notable projects using this library + +- [0 A.D.](https://play0ad.com/): a free, open-source, cross-platform + real-time strategy game +- [AMPL/MP](https://github.com/ampl/mp): an open-source library for + mathematical programming +- [Apple's FoundationDB](https://github.com/apple/foundationdb): an open-source, + distributed, transactional key-value store +- [Aseprite](https://github.com/aseprite/aseprite): animated sprite + editor & pixel art tool +- [AvioBook](https://www.aviobook.aero/en): a comprehensive aircraft + operations suite +- [Blizzard Battle.net](https://battle.net/): an online gaming + platform +- [Celestia](https://celestia.space/): real-time 3D visualization of + space +- [Ceph](https://ceph.com/): a scalable distributed storage system +- [ccache](https://ccache.dev/): a compiler cache +- [ClickHouse](https://github.com/ClickHouse/ClickHouse): an + analytical database management system +- [Contour](https://github.com/contour-terminal/contour/): a modern + terminal emulator +- [CUAUV](https://cuauv.org/): Cornell University\'s autonomous + underwater vehicle +- [Drake](https://drake.mit.edu/): a planning, control, and analysis + toolbox for nonlinear dynamical systems (MIT) +- [Envoy](https://lyft.github.io/envoy/): C++ L7 proxy and + communication bus (Lyft) +- [FiveM](https://fivem.net/): a modification framework for GTA V +- [fmtlog](https://github.com/MengRao/fmtlog): a performant + fmtlib-style logging library with latency in nanoseconds +- [Folly](https://github.com/facebook/folly): Facebook open-source + library +- [GemRB](https://gemrb.org/): a portable open-source implementation + of Bioware's Infinity Engine +- [Grand Mountain + Adventure](https://store.steampowered.com/app/1247360/Grand_Mountain_Adventure/): + a beautiful open-world ski & snowboarding game +- [HarpyWar/pvpgn](https://github.com/pvpgn/pvpgn-server): Player vs + Player Gaming Network with tweaks +- [KBEngine](https://github.com/kbengine/kbengine): an open-source + MMOG server engine +- [Keypirinha](https://keypirinha.com/): a semantic launcher for + Windows +- [Kodi](https://kodi.tv/) (formerly xbmc): home theater software +- [Knuth](https://kth.cash/): high-performance Bitcoin full-node +- [libunicode](https://github.com/contour-terminal/libunicode/): a + modern C++17 Unicode library +- [MariaDB](https://mariadb.org/): relational database management + system +- [Microsoft Verona](https://github.com/microsoft/verona): research + programming language for concurrent ownership +- [MongoDB](https://mongodb.com/): distributed document database +- [MongoDB Smasher](https://github.com/duckie/mongo_smasher): a small + tool to generate randomized datasets +- [OpenSpace](https://openspaceproject.com/): an open-source + astrovisualization framework +- [PenUltima Online (POL)](https://www.polserver.com/): an MMO server, + compatible with most Ultima Online clients +- [PyTorch](https://github.com/pytorch/pytorch): an open-source + machine learning library +- [quasardb](https://www.quasardb.net/): a distributed, + high-performance, associative database +- [Quill](https://github.com/odygrd/quill): asynchronous low-latency + logging library +- [QKW](https://github.com/ravijanjam/qkw): generalizing aliasing to + simplify navigation, and executing complex multi-line terminal + command sequences +- [redis-cerberus](https://github.com/HunanTV/redis-cerberus): a Redis + cluster proxy +- [redpanda](https://vectorized.io/redpanda): a 10x faster Kafka® + replacement for mission-critical systems written in C++ +- [rpclib](http://rpclib.net/): a modern C++ msgpack-RPC server and + client library +- [Salesforce Analytics + Cloud](https://www.salesforce.com/analytics-cloud/overview/): + business intelligence software +- [Scylla](https://www.scylladb.com/): a Cassandra-compatible NoSQL + data store that can handle 1 million transactions per second on a + single server +- [Seastar](http://www.seastar-project.org/): an advanced, open-source + C++ framework for high-performance server applications on modern + hardware +- [spdlog](https://github.com/gabime/spdlog): super fast C++ logging + library +- [Stellar](https://www.stellar.org/): financial platform +- [Touch Surgery](https://www.touchsurgery.com/): surgery simulator +- [TrinityCore](https://github.com/TrinityCore/TrinityCore): + open-source MMORPG framework +- [🐙 userver framework](https://userver.tech/): open-source + asynchronous framework with a rich set of abstractions and database + drivers +- [Windows Terminal](https://github.com/microsoft/terminal): the new + Windows terminal + +[More\...](https://github.com/search?q=fmtlib&type=Code) + +If you are aware of other projects using this library, please let me +know by [email](mailto:victor.zverovich@gmail.com) or by submitting an +[issue](https://github.com/fmtlib/fmt/issues). + +# Motivation + +So why yet another formatting library? + +There are plenty of methods for doing this task, from standard ones like +the printf family of function and iostreams to Boost Format and +FastFormat libraries. The reason for creating a new library is that +every existing solution that I found either had serious issues or +didn\'t provide all the features I needed. + +## printf + +The good thing about `printf` is that it is pretty fast and readily +available being a part of the C standard library. The main drawback is +that it doesn\'t support user-defined types. `printf` also has safety +issues although they are somewhat mitigated with [\_\_attribute\_\_ +((format (printf, +\...))](https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html) in +GCC. There is a POSIX extension that adds positional arguments required +for +[i18n](https://en.wikipedia.org/wiki/Internationalization_and_localization) +to `printf` but it is not a part of C99 and may not be available on some +platforms. + +## iostreams + +The main issue with iostreams is best illustrated with an example: + +``` c++ +std::cout << std::setprecision(2) << std::fixed << 1.23456 << "\n"; +``` + +which is a lot of typing compared to printf: + +``` c++ +printf("%.2f\n", 1.23456); +``` + +Matthew Wilson, the author of FastFormat, called this \"chevron hell\". +iostreams don\'t support positional arguments by design. + +The good part is that iostreams support user-defined types and are safe +although error handling is awkward. + +## Boost Format + +This is a very powerful library that supports both `printf`-like format +strings and positional arguments. Its main drawback is performance. +According to various benchmarks, it is much slower than other methods +considered here. Boost Format also has excessive build times and severe +code bloat issues (see [Benchmarks](#benchmarks)). + +## FastFormat + +This is an interesting library that is fast, safe, and has positional +arguments. However, it has significant limitations, citing its author: + +> Three features that have no hope of being accommodated within the +> current design are: +> +> - Leading zeros (or any other non-space padding) +> - Octal/hexadecimal encoding +> - Runtime width/alignment specification + +It is also quite big and has a heavy dependency, STLSoft, which might be +too restrictive for using it in some projects. + +## Boost Spirit.Karma + +This is not a formatting library but I decided to include it here for +completeness. As iostreams, it suffers from the problem of mixing +verbatim text with arguments. The library is pretty fast, but slower on +integer formatting than `fmt::format_to` with format string compilation +on Karma\'s own benchmark, see [Converting a hundred million integers to +strings per +second](http://www.zverovich.net/2020/06/13/fast-int-to-string-revisited.html). + +# License + +{fmt} is distributed under the MIT +[license](https://github.com/fmtlib/fmt/blob/master/LICENSE). + +# Documentation License + +The [Format String Syntax](https://fmt.dev/latest/syntax.html) section +in the documentation is based on the one from Python [string module +documentation](https://docs.python.org/3/library/string.html#module-string). +For this reason, the documentation is distributed under the Python +Software Foundation license available in +[doc/python-license.txt](https://raw.github.com/fmtlib/fmt/master/doc/python-license.txt). +It only applies if you distribute the documentation of {fmt}. + +# Maintainers + +The {fmt} library is maintained by Victor Zverovich +([vitaut](https://github.com/vitaut)) with contributions from many other +people. See +[Contributors](https://github.com/fmtlib/fmt/graphs/contributors) and +[Releases](https://github.com/fmtlib/fmt/releases) for some of the +names. Let us know if your contribution is not listed or mentioned +incorrectly and we\'ll make it right. + +# Security Policy + +To report a security issue, please disclose it at [security +advisory](https://github.com/fmtlib/fmt/security/advisories/new). + +This project is maintained by a team of volunteers on a +reasonable-effort basis. As such, please give us at least 90 days to +work on a fix before public exposure. diff --git a/fmt/README.rst b/fmt/README.rst deleted file mode 100644 index 81948bd6..00000000 --- a/fmt/README.rst +++ /dev/null @@ -1,553 +0,0 @@ -.. image:: https://user-images.githubusercontent.com/ - 576385/156254208-f5b743a9-88cf-439d-b0c0-923d53e8d551.png - :width: 25% - :alt: {fmt} - -.. image:: https://github.com/fmtlib/fmt/workflows/linux/badge.svg - :target: https://github.com/fmtlib/fmt/actions?query=workflow%3Alinux - -.. image:: https://github.com/fmtlib/fmt/workflows/macos/badge.svg - :target: https://github.com/fmtlib/fmt/actions?query=workflow%3Amacos - -.. image:: https://github.com/fmtlib/fmt/workflows/windows/badge.svg - :target: https://github.com/fmtlib/fmt/actions?query=workflow%3Awindows - -.. image:: https://oss-fuzz-build-logs.storage.googleapis.com/badges/fmt.svg - :alt: fmt is continuously fuzzed at oss-fuzz - :target: https://bugs.chromium.org/p/oss-fuzz/issues/list?\ - colspec=ID%20Type%20Component%20Status%20Proj%20Reported%20Owner%20\ - Summary&q=proj%3Dfmt&can=1 - -.. image:: https://img.shields.io/badge/stackoverflow-fmt-blue.svg - :alt: Ask questions at StackOverflow with the tag fmt - :target: https://stackoverflow.com/questions/tagged/fmt - -.. image:: https://api.securityscorecards.dev/projects/github.com/fmtlib/fmt/badge - :target: https://securityscorecards.dev/viewer/?uri=github.com/fmtlib/fmt - -**{fmt}** is an open-source formatting library providing a fast and safe -alternative to C stdio and C++ iostreams. - -If you like this project, please consider donating to one of the funds that -help victims of the war in Ukraine: https://www.stopputin.net/. - -`Documentation `__ - -`Cheat Sheets `__ - -Q&A: ask questions on `StackOverflow with the tag fmt -`_. - -Try {fmt} in `Compiler Explorer `_. - -Features --------- - -* Simple `format API `_ with positional arguments - for localization -* Implementation of `C++20 std::format - `__ and `C++23 std::print - `__ -* `Format string syntax `_ similar to Python's - `format `_ -* Fast IEEE 754 floating-point formatter with correct rounding, shortness and - round-trip guarantees using the `Dragonbox `_ - algorithm -* Portable Unicode support -* Safe `printf implementation - `_ including the POSIX - extension for positional arguments -* Extensibility: `support for user-defined types - `_ -* High performance: faster than common standard library implementations of - ``(s)printf``, iostreams, ``to_string`` and ``to_chars``, see `Speed tests`_ - and `Converting a hundred million integers to strings per second - `_ -* Small code size both in terms of source code with the minimum configuration - consisting of just three files, ``core.h``, ``format.h`` and ``format-inl.h``, - and compiled code; see `Compile time and code bloat`_ -* Reliability: the library has an extensive set of `tests - `_ and is `continuously fuzzed - `_ -* Safety: the library is fully type-safe, errors in format strings can be - reported at compile time, automatic memory management prevents buffer overflow - errors -* Ease of use: small self-contained code base, no external dependencies, - permissive MIT `license - `_ -* `Portability `_ with - consistent output across platforms and support for older compilers -* Clean warning-free codebase even on high warning levels such as - ``-Wall -Wextra -pedantic`` -* Locale independence by default -* Optional header-only configuration enabled with the ``FMT_HEADER_ONLY`` macro - -See the `documentation `_ for more details. - -Examples --------- - -**Print to stdout** (`run `_) - -.. code:: c++ - - #include - - int main() { - fmt::print("Hello, world!\n"); - } - -**Format a string** (`run `_) - -.. code:: c++ - - std::string s = fmt::format("The answer is {}.", 42); - // s == "The answer is 42." - -**Format a string using positional arguments** (`run `_) - -.. code:: c++ - - std::string s = fmt::format("I'd rather be {1} than {0}.", "right", "happy"); - // s == "I'd rather be happy than right." - -**Print chrono durations** (`run `_) - -.. code:: c++ - - #include - - int main() { - using namespace std::literals::chrono_literals; - fmt::print("Default format: {} {}\n", 42s, 100ms); - fmt::print("strftime-like format: {:%H:%M:%S}\n", 3h + 15min + 30s); - } - -Output:: - - Default format: 42s 100ms - strftime-like format: 03:15:30 - -**Print a container** (`run `_) - -.. code:: c++ - - #include - #include - - int main() { - std::vector v = {1, 2, 3}; - fmt::print("{}\n", v); - } - -Output:: - - [1, 2, 3] - -**Check a format string at compile time** - -.. code:: c++ - - std::string s = fmt::format("{:d}", "I am not a number"); - -This gives a compile-time error in C++20 because ``d`` is an invalid format -specifier for a string. - -**Write a file from a single thread** - -.. code:: c++ - - #include - - int main() { - auto out = fmt::output_file("guide.txt"); - out.print("Don't {}", "Panic"); - } - -This can be `5 to 9 times faster than fprintf -`_. - -**Print with colors and text styles** - -.. code:: c++ - - #include - - int main() { - fmt::print(fg(fmt::color::crimson) | fmt::emphasis::bold, - "Hello, {}!\n", "world"); - fmt::print(fg(fmt::color::floral_white) | bg(fmt::color::slate_gray) | - fmt::emphasis::underline, "Olá, {}!\n", "Mundo"); - fmt::print(fg(fmt::color::steel_blue) | fmt::emphasis::italic, - "你好{}!\n", "世界"); - } - -Output on a modern terminal with Unicode support: - -.. image:: https://github.com/fmtlib/fmt/assets/ - 576385/2a93c904-d6fa-4aa6-b453-2618e1c327d7 - -Benchmarks ----------- - -Speed tests -~~~~~~~~~~~ - -================= ============= =========== -Library Method Run Time, s -================= ============= =========== -libc printf 0.91 -libc++ std::ostream 2.49 -{fmt} 9.1 fmt::print 0.74 -Boost Format 1.80 boost::format 6.26 -Folly Format folly::format 1.87 -================= ============= =========== - -{fmt} is the fastest of the benchmarked methods, ~20% faster than ``printf``. - -The above results were generated by building ``tinyformat_test.cpp`` on macOS -12.6.1 with ``clang++ -O3 -DNDEBUG -DSPEED_TEST -DHAVE_FORMAT``, and taking the -best of three runs. In the test, the format string ``"%0.10f:%04d:%+g:%s:%p:%c:%%\n"`` -or equivalent is filled 2,000,000 times with output sent to ``/dev/null``; for -further details refer to the `source -`_. - -{fmt} is up to 20-30x faster than ``std::ostringstream`` and ``sprintf`` on -IEEE754 ``float`` and ``double`` formatting (`dtoa-benchmark `_) -and faster than `double-conversion `_ and -`ryu `_: - -.. image:: https://user-images.githubusercontent.com/576385/ - 95684665-11719600-0ba8-11eb-8e5b-972ff4e49428.png - :target: https://fmt.dev/unknown_mac64_clang12.0.html - -Compile time and code bloat -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The script `bloat-test.py -`_ -from `format-benchmark `_ -tests compile time and code bloat for nontrivial projects. -It generates 100 translation units and uses ``printf()`` or its alternative -five times in each to simulate a medium-sized project. The resulting -executable size and compile time (Apple LLVM version 8.1.0 (clang-802.0.42), -macOS Sierra, best of three) is shown in the following tables. - -**Optimized build (-O3)** - -============= =============== ==================== ================== -Method Compile Time, s Executable size, KiB Stripped size, KiB -============= =============== ==================== ================== -printf 2.6 29 26 -printf+string 16.4 29 26 -iostreams 31.1 59 55 -{fmt} 19.0 37 34 -Boost Format 91.9 226 203 -Folly Format 115.7 101 88 -============= =============== ==================== ================== - -As you can see, {fmt} has 60% less overhead in terms of resulting binary code -size compared to iostreams and comes pretty close to ``printf``. Boost Format -and Folly Format have the largest overheads. - -``printf+string`` is the same as ``printf`` but with an extra ```` -include to measure the overhead of the latter. - -**Non-optimized build** - -============= =============== ==================== ================== -Method Compile Time, s Executable size, KiB Stripped size, KiB -============= =============== ==================== ================== -printf 2.2 33 30 -printf+string 16.0 33 30 -iostreams 28.3 56 52 -{fmt} 18.2 59 50 -Boost Format 54.1 365 303 -Folly Format 79.9 445 430 -============= =============== ==================== ================== - -``libc``, ``lib(std)c++``, and ``libfmt`` are all linked as shared libraries to -compare formatting function overhead only. Boost Format is a -header-only library so it doesn't provide any linkage options. - -Running the tests -~~~~~~~~~~~~~~~~~ - -Please refer to `Building the library`__ for instructions on how to build -the library and run the unit tests. - -__ https://fmt.dev/latest/usage.html#building-the-library - -Benchmarks reside in a separate repository, -`format-benchmarks `_, -so to run the benchmarks you first need to clone this repository and -generate Makefiles with CMake:: - - $ git clone --recursive https://github.com/fmtlib/format-benchmark.git - $ cd format-benchmark - $ cmake . - -Then you can run the speed test:: - - $ make speed-test - -or the bloat test:: - - $ make bloat-test - -Migrating code --------------- - -`clang-tidy `_ v17 (not yet -released) provides the `modernize-use-std-print -`_ -check that is capable of converting occurrences of ``printf`` and -``fprintf`` to ``fmt::print`` if configured to do so. (By default it -converts to ``std::print``.) - -Projects using this library ---------------------------- - -* `0 A.D. `_: a free, open-source, cross-platform - real-time strategy game - -* `AMPL/MP `_: - an open-source library for mathematical programming - -* `Aseprite `_: - animated sprite editor & pixel art tool - -* `AvioBook `_: a comprehensive aircraft - operations suite - -* `Blizzard Battle.net `_: an online gaming platform - -* `Celestia `_: real-time 3D visualization of space - -* `Ceph `_: a scalable distributed storage system - -* `ccache `_: a compiler cache - -* `ClickHouse `_: an analytical database - management system - -* `Contour `_: a modern terminal emulator - -* `CUAUV `_: Cornell University's autonomous underwater - vehicle - -* `Drake `_: a planning, control, and analysis toolbox - for nonlinear dynamical systems (MIT) - -* `Envoy `_: C++ L7 proxy and communication bus - (Lyft) - -* `FiveM `_: a modification framework for GTA V - -* `fmtlog `_: a performant fmtlib-style - logging library with latency in nanoseconds - -* `Folly `_: Facebook open-source library - -* `GemRB `_: a portable open-source implementation of - Bioware’s Infinity Engine - -* `Grand Mountain Adventure - `_: - a beautiful open-world ski & snowboarding game - -* `HarpyWar/pvpgn `_: - Player vs Player Gaming Network with tweaks - -* `KBEngine `_: an open-source MMOG server - engine - -* `Keypirinha `_: a semantic launcher for Windows - -* `Kodi `_ (formerly xbmc): home theater software - -* `Knuth `_: high-performance Bitcoin full-node - -* `libunicode `_: a modern C++17 Unicode library - -* `MariaDB `_: relational database management system - -* `Microsoft Verona `_: - research programming language for concurrent ownership - -* `MongoDB `_: distributed document database - -* `MongoDB Smasher `_: a small tool to - generate randomized datasets - -* `OpenSpace `_: an open-source - astrovisualization framework - -* `PenUltima Online (POL) `_: - an MMO server, compatible with most Ultima Online clients - -* `PyTorch `_: an open-source machine - learning library - -* `quasardb `_: a distributed, high-performance, - associative database - -* `Quill `_: asynchronous low-latency logging library - -* `QKW `_: generalizing aliasing to simplify - navigation, and executing complex multi-line terminal command sequences - -* `redis-cerberus `_: a Redis cluster - proxy - -* `redpanda `_: a 10x faster Kafka® replacement - for mission-critical systems written in C++ - -* `rpclib `_: a modern C++ msgpack-RPC server and client - library - -* `Salesforce Analytics Cloud - `_: - business intelligence software - -* `Scylla `_: a Cassandra-compatible NoSQL data store - that can handle 1 million transactions per second on a single server - -* `Seastar `_: an advanced, open-source C++ - framework for high-performance server applications on modern hardware - -* `spdlog `_: super fast C++ logging library - -* `Stellar `_: financial platform - -* `Touch Surgery `_: surgery simulator - -* `TrinityCore `_: open-source - MMORPG framework - -* `🐙 userver framework `_: open-source asynchronous - framework with a rich set of abstractions and database drivers - -* `Windows Terminal `_: the new Windows - terminal - -`More... `_ - -If you are aware of other projects using this library, please let me know -by `email `_ or by submitting an -`issue `_. - -Motivation ----------- - -So why yet another formatting library? - -There are plenty of methods for doing this task, from standard ones like -the printf family of function and iostreams to Boost Format and FastFormat -libraries. The reason for creating a new library is that every existing -solution that I found either had serious issues or didn't provide -all the features I needed. - -printf -~~~~~~ - -The good thing about ``printf`` is that it is pretty fast and readily available -being a part of the C standard library. The main drawback is that it -doesn't support user-defined types. ``printf`` also has safety issues although -they are somewhat mitigated with `__attribute__ ((format (printf, ...)) -`_ in GCC. -There is a POSIX extension that adds positional arguments required for -`i18n `_ -to ``printf`` but it is not a part of C99 and may not be available on some -platforms. - -iostreams -~~~~~~~~~ - -The main issue with iostreams is best illustrated with an example: - -.. code:: c++ - - std::cout << std::setprecision(2) << std::fixed << 1.23456 << "\n"; - -which is a lot of typing compared to printf: - -.. code:: c++ - - printf("%.2f\n", 1.23456); - -Matthew Wilson, the author of FastFormat, called this "chevron hell". iostreams -don't support positional arguments by design. - -The good part is that iostreams support user-defined types and are safe although -error handling is awkward. - -Boost Format -~~~~~~~~~~~~ - -This is a very powerful library that supports both ``printf``-like format -strings and positional arguments. Its main drawback is performance. According to -various benchmarks, it is much slower than other methods considered here. Boost -Format also has excessive build times and severe code bloat issues (see -`Benchmarks`_). - -FastFormat -~~~~~~~~~~ - -This is an interesting library that is fast, safe, and has positional arguments. -However, it has significant limitations, citing its author: - - Three features that have no hope of being accommodated within the - current design are: - - * Leading zeros (or any other non-space padding) - * Octal/hexadecimal encoding - * Runtime width/alignment specification - -It is also quite big and has a heavy dependency, STLSoft, which might be too -restrictive for using it in some projects. - -Boost Spirit.Karma -~~~~~~~~~~~~~~~~~~ - -This is not a formatting library but I decided to include it here for -completeness. As iostreams, it suffers from the problem of mixing verbatim text -with arguments. The library is pretty fast, but slower on integer formatting -than ``fmt::format_to`` with format string compilation on Karma's own benchmark, -see `Converting a hundred million integers to strings per second -`_. - -License -------- - -{fmt} is distributed under the MIT `license -`_. - -Documentation License ---------------------- - -The `Format String Syntax `_ -section in the documentation is based on the one from Python `string module -documentation `_. -For this reason, the documentation is distributed under the Python Software -Foundation license available in `doc/python-license.txt -`_. -It only applies if you distribute the documentation of {fmt}. - -Maintainers ------------ - -The {fmt} library is maintained by Victor Zverovich (`vitaut -`_) with contributions from many other people. -See `Contributors `_ and -`Releases `_ for some of the names. -Let us know if your contribution is not listed or mentioned incorrectly and -we'll make it right. - -Security Policy ---------------- - -To report a security issue, please disclose it at `security advisory `_. - -This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure. diff --git a/fmt/include/fmt/chrono.h b/fmt/include/fmt/chrono.h index 9b4f9d4e..bed584b6 100644 --- a/fmt/include/fmt/chrono.h +++ b/fmt/include/fmt/chrono.h @@ -1049,10 +1049,10 @@ inline void tzset_once() { // Converts value to Int and checks that it's in the range [0, upper). template ::value)> inline Int to_nonnegative_int(T value, Int upper) { - FMT_ASSERT(std::is_unsigned::value || - (value >= 0 && to_unsigned(value) <= to_unsigned(upper)), - "invalid value"); - (void)upper; + if (!std::is_unsigned::value && + (value < 0 || to_unsigned(value) > to_unsigned(upper))) { + FMT_THROW(fmt::format_error("chrono value is out of range")); + } return static_cast(value); } template ::value)> @@ -1622,6 +1622,7 @@ struct chrono_format_checker : null_chrono_spec_handler { template FMT_CONSTEXPR void on_text(const Char*, const Char*) {} + FMT_CONSTEXPR void on_day_of_year() {} FMT_CONSTEXPR void on_24_hour(numeric_system, pad_type) {} FMT_CONSTEXPR void on_12_hour(numeric_system, pad_type) {} FMT_CONSTEXPR void on_minute(numeric_system, pad_type) {} @@ -1806,6 +1807,7 @@ struct chrono_formatter { return true; } + Rep days() const { return static_cast(s.count() / 86400); } Rep hour() const { return static_cast(mod((s.count() / 3600), 24)); } Rep hour12() const { @@ -1884,10 +1886,14 @@ struct chrono_formatter { void on_dec0_week_of_year(numeric_system) {} void on_dec1_week_of_year(numeric_system) {} void on_iso_week_of_year(numeric_system) {} - void on_day_of_year() {} void on_day_of_month(numeric_system) {} void on_day_of_month_space(numeric_system) {} + void on_day_of_year() { + if (handle_nan_inf()) return; + write(days(), 0); + } + void on_24_hour(numeric_system ns, pad_type pad) { if (handle_nan_inf()) return; diff --git a/fmt/include/fmt/color.h b/fmt/include/fmt/color.h index 57b7f578..34de634c 100644 --- a/fmt/include/fmt/color.h +++ b/fmt/include/fmt/color.h @@ -563,9 +563,10 @@ OutputIt vformat_to( fmt::emphasis::bold | fg(fmt::color::red), "{}", 42); \endrst */ -template >::value&& - detail::is_string::value> +template < + typename OutputIt, typename S, typename... Args, + bool enable = detail::is_output_iterator>::value && + detail::is_string::value> inline auto format_to(OutputIt out, const text_style& ts, const S& format_str, Args&&... args) -> typename std::enable_if::type { diff --git a/fmt/include/fmt/core.h b/fmt/include/fmt/core.h index 2fcaf845..9bfee019 100644 --- a/fmt/include/fmt/core.h +++ b/fmt/include/fmt/core.h @@ -817,7 +817,7 @@ template class buffer { protected: // Don't initialize ptr_ since it is not accessed to save a few cycles. FMT_MSC_WARNING(suppress : 26495) - buffer(size_t sz) noexcept : size_(sz), capacity_(sz) {} + FMT_CONSTEXPR buffer(size_t sz) noexcept : size_(sz), capacity_(sz) {} FMT_CONSTEXPR20 buffer(T* p = nullptr, size_t sz = 0, size_t cap = 0) noexcept : ptr_(p), size_(sz), capacity_(cap) {} @@ -1332,7 +1332,7 @@ using ulong_type = conditional_t; template struct format_as_result { template ::value || std::is_class::value)> - static auto map(U*) -> decltype(format_as(std::declval())); + static auto map(U*) -> remove_cvref_t()))>; static auto map(...) -> void; using type = decltype(map(static_cast(nullptr))); @@ -2429,6 +2429,8 @@ FMT_CONSTEXPR FMT_INLINE auto parse_format_specs( case 'G': return parse_presentation_type(pres::general_upper, float_set); case 'c': + if (arg_type == type::bool_type) + throw_format_error("invalid format specifier"); return parse_presentation_type(pres::chr, integral_set); case 's': return parse_presentation_type(pres::string, diff --git a/fmt/include/fmt/format-inl.h b/fmt/include/fmt/format-inl.h index 5f8c83a2..bfd00566 100644 --- a/fmt/include/fmt/format-inl.h +++ b/fmt/include/fmt/format-inl.h @@ -984,7 +984,7 @@ template <> struct cache_accessor { {0xe0accfa875af45a7, 0x93eb1b80a33b8606}, {0x8c6c01c9498d8b88, 0xbc72f130660533c4}, {0xaf87023b9bf0ee6a, 0xeb8fad7c7f8680b5}, - {0xdb68c2ca82ed2a05, 0xa67398db9f6820e2} + {0xdb68c2ca82ed2a05, 0xa67398db9f6820e2}, #else {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b}, {0xce5d73ff402d98e3, 0xfb0a3d212dc81290}, diff --git a/fmt/include/fmt/format.h b/fmt/include/fmt/format.h index 79bf5256..fa76aa11 100644 --- a/fmt/include/fmt/format.h +++ b/fmt/include/fmt/format.h @@ -2113,24 +2113,66 @@ template class digit_grouping { } }; +FMT_CONSTEXPR inline void prefix_append(unsigned& prefix, unsigned value) { + prefix |= prefix != 0 ? value << 8 : value; + prefix += (1u + (value > 0xff ? 1 : 0)) << 24; +} + // Writes a decimal integer with digit grouping. template auto write_int(OutputIt out, UInt value, unsigned prefix, const format_specs& specs, const digit_grouping& grouping) -> OutputIt { - static_assert(std::is_same, UInt>::value, ""); - int num_digits = count_digits(value); - char digits[40]; - format_decimal(digits, value, num_digits); - unsigned size = to_unsigned((prefix != 0 ? 1 : 0) + num_digits + - grouping.count_separators(num_digits)); + static_assert(std::is_same, UInt>::value, ""); + int num_digits = 0; + auto buffer = memory_buffer(); + switch (specs.type) { + case presentation_type::none: + case presentation_type::dec: { + num_digits = count_digits(value); + format_decimal(appender(buffer), value, num_digits); + break; + } + case presentation_type::hex_lower: + case presentation_type::hex_upper: { + bool upper = specs.type == presentation_type::hex_upper; + if (specs.alt) + prefix_append(prefix, unsigned(upper ? 'X' : 'x') << 8 | '0'); + num_digits = count_digits<4>(value); + format_uint<4,Char>(appender(buffer), value, num_digits, upper); + break; + } + case presentation_type::bin_lower: + case presentation_type::bin_upper: { + bool upper = specs.type == presentation_type::bin_upper; + if (specs.alt) + prefix_append(prefix, unsigned(upper ? 'B' : 'b') << 8 | '0'); + num_digits = count_digits<1>(value); + format_uint<1,Char>(appender(buffer), value, num_digits); + break; + } + case presentation_type::oct: { + num_digits = count_digits<3>(value); + // Octal prefix '0' is counted as a digit, so only add it if precision + // is not greater than the number of digits. + if (specs.alt && specs.precision <= num_digits && value != 0) + prefix_append(prefix, '0'); + format_uint<3,Char>(appender(buffer), value, num_digits); + break; + } + case presentation_type::chr: + return write_char(out, static_cast(value), specs); + default: + throw_format_error("invalid format specifier"); + } + + unsigned size = (prefix != 0 ? prefix >> 24 : 0) + to_unsigned(num_digits) + + to_unsigned(grouping.count_separators(num_digits)); return write_padded( out, specs, size, size, [&](reserve_iterator it) { - if (prefix != 0) { - char sign = static_cast(prefix); - *it++ = static_cast(sign); - } - return grouping.apply(it, string_view(digits, to_unsigned(num_digits))); + for (unsigned p = prefix & 0xffffff; p != 0; p >>= 8) + *it++ = static_cast(p & 0xff); + return grouping.apply(it, string_view(buffer.data(), buffer.size())); }); } @@ -2143,11 +2185,6 @@ inline auto write_loc(OutputIt, loc_value, const format_specs&, return false; } -FMT_CONSTEXPR inline void prefix_append(unsigned& prefix, unsigned value) { - prefix |= prefix != 0 ? value << 8 : value; - prefix += (1u + (value > 0xff ? 1 : 0)) << 24; -} - template struct write_int_arg { UInt abs_value; unsigned prefix; diff --git a/fmt/include/fmt/ostream.h b/fmt/include/fmt/ostream.h index 2ed35df1..3086191a 100644 --- a/fmt/include/fmt/ostream.h +++ b/fmt/include/fmt/ostream.h @@ -95,7 +95,7 @@ void format_value(buffer& buf, const T& value) { auto&& format_buf = formatbuf>(buf); auto&& output = std::basic_ostream(&format_buf); #if !defined(FMT_STATIC_THOUSANDS_SEPARATOR) - output.imbue(std::locale::classic()); // The default is always unlocalized. + output.imbue(std::locale::classic()); // The default is always unlocalized. #endif output << value; output.exceptions(std::ios_base::failbit | std::ios_base::badbit); diff --git a/fmt/include/fmt/std.h b/fmt/include/fmt/std.h index 6f6b23ff..5bafcefb 100644 --- a/fmt/include/fmt/std.h +++ b/fmt/include/fmt/std.h @@ -137,8 +137,7 @@ template struct formatter { debug_ = true; ++it; } - if (it != end && (*it == 'g' || *it == 'n')) - path_type_ = *it++; + if (it != end && (*it == 'g' || *it == 'n')) path_type_ = *it++; return it; } @@ -246,8 +245,7 @@ FMT_END_NAMESPACE #ifdef __cpp_lib_source_location FMT_BEGIN_NAMESPACE FMT_EXPORT -template<> -struct formatter { +template <> struct formatter { template FMT_CONSTEXPR auto parse(ParseContext& ctx) { return ctx.begin(); } @@ -384,7 +382,7 @@ template struct formatter { FMT_EXPORT template struct formatter< - T, Char, // DEPRECATED! Mixing code unit types. + T, Char, // DEPRECATED! Mixing code unit types. typename std::enable_if::value>::type> { private: bool with_typename_ = false; @@ -415,7 +413,7 @@ struct formatter< # ifdef FMT_HAS_ABI_CXA_DEMANGLE int status = 0; std::size_t size = 0; - std::unique_ptr demangled_name_ptr( + std::unique_ptr demangled_name_ptr( abi::__cxa_demangle(ti.name(), nullptr, &size, &status), &std::free); string_view demangled_name_view; diff --git a/fmt/include/fmt/xchar.h b/fmt/include/fmt/xchar.h index 625ec369..9a7aa4d7 100644 --- a/fmt/include/fmt/xchar.h +++ b/fmt/include/fmt/xchar.h @@ -70,7 +70,7 @@ constexpr format_arg_store make_wformat_args( inline namespace literals { #if FMT_USE_USER_DEFINED_LITERALS && !FMT_USE_NONTYPE_TEMPLATE_ARGS -constexpr detail::udl_arg operator"" _a(const wchar_t* s, size_t) { +constexpr detail::udl_arg operator""_a(const wchar_t* s, size_t) { return {s}; } #endif @@ -172,11 +172,11 @@ inline auto vformat_to( return detail::get_iterator(buf, out); } -template < - typename OutputIt, typename Locale, typename S, typename... T, - typename Char = char_t, - bool enable = detail::is_output_iterator::value&& - detail::is_locale::value&& detail::is_exotic_char::value> +template , + bool enable = detail::is_output_iterator::value && + detail::is_locale::value && + detail::is_exotic_char::value> inline auto format_to(OutputIt out, const Locale& loc, const S& format_str, T&&... args) -> typename std::enable_if::type { diff --git a/fmt/src/fmt.cc b/fmt/src/fmt.cc index 6638bb4a..5330463a 100644 --- a/fmt/src/fmt.cc +++ b/fmt/src/fmt.cc @@ -101,7 +101,7 @@ extern "C++" { // gcc doesn't yet implement private module fragments #if !FMT_GCC_VERSION -module : private; +module :private; #endif #include "format.cc" diff --git a/fmt/support/bazel/.bazelrc b/fmt/support/bazel/.bazelrc deleted file mode 100644 index 583cbbd2..00000000 --- a/fmt/support/bazel/.bazelrc +++ /dev/null @@ -1 +0,0 @@ -build --symlink_prefix=/ # Out of source build diff --git a/fmt/support/rst2md.py b/fmt/support/rst2md.py deleted file mode 100644 index 3f072007..00000000 --- a/fmt/support/rst2md.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/usr/bin/env python -# reStructuredText (RST) to GitHub-flavored Markdown converter - -import re, sys -from docutils import core, nodes, writers - - -def is_github_ref(node): - return re.match('https://github.com/.*/(issues|pull)/.*', node['refuri']) - - -class Translator(nodes.NodeVisitor): - def __init__(self, document): - nodes.NodeVisitor.__init__(self, document) - self.output = '' - self.indent = 0 - self.preserve_newlines = False - - def write(self, text): - self.output += text.replace('\n', '\n' + ' ' * self.indent) - - def visit_document(self, node): - pass - - def depart_document(self, node): - pass - - def visit_section(self, node): - pass - - def depart_section(self, node): - # Skip all sections except the first one. - raise nodes.StopTraversal - - def visit_title(self, node): - self.version = re.match(r'(\d+\.\d+\.\d+).*', node.children[0]).group(1) - raise nodes.SkipChildren - - def visit_title_reference(self, node): - raise Exception(node) - - def depart_title(self, node): - pass - - def visit_Text(self, node): - if not self.preserve_newlines: - node = node.replace('\n', ' ') - self.write(node) - - def depart_Text(self, node): - pass - - def visit_bullet_list(self, node): - pass - - def depart_bullet_list(self, node): - pass - - def visit_list_item(self, node): - self.write('* ') - self.indent += 2 - - def depart_list_item(self, node): - self.indent -= 2 - self.write('\n\n') - - def visit_paragraph(self, node): - self.write('\n\n') - - def depart_paragraph(self, node): - pass - - def visit_reference(self, node): - if not is_github_ref(node): - self.write('[') - - def depart_reference(self, node): - if not is_github_ref(node): - self.write('](' + node['refuri'] + ')') - - def visit_target(self, node): - pass - - def depart_target(self, node): - pass - - def visit_literal(self, node): - self.write('`') - - def depart_literal(self, node): - self.write('`') - - def visit_literal_block(self, node): - self.write('\n\n```') - if 'c++' in node['classes']: - self.write('c++') - self.write('\n') - self.preserve_newlines = True - - def depart_literal_block(self, node): - self.write('\n```\n') - self.preserve_newlines = False - - def visit_inline(self, node): - pass - - def depart_inline(self, node): - pass - - def visit_image(self, node): - self.write('![](' + node['uri'] + ')') - - def depart_image(self, node): - pass - - def write_row(self, row, widths): - for i, entry in enumerate(row): - text = entry[0][0] if len(entry) > 0 else '' - if i != 0: - self.write('|') - self.write('{:{}}'.format(text, widths[i])) - self.write('\n') - - def visit_table(self, node): - table = node.children[0] - colspecs = table[:-2] - thead = table[-2] - tbody = table[-1] - widths = [int(cs['colwidth']) for cs in colspecs] - sep = '|'.join(['-' * w for w in widths]) + '\n' - self.write('\n\n') - self.write_row(thead[0], widths) - self.write(sep) - for row in tbody: - self.write_row(row, widths) - raise nodes.SkipChildren - - def depart_table(self, node): - pass - -class MDWriter(writers.Writer): - """GitHub-flavored markdown writer""" - - supported = ('md',) - """Formats this writer supports.""" - - def translate(self): - translator = Translator(self.document) - self.document.walkabout(translator) - self.output = (translator.output, translator.version) - - -def convert(rst_path): - """Converts RST file to Markdown.""" - return core.publish_file(source_path=rst_path, writer=MDWriter()) - - -if __name__ == '__main__': - convert(sys.argv[1]) diff --git a/fmt/test/chrono-test.cc b/fmt/test/chrono-test.cc index b562a50e..56fbd382 100644 --- a/fmt/test/chrono-test.cc +++ b/fmt/test/chrono-test.cc @@ -24,6 +24,12 @@ using testing::Contains; # define FMT_HAS_C99_STRFTIME 1 #endif +#if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907L +using days = std::chrono::days; +#else +using days = std::chrono::duration>; +#endif + auto make_tm() -> std::tm { auto time = std::tm(); time.tm_mday = 1; @@ -456,9 +462,7 @@ TEST(chrono_test, format_default) { fmt::format("{}", std::chrono::duration(42))); EXPECT_EQ("42min", fmt::format("{}", std::chrono::minutes(42))); EXPECT_EQ("42h", fmt::format("{}", std::chrono::hours(42))); -# if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907L - EXPECT_EQ("42d", fmt::format("{}", std::chrono::days(42))); -# endif + EXPECT_EQ("42d", fmt::format("{}", days(42))); EXPECT_EQ( "42[15]s", fmt::format("{}", std::chrono::duration>(42))); @@ -533,6 +537,8 @@ TEST(chrono_test, format_specs) { EXPECT_EQ("12", fmt::format("{:%I}", std::chrono::hours(24))); EXPECT_EQ("04", fmt::format("{:%I}", std::chrono::hours(4))); EXPECT_EQ("02", fmt::format("{:%I}", std::chrono::hours(14))); + EXPECT_EQ("12345", fmt::format("{:%j}", days(12345))); + EXPECT_EQ("12345", fmt::format("{:%j}", std::chrono::hours(12345 * 24 + 12))); EXPECT_EQ("03:25:45", fmt::format("{:%H:%M:%S}", std::chrono::seconds(12345))); EXPECT_EQ("03:25", fmt::format("{:%R}", std::chrono::seconds(12345))); @@ -734,8 +740,8 @@ TEST(chrono_test, special_durations) { EXPECT_EQ(fmt::format("{:%T}", std::chrono::duration{2}), "03:33:20"); EXPECT_EQ("01.234", - fmt::format("{:.3%S}", std::chrono::duration( - 1.234e12))); + fmt::format("{:.3%S}", + std::chrono::duration(1.234e12))); } TEST(chrono_test, unsigned_duration) { @@ -858,18 +864,18 @@ TEST(chrono_test, timestamps_ratios) { EXPECT_EQ(fmt::format("{:%M:%S}", t1), "01:07.890"); - std::chrono::time_point - t2(std::chrono::minutes(7)); + std::chrono::time_point t2( + std::chrono::minutes(7)); EXPECT_EQ(fmt::format("{:%M:%S}", t2), "07:00"); - std::chrono::time_point>> t3(std::chrono::duration>(7)); EXPECT_EQ(fmt::format("{:%M:%S}", t3), "01:03"); - std::chrono::time_point>> t4(std::chrono::duration>(1)); @@ -1017,3 +1023,8 @@ TEST(chrono_test, glibc_extensions) { EXPECT_EQ(fmt::format("{:%-S}", d), "3.140000"); } } + +TEST(chrono_test, out_of_range) { + auto d = std::chrono::duration(538976288); + EXPECT_THROW((void)fmt::format("{:%j}", d), fmt::format_error); +} \ No newline at end of file diff --git a/fmt/test/format-test.cc b/fmt/test/format-test.cc index 34eb28a3..e967ed32 100644 --- a/fmt/test/format-test.cc +++ b/fmt/test/format-test.cc @@ -1159,6 +1159,8 @@ TEST(format_test, format_bool) { EXPECT_EQ("true", fmt::format("{:s}", true)); EXPECT_EQ("false", fmt::format("{:s}", false)); EXPECT_EQ("false ", fmt::format("{:6s}", false)); + EXPECT_THROW_MSG((void)fmt::format(runtime("{:c}"), false), format_error, + "invalid format specifier"); } TEST(format_test, format_short) { @@ -2171,6 +2173,13 @@ auto format_as(scoped_enum_as_string) -> std::string { return "foo"; } struct struct_as_int {}; auto format_as(struct_as_int) -> int { return 42; } + +struct struct_as_const_reference { + const std::string name = "foo"; +}; +auto format_as(const struct_as_const_reference& s) -> const std::string& { + return s.name; +} } // namespace test TEST(format_test, format_as) { @@ -2178,6 +2187,7 @@ TEST(format_test, format_as) { EXPECT_EQ(fmt::format("{}", test::scoped_enum_as_string_view()), "foo"); EXPECT_EQ(fmt::format("{}", test::scoped_enum_as_string()), "foo"); EXPECT_EQ(fmt::format("{}", test::struct_as_int()), "42"); + EXPECT_EQ(fmt::format("{}", test::struct_as_const_reference()), "foo"); } TEST(format_test, format_as_to_string) { @@ -2287,6 +2297,14 @@ TEST(format_test, format_named_arg_with_locale) { "42"); } +TEST(format_test, format_locale) { + auto loc = + std::locale({}, new fmt::format_facet(",")); + EXPECT_EQ("7,5bc,d15", fmt::format(loc, "{:Lx}", 123456789)); + EXPECT_EQ("-0b111,010,110,111,100,110,100,010,101", fmt::format(loc, "{:#Lb}", -123456789)); + EXPECT_EQ(" 30,071", fmt::format(loc, "{:10Lo}", 12345)); +} + #endif // FMT_STATIC_THOUSANDS_SEPARATOR struct convertible_to_nonconst_cstring { diff --git a/fmt/test/gtest/gmock-gtest-all.cc b/fmt/test/gtest/gmock-gtest-all.cc index 7b33134f..9d3b9bc1 100644 --- a/fmt/test/gtest/gmock-gtest-all.cc +++ b/fmt/test/gtest/gmock-gtest-all.cc @@ -1912,7 +1912,7 @@ void AssertHelper::operator=(const Message& message) const { namespace { // When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P -// to creates test cases for it, a syntetic test case is +// to creates test cases for it, a synthetic test case is // inserted to report ether an error or a log message. // // This configuration bit will likely be removed at some point. diff --git a/fmt/test/scan-test.cc b/fmt/test/scan-test.cc index ada5f698..25f76109 100644 --- a/fmt/test/scan-test.cc +++ b/fmt/test/scan-test.cc @@ -6,24 +6,24 @@ // For the license information refer to format.h. #include "scan.h" -#include "fmt/os.h" #include #include +#include "fmt/os.h" #include "gmock/gmock.h" #include "gtest-extra.h" TEST(scan_test, read_text) { - auto s = fmt::string_view("foo"); + fmt::string_view s = "foo"; auto end = fmt::scan(s, "foo"); EXPECT_EQ(end, s.end()); EXPECT_THROW_MSG(fmt::scan("fob", "foo"), fmt::format_error, "invalid input"); } TEST(scan_test, read_int) { - auto n = int(); + int n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); fmt::scan("-42", "{}", n); @@ -39,7 +39,7 @@ TEST(scan_test, read_longlong) { } TEST(scan_test, read_uint) { - auto n = unsigned(); + unsigned n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error, @@ -55,13 +55,13 @@ TEST(scan_test, read_ulonglong) { } TEST(scan_test, read_string) { - auto s = std::string(); + std::string s; fmt::scan("foo", "{}", s); EXPECT_EQ(s, "foo"); } TEST(scan_test, read_string_view) { - auto s = fmt::string_view(); + fmt::string_view s; fmt::scan("foo", "{}", s); EXPECT_EQ(s, "foo"); } @@ -83,21 +83,23 @@ template <> struct scanner { } template - auto scan(tm& t, ScanContext& ctx) const -> typename ScanContext::iterator { - auto result = strptime(ctx.begin(), format.c_str(), &t); - if (!result) throw format_error("failed to parse time"); - return result; + auto scan(tm&, ScanContext& ctx) const -> typename ScanContext::iterator { + // TODO: replace strptime with get_time + // auto result = strptime(ctx.begin(), format.c_str(), &t); + // if (!result) throw format_error("failed to parse time"); + // return result; + return ctx.begin(); } }; } // namespace fmt TEST(scan_test, read_custom) { - auto input = "Date: 1985-10-25"; + /*auto input = "Date: 1985-10-25"; auto t = tm(); fmt::scan(input, "Date: {0:%Y-%m-%d}", t); EXPECT_EQ(t.tm_year, 85); EXPECT_EQ(t.tm_mon, 9); - EXPECT_EQ(t.tm_mday, 25); + EXPECT_EQ(t.tm_mday, 25);*/ } #endif diff --git a/fmt/test/scan.h b/fmt/test/scan.h index 96e46678..6a44b646 100644 --- a/fmt/test/scan.h +++ b/fmt/test/scan.h @@ -14,37 +14,118 @@ FMT_BEGIN_NAMESPACE namespace detail { +struct maybe_contiguous_range { + const char* begin; + const char* end; + + explicit operator bool() const { return begin != nullptr; } +}; + class scan_buffer { private: const char* ptr_; - size_t size_; + const char* end_; + bool contiguous_; protected: - scan_buffer(const char* ptr, size_t size) : ptr_(ptr), size_(size) {} + scan_buffer(const char* ptr, const char* end, bool contiguous) + : ptr_(ptr), end_(end), contiguous_(contiguous) {} ~scan_buffer() = default; - void set(const char* data, size_t size) noexcept { - ptr_ = data; - size_ = size; + auto is_empty() const -> bool { return ptr_ == end_; } + + void set(const char* ptr, const char* end) noexcept { + ptr_ = ptr; + end_ = end; } - // Fills the buffer with more input. + auto peek() -> int { + if (ptr_ == end_) { + // TODO: refill buffer + return EOF; + } + return *ptr_; + } + + // Fills the buffer with more input if available. virtual void fill() = 0; public: scan_buffer(const scan_buffer&) = delete; void operator=(const scan_buffer&) = delete; - auto begin() noexcept -> const char* { return ptr_; } - auto end() noexcept -> const char* { return ptr_ + size_; } + class iterator { + private: + const char** ptr_; + scan_buffer* buf_; // This could be merged with ptr_. + char value_; + + static auto sentinel() -> const char** { + static const char* ptr = nullptr; + return &ptr; + } + + friend class scan_buffer; + + friend auto operator==(iterator lhs, iterator rhs) -> bool { + return *lhs.ptr_ == *rhs.ptr_; + } + friend auto operator!=(iterator lhs, iterator rhs) -> bool { + return *lhs.ptr_ != *rhs.ptr_; + } + + iterator(scan_buffer* buf) + : ptr_(&buf->ptr_), buf_(buf), value_(static_cast(buf->peek())) { + if (value_ == EOF) ptr_ = sentinel(); + } + + public: + iterator() : ptr_(sentinel()), buf_(nullptr) {} - auto size() const -> size_t { return size_; } + auto operator++() -> iterator& { + if (!buf_->try_consume()) ptr_ = sentinel(); + value_ = *buf_->ptr_; + return *this; + } + auto operator++(int) -> iterator { + iterator copy = *this; + ++*this; + return copy; + } + auto operator*() const -> char { return value_; } + + auto base() const -> const char* { return buf_->ptr_; } + + friend auto to_contiguous(iterator it) -> maybe_contiguous_range; + friend void advance(iterator& it, size_t n); + }; + + friend auto to_contiguous(iterator it) -> maybe_contiguous_range { + if (it.buf_->is_contiguous()) return {it.buf_->ptr_, it.buf_->end_}; + return {nullptr, nullptr}; + } + friend void advance(iterator& it, size_t n) { + FMT_ASSERT(it.buf_->is_contiguous(), ""); + const char*& ptr = it.buf_->ptr_; + ptr += n; + it.value_ = *ptr; + if (ptr == it.buf_->end_) it.ptr_ = iterator::sentinel(); + } - // Consume n code units from the buffer. - void consume(size_t n) { - FMT_ASSERT(n <= size_, ""); - ptr_ += n; - size_ -= n; + auto begin() noexcept -> iterator { return this; } + auto end() noexcept -> iterator { return {}; } + + auto is_contiguous() const -> bool { return contiguous_; } + + // Tries consuming a single code unit. + auto try_consume() -> bool { + FMT_ASSERT(ptr_ != end_, ""); + ++ptr_; + if (ptr_ == end_) { + // TODO: refill buffer + return false; + } + return true; } }; @@ -53,8 +134,8 @@ class string_scan_buffer : public scan_buffer { void fill() override {} public: - explicit string_scan_buffer(string_view s) : scan_buffer(s.data(), s.size()) { - } + explicit string_scan_buffer(string_view s) + : scan_buffer(s.begin(), s.end(), true) {} }; class file_scan_buffer : public scan_buffer { @@ -64,12 +145,13 @@ class file_scan_buffer : public scan_buffer { template void set_buffer(int, F* f) { - this->set(reinterpret_cast(f->_p), detail::to_unsigned(f->_r)); + const char* ptr = reinterpret_cast(f->_p); + this->set(ptr, ptr + f->_r); } void set_buffer(int c, ...) { if (c == EOF) return; next_ = static_cast(c); - this->set(&next_, 1); + this->set(&next_, &next_ + 1); } void fill() override { @@ -87,10 +169,10 @@ class file_scan_buffer : public scan_buffer { public: explicit file_scan_buffer(FILE* f) - : scan_buffer(nullptr, 0), file_(f) { + : scan_buffer(nullptr, nullptr, false), file_(f) { // TODO: lock file? set_buffer(EOF, f); - if (size() == 0) fill(); + if (is_empty()) fill(); } }; } // namespace detail @@ -123,16 +205,16 @@ struct scan_context { detail::scan_buffer& buf_; public: - using iterator = const char*; + using iterator = detail::scan_buffer::iterator; explicit FMT_CONSTEXPR scan_context(detail::scan_buffer& buf) : buf_(buf) {} - // TODO: an iterator that automatically calls read on end of buffer auto begin() const -> iterator { return buf_.begin(); } auto end() const -> iterator { return buf_.end(); } - void advance_to(iterator it) { - buf_.consume(detail::to_unsigned(it - begin())); + void advance_to(iterator) { + // The scan_buffer iterator automatically updates the buffer position when + // incremented. } }; @@ -242,17 +324,18 @@ struct scan_handler : error_handler { } public: - FMT_CONSTEXPR scan_handler(string_view format, scan_buffer& buf, scan_args args) + FMT_CONSTEXPR scan_handler(string_view format, scan_buffer& buf, + scan_args args) : parse_ctx_(format), scan_ctx_(buf), args_(args), next_arg_id_(0) {} - auto pos() const -> const char* { return scan_ctx_.begin(); } + auto pos() const -> scan_buffer::iterator { return scan_ctx_.begin(); } void on_text(const char* begin, const char* end) { - auto size = to_unsigned(end - begin); - auto it = scan_ctx_.begin(); - if (it + size > scan_ctx_.end() || !std::equal(begin, end, it)) - on_error("invalid input"); - scan_ctx_.advance_to(it + size); + auto it = scan_ctx_.begin(), scan_end = scan_ctx_.end(); + for (; begin != end; ++begin, ++it) { + if (it == scan_end || *begin != *it) on_error("invalid input"); + } + scan_ctx_.advance_to(it); } FMT_CONSTEXPR auto on_arg_id() -> int { return on_arg_id(next_arg_id_++); } @@ -286,9 +369,14 @@ struct scan_handler : error_handler { scan_ctx_.advance_to(it); break; case scan_type::string_view_type: { - auto s = it; - while (it != end && *it != ' ') ++it; - *arg_.string_view = fmt::string_view(s, to_unsigned(it - s)); + auto range = to_contiguous(it); + // This could also be checked at compile time in scan. + if (!range) on_error("string_view requires contiguous input"); + auto p = range.begin; + while (p != range.end && *p != ' ') ++p; + size_t size = to_unsigned(p - range.begin); + *arg_.string_view = {range.begin, size}; + advance(it, size); scan_ctx_.advance_to(it); break; } @@ -322,11 +410,10 @@ auto scan(string_view input, string_view fmt, T&... args) -> string_view::iterator { auto&& buf = detail::string_scan_buffer(input); vscan(buf, fmt, make_scan_args(args...)); - return input.begin() + (buf.begin() - input.data()); + return input.begin() + (buf.begin().base() - input.data()); } -template -void scan(std::FILE* f, string_view fmt, T&... args) { +template void scan(std::FILE* f, string_view fmt, T&... args) { auto&& buf = detail::file_scan_buffer(f); vscan(buf, fmt, make_scan_args(args...)); } diff --git a/glfw/CONTRIBUTORS.md b/glfw/CONTRIBUTORS.md index 1b9a277a..75533ec3 100644 --- a/glfw/CONTRIBUTORS.md +++ b/glfw/CONTRIBUTORS.md @@ -66,11 +66,13 @@ video tutorials. - Nikita Fediuchin - Felipe Ferreira - Michael Fogleman + - forworldm - Jason Francis - Gerald Franz - Mário Freitas - GeO4d - Marcus Geelnard + - Gegy - ghuser404 - Charles Giessen - Ryan C. Gordon @@ -83,6 +85,7 @@ video tutorials. - Andrew Gutekanst - Stephen Gutekanst - Jonathan Hale + - Daniel Hauser - hdf89shfdfs - Moritz Heinemann - Sylvain Hellegouarch @@ -102,6 +105,7 @@ video tutorials. - JannikGM - Erik S. V. Jansson - jjYBdx4IL + - Peter Johnson - Toni Jovanoski - Arseny Kapoulkine - Cem Karan @@ -124,11 +128,13 @@ video tutorials. - Anders Lindqvist - Leon Linhart - Marco Lizza + - lo-v-ol - Eyal Lotem - Aaron Loucks - Luflosi - lukect - Tristam MacDonald + - Jean-Luc Mackail - Hans Mackowiak - Ramiro Magno - Дмитри Малышев @@ -212,6 +218,7 @@ video tutorials. - Matt Sealey - Steve Sexton - Arkady Shapkin + - Mingjie Shen - Ali Sherief - Yoshiki Shibukawa - Dmitri Shuralyov @@ -249,6 +256,7 @@ video tutorials. - Jari Vetoniemi - Ricardo Vieira - Nicholas Vitovitch + - Vladimír Vondruš - Simon Voordouw - Corentin Wallez - Torsten Walluhn diff --git a/glfw/README.md b/glfw/README.md index 52081c1c..cebe62bc 100644 --- a/glfw/README.md +++ b/glfw/README.md @@ -183,6 +183,8 @@ information on what to include when reporting a bug. - Bugfix: `glfwMakeContextCurrent` would access TLS slot before initialization - Bugfix: `glfwSetGammaRamp` could emit `GLFW_INVALID_VALUE` before initialization - Bugfix: `glfwGetJoystickUserPointer` returned `NULL` during disconnection (#2092) + - Bugfix: `glfwGetKeyScancode` returned `0` on error when initialized instead of `-1` + - Bugfix: Failure to make a newly created context current could cause segfault (#2327) - [Win32] Added the `GLFW_WIN32_KEYBOARD_MENU` window hint for enabling access to the window menu - [Win32] Added a version info resource to the GLFW DLL @@ -231,6 +233,7 @@ information on what to include when reporting a bug. - [Win32] Bugfix: Right shift emitted `GLFW_KEY_UNKNOWN` when using a CJK IME (#2050) - [Win32] Bugfix: `glfwWaitEventsTimeout` did not return for some sent messages (#2408) - [Win32] Bugfix: Fix pkg-config for dynamic library on Windows (#2386, #2420) + - [Win32] Bugfix: XInput could reportedly provide invalid DPad bit masks (#2291) - [Cocoa] Added support for `VK_EXT_metal_surface` (#1619) - [Cocoa] Added locating the Vulkan loader at runtime in an application bundle - [Cocoa] Moved main menu creation to GLFW initialization time (#1649) @@ -271,6 +274,10 @@ information on what to include when reporting a bug. application (#2110) - [Cocoa] Bugfix: The Vulkan loader was not loaded from the `Frameworks` bundle subdirectory (#2113,#2120) + - [Cocoa] Bugfix: Compilation failed on OS X 10.8 due to unconditional use of 10.9+ + symbols (#2161) + - [Cocoa] Bugfix: Querying joystick elements could reportedly segfault on macOS + 13 Ventura (#2320) - [X11] Bugfix: The CMake files did not check for the XInput headers (#1480) - [X11] Bugfix: Key names were not updated when the keyboard layout changed (#1462,#1528) @@ -387,7 +394,6 @@ information on what to include when reporting a bug. - [Wayland] Bugfix: Connecting a mouse after `glfwInit` would segfault (#1450) - [Wayland] Bugfix: Joysticks connected after `glfwInit` were not detected (#2198) - [Wayland] Bugfix: Fallback decorations emitted `GLFW_CURSOR_UNAVAILABLE` errors - - [Wayland] Bugfix: Showing an undecorated window would cause a protocol error - [POSIX] Removed use of deprecated function `gettimeofday` - [POSIX] Bugfix: `CLOCK_MONOTONIC` was not correctly tested for or enabled - [Linux] Bugfix: Joysticks without buttons were ignored (#2042,#2043) @@ -403,8 +409,9 @@ information on what to include when reporting a bug. (#442) - [EGL] Added ANGLE backend selection via `EGL_ANGLE_platform_angle` extension (#1380) - [EGL] Added loading of glvnd `libOpenGL.so.0` where available for OpenGL + - [EGL] Added loading of glvnd `libOpenGL.so.0` where available for OpenGL - [EGL] Bugfix: The `GLFW_DOUBLEBUFFER` context attribute was ignored (#1843) + - [EGL] Bugfix: Setting `GLFW_CONTEXT_DEBUG` caused creation to fail (#2348) - [GLX] Added loading of glvnd `libGLX.so.0` where available - [GLX] Bugfix: Context creation failed if GLX 1.4 was not exported by GLX library diff --git a/glfw/docs/input.dox b/glfw/docs/input.dox index d3904f46..f57520bb 100644 --- a/glfw/docs/input.dox +++ b/glfw/docs/input.dox @@ -95,7 +95,7 @@ new size before everything returns back out of the @ref glfwSetWindowSize call. GLFW divides keyboard input into two categories; key events and character events. Key events relate to actual physical keyboard keys, whereas character -events relate to the Unicode code points generated by pressing some of them. +events relate to the text that is generated by pressing some of them. Keys and characters do not map 1:1. A single key press may produce several characters, and a single character may require several keys to produce. This @@ -127,6 +127,10 @@ The action is one of `GLFW_PRESS`, `GLFW_REPEAT` or `GLFW_RELEASE`. Events with `GLFW_PRESS` and `GLFW_RELEASE` actions are emitted for every key press. Most keys will also emit events with `GLFW_REPEAT` actions while a key is held down. +Note that many keyboards have a limit on how many keys being simultaneous held +down that they can detect. This limit is called +[key rollover](https://en.wikipedia.org/wiki/Key_rollover). + Key events with `GLFW_REPEAT` actions are intended for text input. They are emitted at the rate set in the user's keyboard settings. At most one key is repeated even if several keys are held down. `GLFW_REPEAT` actions should not @@ -142,16 +146,16 @@ keys. The scancode is unique for every key, regardless of whether it has a key token. Scancodes are platform-specific but consistent over time, so keys will have different scancodes depending on the platform but they are safe to save to disk. -You can query the scancode for any [named key](@ref keys) on the current -platform with @ref glfwGetKeyScancode. +You can query the scancode for any [key token](@ref keys) supported on the +current platform with @ref glfwGetKeyScancode. @code const int scancode = glfwGetKeyScancode(GLFW_KEY_X); set_key_mapping(scancode, swap_weapons); @endcode -The last reported state for every [named key](@ref keys) is also saved in -per-window state arrays that can be polled with @ref glfwGetKey. +The last reported state for every physical key with a [key token](@ref keys) is +also saved in per-window state arrays that can be polled with @ref glfwGetKey. @code int state = glfwGetKey(window, GLFW_KEY_E); @@ -164,7 +168,8 @@ if (state == GLFW_PRESS) The returned state is one of `GLFW_PRESS` or `GLFW_RELEASE`. This function only returns cached key event state. It does not poll the -system for the current physical state of the key. +system for the current state of the physical key. It also does not provide any +key repeat information. @anchor GLFW_STICKY_KEYS Whenever you poll state, you risk missing the state change you are looking for. @@ -195,15 +200,15 @@ Lock was on when the event occurred and the @ref GLFW_MOD_NUM_LOCK bit set if Num Lock was on. The `GLFW_KEY_LAST` constant holds the highest value of any -[named key](@ref keys). +[key token](@ref keys). @subsection input_char Text input GLFW supports text input in the form of a stream of [Unicode code points](https://en.wikipedia.org/wiki/Unicode), as produced by the -operating system text input system. Unlike key input, text input obeys keyboard -layouts and modifier keys and supports composing characters using +operating system text input system. Unlike key input, text input is affected by +keyboard layouts and modifier keys and supports composing characters using [dead keys](https://en.wikipedia.org/wiki/Dead_key). Once received, you can encode the code points into UTF-8 or any other encoding you prefer. @@ -502,8 +507,9 @@ void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) The action is one of `GLFW_PRESS` or `GLFW_RELEASE`. -Mouse button states for [named buttons](@ref buttons) are also saved in -per-window state arrays that can be polled with @ref glfwGetMouseButton. +The last reported state for every [supported mouse button](@ref buttons) is also +saved in per-window state arrays that can be polled with @ref +glfwGetMouseButton. @code int state = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT); @@ -536,7 +542,7 @@ had been processed in the meantime, the state will reset to `GLFW_RELEASE`, otherwise it will remain `GLFW_PRESS`. The `GLFW_MOUSE_BUTTON_LAST` constant holds the highest value of any -[named button](@ref buttons). +[supported mouse button](@ref buttons). @subsection scrolling Scroll input diff --git a/glfw/docs/news.dox b/glfw/docs/news.dox index e16267b2..28c500d9 100644 --- a/glfw/docs/news.dox +++ b/glfw/docs/news.dox @@ -277,6 +277,7 @@ then GLFW will fail to initialize. - @ref GLFW_POSITION_X - @ref GLFW_POSITION_Y - @ref GLFW_ANY_POSITION + - @ref GLFW_WAYLAND_APP_ID - @ref GLFW_WAYLAND_LIBDECOR - @ref GLFW_WAYLAND_PREFER_LIBDECOR - @ref GLFW_WAYLAND_DISABLE_LIBDECOR diff --git a/glfw/include/GLFW/glfw3.h b/glfw/include/GLFW/glfw3.h index f8b0ae00..eb98dafd 100644 --- a/glfw/include/GLFW/glfw3.h +++ b/glfw/include/GLFW/glfw3.h @@ -361,10 +361,15 @@ extern "C" { #define GLFW_HAT_RIGHT_DOWN (GLFW_HAT_RIGHT | GLFW_HAT_DOWN) #define GLFW_HAT_LEFT_UP (GLFW_HAT_LEFT | GLFW_HAT_UP) #define GLFW_HAT_LEFT_DOWN (GLFW_HAT_LEFT | GLFW_HAT_DOWN) + +/*! @ingroup input + */ +#define GLFW_KEY_UNKNOWN -1 + /*! @} */ -/*! @defgroup keys Keyboard keys - * @brief Keyboard key IDs. +/*! @defgroup keys Keyboard key tokens + * @brief Keyboard key tokens. * * See [key input](@ref input_key) for how these are used. * @@ -387,9 +392,6 @@ extern "C" { * @{ */ -/* The unknown key */ -#define GLFW_KEY_UNKNOWN -1 - /* Printable keys */ #define GLFW_KEY_SPACE 32 #define GLFW_KEY_APOSTROPHE 39 /* ' */ @@ -4718,8 +4720,8 @@ GLFWAPI int glfwRawMouseMotionSupported(void); * @param[in] scancode The scancode of the key to query. * @return The UTF-8 encoded, layout-specific name of the key, or `NULL`. * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref - * GLFW_PLATFORM_ERROR. + * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref + * GLFW_INVALID_VALUE, @ref GLFW_INVALID_ENUM and @ref GLFW_PLATFORM_ERROR. * * @remark The contents of the returned string may change when a keyboard * layout change event is received. @@ -4741,15 +4743,18 @@ GLFWAPI const char* glfwGetKeyName(int key, int scancode); * * This function returns the platform-specific scancode of the specified key. * - * If the key is `GLFW_KEY_UNKNOWN` or does not exist on the keyboard this - * method will return `-1`. + * If the specified [key token](@ref keys) corresponds to a physical key not + * supported on the current platform then this method will return `-1`. + * Calling this function with anything other than a key token will return `-1` + * and generate a @ref GLFW_INVALID_ENUM error. * - * @param[in] key Any [named key](@ref keys). - * @return The platform-specific scancode for the key, or `-1` if an - * [error](@ref error_handling) occurred. + * @param[in] key Any [key token](@ref keys). + * @return The platform-specific scancode for the key, or `-1` if the key is + * not supported on the current platform or an [error](@ref error_handling) + * occurred. * - * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref - * GLFW_INVALID_ENUM and @ref GLFW_PLATFORM_ERROR. + * @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref + * GLFW_INVALID_ENUM. * * @thread_safety This function may be called from any thread. * @@ -5058,9 +5063,9 @@ GLFWAPI void glfwSetCursor(GLFWwindow* window, GLFWcursor* cursor); * [character callback](@ref glfwSetCharCallback) instead. * * When a window loses input focus, it will generate synthetic key release - * events for all pressed named keys. You can tell these events from - * user-generated events by the fact that the synthetic ones are generated - * after the focus loss event has been processed, i.e. after the + * events for all pressed keys with associated key tokens. You can tell these + * events from user-generated events by the fact that the synthetic ones are + * generated after the focus loss event has been processed, i.e. after the * [window focus callback](@ref glfwSetWindowFocusCallback) has been called. * * The scancode of a key is specific to that platform or sometimes even to that @@ -5959,12 +5964,15 @@ GLFWAPI uint64_t glfwGetTimerFrequency(void); * thread. * * This function makes the OpenGL or OpenGL ES context of the specified window - * current on the calling thread. A context must only be made current on - * a single thread at a time and each thread can have only a single current - * context at a time. + * current on the calling thread. It can also detach the current context from + * the calling thread without making a new one current by passing in `NULL`. * - * When moving a context between threads, you must make it non-current on the - * old thread before making it current on the new one. + * A context must only be made current on a single thread at a time and each + * thread can have only a single current context at a time. Making a context + * current detaches any previously current context on the calling thread. + * + * When moving a context between threads, you must detach it (make it + * non-current) on the old thread before making it current on the new one. * * By default, making a context non-current implicitly forces a pipeline flush. * On machines that support `GL_KHR_context_flush_control`, you can control @@ -5979,6 +5987,10 @@ GLFWAPI uint64_t glfwGetTimerFrequency(void); * @param[in] window The window whose context to make current, or `NULL` to * detach the current context. * + * @remarks If the previously current context was created via a different + * context creation API than the one passed to this function, GLFW will still + * detach the previous one from its API before making the new one current. + * * @errors Possible errors include @ref GLFW_NOT_INITIALIZED, @ref * GLFW_NO_WINDOW_CONTEXT and @ref GLFW_PLATFORM_ERROR. * diff --git a/glfw/src/cocoa_joystick.m b/glfw/src/cocoa_joystick.m index 865adac7..caeb4725 100644 --- a/glfw/src/cocoa_joystick.m +++ b/glfw/src/cocoa_joystick.m @@ -136,6 +136,14 @@ static void matchCallback(void* context, return; } + CFArrayRef elements = + IOHIDDeviceCopyMatchingElements(device, NULL, kIOHIDOptionsTypeNone); + + // It is reportedly possible for this to fail on macOS 13 Ventura + // if the application does not have input monitoring permissions + if (!elements) + return; + axes = CFArrayCreateMutable(NULL, 0, NULL); buttons = CFArrayCreateMutable(NULL, 0, NULL); hats = CFArrayCreateMutable(NULL, 0, NULL); @@ -179,9 +187,6 @@ static void matchCallback(void* context, name[8], name[9], name[10]); } - CFArrayRef elements = - IOHIDDeviceCopyMatchingElements(device, NULL, kIOHIDOptionsTypeNone); - for (CFIndex i = 0; i < CFArrayGetCount(elements); i++) { IOHIDElementRef native = (IOHIDElementRef) diff --git a/glfw/src/cocoa_window.m b/glfw/src/cocoa_window.m index 6f8aa978..9d794940 100644 --- a/glfw/src/cocoa_window.m +++ b/glfw/src/cocoa_window.m @@ -311,10 +311,15 @@ - (void)windowDidResignKey:(NSNotification *)notification - (void)windowDidChangeOcclusionState:(NSNotification* )notification { - if ([window->ns.object occlusionState] & NSWindowOcclusionStateVisible) - window->ns.occluded = GLFW_FALSE; - else - window->ns.occluded = GLFW_TRUE; +#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1090 + if ([window->ns.object respondsToSelector:@selector(occlusionState)]) + { + if ([window->ns.object occlusionState] & NSWindowOcclusionStateVisible) + window->ns.occluded = GLFW_FALSE; + else + window->ns.occluded = GLFW_TRUE; + } +#endif } @end @@ -1279,7 +1284,7 @@ void _glfwSetWindowMonitorCocoa(_GLFWwindow* window, if (window->monitor) { - styleMask &= ~(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable); + styleMask &= ~(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable); styleMask |= NSWindowStyleMaskBorderless; } else diff --git a/glfw/src/context.c b/glfw/src/context.c index 33b399c9..f8610e1e 100644 --- a/glfw/src/context.c +++ b/glfw/src/context.c @@ -363,6 +363,8 @@ GLFWbool _glfwRefreshContextAttribs(_GLFWwindow* window, previous = _glfwPlatformGetTls(&_glfw.contextSlot); glfwMakeContextCurrent((GLFWwindow*) window); + if (_glfwPlatformGetTls(&_glfw.contextSlot) != window) + return GLFW_FALSE; window->context.GetIntegerv = (PFNGLGETINTEGERVPROC) window->context.getProcAddress("glGetIntegerv"); diff --git a/glfw/src/egl_context.c b/glfw/src/egl_context.c index 64dcdd6f..6e997b11 100644 --- a/glfw/src/egl_context.c +++ b/glfw/src/egl_context.c @@ -311,6 +311,7 @@ static int extensionSupportedEGL(const char* extension) static GLFWglproc getProcAddressEGL(const char* procname) { _GLFWwindow* window = _glfwPlatformGetTls(&_glfw.contextSlot); + assert(window != NULL); if (window->context.egl.client) { @@ -640,18 +641,18 @@ GLFWbool _glfwCreateContextEGL(_GLFWwindow* window, flags |= EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR; } - if (ctxconfig->noerror) - { - if (_glfw.egl.KHR_create_context_no_error) - SET_ATTRIB(EGL_CONTEXT_OPENGL_NO_ERROR_KHR, GLFW_TRUE); - } - if (ctxconfig->major != 1 || ctxconfig->minor != 0) { SET_ATTRIB(EGL_CONTEXT_MAJOR_VERSION_KHR, ctxconfig->major); SET_ATTRIB(EGL_CONTEXT_MINOR_VERSION_KHR, ctxconfig->minor); } + if (ctxconfig->noerror) + { + if (_glfw.egl.KHR_create_context_no_error) + SET_ATTRIB(EGL_CONTEXT_OPENGL_NO_ERROR_KHR, GLFW_TRUE); + } + if (mask) SET_ATTRIB(EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR, mask); @@ -703,8 +704,11 @@ GLFWbool _glfwCreateContextEGL(_GLFWwindow* window, if (!fbconfig->doublebuffer) SET_ATTRIB(EGL_RENDER_BUFFER, EGL_SINGLE_BUFFER); - if (_glfw.egl.EXT_present_opaque) - SET_ATTRIB(EGL_PRESENT_OPAQUE_EXT, !fbconfig->transparent); + if (_glfw.platform.platformID == GLFW_PLATFORM_WAYLAND) + { + if (_glfw.egl.EXT_present_opaque) + SET_ATTRIB(EGL_PRESENT_OPAQUE_EXT, !fbconfig->transparent); + } SET_ATTRIB(EGL_NONE, EGL_NONE); diff --git a/glfw/src/glx_context.c b/glfw/src/glx_context.c index 4406dfd3..f3f4b3ec 100644 --- a/glfw/src/glx_context.c +++ b/glfw/src/glx_context.c @@ -192,6 +192,7 @@ static void swapBuffersGLX(_GLFWwindow* window) static void swapIntervalGLX(int interval) { _GLFWwindow* window = _glfwPlatformGetTls(&_glfw.contextSlot); + assert(window != NULL); if (_glfw.glx.EXT_swap_control) { diff --git a/glfw/src/input.c b/glfw/src/input.c index 36128e10..8b7ef29c 100644 --- a/glfw/src/input.c +++ b/glfw/src/input.c @@ -462,10 +462,11 @@ void _glfwInputJoystickHat(_GLFWjoystick* js, int hat, char value) assert(hat >= 0); assert(hat < js->hatCount); - // Valid hat values only use the least significant nibble and have at most two bits - // set, which can be considered adjacent plus an arbitrary rotation within the nibble + // Valid hat values only use the least significant nibble assert((value & 0xf0) == 0); - assert((value & ((value << 2) | (value >> 2))) == 0); + // Valid hat values do not have both bits of an axis set + assert((value & GLFW_HAT_LEFT) == 0 || (value & GLFW_HAT_RIGHT) == 0); + assert((value & GLFW_HAT_UP) == 0 || (value & GLFW_HAT_DOWN) == 0); base = js->buttonCount + hat * 4; @@ -701,6 +702,12 @@ GLFWAPI const char* glfwGetKeyName(int key, int scancode) if (key != GLFW_KEY_UNKNOWN) { + if (key < GLFW_KEY_SPACE || key > GLFW_KEY_LAST) + { + _glfwInputError(GLFW_INVALID_ENUM, "Invalid key %i", key); + return NULL; + } + if (key != GLFW_KEY_KP_EQUAL && (key < GLFW_KEY_KP_0 || key > GLFW_KEY_KP_ADD) && (key < GLFW_KEY_APOSTROPHE || key > GLFW_KEY_WORLD_2)) @@ -721,7 +728,7 @@ GLFWAPI int glfwGetKeyScancode(int key) if (key < GLFW_KEY_SPACE || key > GLFW_KEY_LAST) { _glfwInputError(GLFW_INVALID_ENUM, "Invalid key %i", key); - return GLFW_RELEASE; + return -1; } return _glfw.platform.getKeyScancode(key); diff --git a/glfw/src/nsgl_context.m b/glfw/src/nsgl_context.m index 878f32ed..de89e421 100644 --- a/glfw/src/nsgl_context.m +++ b/glfw/src/nsgl_context.m @@ -83,11 +83,10 @@ static void swapIntervalNSGL(int interval) @autoreleasepool { _GLFWwindow* window = _glfwPlatformGetTls(&_glfw.contextSlot); - if (window) - { - [window->context.nsgl.object setValues:&interval - forParameter:NSOpenGLContextParameterSwapInterval]; - } + assert(window != NULL); + + [window->context.nsgl.object setValues:&interval + forParameter:NSOpenGLContextParameterSwapInterval]; } // autoreleasepool } diff --git a/glfw/src/wgl_context.c b/glfw/src/wgl_context.c index cfe24b27..08c499ff 100644 --- a/glfw/src/wgl_context.c +++ b/glfw/src/wgl_context.c @@ -332,6 +332,7 @@ static void swapBuffersWGL(_GLFWwindow* window) static void swapIntervalWGL(int interval) { _GLFWwindow* window = _glfwPlatformGetTls(&_glfw.contextSlot); + assert(window != NULL); window->context.wgl.interval = interval; diff --git a/glfw/src/win32_joystick.c b/glfw/src/win32_joystick.c index 4e83577a..eae44edf 100644 --- a/glfw/src/win32_joystick.c +++ b/glfw/src/win32_joystick.c @@ -736,6 +736,13 @@ GLFWbool _glfwPollJoystickWin32(_GLFWjoystick* js, int mode) if (xis.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT) dpad |= GLFW_HAT_LEFT; + // Treat invalid combinations as neither being pressed + // while preserving what data can be preserved + if ((dpad & GLFW_HAT_RIGHT) && (dpad & GLFW_HAT_LEFT)) + dpad &= ~(GLFW_HAT_RIGHT | GLFW_HAT_LEFT); + if ((dpad & GLFW_HAT_UP) && (dpad & GLFW_HAT_DOWN)) + dpad &= ~(GLFW_HAT_UP | GLFW_HAT_DOWN); + _glfwInputJoystickHat(js, 0, dpad); } diff --git a/imgui/backends/imgui_impl_android.cpp b/imgui/backends/imgui_impl_android.cpp index 39545360..7dd2afc2 100644 --- a/imgui/backends/imgui_impl_android.cpp +++ b/imgui/backends/imgui_impl_android.cpp @@ -183,7 +183,7 @@ int32_t ImGui_ImplAndroid_HandleInputEvent(const AInputEvent* input_event) case AKEY_EVENT_ACTION_UP: { ImGuiKey key = ImGui_ImplAndroid_KeyCodeToImGuiKey(event_key_code); - if (key != ImGuiKey_None && (event_action == AKEY_EVENT_ACTION_DOWN || event_action == AKEY_EVENT_ACTION_UP)) + if (key != ImGuiKey_None) { io.AddKeyEvent(key, event_action == AKEY_EVENT_ACTION_DOWN); io.SetKeyEventNativeData(key, event_key_code, event_scan_code); diff --git a/imgui/docs/CHANGELOG.txt b/imgui/docs/CHANGELOG.txt index ec709cf1..f4543da0 100644 --- a/imgui/docs/CHANGELOG.txt +++ b/imgui/docs/CHANGELOG.txt @@ -42,20 +42,41 @@ HOW TO UPDATE? Breaking changes: +- DragScalarN, SliderScalarN, InputScalarN: Fixed incorrect pushes into ItemWidth + stack when number of components is 1. [#7095] [@Nahor] +- imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. + Prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls. +- Removed CalcListClipping() marked obsolete in 1.86. (#3841) + Prefer using ImGuiListClipper which can return non-contiguous ranges. +- Internals, Columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting + to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80. + Other changes: - Windows: BeginChild(): Fixed auto-resizing erroneously limiting size to host viewport minus padding. There are no limit to a child width/height. (#7063) [@Devyre] +- Windows: Fixed some auto-resizing path using style.WindowMinSize.x (instead of x/y) + for both axises since 1.90. (#7106) [@n0bodysec] +- Scrolling: internal scrolling value is rounded instead of truncated, as a way to reduce + speed asymetry when (incorrectly) attempting to scroll by non-integer amount. (#6677) - Nav, IO: SetNextFrameWantCaptureKeyboard(false) calls are not overrided back to true when navigation is enabled. SetNextFrameWantCaptureKeyboard() is always higher priority. (#6997) - Drag and Drop: Fixed drop target highlight on items temporarily pushing a widened clip rect (namely Selectables and Treenodes using SpanAllColumn flag) so the highlight properly covers all columns. (#7049, #4281, #3272) +- InputTextMultiline: Fixed Tab character input not repeating (1.89.4 regression). +- InputTextMultiline: Tabbing through a multi-line text editor which allows Tab character inputs + (using the ImGuiInputTextFlags_AllowTabInput flag) doesn't automatically activate it, in order + to allow passing through multiple widgets easily. (#3092, #5759, #787) +- DragScalarN, SliderScalarN, InputScalarN, PushMultiItemsWidths: improve multi-components + width computation to better distribute the error. (#7120, #7121) [@Nahor] - Menus: Tweaked hover slack logic, adding a timer to avoid situations where a slow vertical movements toward another parent BeginMenu() can keep the wrong child menu open. (#6671, #6926) - Debug Tools: Added DebugFlashStyleColor() to identify a style color. Added to Style Editor. - Misc: Added IMGUI_USER_H_FILENAME to change the path included when using IMGUI_INCLUDE_IMGUI_USER_H. (#7039) [@bryceberger] +- Misc: Rework debug display of texture id in Metrics window to avoid compile-error when + ImTextureID is defined to be larger than 64-bits. (#7090) - Misc: Added extra courtesy ==/!= operators when IMGUI_DEFINE_MATH_OPERATORS is defined. - Misc: Fixed text functions fast-path for handling "%s" and "%.*s" to handle null pointers gracefully, like most printf implementations. (#7016, #3466, #6846) [@codefrog2002] @@ -3456,6 +3477,8 @@ Decorated log and release notes: https://github.com/ocornut/imgui/releases/tag/v Breaking Changes: +- Tabs: Added ImGuiTabItemFlags_NoAssumedClosure to enable app to react on closure attempt, without having to draw + an unsaved document marker (ImGuiTabItemFlags_UnsavedDocument sets _NoAssumedClosure automatically). (#7084) - DragInt(): The default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more. If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format. To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, diff --git a/imgui/imgui.cpp b/imgui/imgui.cpp index 09f154b6..a7a9cf98 100644 --- a/imgui/imgui.cpp +++ b/imgui/imgui.cpp @@ -424,6 +424,9 @@ CODE When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. + - 2023/11/06 (1.90.1) - removed CalcListClipping() marked obsolete in 1.86. Prefer using ImGuiListClipper which can return non-contiguous ranges. + - 2023/11/05 (1.90.1) - imgui_freetype: commented out ImGuiFreeType::BuildFontAtlas() obsoleted in 1.81. prefer using #define IMGUI_ENABLE_FREETYPE or see commented code for manual calls. + - 2023/11/05 (1.90.1) - internals,columns: commented out legacy ImGuiColumnsFlags_XXX symbols redirecting to ImGuiOldColumnsFlags_XXX, obsoleted from imgui_internal.h in 1.80. - 2023/11/09 (1.90.0) - removed IM_OFFSETOF() macro in favor of using offsetof() available in C++11. Kept redirection define (will obsolete). - 2023/11/07 (1.90.0) - removed BeginChildFrame()/EndChildFrame() in favor of using BeginChild() with the ImGuiChildFlags_FrameStyle flag. kept inline redirection function (will obsolete). those functions were merely PushStyle/PopStyle helpers, the removal isn't so much motivated by needing to add the feature in BeginChild(), but by the necessity to avoid BeginChildFrame() signature mismatching BeginChild() signature and features. @@ -2724,54 +2727,6 @@ static bool GetSkipItemForListClipping() return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems); } -#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS -// Legacy helper to calculate coarse clipping of large list of evenly sized items. -// This legacy API is not ideal because it assumes we will return a single contiguous rectangle. -// Prefer using ImGuiListClipper which can returns non-contiguous ranges. -void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end) -{ - ImGuiContext& g = *GImGui; - ImGuiWindow* window = g.CurrentWindow; - if (g.LogEnabled) - { - // If logging is active, do not perform any clipping - *out_items_display_start = 0; - *out_items_display_end = items_count; - return; - } - if (GetSkipItemForListClipping()) - { - *out_items_display_start = *out_items_display_end = 0; - return; - } - - // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect - // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly. - ImRect rect = window->ClipRect; - if (g.NavMoveScoringItems) - rect.Add(g.NavScoringNoClipRect); - if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId) - rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel - - const ImVec2 pos = window->DC.CursorPos; - int start = (int)((rect.Min.y - pos.y) / items_height); - int end = (int)((rect.Max.y - pos.y) / items_height); - - // When performing a navigation request, ensure we have one item extra in the direction we are moving to - // FIXME: Verify this works with tabbing - const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav); - if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) - start--; - if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) - end++; - - start = ImClamp(start, 0, items_count); - end = ImClamp(end + 1, start, items_count); - *out_items_display_start = start; - *out_items_display_end = end; -} -#endif - static void ImGuiListClipper_SortAndFuseRanges(ImVector& ranges, int offset = 0) { if (ranges.Size - offset <= 1) @@ -5719,7 +5674,7 @@ static inline ImVec2 CalcWindowMinSize(ImGuiWindow* window) { ImGuiWindow* window_for_height = window; size_min.x = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f; - size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.x : 4.0f; + size_min.y = ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) == 0) ? g.Style.WindowMinSize.y : 4.0f; size_min.y = ImMax(size_min.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows } return size_min; @@ -8339,22 +8294,25 @@ static int CalcRoutingScore(ImGuiWindow* location, ImGuiID owner_id, ImGuiInputF if (owner_id != 0 && g.ActiveId == owner_id) return 1; + // Early out when not in focus stack + if (focused == NULL || focused->RootWindow != location->RootWindow) + return 255; + // Score based on distance to focused window (lower is better) // Assuming both windows are submitting a routing request, // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match) // - When Window/ChildB is focused -> Window scores 4, Window/ChildB scores 3 (best) // Assuming only WindowA is submitting a routing request, // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score. - if (focused != NULL && focused->RootWindow == location->RootWindow) - for (int next_score = 3; focused != NULL; next_score++) + for (int next_score = 3; focused != NULL; next_score++) + { + if (focused == location) { - if (focused == location) - { - IM_ASSERT(next_score < 255); - return next_score; - } - focused = (focused->RootWindow != focused) ? focused->ParentWindow : NULL; // FIXME: This could be later abstracted as a focus path + IM_ASSERT(next_score < 255); + return next_score; } + focused = (focused->RootWindow != focused) ? focused->ParentWindow : NULL; // FIXME: This could be later abstracted as a focus path + } return 255; } @@ -9902,14 +9860,18 @@ void ImGui::PushMultiItemsWidths(int components, float w_full) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; + IM_ASSERT(components > 0); const ImGuiStyle& style = g.Style; - const float w_item_one = ImMax(1.0f, IM_TRUNC((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components)); - const float w_item_last = ImMax(1.0f, IM_TRUNC(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1))); window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width - window->DC.ItemWidthStack.push_back(w_item_last); - for (int i = 0; i < components - 2; i++) - window->DC.ItemWidthStack.push_back(w_item_one); - window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one; + float w_items = w_full - style.ItemInnerSpacing.x * (components - 1); + float prev_split = w_items; + for (int i = components - 1; i > 0; i--) + { + float next_split = IM_TRUNC(w_items * i / components); + window->DC.ItemWidthStack.push_back(prev_split - next_split); + prev_split = next_split; + } + window->DC.ItemWidth = prev_split; g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth; } @@ -10163,7 +10125,7 @@ static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window) } scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]); } - scroll[axis] = IM_TRUNC(ImMax(scroll[axis], 0.0f)); + scroll[axis] = IM_ROUND(ImMax(scroll[axis], 0.0f)); if (!window->Collapsed && !window->SkipItems) scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]); } @@ -12072,7 +12034,7 @@ void ImGui::NavMoveRequestApplyResult() g.NavNextActivateId = result->ID; g.NavNextActivateFlags = ImGuiActivateFlags_None; if (g.NavMoveFlags & ImGuiNavMoveFlags_IsTabbing) - g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState; + g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState | ImGuiActivateFlags_FromTabbing; } // Enable nav highlight @@ -14510,6 +14472,14 @@ void ImGui::DebugNodeColumns(ImGuiOldColumns* columns) TreePop(); } +static void FormatTextureIDForDebugDisplay(char* buf, int buf_size, ImTextureID tex_id) +{ + if (sizeof(tex_id) >= sizeof(void*)) + ImFormatString(buf, buf_size, "0x%p", (void*)*(intptr_t*)(void*)&tex_id); + else + ImFormatString(buf, buf_size, "0x%04X", *(int*)(void*)&tex_id); +} + // [DEBUG] Display contents of ImDrawList void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label) { @@ -14546,10 +14516,11 @@ void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, con continue; } + char texid_desc[20]; + FormatTextureIDForDebugDisplay(texid_desc, IM_ARRAYSIZE(texid_desc), pcmd->TextureId); char buf[300]; - ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", - pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId, - pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); + ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex %s, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)", + pcmd->ElemCount / 3, texid_desc, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf); if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list) DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes); diff --git a/imgui/imgui.h b/imgui/imgui.h index b4a5a924..0b7be292 100644 --- a/imgui/imgui.h +++ b/imgui/imgui.h @@ -34,10 +34,11 @@ Index of this file: // [SECTION] Forward declarations and basic types // [SECTION] Dear ImGui end-user API functions // [SECTION] Flags & Enumerations +// [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) // [SECTION] Helpers: Memory allocations macros, ImVector<> // [SECTION] ImGuiStyle // [SECTION] ImGuiIO -// [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) +// [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) // [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) // [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData) // [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont) @@ -182,7 +183,7 @@ typedef int ImGuiSortDirection; // -> enum ImGuiSortDirection_ // Enum: A typedef int ImGuiStyleVar; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling typedef int ImGuiTableBgTarget; // -> enum ImGuiTableBgTarget_ // Enum: A color target for TableSetBgColor() -// Flags (declared as int for compatibility with old C++, to allow using as flags without overhead, and to not pollute the top of this file) +// Flags (declared as int to allow using as flags without overhead, and to not pollute the top of this file) // - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists! // In Visual Studio IDE: CTRL+comma ("Edit.GoToAll") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot. // With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments. @@ -199,7 +200,7 @@ typedef int ImGuiDragDropFlags; // -> enum ImGuiDragDropFlags_ // Flags: f typedef int ImGuiFocusedFlags; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused() typedef int ImGuiHoveredFlags; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc. typedef int ImGuiInputTextFlags; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline() -typedef int ImGuiKeyChord; // -> ImGuiKey | ImGuiMod_XXX // Flags: for storage only for now: an ImGuiKey optionally OR-ed with one or more ImGuiMod_XXX values. +typedef int ImGuiKeyChord; // -> ImGuiKey | ImGuiMod_XXX // Flags: for IsKeyChordPressed(), Shortcut() etc. an ImGuiKey optionally OR-ed with one or more ImGuiMod_XXX values. typedef int ImGuiPopupFlags; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() typedef int ImGuiSelectableFlags; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable() typedef int ImGuiSliderFlags; // -> enum ImGuiSliderFlags_ // Flags: for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. @@ -531,8 +532,8 @@ namespace ImGui // Widgets: Images // - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples - // - Note that ImageButton() adds style.FramePadding*2.0f to provided size. This is in order to facilitate fitting an image in a button. - IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& tint_col = ImVec4(1, 1, 1, 1), const ImVec4& border_col = ImVec4(0, 0, 0, 0)); + // - Note that Image() may add +2.0f to provided size if a border is visible, ImageButton() adds style.FramePadding*2.0f to provided size. + IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& tint_col = ImVec4(1, 1, 1, 1), const ImVec4& border_col = ImVec4(0, 0, 0, 0)); IMGUI_API bool ImageButton(const char* str_id, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1, 1), const ImVec4& bg_col = ImVec4(0, 0, 0, 0), const ImVec4& tint_col = ImVec4(1, 1, 1, 1)); // Widgets: Combo Box (Dropdown) @@ -630,9 +631,9 @@ namespace ImGui IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3); IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3); - IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired. + IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushID(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired. IMGUI_API void TreePush(const void* ptr_id); // " - IMGUI_API void TreePop(); // ~ Unindent()+PopId() + IMGUI_API void TreePop(); // ~ Unindent()+PopID() IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). IMGUI_API bool CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags = 0); // when 'p_visible != NULL': if '*p_visible==true' display an additional small close button on upper right of the header which will set the bool to false when clicked, if '*p_visible==false' don't display the header. @@ -707,9 +708,7 @@ namespace ImGui // - You can bypass the hovering restriction by using ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered(). // - IMPORTANT: Popup identifiers are relative to the current ID stack, so OpenPopup and BeginPopup generally needs to be at the same level of the stack. // This is sometimes leading to confusing mistakes. May rework this in the future. - - // Popups: begin/end functions - // - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards. ImGuiWindowFlags are forwarded to the window. + // - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards if returned true. ImGuiWindowFlags are forwarded to the window. // - BeginPopupModal(): block every interaction behind the window, cannot be closed by user, add a dimming background, has a title bar. IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it. IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it. @@ -759,12 +758,10 @@ namespace ImGui // TableNextColumn() will automatically wrap-around into the next row if needed. // - IMPORTANT: Comparatively to the old Columns() API, we need to call TableNextColumn() for the first column! // - Summary of possible call flow: - // -------------------------------------------------------------------------------------------------------- - // TableNextRow() -> TableSetColumnIndex(0) -> Text("Hello 0") -> TableSetColumnIndex(1) -> Text("Hello 1") // OK - // TableNextRow() -> TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK - // TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK: TableNextColumn() automatically gets to next row! - // TableNextRow() -> Text("Hello 0") // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear! - // -------------------------------------------------------------------------------------------------------- + // - TableNextRow() -> TableSetColumnIndex(0) -> Text("Hello 0") -> TableSetColumnIndex(1) -> Text("Hello 1") // OK + // - TableNextRow() -> TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK + // - TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK: TableNextColumn() automatically gets to next row! + // - TableNextRow() -> Text("Hello 0") // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear! // - 5. Call EndTable() IMGUI_API bool BeginTable(const char* str_id, int column, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0.0f, 0.0f), float inner_width = 0.0f); IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true! @@ -963,6 +960,7 @@ namespace ImGui IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings. // Debug Utilities + // - Your main debugging friend is the ShowMetricsWindow() function, which is also accessible from Demo->Tools->Metrics Debugger IMGUI_API void DebugTextEncoding(const char* text); IMGUI_API void DebugFlashStyleColor(ImGuiCol idx); IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx); // This is called by IMGUI_CHECKVERSION() macro. @@ -1096,7 +1094,7 @@ enum ImGuiTreeNodeFlags_ ImGuiTreeNodeFlags_SpanFullWidth = 1 << 12, // Extend hit box to the left-most and right-most edges (bypass the indented area). ImGuiTreeNodeFlags_SpanAllColumns = 1 << 13, // Frame will span all columns of its container table (text will still fit in current column) ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 14, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop) - //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 14, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible + //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 15, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog, #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS @@ -1164,7 +1162,7 @@ enum ImGuiTabBarFlags_ ImGuiTabBarFlags_Reorderable = 1 << 0, // Allow manually dragging tabs to re-order them + New tabs are appended at the end of list ImGuiTabBarFlags_AutoSelectNewTabs = 1 << 1, // Automatically select new tabs when they appear ImGuiTabBarFlags_TabListPopupButton = 1 << 2, // Disable buttons to open the tab list popup - ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 3, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. + ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 1 << 3, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. ImGuiTabBarFlags_NoTabListScrollingButtons = 1 << 4, // Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags_FittingPolicyScroll) ImGuiTabBarFlags_NoTooltip = 1 << 5, // Disable tooltips when hovering a tab ImGuiTabBarFlags_FittingPolicyResizeDown = 1 << 6, // Resize tabs when they don't fit @@ -1177,150 +1175,15 @@ enum ImGuiTabBarFlags_ enum ImGuiTabItemFlags_ { ImGuiTabItemFlags_None = 0, - ImGuiTabItemFlags_UnsavedDocument = 1 << 0, // Display a dot next to the title + tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + ImGuiTabItemFlags_UnsavedDocument = 1 << 0, // Display a dot next to the title + set ImGuiTabItemFlags_NoAssumedClosure. ImGuiTabItemFlags_SetSelected = 1 << 1, // Trigger flag to programmatically make the tab selected when calling BeginTabItem() - ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. - ImGuiTabItemFlags_NoPushId = 1 << 3, // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem() + ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false. + ImGuiTabItemFlags_NoPushId = 1 << 3, // Don't call PushID()/PopID() on BeginTabItem()/EndTabItem() ImGuiTabItemFlags_NoTooltip = 1 << 4, // Disable tooltip for the given tab ImGuiTabItemFlags_NoReorder = 1 << 5, // Disable reordering this tab or having another tab cross over this tab ImGuiTabItemFlags_Leading = 1 << 6, // Enforce the tab position to the left of the tab bar (after the tab list popup button) ImGuiTabItemFlags_Trailing = 1 << 7, // Enforce the tab position to the right of the tab bar (before the scrolling buttons) -}; - -// Flags for ImGui::BeginTable() -// - Important! Sizing policies have complex and subtle side effects, much more so than you would expect. -// Read comments/demos carefully + experiment with live demos to get acquainted with them. -// - The DEFAULT sizing policies are: -// - Default to ImGuiTableFlags_SizingFixedFit if ScrollX is on, or if host window has ImGuiWindowFlags_AlwaysAutoResize. -// - Default to ImGuiTableFlags_SizingStretchSame if ScrollX is off. -// - When ScrollX is off: -// - Table defaults to ImGuiTableFlags_SizingStretchSame -> all Columns defaults to ImGuiTableColumnFlags_WidthStretch with same weight. -// - Columns sizing policy allowed: Stretch (default), Fixed/Auto. -// - Fixed Columns (if any) will generally obtain their requested width (unless the table cannot fit them all). -// - Stretch Columns will share the remaining width according to their respective weight. -// - Mixed Fixed/Stretch columns is possible but has various side-effects on resizing behaviors. -// The typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. -// (this is because the visible order of columns have subtle but necessary effects on how they react to manual resizing). -// - When ScrollX is on: -// - Table defaults to ImGuiTableFlags_SizingFixedFit -> all Columns defaults to ImGuiTableColumnFlags_WidthFixed -// - Columns sizing policy allowed: Fixed/Auto mostly. -// - Fixed Columns can be enlarged as needed. Table will show a horizontal scrollbar if needed. -// - When using auto-resizing (non-resizable) fixed columns, querying the content width to use item right-alignment e.g. SetNextItemWidth(-FLT_MIN) doesn't make sense, would create a feedback loop. -// - Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable(). -// If you specify a value for 'inner_width' then effectively the scrolling space is known and Stretch or mixed Fixed/Stretch columns become meaningful again. -// - Read on documentation at the top of imgui_tables.cpp for details. -enum ImGuiTableFlags_ -{ - // Features - ImGuiTableFlags_None = 0, - ImGuiTableFlags_Resizable = 1 << 0, // Enable resizing columns. - ImGuiTableFlags_Reorderable = 1 << 1, // Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers) - ImGuiTableFlags_Hideable = 1 << 2, // Enable hiding/disabling columns in context menu. - ImGuiTableFlags_Sortable = 1 << 3, // Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate. - ImGuiTableFlags_NoSavedSettings = 1 << 4, // Disable persisting columns order, width and sort settings in the .ini file. - ImGuiTableFlags_ContextMenuInBody = 1 << 5, // Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). - // Decorations - ImGuiTableFlags_RowBg = 1 << 6, // Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) - ImGuiTableFlags_BordersInnerH = 1 << 7, // Draw horizontal borders between rows. - ImGuiTableFlags_BordersOuterH = 1 << 8, // Draw horizontal borders at the top and bottom. - ImGuiTableFlags_BordersInnerV = 1 << 9, // Draw vertical borders between columns. - ImGuiTableFlags_BordersOuterV = 1 << 10, // Draw vertical borders on the left and right sides. - ImGuiTableFlags_BordersH = ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_BordersOuterH, // Draw horizontal borders. - ImGuiTableFlags_BordersV = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterV, // Draw vertical borders. - ImGuiTableFlags_BordersInner = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersInnerH, // Draw inner borders. - ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersOuterH, // Draw outer borders. - ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders. - ImGuiTableFlags_NoBordersInBody = 1 << 11, // [ALPHA] Disable vertical borders in columns Body (borders will always appear in Headers). -> May move to style - ImGuiTableFlags_NoBordersInBodyUntilResize = 1 << 12, // [ALPHA] Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers). -> May move to style - // Sizing Policy (read above for defaults) - ImGuiTableFlags_SizingFixedFit = 1 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width. - ImGuiTableFlags_SizingFixedSame = 2 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags_NoKeepColumnsVisible. - ImGuiTableFlags_SizingStretchProp = 3 << 13, // Columns default to _WidthStretch with default weights proportional to each columns contents widths. - ImGuiTableFlags_SizingStretchSame = 4 << 13, // Columns default to _WidthStretch with default weights all equal, unless overridden by TableSetupColumn(). - // Sizing Extra Options - ImGuiTableFlags_NoHostExtendX = 1 << 16, // Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. - ImGuiTableFlags_NoHostExtendY = 1 << 17, // Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. - ImGuiTableFlags_NoKeepColumnsVisible = 1 << 18, // Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. - ImGuiTableFlags_PreciseWidths = 1 << 19, // Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. - // Clipping - ImGuiTableFlags_NoClip = 1 << 20, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze(). - // Padding - ImGuiTableFlags_PadOuterX = 1 << 21, // Default if BordersOuterV is on. Enable outermost padding. Generally desirable if you have headers. - ImGuiTableFlags_NoPadOuterX = 1 << 22, // Default if BordersOuterV is off. Disable outermost padding. - ImGuiTableFlags_NoPadInnerX = 1 << 23, // Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). - // Scrolling - ImGuiTableFlags_ScrollX = 1 << 24, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this creates a child window, ScrollY is currently generally recommended when using ScrollX. - ImGuiTableFlags_ScrollY = 1 << 25, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. - // Sorting - ImGuiTableFlags_SortMulti = 1 << 26, // Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1). - ImGuiTableFlags_SortTristate = 1 << 27, // Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0). - // Miscellaneous - ImGuiTableFlags_HighlightHoveredColumn = 1 << 28, // Highlight column headers when hovered (may evolve into a fuller highlight) - - // [Internal] Combinations and masks - ImGuiTableFlags_SizingMask_ = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_SizingFixedSame | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_SizingStretchSame, -}; - -// Flags for ImGui::TableSetupColumn() -enum ImGuiTableColumnFlags_ -{ - // Input configuration flags - ImGuiTableColumnFlags_None = 0, - ImGuiTableColumnFlags_Disabled = 1 << 0, // Overriding/master disable flag: hide column, won't show in context menu (unlike calling TableSetColumnEnabled() which manipulates the user accessible state) - ImGuiTableColumnFlags_DefaultHide = 1 << 1, // Default as a hidden/disabled column. - ImGuiTableColumnFlags_DefaultSort = 1 << 2, // Default as a sorting column. - ImGuiTableColumnFlags_WidthStretch = 1 << 3, // Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). - ImGuiTableColumnFlags_WidthFixed = 1 << 4, // Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). - ImGuiTableColumnFlags_NoResize = 1 << 5, // Disable manual resizing. - ImGuiTableColumnFlags_NoReorder = 1 << 6, // Disable manual reordering this column, this will also prevent other columns from crossing over this column. - ImGuiTableColumnFlags_NoHide = 1 << 7, // Disable ability to hide/disable this column. - ImGuiTableColumnFlags_NoClip = 1 << 8, // Disable clipping for this column (all NoClip columns will render in a same draw command). - ImGuiTableColumnFlags_NoSort = 1 << 9, // Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). - ImGuiTableColumnFlags_NoSortAscending = 1 << 10, // Disable ability to sort in the ascending direction. - ImGuiTableColumnFlags_NoSortDescending = 1 << 11, // Disable ability to sort in the descending direction. - ImGuiTableColumnFlags_NoHeaderLabel = 1 << 12, // TableHeadersRow() will not submit horizontal label for this column. Convenient for some small columns. Name will still appear in context menu or in angled headers. - ImGuiTableColumnFlags_NoHeaderWidth = 1 << 13, // Disable header text width contribution to automatic column width. - ImGuiTableColumnFlags_PreferSortAscending = 1 << 14, // Make the initial sort direction Ascending when first sorting on this column (default). - ImGuiTableColumnFlags_PreferSortDescending = 1 << 15, // Make the initial sort direction Descending when first sorting on this column. - ImGuiTableColumnFlags_IndentEnable = 1 << 16, // Use current Indent value when entering cell (default for column 0). - ImGuiTableColumnFlags_IndentDisable = 1 << 17, // Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. - ImGuiTableColumnFlags_AngledHeader = 1 << 18, // TableHeadersRow() will submit an angled header row for this column. Note this will add an extra row. - - // Output status flags, read-only via TableGetColumnFlags() - ImGuiTableColumnFlags_IsEnabled = 1 << 24, // Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags. - ImGuiTableColumnFlags_IsVisible = 1 << 25, // Status: is visible == is enabled AND not clipped by scrolling. - ImGuiTableColumnFlags_IsSorted = 1 << 26, // Status: is currently part of the sort specs - ImGuiTableColumnFlags_IsHovered = 1 << 27, // Status: is hovered by mouse - - // [Internal] Combinations and masks - ImGuiTableColumnFlags_WidthMask_ = ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthFixed, - ImGuiTableColumnFlags_IndentMask_ = ImGuiTableColumnFlags_IndentEnable | ImGuiTableColumnFlags_IndentDisable, - ImGuiTableColumnFlags_StatusMask_ = ImGuiTableColumnFlags_IsEnabled | ImGuiTableColumnFlags_IsVisible | ImGuiTableColumnFlags_IsSorted | ImGuiTableColumnFlags_IsHovered, - ImGuiTableColumnFlags_NoDirectResize_ = 1 << 30, // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) -}; - -// Flags for ImGui::TableNextRow() -enum ImGuiTableRowFlags_ -{ - ImGuiTableRowFlags_None = 0, - ImGuiTableRowFlags_Headers = 1 << 0, // Identify header row (set default background color + width of its contents accounted differently for auto column width) -}; - -// Enum for ImGui::TableSetBgColor() -// Background colors are rendering in 3 layers: -// - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set. -// - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set. -// - Layer 2: draw with CellBg color if set. -// The purpose of the two row/columns layers is to let you decide if a background color change should override or blend with the existing color. -// When using ImGuiTableFlags_RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows. -// If you set the color of RowBg0 target, your color will override the existing RowBg0 color. -// If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color. -enum ImGuiTableBgTarget_ -{ - ImGuiTableBgTarget_None = 0, - ImGuiTableBgTarget_RowBg0 = 1, // Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags_RowBg is used) - ImGuiTableBgTarget_RowBg1 = 2, // Set row background color 1 (generally used for selection marking) - ImGuiTableBgTarget_CellBg = 3, // Set cell background color (top-most color) + ImGuiTabItemFlags_NoAssumedClosure = 1 << 8, // Tab is selected when trying to close + closure is not immediately assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. }; // Flags for ImGui::IsWindowFocused() @@ -1622,15 +1485,15 @@ enum ImGuiCol_ ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive, - ImGuiCol_TitleBg, - ImGuiCol_TitleBgActive, - ImGuiCol_TitleBgCollapsed, + ImGuiCol_TitleBg, // Title bar + ImGuiCol_TitleBgActive, // Title bar when focused + ImGuiCol_TitleBgCollapsed, // Title bar when collapsed ImGuiCol_MenuBarBg, ImGuiCol_ScrollbarBg, ImGuiCol_ScrollbarGrab, ImGuiCol_ScrollbarGrabHovered, ImGuiCol_ScrollbarGrabActive, - ImGuiCol_CheckMark, + ImGuiCol_CheckMark, // Checkbox tick and RadioButton circle ImGuiCol_SliderGrab, ImGuiCol_SliderGrabActive, ImGuiCol_Button, @@ -1822,7 +1685,7 @@ enum ImGuiMouseSource : int ImGuiMouseSource_COUNT }; -// Enumeration for ImGui::SetWindow***(), SetNextWindow***(), SetNextItem***() functions +// Enumeration for ImGui::SetNextWindow***(), SetWindow***(), SetNextItem***() functions // Represent a condition. // Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond_Always. enum ImGuiCond_ @@ -1834,6 +1697,170 @@ enum ImGuiCond_ ImGuiCond_Appearing = 1 << 3, // Set the variable if the object/window is appearing after being hidden/inactive (or the first time) }; +//----------------------------------------------------------------------------- +// [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) +//----------------------------------------------------------------------------- + +// Flags for ImGui::BeginTable() +// - Important! Sizing policies have complex and subtle side effects, much more so than you would expect. +// Read comments/demos carefully + experiment with live demos to get acquainted with them. +// - The DEFAULT sizing policies are: +// - Default to ImGuiTableFlags_SizingFixedFit if ScrollX is on, or if host window has ImGuiWindowFlags_AlwaysAutoResize. +// - Default to ImGuiTableFlags_SizingStretchSame if ScrollX is off. +// - When ScrollX is off: +// - Table defaults to ImGuiTableFlags_SizingStretchSame -> all Columns defaults to ImGuiTableColumnFlags_WidthStretch with same weight. +// - Columns sizing policy allowed: Stretch (default), Fixed/Auto. +// - Fixed Columns (if any) will generally obtain their requested width (unless the table cannot fit them all). +// - Stretch Columns will share the remaining width according to their respective weight. +// - Mixed Fixed/Stretch columns is possible but has various side-effects on resizing behaviors. +// The typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. +// (this is because the visible order of columns have subtle but necessary effects on how they react to manual resizing). +// - When ScrollX is on: +// - Table defaults to ImGuiTableFlags_SizingFixedFit -> all Columns defaults to ImGuiTableColumnFlags_WidthFixed +// - Columns sizing policy allowed: Fixed/Auto mostly. +// - Fixed Columns can be enlarged as needed. Table will show a horizontal scrollbar if needed. +// - When using auto-resizing (non-resizable) fixed columns, querying the content width to use item right-alignment e.g. SetNextItemWidth(-FLT_MIN) doesn't make sense, would create a feedback loop. +// - Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable(). +// If you specify a value for 'inner_width' then effectively the scrolling space is known and Stretch or mixed Fixed/Stretch columns become meaningful again. +// - Read on documentation at the top of imgui_tables.cpp for details. +enum ImGuiTableFlags_ +{ + // Features + ImGuiTableFlags_None = 0, + ImGuiTableFlags_Resizable = 1 << 0, // Enable resizing columns. + ImGuiTableFlags_Reorderable = 1 << 1, // Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers) + ImGuiTableFlags_Hideable = 1 << 2, // Enable hiding/disabling columns in context menu. + ImGuiTableFlags_Sortable = 1 << 3, // Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate. + ImGuiTableFlags_NoSavedSettings = 1 << 4, // Disable persisting columns order, width and sort settings in the .ini file. + ImGuiTableFlags_ContextMenuInBody = 1 << 5, // Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow(). + // Decorations + ImGuiTableFlags_RowBg = 1 << 6, // Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually) + ImGuiTableFlags_BordersInnerH = 1 << 7, // Draw horizontal borders between rows. + ImGuiTableFlags_BordersOuterH = 1 << 8, // Draw horizontal borders at the top and bottom. + ImGuiTableFlags_BordersInnerV = 1 << 9, // Draw vertical borders between columns. + ImGuiTableFlags_BordersOuterV = 1 << 10, // Draw vertical borders on the left and right sides. + ImGuiTableFlags_BordersH = ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_BordersOuterH, // Draw horizontal borders. + ImGuiTableFlags_BordersV = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterV, // Draw vertical borders. + ImGuiTableFlags_BordersInner = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersInnerH, // Draw inner borders. + ImGuiTableFlags_BordersOuter = ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersOuterH, // Draw outer borders. + ImGuiTableFlags_Borders = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter, // Draw all borders. + ImGuiTableFlags_NoBordersInBody = 1 << 11, // [ALPHA] Disable vertical borders in columns Body (borders will always appear in Headers). -> May move to style + ImGuiTableFlags_NoBordersInBodyUntilResize = 1 << 12, // [ALPHA] Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers). -> May move to style + // Sizing Policy (read above for defaults) + ImGuiTableFlags_SizingFixedFit = 1 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width. + ImGuiTableFlags_SizingFixedSame = 2 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags_NoKeepColumnsVisible. + ImGuiTableFlags_SizingStretchProp = 3 << 13, // Columns default to _WidthStretch with default weights proportional to each columns contents widths. + ImGuiTableFlags_SizingStretchSame = 4 << 13, // Columns default to _WidthStretch with default weights all equal, unless overridden by TableSetupColumn(). + // Sizing Extra Options + ImGuiTableFlags_NoHostExtendX = 1 << 16, // Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. + ImGuiTableFlags_NoHostExtendY = 1 << 17, // Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. + ImGuiTableFlags_NoKeepColumnsVisible = 1 << 18, // Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. + ImGuiTableFlags_PreciseWidths = 1 << 19, // Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. + // Clipping + ImGuiTableFlags_NoClip = 1 << 20, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze(). + // Padding + ImGuiTableFlags_PadOuterX = 1 << 21, // Default if BordersOuterV is on. Enable outermost padding. Generally desirable if you have headers. + ImGuiTableFlags_NoPadOuterX = 1 << 22, // Default if BordersOuterV is off. Disable outermost padding. + ImGuiTableFlags_NoPadInnerX = 1 << 23, // Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). + // Scrolling + ImGuiTableFlags_ScrollX = 1 << 24, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this creates a child window, ScrollY is currently generally recommended when using ScrollX. + ImGuiTableFlags_ScrollY = 1 << 25, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. + // Sorting + ImGuiTableFlags_SortMulti = 1 << 26, // Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1). + ImGuiTableFlags_SortTristate = 1 << 27, // Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0). + // Miscellaneous + ImGuiTableFlags_HighlightHoveredColumn = 1 << 28, // Highlight column headers when hovered (may evolve into a fuller highlight) + + // [Internal] Combinations and masks + ImGuiTableFlags_SizingMask_ = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_SizingFixedSame | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_SizingStretchSame, +}; + +// Flags for ImGui::TableSetupColumn() +enum ImGuiTableColumnFlags_ +{ + // Input configuration flags + ImGuiTableColumnFlags_None = 0, + ImGuiTableColumnFlags_Disabled = 1 << 0, // Overriding/master disable flag: hide column, won't show in context menu (unlike calling TableSetColumnEnabled() which manipulates the user accessible state) + ImGuiTableColumnFlags_DefaultHide = 1 << 1, // Default as a hidden/disabled column. + ImGuiTableColumnFlags_DefaultSort = 1 << 2, // Default as a sorting column. + ImGuiTableColumnFlags_WidthStretch = 1 << 3, // Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). + ImGuiTableColumnFlags_WidthFixed = 1 << 4, // Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). + ImGuiTableColumnFlags_NoResize = 1 << 5, // Disable manual resizing. + ImGuiTableColumnFlags_NoReorder = 1 << 6, // Disable manual reordering this column, this will also prevent other columns from crossing over this column. + ImGuiTableColumnFlags_NoHide = 1 << 7, // Disable ability to hide/disable this column. + ImGuiTableColumnFlags_NoClip = 1 << 8, // Disable clipping for this column (all NoClip columns will render in a same draw command). + ImGuiTableColumnFlags_NoSort = 1 << 9, // Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table). + ImGuiTableColumnFlags_NoSortAscending = 1 << 10, // Disable ability to sort in the ascending direction. + ImGuiTableColumnFlags_NoSortDescending = 1 << 11, // Disable ability to sort in the descending direction. + ImGuiTableColumnFlags_NoHeaderLabel = 1 << 12, // TableHeadersRow() will not submit horizontal label for this column. Convenient for some small columns. Name will still appear in context menu or in angled headers. + ImGuiTableColumnFlags_NoHeaderWidth = 1 << 13, // Disable header text width contribution to automatic column width. + ImGuiTableColumnFlags_PreferSortAscending = 1 << 14, // Make the initial sort direction Ascending when first sorting on this column (default). + ImGuiTableColumnFlags_PreferSortDescending = 1 << 15, // Make the initial sort direction Descending when first sorting on this column. + ImGuiTableColumnFlags_IndentEnable = 1 << 16, // Use current Indent value when entering cell (default for column 0). + ImGuiTableColumnFlags_IndentDisable = 1 << 17, // Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. + ImGuiTableColumnFlags_AngledHeader = 1 << 18, // TableHeadersRow() will submit an angled header row for this column. Note this will add an extra row. + + // Output status flags, read-only via TableGetColumnFlags() + ImGuiTableColumnFlags_IsEnabled = 1 << 24, // Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags. + ImGuiTableColumnFlags_IsVisible = 1 << 25, // Status: is visible == is enabled AND not clipped by scrolling. + ImGuiTableColumnFlags_IsSorted = 1 << 26, // Status: is currently part of the sort specs + ImGuiTableColumnFlags_IsHovered = 1 << 27, // Status: is hovered by mouse + + // [Internal] Combinations and masks + ImGuiTableColumnFlags_WidthMask_ = ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthFixed, + ImGuiTableColumnFlags_IndentMask_ = ImGuiTableColumnFlags_IndentEnable | ImGuiTableColumnFlags_IndentDisable, + ImGuiTableColumnFlags_StatusMask_ = ImGuiTableColumnFlags_IsEnabled | ImGuiTableColumnFlags_IsVisible | ImGuiTableColumnFlags_IsSorted | ImGuiTableColumnFlags_IsHovered, + ImGuiTableColumnFlags_NoDirectResize_ = 1 << 30, // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) +}; + +// Flags for ImGui::TableNextRow() +enum ImGuiTableRowFlags_ +{ + ImGuiTableRowFlags_None = 0, + ImGuiTableRowFlags_Headers = 1 << 0, // Identify header row (set default background color + width of its contents accounted differently for auto column width) +}; + +// Enum for ImGui::TableSetBgColor() +// Background colors are rendering in 3 layers: +// - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set. +// - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set. +// - Layer 2: draw with CellBg color if set. +// The purpose of the two row/columns layers is to let you decide if a background color change should override or blend with the existing color. +// When using ImGuiTableFlags_RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows. +// If you set the color of RowBg0 target, your color will override the existing RowBg0 color. +// If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color. +enum ImGuiTableBgTarget_ +{ + ImGuiTableBgTarget_None = 0, + ImGuiTableBgTarget_RowBg0 = 1, // Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags_RowBg is used) + ImGuiTableBgTarget_RowBg1 = 2, // Set row background color 1 (generally used for selection marking) + ImGuiTableBgTarget_CellBg = 3, // Set cell background color (top-most color) +}; + +// Sorting specifications for a table (often handling sort specs for a single column, occasionally more) +// Obtained by calling TableGetSortSpecs(). +// When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time. +// Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame! +struct ImGuiTableSortSpecs +{ + const ImGuiTableColumnSortSpecs* Specs; // Pointer to sort spec array. + int SpecsCount; // Sort spec count. Most often 1. May be > 1 when ImGuiTableFlags_SortMulti is enabled. May be == 0 when ImGuiTableFlags_SortTristate is enabled. + bool SpecsDirty; // Set to true when specs have changed since last time! Use this to sort again, then clear the flag. + + ImGuiTableSortSpecs() { memset(this, 0, sizeof(*this)); } +}; + +// Sorting specification for one column of a table (sizeof == 12 bytes) +struct ImGuiTableColumnSortSpecs +{ + ImGuiID ColumnUserID; // User id of the column (if specified by a TableSetupColumn() call) + ImS16 ColumnIndex; // Index of the column + ImS16 SortOrder; // Index within parent ImGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here) + ImGuiSortDirection SortDirection : 8; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending + + ImGuiTableColumnSortSpecs() { memset(this, 0, sizeof(*this)); } +}; + //----------------------------------------------------------------------------- // [SECTION] Helpers: Memory allocations macros, ImVector<> //----------------------------------------------------------------------------- @@ -2207,7 +2234,7 @@ struct ImGuiIO }; //----------------------------------------------------------------------------- -// [SECTION] Misc data structures +// [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) //----------------------------------------------------------------------------- // Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used. @@ -2281,30 +2308,6 @@ struct ImGuiPayload bool IsDelivery() const { return Delivery; } }; -// Sorting specification for one column of a table (sizeof == 12 bytes) -struct ImGuiTableColumnSortSpecs -{ - ImGuiID ColumnUserID; // User id of the column (if specified by a TableSetupColumn() call) - ImS16 ColumnIndex; // Index of the column - ImS16 SortOrder; // Index within parent ImGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here) - ImGuiSortDirection SortDirection : 8; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending - - ImGuiTableColumnSortSpecs() { memset(this, 0, sizeof(*this)); } -}; - -// Sorting specifications for a table (often handling sort specs for a single column, occasionally more) -// Obtained by calling TableGetSortSpecs(). -// When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time. -// Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame! -struct ImGuiTableSortSpecs -{ - const ImGuiTableColumnSortSpecs* Specs; // Pointer to sort spec array. - int SpecsCount; // Sort spec count. Most often 1. May be > 1 when ImGuiTableFlags_SortMulti is enabled. May be == 0 when ImGuiTableFlags_SortTristate is enabled. - bool SpecsDirty; // Set to true when specs have changed since last time! Use this to sort again, then clear the flag. - - ImGuiTableSortSpecs() { memset(this, 0, sizeof(*this)); } -}; - //----------------------------------------------------------------------------- // [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) //----------------------------------------------------------------------------- @@ -3177,10 +3180,10 @@ namespace ImGui // OBSOLETED in 1.88 (from May 2022) static inline void CaptureKeyboardFromApp(bool want_capture_keyboard = true) { SetNextFrameWantCaptureKeyboard(want_capture_keyboard); } // Renamed as name was misleading + removed default value. static inline void CaptureMouseFromApp(bool want_capture_mouse = true) { SetNextFrameWantCaptureMouse(want_capture_mouse); } // Renamed as name was misleading + removed default value. - // OBSOLETED in 1.86 (from November 2021) - IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // Calculate coarse clipping for large list of evenly sized items. Prefer using ImGuiListClipper. // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE) + //-- OBSOLETED in 1.86 (from November 2021) + //IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // Code removed, see 1.90 for last version of the code. Calculate range of visible items for large list of evenly sized items. Prefer using ImGuiListClipper. //-- OBSOLETED in 1.85 (from August 2021) //static inline float GetWindowContentRegionWidth() { return GetWindowContentRegionMax().x - GetWindowContentRegionMin().x; } //-- OBSOLETED in 1.81 (from February 2021) diff --git a/imgui/imgui_demo.cpp b/imgui/imgui_demo.cpp index 86d5ad36..763e0a9e 100644 --- a/imgui/imgui_demo.cpp +++ b/imgui/imgui_demo.cpp @@ -1479,6 +1479,7 @@ static void ShowDemoWindowWidgets() HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp because we don't want to include in here)"); ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", &flags, ImGuiInputTextFlags_ReadOnly); ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", &flags, ImGuiInputTextFlags_AllowTabInput); + ImGui::SameLine(); HelpMarker("When _AllowTabInput is set, passing through the widget with Tabbing doesn't automatically activate it, in order to also cycling through subsequent widgets."); ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", &flags, ImGuiInputTextFlags_CtrlEnterForNewLine); ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16), flags); ImGui::TreePop(); diff --git a/imgui/imgui_internal.h b/imgui/imgui_internal.h index bb80eeab..35c48616 100644 --- a/imgui/imgui_internal.h +++ b/imgui/imgui_internal.h @@ -835,9 +835,8 @@ enum ImGuiItemStatusFlags_ ImGuiItemStatusFlags_HasDeactivated = 1 << 5, // Set if the widget/group is able to provide data for the ImGuiItemStatusFlags_Deactivated flag. ImGuiItemStatusFlags_Deactivated = 1 << 6, // Only valid if ImGuiItemStatusFlags_HasDeactivated is set. ImGuiItemStatusFlags_HoveredWindow = 1 << 7, // Override the HoveredWindow test to allow cross-window hover testing. - ImGuiItemStatusFlags_FocusedByTabbing = 1 << 8, // Set when the Focusable item just got focused by Tabbing (FIXME: to be removed soon) - ImGuiItemStatusFlags_Visible = 1 << 9, // [WIP] Set when item is overlapping the current clipping rectangle (Used internally. Please don't use yet: API/system will change as we refactor Itemadd()). - ImGuiItemStatusFlags_HasClipRect = 1 << 10, // g.LastItemData.ClipRect is valid + ImGuiItemStatusFlags_Visible = 1 << 8, // [WIP] Set when item is overlapping the current clipping rectangle (Used internally. Please don't use yet: API/system will change as we refactor Itemadd()). + ImGuiItemStatusFlags_HasClipRect = 1 << 9, // g.LastItemData.ClipRect is valid // Additional status + semantic for ImGuiTestEngine #ifdef IMGUI_ENABLE_TEST_ENGINE @@ -1489,6 +1488,7 @@ enum ImGuiActivateFlags_ ImGuiActivateFlags_PreferInput = 1 << 0, // Favor activation that requires keyboard text input (e.g. for Slider/Drag). Default for Enter key. ImGuiActivateFlags_PreferTweak = 1 << 1, // Favor activation for tweaking with arrows or gamepad (e.g. for Slider/Drag). Default for Space key and if keyboard is not used. ImGuiActivateFlags_TryToPreserveState = 1 << 2, // Request widget to preserve state if it can (e.g. InputText will try to preserve cursor/selection) + ImGuiActivateFlags_FromTabbing = 1 << 3, // Activation requested by a tabbing request }; // Early work-in-progress API for ScrollToItem() @@ -1600,7 +1600,7 @@ struct IMGUI_API ImGuiTypingSelectState // [SECTION] Columns support //----------------------------------------------------------------------------- -// Flags for internal's BeginColumns(). Prefix using BeginTable() nowadays! +// Flags for internal's BeginColumns(). This is an obsolete API. Prefer using BeginTable() nowadays! enum ImGuiOldColumnFlags_ { ImGuiOldColumnFlags_None = 0, @@ -1608,16 +1608,16 @@ enum ImGuiOldColumnFlags_ ImGuiOldColumnFlags_NoResize = 1 << 1, // Disable resizing columns when clicking on the dividers ImGuiOldColumnFlags_NoPreserveWidths = 1 << 2, // Disable column width preservation when adjusting columns ImGuiOldColumnFlags_NoForceWithinWindow = 1 << 3, // Disable forcing columns to fit within window - ImGuiOldColumnFlags_GrowParentContentsSize = 1 << 4, // (WIP) Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. + ImGuiOldColumnFlags_GrowParentContentsSize = 1 << 4, // Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. // Obsolete names (will be removed) #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - ImGuiColumnsFlags_None = ImGuiOldColumnFlags_None, - ImGuiColumnsFlags_NoBorder = ImGuiOldColumnFlags_NoBorder, - ImGuiColumnsFlags_NoResize = ImGuiOldColumnFlags_NoResize, - ImGuiColumnsFlags_NoPreserveWidths = ImGuiOldColumnFlags_NoPreserveWidths, - ImGuiColumnsFlags_NoForceWithinWindow = ImGuiOldColumnFlags_NoForceWithinWindow, - ImGuiColumnsFlags_GrowParentContentsSize = ImGuiOldColumnFlags_GrowParentContentsSize, + //ImGuiColumnsFlags_None = ImGuiOldColumnFlags_None, + //ImGuiColumnsFlags_NoBorder = ImGuiOldColumnFlags_NoBorder, + //ImGuiColumnsFlags_NoResize = ImGuiOldColumnFlags_NoResize, + //ImGuiColumnsFlags_NoPreserveWidths = ImGuiOldColumnFlags_NoPreserveWidths, + //ImGuiColumnsFlags_NoForceWithinWindow = ImGuiOldColumnFlags_NoForceWithinWindow, + //ImGuiColumnsFlags_GrowParentContentsSize = ImGuiOldColumnFlags_GrowParentContentsSize, #endif }; diff --git a/imgui/imgui_widgets.cpp b/imgui/imgui_widgets.cpp index 6b9bba5e..ac5455b0 100644 --- a/imgui/imgui_widgets.cpp +++ b/imgui/imgui_widgets.cpp @@ -1007,28 +1007,23 @@ bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS6 return held; } -void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) +void ImGui::Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; - ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); - if (border_col.w > 0.0f) - bb.Max += ImVec2(2, 2); + const float border_size = (border_col.w > 0.0f) ? 1.0f : 0.0f; + const ImVec2 padding(border_size, border_size); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + image_size + padding * 2.0f); ItemSize(bb); if (!ItemAdd(bb, 0)) return; - if (border_col.w > 0.0f) - { - window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f); - window->DrawList->AddImage(user_texture_id, bb.Min + ImVec2(1, 1), bb.Max - ImVec2(1, 1), uv0, uv1, GetColorU32(tint_col)); - } - else - { - window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col)); - } + // Render + if (border_size > 0.0f) + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f, ImDrawFlags_None, border_size); + window->DrawList->AddImage(user_texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col)); } // ImageButton() is flawed as 'id' is always derived from 'texture_id' (see #2464 #1390) @@ -1679,7 +1674,7 @@ bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboF const ImGuiID id = window->GetID(label); IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together if (flags & ImGuiComboFlags_WidthFitPreview) - IM_ASSERT((flags & (ImGuiComboFlags_NoPreview | ImGuiComboFlags_CustomPreview)) == 0); + IM_ASSERT((flags & (ImGuiComboFlags_NoPreview | (ImGuiComboFlags)ImGuiComboFlags_CustomPreview)) == 0); const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight(); const ImVec2 label_size = CalcTextSize(label, NULL, true); @@ -2432,14 +2427,13 @@ bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, if (!temp_input_is_active) { // Tabbing or CTRL-clicking on Drag turns it into an InputText - const bool input_requested_by_tabbing = temp_input_allowed && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_FocusedByTabbing) != 0; const bool clicked = hovered && IsMouseClicked(0, id); const bool double_clicked = (hovered && g.IO.MouseClickedCount[0] == 2 && TestKeyOwner(ImGuiKey_MouseLeft, id)); - const bool make_active = (input_requested_by_tabbing || clicked || double_clicked || g.NavActivateId == id); + const bool make_active = (clicked || double_clicked || g.NavActivateId == id); if (make_active && (clicked || double_clicked)) SetKeyOwner(ImGuiKey_MouseLeft, id); if (make_active && temp_input_allowed) - if (input_requested_by_tabbing || (clicked && g.IO.KeyCtrl) || double_clicked || (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput))) + if ((clicked && g.IO.KeyCtrl) || double_clicked || (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput))) temp_input_is_active = true; // (Optional) simple click (without moving) turns Drag into an InputText @@ -3024,13 +3018,12 @@ bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_dat if (!temp_input_is_active) { // Tabbing or CTRL-clicking on Slider turns it into an input box - const bool input_requested_by_tabbing = temp_input_allowed && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_FocusedByTabbing) != 0; const bool clicked = hovered && IsMouseClicked(0, id); - const bool make_active = (input_requested_by_tabbing || clicked || g.NavActivateId == id); + const bool make_active = (clicked || g.NavActivateId == id); if (make_active && clicked) SetKeyOwner(ImGuiKey_MouseLeft, id); if (make_active && temp_input_allowed) - if (input_requested_by_tabbing || (clicked && g.IO.KeyCtrl) || (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput))) + if ((clicked && g.IO.KeyCtrl) || (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput))) temp_input_is_active = true; if (make_active && !temp_input_is_active) @@ -3426,7 +3419,7 @@ bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImG DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, p_data, format); ImStrTrimBlanks(data_buf); - ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited; + ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | (ImGuiInputTextFlags)ImGuiInputTextFlags_NoMarkEdited; flags |= InputScalar_DefaultCharsFilter(data_type, format); bool value_changed = false; @@ -3474,7 +3467,7 @@ bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data // Testing ActiveId as a minor optimization as filtering is not needed until active if (g.ActiveId == 0 && (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsScientific)) == 0) flags |= InputScalar_DefaultCharsFilter(data_type, format); - flags |= ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited; // We call MarkItemEdited() ourselves by comparing the actual data rather than the string. + flags |= ImGuiInputTextFlags_AutoSelectAll | (ImGuiInputTextFlags)ImGuiInputTextFlags_NoMarkEdited; // We call MarkItemEdited() ourselves by comparing the actual data rather than the string. bool value_changed = false; if (p_step == NULL) @@ -4118,7 +4111,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ ImGuiWindow* draw_window = window; ImVec2 inner_size = frame_size; - ImGuiItemStatusFlags item_status_flags = 0; ImGuiLastItemData item_data_backup; if (is_multiline) { @@ -4129,11 +4121,14 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ EndGroup(); return false; } - item_status_flags = g.LastItemData.StatusFlags; item_data_backup = g.LastItemData; window->DC.CursorPos = backup_pos; - // Prevent NavActivate reactivating in BeginChild(). + // Prevent NavActivation from Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping. + if (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_FromTabbing) && (flags & ImGuiInputTextFlags_AllowTabInput)) + g.NavActivateId = 0; + + // Prevent NavActivate reactivating in BeginChild() when we are already active. const ImGuiID backup_activate_id = g.NavActivateId; if (g.ActiveId == id) // Prevent reactivation g.NavActivateId = 0; @@ -4165,7 +4160,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (!(flags & ImGuiInputTextFlags_MergedItem)) if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_Inputable)) return false; - item_status_flags = g.LastItemData.StatusFlags; } const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.InFlags); if (hovered) @@ -4183,7 +4177,6 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ if (is_resizable) IM_ASSERT(callback != NULL); // Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag! - const bool input_requested_by_tabbing = (item_status_flags & ImGuiItemStatusFlags_FocusedByTabbing) != 0; const bool input_requested_by_nav = (g.ActiveId != id) && ((g.NavActivateId == id) && ((g.NavActivateFlags & ImGuiActivateFlags_PreferInput) || (g.NavInputSource == ImGuiInputSource_Keyboard))); const bool user_clicked = hovered && io.MouseClicked[0]; @@ -4195,7 +4188,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ float scroll_y = is_multiline ? draw_window->Scroll.y : FLT_MAX; const bool init_changed_specs = (state != NULL && state->Stb.single_line != !is_multiline); // state != NULL means its our state. - const bool init_make_active = (user_clicked || user_scroll_finish || input_requested_by_nav || input_requested_by_tabbing); + const bool init_make_active = (user_clicked || user_scroll_finish || input_requested_by_nav); const bool init_state = (init_make_active || user_scroll_active); if ((init_state && g.ActiveId != id) || init_changed_specs) { @@ -4245,7 +4238,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ select_all = true; if (input_requested_by_nav && (!recycle_state || !(g.NavActivateFlags & ImGuiActivateFlags_TryToPreserveState))) select_all = true; - if (input_requested_by_tabbing || (user_clicked && io.KeyCtrl)) + if (user_clicked && io.KeyCtrl) select_all = true; } @@ -4408,7 +4401,7 @@ bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_ // We expect backends to emit a Tab key but some also emit a Tab character which we ignore (#2467, #1336) // (For Tab and Enter: Win32/SFML/Allegro are sending both keys and chars, GLFW and SDL are only sending keys. For Space they all send all threes) - if ((flags & ImGuiInputTextFlags_AllowTabInput) && Shortcut(ImGuiKey_Tab, id) && !is_readonly) + if ((flags & ImGuiInputTextFlags_AllowTabInput) && Shortcut(ImGuiKey_Tab, id, ImGuiInputFlags_Repeat) && !is_readonly) { unsigned int c = '\t'; // Insert TAB if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data, ImGuiInputSource_Keyboard)) @@ -5194,10 +5187,9 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag if ((flags & (ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) { // RGB/HSV 0..255 Sliders - const float w_item_one = ImMax(1.0f, IM_TRUNC((w_inputs - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components)); - const float w_item_last = ImMax(1.0f, IM_TRUNC(w_inputs - (w_item_one + style.ItemInnerSpacing.x) * (components - 1))); + const float w_items = w_inputs - style.ItemInnerSpacing.x * (components - 1); - const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x); + const bool hide_prefix = (IM_TRUNC(w_items / components) <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x); static const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; static const char* fmt_table_int[3][4] = { @@ -5213,11 +5205,14 @@ bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flag }; const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_DisplayHSV) ? 2 : 1; + float prev_split = 0.0f; for (int n = 0; n < components; n++) { if (n > 0) SameLine(0, style.ItemInnerSpacing.x); - SetNextItemWidth((n + 1 < components) ? w_item_one : w_item_last); + float next_split = IM_TRUNC(w_items * (n + 1) / components); + SetNextItemWidth(next_split - prev_split); + prev_split = next_split; // FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0. if (flags & ImGuiColorEditFlags_Float) @@ -6469,7 +6464,7 @@ bool ImGui::CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFl ImGuiID id = window->GetID(label); flags |= ImGuiTreeNodeFlags_CollapsingHeader; if (p_visible) - flags |= ImGuiTreeNodeFlags_AllowOverlap | ImGuiTreeNodeFlags_ClipLabelForTrailingButton; + flags |= ImGuiTreeNodeFlags_AllowOverlap | (ImGuiTreeNodeFlags)ImGuiTreeNodeFlags_ClipLabelForTrailingButton; bool is_open = TreeNodeBehavior(id, flags, label); if (p_visible != NULL) { @@ -8257,7 +8252,7 @@ void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) if (tab->Flags & ImGuiTabItemFlags_Button) return; // A button appended with TabItemButton(). - if (!(tab->Flags & ImGuiTabItemFlags_UnsavedDocument)) + if ((tab->Flags & (ImGuiTabItemFlags_UnsavedDocument | ImGuiTabItemFlags_NoAssumedClosure)) == 0) { // This will remove a frame of lag for selecting another tab on closure. // However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure diff --git a/imgui/misc/freetype/imgui_freetype.h b/imgui/misc/freetype/imgui_freetype.h index cc58ba6a..b4e1d489 100644 --- a/imgui/misc/freetype/imgui_freetype.h +++ b/imgui/misc/freetype/imgui_freetype.h @@ -43,9 +43,8 @@ namespace ImGuiFreeType IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data = nullptr); // Obsolete names (will be removed soon) - // Prefer using '#define IMGUI_ENABLE_FREETYPE' #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS - static inline bool BuildFontAtlas(ImFontAtlas* atlas, unsigned int flags = 0) { atlas->FontBuilderIO = GetBuilderForFreeType(); atlas->FontBuilderFlags = flags; return atlas->Build(); } + //static inline bool BuildFontAtlas(ImFontAtlas* atlas, unsigned int flags = 0) { atlas->FontBuilderIO = GetBuilderForFreeType(); atlas->FontBuilderFlags = flags; return atlas->Build(); } // Prefer using '#define IMGUI_ENABLE_FREETYPE' #endif } diff --git a/src/bsp/Bsp.cpp b/src/bsp/Bsp.cpp index fe4a0414..077508d0 100644 --- a/src/bsp/Bsp.cpp +++ b/src/bsp/Bsp.cpp @@ -4275,19 +4275,23 @@ bool Bsp::validate() BSPMIPTEX* tex = (BSPMIPTEX*)(textures + texOffset); if (tex->szName[0] == '\0') { + isValid = false; print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_0133), i); } else if (strlen(tex->szName) >= MAXTEXTURENAME) { + isValid = false; print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_0134), i); } - if (tex->nOffsets[0] > 0 && dataOffset + texOffset + texlen > bsp_header.lump[LUMP_TEXTURES].nLength) + if (tex->nOffsets[0] > 0 && /*dataOffset + */texOffset + texlen > bsp_header.lump[LUMP_TEXTURES].nLength) { - print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_0135), i, dataOffset + texOffset + texlen, bsp_header.lump[LUMP_TEXTURES].nLength); + isValid = false; + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_0135), i, /*dataOffset + */texOffset + texlen, bsp_header.lump[LUMP_TEXTURES].nLength); print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_0136), texlen, tex->szName[0] != '\0' ? tex->szName : "UNKNOWN_NAME", texOffset, dataOffset); } if (texlen == 0) { + isValid = false; print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string("LANG_ERROR_TEXLEN"), i); print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_0136), texlen, tex->szName[0] != '\0' ? tex->szName : "UNKNOWN_NAME", texOffset, dataOffset); } @@ -6210,16 +6214,17 @@ void Bsp::copy_bsp_model(int modelIdx, Bsp* targetMap, STRUCTREMAP& remap, std:: newLightmaps.push_back(lightmapSrc[k]); } } + face.nLightmapOffset = targetMap->lightDataLength + lightmapAppendSz; + if (face.nLightmapOffset < 0) + { + memset(face.nStyles, 255, MAX_LIGHTMAPS); + } } - - face.nLightmapOffset = lightmapCount > 0 && face.nLightmapOffset >= 0 ? targetMap->lightDataLength + lightmapAppendSz : -1; - if (face.nLightmapOffset == -1) - { - memset(face.nStyles, 255, MAX_LIGHTMAPS); - } + + newFaces.push_back(face); - lightmapAppendSz += lightmapSz * sizeof(COLOR3); + //lightmapAppendSz += lightmapSz * sizeof(COLOR3); } } @@ -6271,6 +6276,8 @@ void Bsp::copy_bsp_model(int modelIdx, Bsp* targetMap, STRUCTREMAP& remap, std:: } } + + int Bsp::duplicate_model(int modelIdx) { std::vector newPlanes; @@ -6292,7 +6299,14 @@ int Bsp::duplicate_model(int modelIdx) if (newEdges.size()) append_lump(LUMP_EDGES, &newEdges[0], sizeof(BSPEDGE32) * newEdges.size()); if (newFaces.size()) + { append_lump(LUMP_FACES, &newFaces[0], sizeof(BSPFACE32) * newFaces.size()); + print_log("Base light offset = {}\n", lightDataLength); + for (auto f : newFaces) + { + print_log("Face light offset = {}\n", f.nLightmapOffset); + } + } if (newNodes.size()) append_lump(LUMP_NODES, &newNodes[0], sizeof(BSPNODE32) * newNodes.size()); if (newPlanes.size()) @@ -6304,7 +6318,13 @@ int Bsp::duplicate_model(int modelIdx) if (newVerts.size()) append_lump(LUMP_VERTICES, &newVerts[0], sizeof(vec3) * newVerts.size()); if (newLightmaps.size()) + { append_lump(LUMP_LIGHTING, &newLightmaps[0], sizeof(COLOR3) * newLightmaps.size()); + print_log("Added lightmap, size {}\n", newLightmaps.size()); + print_log("Data {}x{}x{}\n", newLightmaps[0].r, newLightmaps[0].g, newLightmaps[0].b); + save_undo_lightmaps(); + resize_all_lightmaps(); + } int newModelIdx = create_model(); BSPMODEL& oldModel = models[modelIdx]; @@ -6312,10 +6332,10 @@ int Bsp::duplicate_model(int modelIdx) memcpy(&newModel, &oldModel, sizeof(BSPMODEL)); newModel.iFirstFace = remap.faces[oldModel.iFirstFace]; - newModel.iHeadnodes[0] = oldModel.iHeadnodes[0] < 0 ? -1 : remap.nodes[oldModel.iHeadnodes[0]]; + newModel.iHeadnodes[0] = remap.nodes[oldModel.iHeadnodes[0]]; for (int i = 1; i < MAX_MAP_HULLS; i++) { - newModel.iHeadnodes[i] = oldModel.iHeadnodes[i] < 0 ? -1 : remap.clipnodes[oldModel.iHeadnodes[i]]; + newModel.iHeadnodes[i] = remap.clipnodes[oldModel.iHeadnodes[i]]; } newModel.nVisLeafs = 0; // techinically should match the old model, but leaves aren't duplicated yet diff --git a/src/editor/BspRenderer.cpp b/src/editor/BspRenderer.cpp index bf63ad39..34fa7b83 100644 --- a/src/editor/BspRenderer.cpp +++ b/src/editor/BspRenderer.cpp @@ -412,7 +412,7 @@ void BspRenderer::loadTextures() void BspRenderer::reload() { - updateLightmapInfos(); + loadLightmaps(); calcFaceMaths(); preRenderFaces(); preRenderEnts(); @@ -513,6 +513,8 @@ void BspRenderer::loadLightmaps() memset(atlasTextures[0]->data, 0, LIGHTMAP_ATLAS_SIZE * LIGHTMAP_ATLAS_SIZE * sizeof(COLOR3)); numRenderLightmapInfos = map->faceCount; + if (lightmaps) + delete[] lightmaps; lightmaps = new LightmapInfo[map->faceCount]{}; print_log(get_localized_string(LANG_0274)); diff --git a/src/editor/Command.cpp b/src/editor/Command.cpp index c2611252..f8c8ace8 100644 --- a/src/editor/Command.cpp +++ b/src/editor/Command.cpp @@ -276,12 +276,10 @@ void DuplicateBspModelCommand::execute() //int dupLumps = FL_CLIPNODES | FL_EDGES | FL_FACES | FL_NODES | FL_PLANES | FL_SURFEDGES | FL_TEXINFO | FL_VERTICES | FL_LIGHTING | FL_MODELS; oldLumps = map->duplicate_lumps(0xFFFFFFFF); - map->resize_all_lightmaps(); newModelIdx = map->duplicate_model(oldModelIdx); ent->setOrAddKeyvalue("model", "*" + std::to_string(newModelIdx)); - renderer->updateLightmapInfos(); renderer->calcFaceMaths(); renderer->preRenderFaces(); renderer->preRenderEnts(); @@ -298,7 +296,6 @@ void DuplicateBspModelCommand::execute() g_app->gui->refresh(); - map->save_undo_lightmaps(); /* if (g_app->pickInfo.entIdx[0] == entIdx) { g_modelIdx = newModelIdx; @@ -324,7 +321,6 @@ void DuplicateBspModelCommand::undo() ent->setOrAddKeyvalue("model", "*" + std::to_string(oldModelIdx)); - renderer->updateLightmapInfos(); renderer->calcFaceMaths(); renderer->preRenderFaces(); renderer->preRenderEnts(); @@ -423,7 +419,6 @@ void CreateBspModelCommand::execute() //renderer->refreshModel(modelIdx); // - renderer->updateLightmapInfos(); renderer->calcFaceMaths(); renderer->preRenderFaces(); renderer->preRenderEnts(); @@ -606,7 +601,7 @@ void EditBspModelCommand::refresh() if (i == LUMP_LIGHTING && newLumps.lumps[i].size()) { // renderer->updateLightmapInfos(); - // map->getBspRender()->reloadLightmaps(); + map->getBspRender()->reloadLightmaps(); } else if (i == LUMP_ENTITIES && newLumps.lumps[i].size()) { diff --git a/src/editor/Gui.cpp b/src/editor/Gui.cpp index a2d46461..d9a92afc 100644 --- a/src/editor/Gui.cpp +++ b/src/editor/Gui.cpp @@ -322,6 +322,7 @@ void ExportModel(Bsp* src_map, int id, int ExportType, bool movemodel) src_map->update_lump_pointers(); src_map->write(src_map->bsp_path + ".tmp.bsp"); + print_log(get_localized_string(LANG_0316)); Bsp* tmpMap = new Bsp(src_map->bsp_path + ".tmp.bsp"); @@ -403,7 +404,6 @@ void ExportModel(Bsp* src_map, int id, int ExportType, bool movemodel) tmpMap->update_ent_lump(); tmpMap->update_lump_pointers(); - print_log(get_localized_string(LANG_0325)); /*int markid = 0; for (int i = 0; i < tmpMap->leafCount; i++) @@ -419,12 +419,14 @@ void ExportModel(Bsp* src_map, int id, int ExportType, bool movemodel) //tmpMap->models[0].nVisLeafs = tmpMap->leafCount - 1; if (movemodel) + { + print_log(get_localized_string(LANG_0325)); tmpMap->move(-modelOrigin, 0, true, true); + } - tmpMap->update_lump_pointers(); - print_log(get_localized_string(LANG_0326)); + tmpMap->update_lump_pointers(); remove_unused_wad_files(src_map, tmpMap, ExportType); print_log(get_localized_string(LANG_0327)); @@ -444,13 +446,19 @@ void ExportModel(Bsp* src_map, int id, int ExportType, bool movemodel) tmpMap->leaves[i].nVisOffset = -1; } + tmpMap->update_ent_lump(); + tmpMap->update_lump_pointers(); + if (tmpMap->validate()) { - tmpMap->update_ent_lump(); - tmpMap->update_lump_pointers(); + createDir(g_working_dir); removeFile(g_working_dir + src_map->bsp_name + "_model" + std::to_string(id) + ".bsp"); tmpMap->write(g_working_dir + src_map->bsp_name + "_model" + std::to_string(id) + ".bsp"); } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_0341)); + } delete tmpMap; delete tmpEnt2; @@ -1145,6 +1153,10 @@ void Gui::drawMenuBar() print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_0341)); } } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_0341)); + } } if (ImGui::IsItemHovered() && g.HoveredIdTimer > g_tooltip_delay) @@ -1193,6 +1205,10 @@ void Gui::drawMenuBar() print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); } } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); + } } if (ImGui::IsItemHovered() && g.HoveredIdTimer > g_tooltip_delay) @@ -1236,10 +1252,17 @@ void Gui::drawMenuBar() is_need_reload = true; map->write(map->bsp_path); } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); + } + } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); } } - if (ImGui::IsItemHovered() && g.HoveredIdTimer > g_tooltip_delay) { ImGui::BeginTooltip(); @@ -1281,11 +1304,17 @@ void Gui::drawMenuBar() is_need_reload = true; map->write(map->bsp_path); } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); + } + } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); } } - - if (ImGui::IsItemHovered() && g.HoveredIdTimer > g_tooltip_delay) { ImGui::BeginTooltip(); @@ -1329,6 +1358,14 @@ void Gui::drawMenuBar() is_need_reload = true; map->write(map->bsp_path); } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); + } + } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); } } @@ -1373,6 +1410,14 @@ void Gui::drawMenuBar() is_need_reload = true; map->write(map->bsp_path); } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); + } + } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); } } @@ -1419,6 +1464,14 @@ void Gui::drawMenuBar() is_need_reload = true; map->write(map->bsp_path); } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); + } + } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); } } @@ -1465,6 +1518,14 @@ void Gui::drawMenuBar() is_need_reload = true; map->write(map->bsp_path); } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); + } + } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); } } @@ -1510,10 +1571,17 @@ void Gui::drawMenuBar() is_need_reload = true; map->write(map->bsp_path); } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); + } + } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); } } - if (ImGui::IsItemHovered() && g.HoveredIdTimer > g_tooltip_delay) { ImGui::BeginTooltip(); @@ -1556,10 +1624,17 @@ void Gui::drawMenuBar() is_need_reload = true; map->write(map->bsp_path); } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); + } + } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); } } - if (ImGui::IsItemHovered() && g.HoveredIdTimer > g_tooltip_delay) { ImGui::BeginTooltip(); @@ -1602,6 +1677,14 @@ void Gui::drawMenuBar() is_need_reload = true; map->write(map->bsp_path); } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); + } + } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); } } @@ -1647,6 +1730,14 @@ void Gui::drawMenuBar() is_need_reload = true; map->write(map->bsp_path); } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); + } + } + else + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); } } @@ -2145,6 +2236,8 @@ void Gui::drawMenuBar() Wad* tmpWad = new Wad(wad->filename); std::vector textureList{}; + + createDir(g_working_dir); fs::path tmpPath = g_working_dir + "wads/" + basename(wad->filename); std::vector files{}; @@ -2259,7 +2352,10 @@ void Gui::drawMenuBar() if (map) { print_log(get_localized_string(LANG_0358), map->bsp_name); - map->validate(); + if (!map->validate()) + { + print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_1051)); + } } } ImGui::Separator(); @@ -3264,6 +3360,7 @@ void Gui::drawDebugWidget() if (ImGui::CollapsingHeader("DEBUG INFO", ImGuiTreeNodeFlags_None)) { ImGui::Text(fmt::format("Mouse: {} {}", mousePos.x, mousePos.y).c_str()); + ImGui::Text(fmt::format("Workdir: {}", g_working_dir).c_str()); if (app && imgui_io) { @@ -8621,7 +8718,6 @@ void Gui::drawFaceEditorWidget() mergeFaceVec = updatedFaceVec = scaledX = scaledY = shiftedX = shiftedY = textureChanged = toggledFlags = updatedTexVec = stylesChanged = false; - mapRenderer->updateLightmapInfos(); mapRenderer->calcFaceMaths(); app->updateModelVerts(); diff --git a/src/editor/Renderer.cpp b/src/editor/Renderer.cpp index d2843736..b897b142 100644 --- a/src/editor/Renderer.cpp +++ b/src/editor/Renderer.cpp @@ -3326,18 +3326,17 @@ bool Renderer::splitModelFace() modelEdges[i].selected = false; } - mapRenderer->updateLightmapInfos(); - mapRenderer->calcFaceMaths(); - mapRenderer->refreshModel(modelIdx); - updateModelVerts(); - gui->reloadLimits(); - map->getBspRender()->pushModelUndoState("Split Face", EDIT_MODEL_LUMPS); map->resize_all_lightmaps(); + mapRenderer->reloadLightmaps(); + mapRenderer->calcFaceMaths(); + mapRenderer->refreshModel(modelIdx); + updateModelVerts(); + return true; } diff --git a/src/editor/Settings.cpp b/src/editor/Settings.cpp index 2e23d02a..5dbb3f48 100644 --- a/src/editor/Settings.cpp +++ b/src/editor/Settings.cpp @@ -9,8 +9,8 @@ std::string g_settings_path = ""; std::string g_config_dir = ""; std::string g_current_dir = "."; -std::string g_game_dir = ""; -std::string g_working_dir = ""; +std::string g_game_dir = "/"; +std::string g_working_dir = "./"; AppSettings g_settings{}; diff --git a/src/qtools/vis.cpp b/src/qtools/vis.cpp index d0717fe0..2dd266db 100644 --- a/src/qtools/vis.cpp +++ b/src/qtools/vis.cpp @@ -196,7 +196,7 @@ void decompress_vis_lump(BSPLEAF32* leafLump, unsigned char* visLump, unsigned c dest = output + i * newVisRowSize; if (lastUsedIdx >= 0) { - if ((i + 1) * sizeof(BSPLEAF32) >= leafMemSize) + if ((i + 1) * sizeof(BSPLEAF32) > leafMemSize) { print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_0994),i + 1,leafMemSize / sizeof(BSPLEAF32)); return; @@ -209,7 +209,7 @@ void decompress_vis_lump(BSPLEAF32* leafLump, unsigned char* visLump, unsigned c continue; } - if (leafLump[i + 1].nVisOffset >= visLumpMemSize) + if (leafLump[i + 1].nVisOffset > visLumpMemSize) { print_log(PRINT_RED | PRINT_INTENSITY, get_localized_string(LANG_0995),leafLump[i + 1].nVisOffset,visLumpMemSize); return; diff --git a/src/util/util.cpp b/src/util/util.cpp index 2a85da61..549933c3 100644 --- a/src/util/util.cpp +++ b/src/util/util.cpp @@ -1524,12 +1524,20 @@ void FixupAllSystemPaths() { if (!dirExists(g_game_dir + g_settings.workingdir)) { - print_log(PRINT_RED | PRINT_INTENSITY, "Error{}: Workdir {} not exits!", "[1]", g_settings.workingdir); - print_log(PRINT_RED | PRINT_INTENSITY, "Error{}: Workdir {} not exits!", "[2]", g_game_dir + g_settings.workingdir); + print_log(PRINT_RED | PRINT_INTENSITY, "Warning: Workdir {} not exits!\n", g_settings.workingdir); + print_log(PRINT_RED | PRINT_INTENSITY, "Warning: Workdir {} not exits!\n", g_game_dir + g_settings.workingdir); + print_log(PRINT_RED | PRINT_GREEN | PRINT_INTENSITY, "Using default path\n"); } - else + g_working_dir = g_game_dir + g_settings.workingdir; + try { - g_working_dir = g_game_dir + g_settings.workingdir; + if (!dirExists(g_working_dir)) + createDir(g_working_dir); + } + catch (...) + { + print_log(PRINT_RED | PRINT_INTENSITY, "Error: Can't create workdir at {} !\n", g_settings.workingdir); + g_working_dir = "./"; } } else @@ -1570,7 +1578,7 @@ float floatRound(float f) { } -void scaleImage(const COLOR4 * inputImage, std::vector& outputImage, +void scaleImage(const COLOR4* inputImage, std::vector& outputImage, int inputWidth, int inputHeight, int outputWidth, int outputHeight) { outputImage.resize(outputWidth * outputHeight); @@ -1610,7 +1618,7 @@ void scaleImage(const COLOR4 * inputImage, std::vector& outputImage, } } -void scaleImage(const COLOR3 * inputImage, std::vector& outputImage, +void scaleImage(const COLOR3* inputImage, std::vector& outputImage, int inputWidth, int inputHeight, int outputWidth, int outputHeight) { outputImage.resize(outputWidth * outputHeight); diff --git a/vs-project/fmt/fmt.vcxproj b/vs-project/fmt/fmt.vcxproj index 0ef00c01..d4eff457 100644 --- a/vs-project/fmt/fmt.vcxproj +++ b/vs-project/fmt/fmt.vcxproj @@ -174,10 +174,6 @@ - - - - diff --git a/vs-project/fmt/fmt.vcxproj.filters b/vs-project/fmt/fmt.vcxproj.filters index 2930bc19..c8e8b9ac 100644 --- a/vs-project/fmt/fmt.vcxproj.filters +++ b/vs-project/fmt/fmt.vcxproj.filters @@ -49,10 +49,6 @@ Header Files - - - - {C09879EB-61FD-3200-896A-5A951468767D}