mirror of
https://github.com/ArthurSonzogni/FTXUI.git
synced 2025-12-16 01:48:56 +08:00
Compare commits
52 Commits
4f1a694e81
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
170c1b94dd | ||
|
|
942ab6a82d | ||
|
|
9f4b2bcf96 | ||
|
|
117417e841 | ||
|
|
c8fbef03c9 | ||
|
|
183a426efa | ||
|
|
d9c62b3678 | ||
|
|
1d5516a8a5 | ||
|
|
e986b98faf | ||
|
|
97ffd572df | ||
|
|
a1df432245 | ||
|
|
26d0aa986a | ||
|
|
73707b5b00 | ||
|
|
69d645ca04 | ||
|
|
229cae78b5 | ||
|
|
e87d5ff95a | ||
|
|
e0d98feb34 | ||
|
|
8bdf7cd701 | ||
|
|
01d2451dfd | ||
|
|
1d0913bfb9 | ||
|
|
a0ce9bf55d | ||
|
|
09e690f8ab | ||
|
|
68281ce3e8 | ||
|
|
d4fda16e20 | ||
|
|
2b9913e2eb | ||
|
|
b1bc0ff982 | ||
|
|
252ce67830 | ||
|
|
e858bf9809 | ||
|
|
e5652f11ec | ||
|
|
412d8c14e4 | ||
|
|
a3103f5cd4 | ||
|
|
8249fcb41e | ||
|
|
f21fcc1995 | ||
|
|
f7ac35ed35 | ||
|
|
fba510ec02 | ||
|
|
775ad9ce5e | ||
|
|
f5785fd3b4 | ||
|
|
853d87e917 | ||
|
|
11f7132886 | ||
|
|
346f751527 | ||
|
|
e56ff89cf3 | ||
|
|
21b24a1b78 | ||
|
|
bfd07ba309 | ||
|
|
d20b84f720 | ||
|
|
0dde21f09e | ||
|
|
40e1fac3d4 | ||
|
|
8ef18ab647 | ||
|
|
994915dbb9 | ||
|
|
3b359e8cd7 | ||
|
|
1073ba414d | ||
|
|
b78b97056b | ||
|
|
68fc9b1212 |
1
.bazelignore
Normal file
1
.bazelignore
Normal file
@@ -0,0 +1 @@
|
||||
bazel/test/
|
||||
5
.bazelrc
5
.bazelrc
@@ -1,7 +1,10 @@
|
||||
common --enable_bzlmod
|
||||
common --enable_workspace
|
||||
|
||||
build --features=layering_check
|
||||
build --enable_bzlmod
|
||||
|
||||
build --enable_platform_specific_config
|
||||
build:linux --cxxopt=-std=c++20
|
||||
build:macos --cxxopt=-std=c++20
|
||||
build:windows --cxxopt=-std:c++20
|
||||
build:windows --cxxopt=/std:c++20
|
||||
|
||||
@@ -2,3 +2,6 @@
|
||||
# http://clang.llvm.org/docs/ClangFormatStyleOptions.html
|
||||
BasedOnStyle: Chromium
|
||||
Standard: Cpp11
|
||||
|
||||
InsertBraces: true
|
||||
InsertNewlineAtEOF: true
|
||||
|
||||
212
.github/copilot-instructions.md
vendored
Normal file
212
.github/copilot-instructions.md
vendored
Normal file
@@ -0,0 +1,212 @@
|
||||
# FTXUI - Functional Terminal (X) User Interface
|
||||
|
||||
FTXUI is a cross-platform C++ library for terminal-based user interfaces with a functional programming approach, inspired by React.
|
||||
|
||||
**ALWAYS reference these instructions first and fallback to search or bash commands only when you encounter unexpected information that does not match the information here.**
|
||||
|
||||
## Working Effectively
|
||||
|
||||
### Build System Setup and Commands
|
||||
- Bootstrap and build the repository:
|
||||
```bash
|
||||
# Basic build (library only) - fast
|
||||
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build --parallel $(nproc)
|
||||
# Build time: ~30 seconds. NEVER CANCEL. Set timeout to 120+ seconds.
|
||||
|
||||
# Build with examples
|
||||
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DFTXUI_BUILD_EXAMPLES=ON
|
||||
cmake --build build --parallel $(nproc)
|
||||
# Build time: ~70 seconds. NEVER CANCEL. Set timeout to 180+ seconds.
|
||||
|
||||
# Build with examples and tests
|
||||
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DFTXUI_BUILD_EXAMPLES=ON -DFTXUI_BUILD_TESTS=ON
|
||||
cmake --build build --parallel $(nproc)
|
||||
# Build time: ~113 seconds (includes GoogleTest download). NEVER CANCEL. Set timeout to 300+ seconds.
|
||||
```
|
||||
|
||||
- Alternative build with Ninja (faster):
|
||||
```bash
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DFTXUI_BUILD_EXAMPLES=ON
|
||||
ninja -C build
|
||||
# Build time: ~62 seconds. NEVER CANCEL. Set timeout to 180+ seconds.
|
||||
```
|
||||
|
||||
- Run unit tests:
|
||||
```bash
|
||||
# Configure with tests enabled first, then:
|
||||
cd build && ctest --output-on-failure
|
||||
# Test time: ~4 seconds (302 tests). NEVER CANCEL. Set timeout to 60+ seconds.
|
||||
```
|
||||
|
||||
### Bazel Support
|
||||
- FTXUI also supports Bazel build system
|
||||
- **WARNING**: Bazel may fail due to network connectivity issues in sandboxed environments
|
||||
- If Bazel is available:
|
||||
```bash
|
||||
bazel build //... # Build everything
|
||||
bazel test //... # Run tests
|
||||
```
|
||||
|
||||
## Validation
|
||||
|
||||
### Manual Testing After Changes
|
||||
- **ALWAYS manually validate changes by building and running examples after making code modifications**
|
||||
- Run example applications to verify functionality:
|
||||
```bash
|
||||
# Build an example first
|
||||
cmake --build build --target ftxui_example_border
|
||||
|
||||
# Run examples (they are interactive, use timeout to terminate)
|
||||
timeout 2s build/examples/dom/ftxui_example_border
|
||||
timeout 2s build/examples/dom/ftxui_example_color_gallery
|
||||
timeout 2s build/examples/component/ftxui_example_button
|
||||
```
|
||||
- Examples should produce visual terminal output with borders, colors, and UI components
|
||||
- **CRITICAL**: Always run at least one DOM example and one Component example to verify both modules work
|
||||
|
||||
### Code Quality and Formatting
|
||||
- Always run formatting before committing:
|
||||
```bash
|
||||
./tools/format.sh
|
||||
# Format time: ~7 seconds. NEVER CANCEL. Set timeout to 60+ seconds.
|
||||
```
|
||||
- The format script adds license headers and runs clang-format on all source files
|
||||
- **Required**: Run formatting or the CI (.github/workflows/build.yaml) will fail
|
||||
|
||||
### Build Validation Requirements
|
||||
- ALWAYS build with both `-DFTXUI_BUILD_EXAMPLES=ON` and `-DFTXUI_BUILD_TESTS=ON` when making changes
|
||||
- Run the complete test suite with `ctest --output-on-failure`
|
||||
- All 302 tests must pass
|
||||
- **Scenario Testing**: Run at least these validation scenarios:
|
||||
1. Build library only (basic validation)
|
||||
2. Build with examples and run 2-3 different examples
|
||||
3. Build with tests and run complete test suite
|
||||
4. Run formatting tool to ensure code style compliance
|
||||
|
||||
## Project Structure
|
||||
|
||||
### Key Directories
|
||||
```
|
||||
/home/runner/work/FTXUI/FTXUI/
|
||||
├── include/ftxui/ # Public header files
|
||||
│ ├── component/ # Interactive component headers
|
||||
│ ├── dom/ # DOM element headers
|
||||
│ ├── screen/ # Screen and rendering headers
|
||||
│ └── util/ # Utility headers
|
||||
├── src/ftxui/ # Implementation files
|
||||
│ ├── component/ # Interactive components (buttons, menus, etc.)
|
||||
│ ├── dom/ # DOM elements (layout, styling, text)
|
||||
│ ├── screen/ # Screen rendering and terminal handling
|
||||
│ └── util/ # Utilities
|
||||
├── examples/ # Example applications
|
||||
│ ├── component/ # Interactive component examples
|
||||
│ └── dom/ # DOM element examples
|
||||
├── cmake/ # CMake configuration files
|
||||
├── tools/ # Development tools (formatting, etc.)
|
||||
└── .github/workflows/ # CI/CD configuration
|
||||
```
|
||||
|
||||
### Core Library Modules
|
||||
FTXUI is organized into three main modules that depend on each other:
|
||||
```
|
||||
┌component──┐ (Interactive UI components)
|
||||
│┌dom──────┐│ (Layout and styling elements)
|
||||
││┌screen─┐││ (Terminal rendering and input)
|
||||
└┴┴───────┴┴┘
|
||||
```
|
||||
|
||||
1. **screen**: Low-level terminal handling, colors, pixels, input
|
||||
2. **dom**: Layout elements (hbox, vbox, text, borders, etc.)
|
||||
3. **component**: Interactive components (buttons, menus, input fields)
|
||||
|
||||
### CMake Build Options
|
||||
| Option | Description | Default |
|
||||
|-----------------------------------|----------------------------------|---------|
|
||||
| FTXUI_BUILD_EXAMPLES | Build example applications | OFF |
|
||||
| FTXUI_BUILD_DOCS | Build documentation | OFF |
|
||||
| FTXUI_BUILD_TESTS | Build and enable tests | OFF |
|
||||
| FTXUI_BUILD_MODULES | Build C++20 modules | OFF |
|
||||
| FTXUI_ENABLE_INSTALL | Generate install targets | ON |
|
||||
| FTXUI_MICROSOFT_TERMINAL_FALLBACK | Windows terminal compatibility | ON/OFF |
|
||||
|
||||
## Common Tasks
|
||||
|
||||
### Building Examples
|
||||
```bash
|
||||
# Build specific examples
|
||||
cmake --build build --target ftxui_example_border
|
||||
cmake --build build --target ftxui_example_button
|
||||
cmake --build build --target ftxui_example_menu
|
||||
|
||||
# List all available examples
|
||||
find build -name "ftxui_example_*" -type f
|
||||
```
|
||||
|
||||
### Running Tests
|
||||
```bash
|
||||
# Run all tests
|
||||
cd build && ctest
|
||||
|
||||
# Run tests with verbose output
|
||||
cd build && ctest --verbose
|
||||
|
||||
# Run specific test pattern
|
||||
cd build && ctest -R "Button" --verbose
|
||||
```
|
||||
|
||||
### Working with Source Code
|
||||
- **Component Development**: Modify files in `src/ftxui/component/` for interactive elements
|
||||
- **DOM Development**: Modify files in `src/ftxui/dom/` for layout and styling
|
||||
- **Screen Development**: Modify files in `src/ftxui/screen/` for terminal rendering
|
||||
- **Adding Examples**: Add new `.cpp` files in `examples/component/` or `examples/dom/`
|
||||
- **Header Files**: Public APIs are in `include/ftxui/[module]/`
|
||||
|
||||
### Integration Patterns
|
||||
When adding FTXUI to a project, use CMake FetchContent (recommended):
|
||||
```cmake
|
||||
include(FetchContent)
|
||||
FetchContent_Declare(ftxui
|
||||
GIT_REPOSITORY https://github.com/ArthurSonzogni/ftxui
|
||||
GIT_TAG v6.1.9
|
||||
)
|
||||
FetchContent_MakeAvailable(ftxui)
|
||||
|
||||
target_link_libraries(your_target PRIVATE
|
||||
ftxui::component # For interactive components
|
||||
ftxui::dom # For layout elements
|
||||
ftxui::screen # For basic rendering
|
||||
)
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Build Issues
|
||||
- If CMake configuration fails, ensure C++20 support: `cmake --version` (need 3.12+)
|
||||
- If Ninja build fails, fall back to Make: `cmake -S . -B build` (without `-G Ninja`)
|
||||
- If tests fail to build, GoogleTest download might have failed - check network connectivity
|
||||
- Build artifacts are in `build/` directory - delete with `rm -rf build` to clean
|
||||
|
||||
### Example Issues
|
||||
- Examples are interactive terminal applications - use `timeout` to terminate them
|
||||
- If examples don't display correctly, terminal might not support colors/Unicode
|
||||
- Examples require terminal size of at least 80x24 for proper display
|
||||
|
||||
### Formatting Issues
|
||||
- Format script requires clang-format to be installed
|
||||
- If format script fails, check that source files are not read-only
|
||||
- Format script modifies files in-place - commit changes afterwards
|
||||
|
||||
## Critical Reminders
|
||||
|
||||
- **NEVER CANCEL long-running builds** - they may take 2-3 minutes
|
||||
- **ALWAYS run the formatting tool** before committing changes
|
||||
- **ALWAYS build and test examples** when making component/dom changes
|
||||
- **SET APPROPRIATE TIMEOUTS**: 300+ seconds for builds, 60+ seconds for tests
|
||||
- **BUILD TIMING EXPECTATIONS**:
|
||||
- Basic library: ~30 seconds
|
||||
- With examples: ~70 seconds
|
||||
- With examples + tests: ~113 seconds (first time, includes GoogleTest download)
|
||||
- Subsequent builds: ~60-70 seconds
|
||||
- Tests execution: ~4 seconds
|
||||
- Formatting: ~7 seconds
|
||||
7
.github/workflows/build.yaml
vendored
7
.github/workflows/build.yaml
vendored
@@ -56,6 +56,13 @@ jobs:
|
||||
CXX: ${{ matrix.cxx }}
|
||||
run: bazel test --test_output=all ...
|
||||
|
||||
- name: "Bazel Smoke test"
|
||||
env:
|
||||
CC: ${{ matrix.cc }}
|
||||
CXX: ${{ matrix.cxx }}
|
||||
run: bazel build //... --enable_bzlmod --override_module=ftxui=../..
|
||||
working-directory: bazel/test
|
||||
|
||||
test_cmake:
|
||||
name: "CMake, ${{ matrix.compiler }}, ${{ matrix.os }}"
|
||||
strategy:
|
||||
|
||||
16
.github/workflows/documentation.yaml
vendored
16
.github/workflows/documentation.yaml
vendored
@@ -12,6 +12,10 @@ jobs:
|
||||
steps:
|
||||
- name: "Checkout repository"
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0 # Need full history.
|
||||
fetch-tags: true # Need tags.
|
||||
|
||||
|
||||
- name: "Install cmake"
|
||||
uses: lukka/get-cmake@latest
|
||||
@@ -30,7 +34,12 @@ jobs:
|
||||
sudo apt-get install graphviz;
|
||||
|
||||
- name: "Build documentation"
|
||||
run: |
|
||||
python3 ./tools/build_multiversion_doc.py
|
||||
|
||||
- name: "Build examples"
|
||||
run: >
|
||||
mkdir -p multiversion_docs/main/examples;
|
||||
mkdir build;
|
||||
cd build;
|
||||
emcmake cmake ..
|
||||
@@ -41,8 +50,7 @@ jobs:
|
||||
-DFTXUI_BUILD_TESTS_FUZZER=OFF
|
||||
-DFTXUI_ENABLE_INSTALL=OFF
|
||||
-DFTXUI_DEV_WARNINGS=OFF;
|
||||
cmake --build . --target doc;
|
||||
cmake --build . ;
|
||||
cmake --build .;
|
||||
rsync -amv
|
||||
--include='*/'
|
||||
--include='*.html'
|
||||
@@ -52,13 +60,13 @@ jobs:
|
||||
--include='*.wasm'
|
||||
--exclude='*'
|
||||
examples
|
||||
doc/doxygen/html;
|
||||
../multiversion_docs/
|
||||
|
||||
- name: "Deploy"
|
||||
uses: peaceiris/actions-gh-pages@v3
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
publish_dir: build/doc/doxygen/html/
|
||||
publish_dir: multiversion_docs
|
||||
enable_jekyll: false
|
||||
allow_empty_commit: false
|
||||
force_orphan: true
|
||||
|
||||
9
.gitignore
vendored
9
.gitignore
vendored
@@ -24,10 +24,12 @@ out/
|
||||
!BUILD.bazel
|
||||
!MODULE.bazel
|
||||
!.bazelrc
|
||||
!.bazelignore
|
||||
|
||||
# .github directory:
|
||||
!.github/**/*.yaml
|
||||
!.github/**/*.yml
|
||||
!.github/**/*.md
|
||||
|
||||
# cmake directory:
|
||||
!cmake/**/*.in
|
||||
@@ -36,6 +38,10 @@ out/
|
||||
# bazel directory:
|
||||
!bazel/**/*.bzl
|
||||
!.bcr/*
|
||||
!bazel/test/*.bazel
|
||||
!bazel/test/*.bazelrc
|
||||
!bazel/test/*.cpp
|
||||
!bazel/test/*.md
|
||||
|
||||
# doc directory:
|
||||
!doc/**/Doxyfile.in
|
||||
@@ -44,6 +50,7 @@ out/
|
||||
!doc/**/*.html
|
||||
!doc/**/*.xml
|
||||
!doc/**/*.md
|
||||
!doc/*.md
|
||||
|
||||
# examples directory:
|
||||
!examples/**/*.cpp
|
||||
@@ -69,4 +76,6 @@ out/
|
||||
|
||||
# tools directory:
|
||||
!tools/**/*.sh
|
||||
!tools/**/*.py
|
||||
!tools/**/*.cpp
|
||||
build/
|
||||
|
||||
21
BUILD.bazel
21
BUILD.bazel
@@ -13,16 +13,18 @@ load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test")
|
||||
load(":bazel/ftxui.bzl", "ftxui_cc_library")
|
||||
load(":bazel/ftxui.bzl", "generate_examples")
|
||||
load(":bazel/ftxui.bzl", "windows_copts")
|
||||
load(":bazel/ftxui.bzl", "pthread_linkopts")
|
||||
|
||||
# A meta target depending on all of the ftxui submodules.
|
||||
# Note that component depends on dom and screen, so ftxui is just an alias for
|
||||
# component.
|
||||
# Note that component depends on dom and screen, so ftxui re-exports all headers.
|
||||
# ┌component──┐
|
||||
# │┌dom──────┐│
|
||||
# ││┌screen─┐││
|
||||
# └┴┴───────┴┴┘
|
||||
alias(name = "ftxui", actual = ":component")
|
||||
ftxui_cc_library(
|
||||
name = "ftxui",
|
||||
hdrs = glob(["include/ftxui/**/*.hpp"]),
|
||||
deps = [":component"],
|
||||
)
|
||||
|
||||
# @ftxui:screen is a module that provides a screen buffer and color management
|
||||
# for terminal applications. A screen is a 2D array of cells, each cell can
|
||||
@@ -159,6 +161,12 @@ ftxui_cc_library(
|
||||
"src/ftxui/component/resizable_split.cpp",
|
||||
"src/ftxui/component/screen_interactive.cpp",
|
||||
"src/ftxui/component/slider.cpp",
|
||||
"src/ftxui/component/task.cpp",
|
||||
"src/ftxui/component/task_internal.hpp",
|
||||
"src/ftxui/component/task_queue.cpp",
|
||||
"src/ftxui/component/task_queue.hpp",
|
||||
"src/ftxui/component/task_runner.cpp",
|
||||
"src/ftxui/component/task_runner.hpp",
|
||||
"src/ftxui/component/terminal_input_parser.cpp",
|
||||
"src/ftxui/component/terminal_input_parser.hpp",
|
||||
"src/ftxui/component/util.cpp",
|
||||
@@ -170,6 +178,9 @@ ftxui_cc_library(
|
||||
# Private header from ftxui:screen.
|
||||
"src/ftxui/screen/string_internal.hpp",
|
||||
"src/ftxui/screen/util.hpp",
|
||||
|
||||
# Private header.
|
||||
"include/ftxui/util/warn_windows_macro.hpp",
|
||||
],
|
||||
hdrs = [
|
||||
"include/ftxui/component/animation.hpp",
|
||||
@@ -184,7 +195,6 @@ ftxui_cc_library(
|
||||
"include/ftxui/component/screen_interactive.hpp",
|
||||
"include/ftxui/component/task.hpp",
|
||||
],
|
||||
linkopts = pthread_linkopts(),
|
||||
deps = [
|
||||
":dom",
|
||||
":screen",
|
||||
@@ -207,7 +217,6 @@ cc_test(
|
||||
"src/ftxui/component/menu_test.cpp",
|
||||
"src/ftxui/component/modal_test.cpp",
|
||||
"src/ftxui/component/radiobox_test.cpp",
|
||||
"src/ftxui/component/receiver_test.cpp",
|
||||
"src/ftxui/component/resizable_split_test.cpp",
|
||||
"src/ftxui/component/slider_test.cpp",
|
||||
"src/ftxui/component/terminal_input_parser_test.cpp",
|
||||
|
||||
27
CHANGELOG.md
27
CHANGELOG.md
@@ -24,7 +24,34 @@ Next
|
||||
import ftxui.util;
|
||||
```
|
||||
Thanks @mikomikotaishi for PR #1015.
|
||||
- Remove dependency on 'pthread'.
|
||||
- Bugfix: Bazel target @ftxui is now visible. Thanks @dskkato in #1157.
|
||||
|
||||
### General
|
||||
- Breaking. Move to `std::string_view` instead of `const std::string&` where
|
||||
applicable. This yields better interoperability with string literals and
|
||||
avoids unnecessary copies. Thanks @mikomikotaishi for PR #1154
|
||||
|
||||
### Component
|
||||
- Feature: POSIX Piped Input Handling.
|
||||
- Allows FTXUI applications to read data from stdin (when piped) while still receiving keyboard input from the terminal.
|
||||
- Enabled by default.
|
||||
- Can be disabled using `ScreenInteractive::HandlePipedInput(false)`.
|
||||
- Only available on Linux and macOS.
|
||||
Thanks @HarryPehkonen for PR #1094.
|
||||
- Fix ScreenInteractive::FixedSize screen stomps on the preceding terminal
|
||||
output. Thanks @zozowell in #1064.
|
||||
- Fix vertical `ftxui::Slider`. The "up" key was previously decreasing the
|
||||
value. Thanks @its-pablo in #1093 for reporting the issue.
|
||||
- Fix Windows UTF-16 key input handling. Emoji and other code points outside the
|
||||
Basic Multilingual Plane (BMP) are now correctly processed. Thanks @739C1AE2
|
||||
in #1160 for fixing the issue.
|
||||
|
||||
### Dom
|
||||
- Fix integer overflow in `ComputeShrinkHard`. Thanks @its-pablo in #1137 for
|
||||
reporting and fixing the issue.
|
||||
- Add specialization for `vbox/hbox/dbox` to allow a container of Element as
|
||||
as input. Thanks @nbusser in #1117.
|
||||
|
||||
6.1.9 (2025-05-07)
|
||||
------------
|
||||
|
||||
@@ -144,26 +144,20 @@ add_library(component
|
||||
src/ftxui/component/resizable_split.cpp
|
||||
src/ftxui/component/screen_interactive.cpp
|
||||
src/ftxui/component/slider.cpp
|
||||
src/ftxui/component/task.cpp
|
||||
src/ftxui/component/task_internal.hpp
|
||||
src/ftxui/component/task_queue.cpp
|
||||
src/ftxui/component/task_queue.hpp
|
||||
src/ftxui/component/task_runner.cpp
|
||||
src/ftxui/component/task_runner.hpp
|
||||
src/ftxui/component/terminal_input_parser.cpp
|
||||
src/ftxui/component/terminal_input_parser.hpp
|
||||
src/ftxui/component/util.cpp
|
||||
src/ftxui/component/window.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(dom
|
||||
PUBLIC screen
|
||||
)
|
||||
|
||||
target_link_libraries(component
|
||||
PUBLIC dom
|
||||
)
|
||||
|
||||
if (NOT EMSCRIPTEN)
|
||||
find_package(Threads)
|
||||
target_link_libraries(component
|
||||
PUBLIC Threads::Threads
|
||||
)
|
||||
endif()
|
||||
target_link_libraries(dom PUBLIC screen)
|
||||
target_link_libraries(component PUBLIC dom)
|
||||
|
||||
include(cmake/ftxui_set_options.cmake)
|
||||
ftxui_set_options(screen)
|
||||
@@ -184,8 +178,8 @@ include(cmake/ftxui_install.cmake)
|
||||
include(cmake/ftxui_package.cmake)
|
||||
include(cmake/ftxui_modules.cmake)
|
||||
|
||||
add_subdirectory(doc)
|
||||
add_subdirectory(examples)
|
||||
add_subdirectory(doc)
|
||||
|
||||
# You can generate ./examples_modules/ by running
|
||||
# ./tools/generate_examples_modules.sh
|
||||
|
||||
24
README.md
24
README.md
@@ -1,3 +1,4 @@
|
||||
|
||||
<p align="center">
|
||||
<img src="https://github.com/ArthurSonzogni/FTXUI/assets/4759106/6925b6da-0a7e-49d9-883c-c890e1f36007" alt="Demo image"></img>
|
||||
<br/>
|
||||
@@ -18,10 +19,16 @@
|
||||
<br/>
|
||||
<a href="https://arthursonzogni.github.io/FTXUI/">Documentation</a> ·
|
||||
<a href="https://github.com/ArthurSonzogni/FTXUI/issues">Report a Bug</a> ·
|
||||
<a href="https://arthursonzogni.github.io/FTXUI/examples.html">Examples</a> .
|
||||
<a href="https://arthursonzogni.github.io/FTXUI/examples/">Examples</a> .
|
||||
<a href="https://github.com/ArthurSonzogni/FTXUI/issues">Request Feature</a> ·
|
||||
<a href="https://github.com/ArthurSonzogni/FTXUI/pulls">Send a Pull Request</a>
|
||||
|
||||
<br/>
|
||||
<a href="https://github.com/ArthurSonzogni/">English</a> |
|
||||
<a href="https://github.com/ArthurSonzogni/ftxui-translations/tree/zh-CH">中文翻译</a> |
|
||||
<a href="https://github.com/ArthurSonzogni/ftxui-translations/tree/zh-CH">繁體中文</a> |
|
||||
<a href="https://github.com/ArthurSonzogni/ftxui-translations/tree/ja">日本語</a>
|
||||
|
||||
</p>
|
||||
|
||||
# FTXUI
|
||||
@@ -362,6 +369,9 @@ Feel free to add your projects here:
|
||||
- [FTB - tertminal file browser](https://github.com/Cyxuan0311/FTB)
|
||||
- [openJuice](https://github.com/mikomikotaishi/openJuice)
|
||||
- [SHOOT!](https://github.com/ShingZhanho/ENGG1340-Project-25Spring)
|
||||
- [VerifySN (Fast Hash Tool)](https://github.com/d06i/verifySN)
|
||||
- [tic-tac-toe](https://github.com/birland/tic-tac-toe)
|
||||
- [typing-speed-test](https://github.com/ymcx/typing-speed-test)
|
||||
|
||||
### [cpp-best-practices/game_jam](https://github.com/cpp-best-practices/game_jam)
|
||||
|
||||
@@ -378,6 +388,8 @@ Several games using the FTXUI have been made during the Game Jam:
|
||||
- [smoothlife](https://github.com/cpp-best-practices/game_jam/blob/main/Jam1_April_2022/smoothlife.md)
|
||||
- [Consu](https://github.com/cpp-best-practices/game_jam/blob/main/Jam1_April_2022/consu.md)
|
||||
|
||||
|
||||
|
||||
## Build using CMake
|
||||
|
||||
It is **highly** recommended to use CMake FetchContent to depend on FTXUI so you may specify which commit you would like to depend on.
|
||||
@@ -413,9 +425,13 @@ cc_binary(
|
||||
name = "your_target",
|
||||
srcs = ["your_source.cc"],
|
||||
deps = [
|
||||
"@ftxui//:ftxui_component",
|
||||
"@ftxui//:ftxui_dom",
|
||||
"@ftxui//:ftxui_screen",
|
||||
# Choose submodules
|
||||
"@ftxui//:component",
|
||||
"@ftxui//:dom",
|
||||
"@ftxui//:screen",
|
||||
|
||||
# Or use the single ftxui target (includes all modules)
|
||||
# "@ftxui//:ftxui",
|
||||
],
|
||||
)
|
||||
```
|
||||
|
||||
@@ -43,16 +43,6 @@ def windows_copts():
|
||||
"//conditions:default": [],
|
||||
})
|
||||
|
||||
def pthread_linkopts():
|
||||
return select({
|
||||
# With MSVC, threading is already built-in (you don't need -pthread.
|
||||
"@rules_cc//cc/compiler:msvc-cl": [],
|
||||
"@rules_cc//cc/compiler:clang-cl": [],
|
||||
"@rules_cc//cc/compiler:clang": ["-pthread"],
|
||||
"@rules_cc//cc/compiler:gcc": ["-pthread"],
|
||||
"//conditions:default": ["-pthread"],
|
||||
})
|
||||
|
||||
def ftxui_cc_library(
|
||||
name,
|
||||
srcs = [],
|
||||
|
||||
1
bazel/test/.bazelrc
Symbolic link
1
bazel/test/.bazelrc
Symbolic link
@@ -0,0 +1 @@
|
||||
../../.bazelrc
|
||||
23
bazel/test/BUILD.bazel
Normal file
23
bazel/test/BUILD.bazel
Normal file
@@ -0,0 +1,23 @@
|
||||
# Copyright 2025 Arthur Sonzogni. All rights reserved.
|
||||
# Use of this source code is governed by the MIT license that can be found in
|
||||
# the LICENSE file.
|
||||
|
||||
# Test using individual submodules
|
||||
cc_binary(
|
||||
name = "smoke",
|
||||
srcs = ["smoke.cpp"],
|
||||
deps = [
|
||||
"@ftxui//:component",
|
||||
"@ftxui//:dom",
|
||||
"@ftxui//:screen",
|
||||
],
|
||||
)
|
||||
|
||||
# Test using the single ftxui target
|
||||
cc_binary(
|
||||
name = "smoke_single_dependency",
|
||||
srcs = ["smoke.cpp"],
|
||||
deps = [
|
||||
"@ftxui",
|
||||
],
|
||||
)
|
||||
9
bazel/test/MODULE.bazel
Normal file
9
bazel/test/MODULE.bazel
Normal file
@@ -0,0 +1,9 @@
|
||||
# Copyright 2025 Arthur Sonzogni. All rights reserved.
|
||||
# Use of this source code is governed by the MIT license that can be found in
|
||||
# the LICENSE file.
|
||||
module(
|
||||
name = "ftxui_integration_test",
|
||||
version = "0.0.1",
|
||||
)
|
||||
|
||||
bazel_dep(name = "ftxui", version = "6.1.9")
|
||||
38
bazel/test/README.md
Normal file
38
bazel/test/README.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# FTXUI Bazel Integration Test
|
||||
|
||||
This directory contains integration tests to verify that FTXUI can be properly consumed as an external dependency using Bazel with Bzlmod.
|
||||
|
||||
## Purpose
|
||||
|
||||
These tests ensure that:
|
||||
- FTXUI's public API is correctly exposed to external projects
|
||||
- Both single-target (`@ftxui//:ftxui`) and submodule-based dependencies work correctly
|
||||
- Headers are properly re-exported and accessible from downstream projects
|
||||
|
||||
## Build Instructions
|
||||
|
||||
To build all targets:
|
||||
|
||||
```bash
|
||||
bazel build //... --enable_bzlmod --override_module=ftxui=../..
|
||||
```
|
||||
|
||||
To build individual targets:
|
||||
|
||||
```bash
|
||||
# Test using individual submodules
|
||||
bazel build //:smoke --enable_bzlmod --override_module=ftxui=../..
|
||||
|
||||
# Test using the single ftxui target
|
||||
bazel build //:smoke_single_dependency --enable_bzlmod --override_module=ftxui=../..
|
||||
```
|
||||
|
||||
## Run the Examples
|
||||
|
||||
```bash
|
||||
# Run the submodules version
|
||||
./bazel-bin/smoke
|
||||
|
||||
# Run the single-target version
|
||||
./bazel-bin/smoke_single_dependency
|
||||
```
|
||||
4
bazel/test/WORKSPACE.bazel
Normal file
4
bazel/test/WORKSPACE.bazel
Normal file
@@ -0,0 +1,4 @@
|
||||
# Copyright 2025 Arthur Sonzogni. All rights reserved.
|
||||
# Use of this source code is governed by the MIT license that can be found in
|
||||
# the LICENSE file.
|
||||
workspace(name = "ftxui_smoke_test")
|
||||
16
bazel/test/smoke.cpp
Normal file
16
bazel/test/smoke.cpp
Normal file
@@ -0,0 +1,16 @@
|
||||
// Copyright 2025 Arthur Sonzogni. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
#include <ftxui/dom/elements.hpp>
|
||||
#include <ftxui/screen/screen.hpp>
|
||||
#include <ftxui/component/component.hpp>
|
||||
#include <ftxui/component/screen_interactive.hpp>
|
||||
|
||||
int main() {
|
||||
using namespace ftxui;
|
||||
auto screen = ScreenInteractive::TerminalOutput();
|
||||
auto component = Button("Quit", screen.ExitLoopClosure());
|
||||
screen.Loop(component);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ include(FetchContent)
|
||||
|
||||
FetchContent_Declare(googletest
|
||||
GIT_REPOSITORY "https://github.com/google/googletest"
|
||||
GIT_TAG 23ef29555ef4789f555f1ba8c51b4c52975f0907
|
||||
GIT_TAG 52eb8108c5bdec04579160ae17225d66034bd723 # v1.17.0
|
||||
GIT_PROGRESS TRUE
|
||||
)
|
||||
|
||||
|
||||
@@ -11,6 +11,9 @@ include(CMakePackageConfigHelpers)
|
||||
install(
|
||||
TARGETS screen dom component
|
||||
EXPORT ftxui-targets
|
||||
ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
|
||||
LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}"
|
||||
RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
|
||||
)
|
||||
|
||||
install(
|
||||
|
||||
@@ -6,6 +6,7 @@ add_library(ftxui-modules)
|
||||
|
||||
target_sources(ftxui-modules
|
||||
PUBLIC FILE_SET CXX_MODULES FILES
|
||||
src/ftxui/ftxui.cppm
|
||||
src/ftxui/component.cppm
|
||||
src/ftxui/component/animation.cppm
|
||||
src/ftxui/component/captured_mouse.cppm
|
||||
|
||||
@@ -101,6 +101,5 @@ endfunction()
|
||||
|
||||
if (EMSCRIPTEN)
|
||||
string(APPEND CMAKE_CXX_FLAGS " -s USE_PTHREADS")
|
||||
string(APPEND CMAKE_EXE_LINKER_FLAGS " -s ASYNCIFY")
|
||||
string(APPEND CMAKE_EXE_LINKER_FLAGS " -s PROXY_TO_PTHREAD")
|
||||
endif()
|
||||
|
||||
@@ -19,11 +19,10 @@ add_executable(ftxui-tests
|
||||
src/ftxui/component/menu_test.cpp
|
||||
src/ftxui/component/modal_test.cpp
|
||||
src/ftxui/component/radiobox_test.cpp
|
||||
src/ftxui/util/ref_test.cpp
|
||||
src/ftxui/component/receiver_test.cpp
|
||||
src/ftxui/component/resizable_split_test.cpp
|
||||
src/ftxui/component/screen_interactive_test.cpp
|
||||
src/ftxui/component/slider_test.cpp
|
||||
src/ftxui/component/task_test.cpp
|
||||
src/ftxui/component/terminal_input_parser_test.cpp
|
||||
src/ftxui/component/toggle_test.cpp
|
||||
src/ftxui/dom/blink_test.cpp
|
||||
@@ -51,6 +50,7 @@ add_executable(ftxui-tests
|
||||
src/ftxui/dom/vbox_test.cpp
|
||||
src/ftxui/screen/color_test.cpp
|
||||
src/ftxui/screen/string_test.cpp
|
||||
src/ftxui/util/ref_test.cpp
|
||||
)
|
||||
|
||||
target_link_libraries(ftxui-tests
|
||||
|
||||
@@ -4,27 +4,16 @@
|
||||
> [!WARNING]
|
||||
> This feature is still in development, and the API may change in future releases.
|
||||
> Your contribution is needed to help us improve the compatibility and usability
|
||||
> of C++20 modules in FTXUI. If you encounter any issues or have suggestions,
|
||||
> of C++ modules in FTXUI. If you encounter any issues or have suggestions,
|
||||
> please open an issue.
|
||||
|
||||
FTXUI experimentally supports
|
||||
[C++20 modules](https://en.cppreference.com/w/cpp/language/modules) to reduce
|
||||
compilation times and improve code organization. Each header has a
|
||||
corresponding module.
|
||||
compilation times and improve code organization. Each part of the library has a
|
||||
corresponding module, split into partitions per each header.
|
||||
|
||||
**Example with CMake and Ninja**
|
||||
|
||||
|
||||
```cpp
|
||||
import ftxui;
|
||||
|
||||
int main() {
|
||||
auto screen = ftxui::ScreenInteractive::TerminalOutput();
|
||||
auto button = ftxui::Button("Click me", screen.QuitClosure());
|
||||
screen.Loop(button);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
Use the FTXUI_BUILD_MODULES option to build the FTXUI project itself to provide C++20 modules,
|
||||
for example with CMake and Ninja:
|
||||
|
||||
```sh
|
||||
cmake \
|
||||
@@ -34,11 +23,48 @@ cmake \
|
||||
|
||||
ninja
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> To use modules, you need a C++20 compatible compiler, CMake version 3.20 or
|
||||
> To use modules, you need a C++≥20 compatible compiler, CMake version 3.20 or
|
||||
> higher, and use a compatible generator like Ninja. Note that Makefile
|
||||
> generators **do not support modules**.
|
||||
|
||||
Then, in your own code you can consume the modules and code as normal:
|
||||
|
||||
```cpp
|
||||
import ftxui;
|
||||
|
||||
using ftxui::Button;
|
||||
using ftxui::ScreenInteractive;
|
||||
|
||||
int main() {
|
||||
auto screen = ScreenInteractive::TerminalOutput();
|
||||
auto button = Button("Click me", screen.QuitClosure());
|
||||
screen.Loop(button);
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
Note, the `ftxui` convenience module which simply pulls together all the modules:
|
||||
|
||||
```cpp
|
||||
export import ftxui.component;
|
||||
export import ftxui.dom;
|
||||
export import ftxui.screen;
|
||||
export import ftxui.util;
|
||||
```
|
||||
You can instead import only the module(s) you need if desired.
|
||||
|
||||
To properly find and link the modules with CMake, use `target_link_libraries` to get the right
|
||||
compiler, linker, etc. flags.
|
||||
|
||||
```cmake
|
||||
target_link_libraries(my_executable
|
||||
#...whatever...
|
||||
PRIVATE ftxui::modules
|
||||
)
|
||||
```
|
||||
|
||||
### Module list
|
||||
|
||||
The modules directly reference the corresponding header, or a group of related
|
||||
@@ -47,38 +73,6 @@ are available:
|
||||
|
||||
- `ftxui`
|
||||
- `ftxui.component`
|
||||
- `ftxui.component.Animation`
|
||||
- `ftxui.component.CapturedMouse`
|
||||
- `ftxui.component.Component`
|
||||
- `ftxui.component.ComponentBase`
|
||||
- `ftxui.component.ComponentOptions`
|
||||
- `ftxui.component.Event`
|
||||
- `ftxui.component.Loop`
|
||||
- `ftxui.component.Mouse`
|
||||
- `ftxui.component.Receiver`
|
||||
- `ftxui.component.ScreenInteractive`
|
||||
- `ftxui.component.Task`
|
||||
- `ftxui.dom`
|
||||
- `ftxui.dom.Canvas`
|
||||
- `ftxui.dom.Deprecated`
|
||||
- `ftxui.dom.Direction`
|
||||
- `ftxui.dom.Elements`
|
||||
- `ftxui.dom.FlexboxConfig`
|
||||
- `ftxui.dom.LinearGradient`
|
||||
- `ftxui.dom.Node`
|
||||
- `ftxui.dom.Requirement`
|
||||
- `ftxui.dom.Selection`
|
||||
- `ftxui.dom.Table`
|
||||
- `ftxui.screen`
|
||||
- `ftxui.screen.Box`
|
||||
- `ftxui.screen.Color`
|
||||
- `ftxui.screen.ColorInfo`
|
||||
- `ftxui.screen.Deprecated`
|
||||
- `ftxui.screen.Image`
|
||||
- `ftxui.screen.Pixel`
|
||||
- `ftxui.screen.Screen`
|
||||
- `ftxui.screen.String`
|
||||
- `ftxui.screen.Terminal`
|
||||
- `ftxui.util`
|
||||
- `ftxui.util.AutoReset`
|
||||
- `ftxui.util.Ref`
|
||||
- `ftxui.dom`
|
||||
- `ftxui.screen`
|
||||
- `ftxui.util`
|
||||
|
||||
@@ -2,16 +2,9 @@
|
||||
<!-- start footer part -->
|
||||
<!--BEGIN GENERATE_TREEVIEW-->
|
||||
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
|
||||
<ul>
|
||||
$navpath
|
||||
<li class="footer">$generatedby <a href="https://www.doxygen.org/index.html"><img class="footer" src="$relpath^doxygen.svg" width="104" height="31" alt="doxygen"/></a> $doxygenversion </li>
|
||||
</ul>
|
||||
</div>
|
||||
<!--END GENERATE_TREEVIEW-->
|
||||
<!--BEGIN !GENERATE_TREEVIEW-->
|
||||
<hr class="footer"/><address class="footer"><small>
|
||||
$generatedby <a href="https://www.doxygen.org/index.html"><img class="footer" src="$relpath^doxygen.svg" width="104" height="31" alt="doxygen"/></a> $doxygenversion
|
||||
</small></address>
|
||||
<!--END !GENERATE_TREEVIEW-->
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -92,6 +92,24 @@
|
||||
|
||||
</script>
|
||||
<script type="module">
|
||||
// Ignore non english pages and/or the main page.
|
||||
const excluded_lang = [
|
||||
"/de",
|
||||
"/es",
|
||||
"/fr",
|
||||
"/it",
|
||||
"/ja",
|
||||
"/ja",
|
||||
"/ko"
|
||||
"/ru",
|
||||
"/zh-CH",
|
||||
"/zh-TW",
|
||||
]
|
||||
if (excluded_lang.some(lang => window.location.pathname.startsWith(lang)) ||
|
||||
window.location.pathname.endsWith("index.html")) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Click on the navtree, except for the main page where this is already done
|
||||
// automatically.
|
||||
let delay = 0;
|
||||
|
||||
@@ -1,19 +1,99 @@
|
||||
@page installation_conan Conan
|
||||
@tableofcontents
|
||||
|
||||
Unofficial recipe for FTXUI exists on Conan Center:
|
||||
<https://conan.io/center/recipes/ftxui>
|
||||
FTXUI can be easily obtained and integrated into your project using the Conan package manager.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
First, ensure that Conan is installed on your system. If not, you can install it via pip:
|
||||
|
||||
```powershell
|
||||
pip install conan
|
||||
```
|
||||
Conan often works in tandem with CMake, so you will need to have CMake installed as well. Once you have confirmed both Conan and CMake are installed, create a project directory, for example, `ftxui-demo`:
|
||||
|
||||
```powershell
|
||||
mkdir C:\ftxui-demo
|
||||
cd C:\ftxui-demo
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
After ensuring your environment is set up correctly, create a Conan configuration file `conanfile.txt`. This file is used to declare your project's dependencies. The community-maintained package for FTXUI can be found on [Conan Center](https://conan.io/center/recipes/ftxui).
|
||||
|
||||
> [!note]
|
||||
> This is an unofficial recipe. That means it is not maintained by the FTXUI
|
||||
> team, but by the community. The package maintainers seems to actively update
|
||||
> the package to the latest version. Thanks to the maintainers for their work!
|
||||
> This is an unofficial build script. This means it is not maintained by the FTXUI
|
||||
> team but by the community. The package maintainer appears to actively update it
|
||||
> to the latest releases. Many thanks to the maintainer for their work!
|
||||
|
||||
@todo If you are familiar with the process, please consider adding an "official" build script to Conan Center.
|
||||
This could be a GitHub Action that automatically updates Conan Center upon new releases.
|
||||
|
||||
@todo Add instructions on how to use the conan recipe.
|
||||
```ini
|
||||
[requires]
|
||||
ftxui/6.0.2
|
||||
|
||||
@todo Please consider adding an "official" recipe to Conan Center if know how.
|
||||
It could be a github action that will automatically update the conan center
|
||||
when a new release is made.
|
||||
[generators]
|
||||
CMakeDeps
|
||||
CMakeToolchain
|
||||
|
||||
[layout]
|
||||
cmake_layout
|
||||
```
|
||||
|
||||
## Install Dependencies and Build
|
||||
|
||||
Once configured, run the following command to install FTXUI and its dependencies:
|
||||
|
||||
```powershell
|
||||
conan install . --output-folder=build --build=missing
|
||||
```
|
||||
|
||||
This will download and install `ftxui/6.0.2` along with all its dependencies from Conan's remote repositories.
|
||||
|
||||
After the installation completes, you can test it by creating a `demo.cpp` file in your project directory:
|
||||
|
||||
```cpp
|
||||
#include <ftxui/screen/screen.hpp>
|
||||
#include <ftxui/dom/elements.hpp>
|
||||
#include <iostream>
|
||||
|
||||
int main() {
|
||||
using namespace ftxui;
|
||||
auto document = hbox({
|
||||
text(" Hello "),
|
||||
text("FTXUI ") | bold | color(Color::Red),
|
||||
text(" world! ")
|
||||
});
|
||||
auto screen = Screen::Create(Dimension::Full(), Dimension::Fit(document));
|
||||
Render(screen, document);
|
||||
std::cout << screen.ToString() << std::endl;
|
||||
return 0;
|
||||
}
|
||||
```
|
||||
|
||||
If the test is successful, you can then create a `CMakeLists.txt` file in the project directory:
|
||||
|
||||
```cmake
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
project(ftxui-demo)
|
||||
|
||||
# Set the C++ standard
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
|
||||
# Find the FTXUI package installed via Conan
|
||||
find_package(ftxui CONFIG REQUIRED)
|
||||
|
||||
# Create the executable
|
||||
add_executable(demo demo.cpp)
|
||||
|
||||
# Link the executable to the FTXUI library
|
||||
target_link_libraries(demo PRIVATE ftxui::component)
|
||||
```
|
||||
|
||||
@todo 中国大陆在这方面的下载可能会受限制,需要一个替代的方案
|
||||
|
||||
---
|
||||
|
||||
<div class="section_buttons">
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ Clone and build the project using CMake:
|
||||
```bash
|
||||
git clone https://github.com/ArthurSonzogni/FTXUI.git
|
||||
cd FTXUI
|
||||
cmake -S . -B build -DFTXUI_ENABLE_INSTALL=ON -D
|
||||
cmake -S . -B build -D FTXUI_ENABLE_INSTALL=ON
|
||||
cmake --build build -j
|
||||
sudo cmake --install build
|
||||
```
|
||||
|
||||
58
doc/posix_pipe.md
Normal file
58
doc/posix_pipe.md
Normal file
@@ -0,0 +1,58 @@
|
||||
# POSIX Piped Input in FTXUI
|
||||
|
||||
> [!WARNING]
|
||||
> This feature works only on Linux and macOS. It is not supported on
|
||||
> Windows and WebAssembly.
|
||||
|
||||
## What is a POSIX Pipe?
|
||||
|
||||
A POSIX pipe is a way for two separate programs to communicate. One program sends its output directly as input to another program. Think of it like a one-way tube for data.
|
||||
|
||||
**Example:**
|
||||
|
||||
Imagine you want to list files and then filter them interactively.
|
||||
|
||||
- `ls`: Lists files.
|
||||
- `interactive_grep`: An FTXUI application that filters text and lets you type.
|
||||
|
||||
You can connect them with a pipe (`|`):
|
||||
|
||||
```bash
|
||||
ls -l | interactive_grep
|
||||
```
|
||||
|
||||
Here's what happens:
|
||||
1. `ls -l` lists files with details.
|
||||
2. The `|` sends this list directly to `interactive_grep`.
|
||||
3. `interactive_grep` receives the list and displays it. Because it's an FTXUI app, you can then type to filter the list, even though it received initial data from `ls`.
|
||||
|
||||
## How FTXUI Handles Piped Input
|
||||
|
||||
Now that you understand what a POSIX pipe is, let's look at how FTXUI uses them.
|
||||
|
||||
FTXUI lets your application read data from other programs (like from a pipe) while still allowing you to use your keyboard for interaction. This is useful for interactive command-line tools that process data.
|
||||
|
||||
Normally, FTXUI applications receive all input from `stdin`. However, when FTXUI detects that `stdin` is connected to the output of a pipe (meaning data is being piped into your application), it automatically switches to reading interactive keyboard input from `/dev/tty`. This ensures that your application can still receive user input even while processing piped data.
|
||||
|
||||
This feature is **turned on by default**.
|
||||
|
||||
If your FTXUI application needs to read piped data and also respond to keyboard input, you typically don't need to do anything special:
|
||||
|
||||
```cpp
|
||||
auto screen = ScreenInteractive::Fullscreen();
|
||||
// screen.HandlePipedInput(true); // This is enabled by default
|
||||
screen.Loop(component);
|
||||
```
|
||||
|
||||
|
||||
## Turning Off Piped Input
|
||||
|
||||
If you don't need this feature, or if it conflicts with your custom input handling, you can turn it off.
|
||||
|
||||
To disable it, call `HandlePipedInput(false)` before starting your application's main loop:
|
||||
|
||||
```cpp
|
||||
auto screen = ScreenInteractive::Fullscreen();
|
||||
screen.HandlePipedInput(false); // Turn off piped input handling
|
||||
screen.Loop(component);
|
||||
```
|
||||
@@ -15,16 +15,14 @@ add_subdirectory(component)
|
||||
add_subdirectory(dom)
|
||||
|
||||
if (EMSCRIPTEN)
|
||||
string(APPEND CMAKE_EXE_LINKER_FLAGS " -s ALLOW_MEMORY_GROWTH=1")
|
||||
target_link_options(component PUBLIC "SHELL: -s ALLOW_MEMORY_GROWTH=1")
|
||||
|
||||
get_property(EXAMPLES GLOBAL PROPERTY FTXUI::EXAMPLES)
|
||||
foreach(file
|
||||
"index.css"
|
||||
"index.html"
|
||||
"index.mjs"
|
||||
"index.css"
|
||||
"run_webassembly.py"
|
||||
"sw.js"
|
||||
"run_webassembly.py")
|
||||
)
|
||||
configure_file(${file} ${file})
|
||||
endforeach(file)
|
||||
endif()
|
||||
|
||||
@@ -39,6 +39,7 @@ example(radiobox)
|
||||
example(radiobox_in_frame)
|
||||
example(renderer)
|
||||
example(resizable_split)
|
||||
example(resizable_split_clamp)
|
||||
example(scrollbar)
|
||||
example(selection)
|
||||
example(slider)
|
||||
|
||||
@@ -1,9 +1,64 @@
|
||||
#include "ftxui/component/component.hpp"
|
||||
#include "ftxui/component/screen_interactive.hpp"
|
||||
// Copyright 2020 Arthur Sonzogni. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
#include <memory> // for shared_ptr, __shared_ptr_access
|
||||
#include <string> // for operator+, to_string
|
||||
|
||||
int main(){
|
||||
auto screen = ftxui::ScreenInteractive::Fullscreen();
|
||||
auto testComponent = ftxui::Renderer([](){return ftxui::text("test Component");});
|
||||
screen.Loop(testComponent);
|
||||
#include "ftxui/component/captured_mouse.hpp" // for ftxui
|
||||
#include "ftxui/component/component.hpp" // for Button, Horizontal, Renderer
|
||||
#include "ftxui/component/component_base.hpp" // for ComponentBase
|
||||
#include "ftxui/component/screen_interactive.hpp" // for ScreenInteractive
|
||||
#include "ftxui/dom/elements.hpp" // for separator, gauge, text, Element, operator|, vbox, border
|
||||
|
||||
using namespace ftxui;
|
||||
|
||||
// This is a helper function to create a button with a custom style.
|
||||
// The style is defined by a lambda function that takes an EntryState and
|
||||
// returns an Element.
|
||||
// We are using `center` to center the text inside the button, then `border` to
|
||||
// add a border around the button, and finally `flex` to make the button fill
|
||||
// the available space.
|
||||
ButtonOption Style() {
|
||||
auto option = ButtonOption::Animated();
|
||||
option.transform = [](const EntryState& s) {
|
||||
auto element = text(s.label);
|
||||
if (s.focused) {
|
||||
element |= bold;
|
||||
}
|
||||
return element | center | borderEmpty | flex;
|
||||
};
|
||||
return option;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int value = 50;
|
||||
|
||||
// clang-format off
|
||||
auto btn_dec_01 = Button("-1", [&] { value -= 1; }, Style());
|
||||
auto btn_inc_01 = Button("+1", [&] { value += 1; }, Style());
|
||||
auto btn_dec_10 = Button("-10", [&] { value -= 10; }, Style());
|
||||
auto btn_inc_10 = Button("+10", [&] { value += 10; }, Style());
|
||||
// clang-format on
|
||||
|
||||
// The tree of components. This defines how to navigate using the keyboard.
|
||||
// The selected `row` is shared to get a grid layout.
|
||||
int row = 0;
|
||||
auto buttons = Container::Vertical({
|
||||
Container::Horizontal({btn_dec_01, btn_inc_01}, &row) | flex,
|
||||
Container::Horizontal({btn_dec_10, btn_inc_10}, &row) | flex,
|
||||
});
|
||||
|
||||
// Modify the way to render them on screen:
|
||||
auto component = Renderer(buttons, [&] {
|
||||
return vbox({
|
||||
text("value = " + std::to_string(value)),
|
||||
separator(),
|
||||
buttons->Render() | flex,
|
||||
}) |
|
||||
flex | border;
|
||||
});
|
||||
|
||||
auto screen = ScreenInteractive::FitComponent();
|
||||
screen.Loop(component);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -133,8 +133,9 @@ int main() {
|
||||
float dy = 50.f;
|
||||
ys[x] = int(dy + 20 * cos(dx * 0.14) + 10 * sin(dx * 0.42));
|
||||
}
|
||||
for (int x = 1; x < 99; x++)
|
||||
for (int x = 1; x < 99; x++) {
|
||||
c.DrawPointLine(x, ys[x], x + 1, ys[x + 1]);
|
||||
}
|
||||
|
||||
return canvas(std::move(c));
|
||||
});
|
||||
|
||||
@@ -82,10 +82,12 @@ int main() {
|
||||
size(WIDTH, EQUAL, dimx) | size(HEIGHT, EQUAL, dimy) |
|
||||
bgcolor(Color::HSV(index * 25, 255, 255)) |
|
||||
color(Color::Black);
|
||||
if (element_xflex_grow)
|
||||
if (element_xflex_grow) {
|
||||
element = element | xflex_grow;
|
||||
if (element_yflex_grow)
|
||||
}
|
||||
if (element_yflex_grow) {
|
||||
element = element | yflex_grow;
|
||||
}
|
||||
return element;
|
||||
};
|
||||
|
||||
@@ -119,10 +121,12 @@ int main() {
|
||||
|
||||
group = group | notflex;
|
||||
|
||||
if (!group_xflex_grow)
|
||||
if (!group_xflex_grow) {
|
||||
group = hbox(group, filler());
|
||||
if (!group_yflex_grow)
|
||||
}
|
||||
if (!group_yflex_grow) {
|
||||
group = vbox(group, filler());
|
||||
}
|
||||
|
||||
group = group | flex;
|
||||
return group;
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
#include <atomic> // for atomic
|
||||
#include <chrono> // for operator""s, chrono_literals
|
||||
#include <cmath> // for sin
|
||||
#include <ftxui/component/loop.hpp>
|
||||
#include <functional> // for ref, reference_wrapper, function
|
||||
#include <memory> // for allocator, shared_ptr, __shared_ptr_access
|
||||
#include <string> // for string, basic_string, char_traits, operator+, to_string
|
||||
@@ -269,7 +270,7 @@ int main() {
|
||||
auto spinner_tab_renderer = Renderer([&] {
|
||||
Elements entries;
|
||||
for (int i = 0; i < 22; ++i) {
|
||||
entries.push_back(spinner(i, shift / 2) | bold |
|
||||
entries.push_back(spinner(i, shift / 5) | bold |
|
||||
size(WIDTH, GREATER_THAN, 2) | border);
|
||||
}
|
||||
return hflow(std::move(entries));
|
||||
@@ -512,24 +513,20 @@ int main() {
|
||||
});
|
||||
});
|
||||
|
||||
std::atomic<bool> refresh_ui_continue = true;
|
||||
std::thread refresh_ui([&] {
|
||||
while (refresh_ui_continue) {
|
||||
using namespace std::chrono_literals;
|
||||
std::this_thread::sleep_for(0.05s);
|
||||
// The |shift| variable belong to the main thread. `screen.Post(task)`
|
||||
// will execute the update on the thread where |screen| lives (e.g. the
|
||||
// main thread). Using `screen.Post(task)` is threadsafe.
|
||||
screen.Post([&] { shift++; });
|
||||
// After updating the state, request a new frame to be drawn. This is done
|
||||
// by simulating a new "custom" event to be handled.
|
||||
screen.Post(Event::Custom);
|
||||
}
|
||||
});
|
||||
Loop loop(&screen, main_renderer);
|
||||
while (!loop.HasQuitted()) {
|
||||
// Update the state of the application.
|
||||
shift++;
|
||||
|
||||
screen.Loop(main_renderer);
|
||||
refresh_ui_continue = false;
|
||||
refresh_ui.join();
|
||||
// Request a new frame to be drawn.
|
||||
screen.RequestAnimationFrame();
|
||||
|
||||
// Execute events, and draw the next frame.
|
||||
loop.RunOnce();
|
||||
|
||||
// Sleep for a short duration to control the frame rate (60 FPS).
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1000 / 60));
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -22,10 +22,12 @@ MenuEntryOption Colored(ftxui::Color c) {
|
||||
option.transform = [c](EntryState state) {
|
||||
state.label = (state.active ? "> " : " ") + state.label;
|
||||
Element e = text(state.label) | color(c);
|
||||
if (state.focused)
|
||||
if (state.focused) {
|
||||
e = e | inverted;
|
||||
if (state.active)
|
||||
}
|
||||
if (state.active) {
|
||||
e = e | bold;
|
||||
}
|
||||
return e;
|
||||
};
|
||||
return option;
|
||||
|
||||
@@ -17,8 +17,9 @@ int main() {
|
||||
std::vector<std::string> entries;
|
||||
int selected = 0;
|
||||
|
||||
for (int i = 0; i < 30; ++i)
|
||||
for (int i = 0; i < 30; ++i) {
|
||||
entries.push_back("Entry " + std::to_string(i));
|
||||
}
|
||||
auto radiobox = Menu(&entries, &selected);
|
||||
auto renderer = Renderer(radiobox, [&] {
|
||||
return radiobox->Render() | vscroll_indicator | frame |
|
||||
|
||||
@@ -17,8 +17,9 @@ int main() {
|
||||
std::vector<std::string> entries;
|
||||
int selected = 0;
|
||||
|
||||
for (int i = 0; i < 100; ++i)
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
entries.push_back(std::to_string(i));
|
||||
}
|
||||
auto radiobox = Menu(&entries, &selected, MenuOption::Horizontal());
|
||||
auto renderer = Renderer(
|
||||
radiobox, [&] { return radiobox->Render() | hscroll_indicator | frame; });
|
||||
|
||||
@@ -116,10 +116,12 @@ Component VMenu1(std::vector<std::string>* entries, int* selected) {
|
||||
option.entries_option.transform = [](EntryState state) {
|
||||
state.label = (state.active ? "> " : " ") + state.label;
|
||||
Element e = text(state.label);
|
||||
if (state.focused)
|
||||
if (state.focused) {
|
||||
e = e | bgcolor(Color::Blue);
|
||||
if (state.active)
|
||||
}
|
||||
if (state.active) {
|
||||
e = e | bold;
|
||||
}
|
||||
return e;
|
||||
};
|
||||
return Menu(entries, selected, option);
|
||||
@@ -130,10 +132,12 @@ Component VMenu2(std::vector<std::string>* entries, int* selected) {
|
||||
option.entries_option.transform = [](EntryState state) {
|
||||
state.label += (state.active ? " <" : " ");
|
||||
Element e = hbox(filler(), text(state.label));
|
||||
if (state.focused)
|
||||
if (state.focused) {
|
||||
e = e | bgcolor(Color::Red);
|
||||
if (state.active)
|
||||
}
|
||||
if (state.active) {
|
||||
e = e | bold;
|
||||
}
|
||||
return e;
|
||||
};
|
||||
return Menu(entries, selected, option);
|
||||
@@ -144,13 +148,16 @@ Component VMenu3(std::vector<std::string>* entries, int* selected) {
|
||||
option.entries_option.transform = [](EntryState state) {
|
||||
Element e = state.active ? text("[" + state.label + "]")
|
||||
: text(" " + state.label + " ");
|
||||
if (state.focused)
|
||||
if (state.focused) {
|
||||
e = e | bold;
|
||||
}
|
||||
|
||||
if (state.focused)
|
||||
if (state.focused) {
|
||||
e = e | color(Color::Blue);
|
||||
if (state.active)
|
||||
}
|
||||
if (state.active) {
|
||||
e = e | bold;
|
||||
}
|
||||
return e;
|
||||
};
|
||||
return Menu(entries, selected, option);
|
||||
@@ -245,10 +252,12 @@ Component HMenu5(std::vector<std::string>* entries, int* selected) {
|
||||
animation::easing::ElasticOut);
|
||||
option.entries_option.transform = [](EntryState state) {
|
||||
Element e = text(state.label) | hcenter | flex;
|
||||
if (state.active && state.focused)
|
||||
if (state.active && state.focused) {
|
||||
e = e | bold;
|
||||
if (!state.focused && !state.active)
|
||||
}
|
||||
if (!state.focused && !state.active) {
|
||||
e = e | dim;
|
||||
}
|
||||
return e;
|
||||
};
|
||||
option.underline.color_inactive = Color::Default;
|
||||
|
||||
@@ -20,8 +20,9 @@ using namespace ftxui;
|
||||
Component DummyComponent(int id) {
|
||||
return Renderer([id](bool focused) {
|
||||
auto t = text("component " + std::to_string(id));
|
||||
if (focused)
|
||||
if (focused) {
|
||||
t = t | inverted;
|
||||
}
|
||||
return t;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -17,8 +17,9 @@ int main() {
|
||||
std::vector<std::string> entries;
|
||||
int selected = 0;
|
||||
|
||||
for (int i = 0; i < 30; ++i)
|
||||
for (int i = 0; i < 30; ++i) {
|
||||
entries.push_back("RadioBox " + std::to_string(i));
|
||||
}
|
||||
auto radiobox = Radiobox(&entries, &selected);
|
||||
auto renderer = Renderer(radiobox, [&] {
|
||||
return radiobox->Render() | vscroll_indicator | frame |
|
||||
|
||||
@@ -19,10 +19,11 @@ int main() {
|
||||
|
||||
// 1. Example of focusable renderer:
|
||||
auto renderer_focusable = Renderer([](bool focused) {
|
||||
if (focused)
|
||||
if (focused) {
|
||||
return text("FOCUSABLE RENDERER()") | center | bold | border;
|
||||
else
|
||||
} else {
|
||||
return text(" Focusable renderer() ") | center | border;
|
||||
}
|
||||
});
|
||||
|
||||
// 2. Examples of a non focusable renderer.
|
||||
@@ -33,10 +34,11 @@ int main() {
|
||||
// 3. Renderer can wrap other components to redefine their Render() function.
|
||||
auto button = Button("Wrapped quit button", screen.ExitLoopClosure());
|
||||
auto renderer_wrap = Renderer(button, [&] {
|
||||
if (button->Focused())
|
||||
if (button->Focused()) {
|
||||
return button->Render() | bold | color(Color::Red);
|
||||
else
|
||||
} else {
|
||||
return button->Render();
|
||||
}
|
||||
});
|
||||
|
||||
// Let's renderer everyone:
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
// the LICENSE file.
|
||||
#include <memory> // for shared_ptr, allocator, __shared_ptr_access
|
||||
|
||||
#include "ftxui/component/captured_mouse.hpp" // for ftxui
|
||||
#include "ftxui/component/component.hpp" // for Renderer, ResizableSplitBottom, ResizableSplitLeft, ResizableSplitRight, ResizableSplitTop
|
||||
#include "ftxui/component/component_base.hpp" // for ComponentBase
|
||||
#include "ftxui/component/screen_interactive.hpp" // for ScreenInteractive
|
||||
@@ -14,17 +13,24 @@ using namespace ftxui;
|
||||
int main() {
|
||||
auto screen = ScreenInteractive::Fullscreen();
|
||||
|
||||
auto middle = Renderer([] { return text("middle") | center; });
|
||||
auto left = Renderer([] { return text("Left") | center; });
|
||||
auto right = Renderer([] { return text("right") | center; });
|
||||
auto top = Renderer([] { return text("top") | center; });
|
||||
auto bottom = Renderer([] { return text("bottom") | center; });
|
||||
|
||||
// State:
|
||||
int left_size = 20;
|
||||
int right_size = 20;
|
||||
int top_size = 10;
|
||||
int bottom_size = 10;
|
||||
|
||||
// Renderers:
|
||||
auto RendererInfo = [](const std::string& name, int* size) {
|
||||
return Renderer([name, size] {
|
||||
return text(name + ": " + std::to_string(*size)) | center;
|
||||
});
|
||||
};
|
||||
auto middle = Renderer([] { return text("Middle") | center; });
|
||||
auto left = RendererInfo("Left", &left_size);
|
||||
auto right = RendererInfo("Right", &right_size);
|
||||
auto top = RendererInfo("Top", &top_size);
|
||||
auto bottom = RendererInfo("Bottom", &bottom_size);
|
||||
|
||||
auto container = middle;
|
||||
container = ResizableSplitLeft(left, container, &left_size);
|
||||
container = ResizableSplitRight(right, container, &right_size);
|
||||
|
||||
43
examples/component/resizable_split_clamp.cpp
Normal file
43
examples/component/resizable_split_clamp.cpp
Normal file
@@ -0,0 +1,43 @@
|
||||
// Copyright 2025 Arthur Sonzogni. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
#include <memory> // for shared_ptr, allocator, __shared_ptr_access
|
||||
|
||||
#include "ftxui/component/component.hpp" // for Renderer, ResizableSplitBottom, ResizableSplitLeft, ResizableSplitRight, ResizableSplitTop
|
||||
#include "ftxui/component/component_base.hpp" // for ComponentBase
|
||||
#include "ftxui/component/screen_interactive.hpp" // for ScreenInteractive
|
||||
#include "ftxui/dom/elements.hpp" // for Element, operator|, text, center, border
|
||||
|
||||
using namespace ftxui;
|
||||
|
||||
int main() {
|
||||
auto screen = ScreenInteractive::Fullscreen();
|
||||
|
||||
// State:
|
||||
int size = 40;
|
||||
int size_min = 10;
|
||||
int size_max = 80;
|
||||
|
||||
// Renderers:
|
||||
auto split = ResizableSplit({
|
||||
.main = Renderer([] { return text("Left") | center; }),
|
||||
.back = Renderer([] { return text("Right") | center; }),
|
||||
.direction = Direction::Left,
|
||||
.main_size = &size,
|
||||
.min = &size_min,
|
||||
.max = &size_max,
|
||||
});
|
||||
|
||||
auto renderer = Renderer(split, [&] {
|
||||
return window(text("Drag the separator with the mouse"),
|
||||
vbox({
|
||||
text("Min: " + std::to_string(size_min)),
|
||||
text("Max: " + std::to_string(size_max)),
|
||||
text("Size: " + std::to_string(size)),
|
||||
separator(),
|
||||
split->Render() | flex,
|
||||
}));
|
||||
});
|
||||
|
||||
screen.Loop(renderer);
|
||||
}
|
||||
@@ -32,10 +32,12 @@ int main() {
|
||||
|
||||
// Plot a function:
|
||||
std::vector<int> ys(100);
|
||||
for (int x = 0; x < 100; x++)
|
||||
for (int x = 0; x < 100; x++) {
|
||||
ys[x] = int(80 + 20 * cos(x * 0.2));
|
||||
for (int x = 0; x < 99; x++)
|
||||
}
|
||||
for (int x = 0; x < 99; x++) {
|
||||
c.DrawPointLine(x, ys[x], x + 1, ys[x + 1], Color::Red);
|
||||
}
|
||||
|
||||
auto document = canvas(&c) | border;
|
||||
|
||||
|
||||
@@ -86,8 +86,9 @@ int main() {
|
||||
|
||||
auto render = [&]() {
|
||||
std::vector<Element> entries;
|
||||
for (auto& task : displayed_task)
|
||||
for (auto& task : displayed_task) {
|
||||
entries.push_back(renderTask(task));
|
||||
}
|
||||
|
||||
return vbox({
|
||||
// List of tasks.
|
||||
@@ -138,8 +139,9 @@ int main() {
|
||||
std::this_thread::sleep_for(0.01s);
|
||||
|
||||
// Exit
|
||||
if (nb_active + nb_queued == 0)
|
||||
if (nb_active + nb_queued == 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Update the model for the next frame.
|
||||
updateModel();
|
||||
|
||||
@@ -21,8 +21,9 @@ int main() {
|
||||
for (int index = 0; index < 200; ++index) {
|
||||
std::vector<Element> entries;
|
||||
for (int i = 0; i < 23; ++i) {
|
||||
if (i != 0)
|
||||
if (i != 0) {
|
||||
entries.push_back(separator());
|
||||
}
|
||||
entries.push_back( //
|
||||
hbox({
|
||||
text(std::to_string(i)) | size(WIDTH, EQUAL, 2),
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
@import url(https://fonts.googleapis.com/css?family=Khula:700);
|
||||
|
||||
html {
|
||||
--toc-width: 250px;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color:#EEE;
|
||||
padding:0px;
|
||||
margin:0px;
|
||||
background-color: #EEE;
|
||||
padding: 0px;
|
||||
margin: 0px;
|
||||
font-family: Khula, Helvetica, sans-serif;
|
||||
font-size: 130%;
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width:1300px;
|
||||
max-width: 1300px;
|
||||
margin: auto;
|
||||
padding: 10px;
|
||||
}
|
||||
@@ -30,45 +34,48 @@ a:hover {
|
||||
|
||||
h1 {
|
||||
text-decoration: underline;
|
||||
width:100%;
|
||||
background-color: rgba(100,100,255,0.5);
|
||||
width: 100%;
|
||||
background-color: rgba(100, 100, 255, 0.5);
|
||||
padding: 10px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
|
||||
#selectExample {
|
||||
flex:1;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
#selectExample, #selectExample option {
|
||||
#selectExample,
|
||||
#selectExample option {
|
||||
font-size: 16px;
|
||||
font-family: sans-serif;
|
||||
font-weight: 700;
|
||||
line-height: 1.3;
|
||||
border:0px;
|
||||
border: 0px;
|
||||
background-color: #bbb;
|
||||
color:black;
|
||||
color: black;
|
||||
}
|
||||
|
||||
#selectExample:focus {
|
||||
outline:none;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
#terminal {
|
||||
width:100%;
|
||||
width: 100%;
|
||||
height 500px;
|
||||
height: calc(clamp(200px, 100vh - 300px, 900px));
|
||||
overflow: hidden;
|
||||
border:none;
|
||||
background-color:black;
|
||||
border: none;
|
||||
padding: 10px;
|
||||
margin: 10px;
|
||||
}
|
||||
|
||||
#terminalContainer {
|
||||
overflow: hidden;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0px 2px 10px 0px rgba(0,0,0,0.75),
|
||||
0px 2px 80px 0px rgba(0,0,0,0.50);
|
||||
box-shadow: 0px 2px 10px 0px rgba(0, 0, 0, 0.75),
|
||||
0px 2px 80px 0px rgba(0, 0, 0, 0.50);
|
||||
background-color: black;
|
||||
}
|
||||
|
||||
.fakeButtons {
|
||||
@@ -76,7 +83,7 @@ h1 {
|
||||
width: 10px;
|
||||
border-radius: 50%;
|
||||
border: 1px solid #000;
|
||||
margin:6px;
|
||||
margin: 6px;
|
||||
background-color: #ff3b47;
|
||||
border-color: #9d252b;
|
||||
display: inline-block;
|
||||
@@ -95,13 +102,79 @@ h1 {
|
||||
}
|
||||
|
||||
.fakeMenu {
|
||||
display:flex;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
width:100%;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
height: 25px;
|
||||
background-color: #bbb;
|
||||
color:black;
|
||||
color: black;
|
||||
margin: 0 auto;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.toc-container {
|
||||
position: fixed;
|
||||
left: 0;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
width: var(--toc-width);
|
||||
background: white;
|
||||
padding: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.toc-title {
|
||||
font-weight: bold;
|
||||
margin-bottom: 5px;
|
||||
font-size: 0.9em;
|
||||
color: #555;
|
||||
|
||||
position: sticky;
|
||||
transition: position 1.0s ease-in-out;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
padding: 20px;
|
||||
margin: 0;
|
||||
|
||||
border-bottom: 1px solid #ddd;
|
||||
|
||||
/* Gradient background for the title */
|
||||
background-color: #f0f0f0;
|
||||
}
|
||||
|
||||
.toc-item {
|
||||
padding: 3px 8px;
|
||||
margin: 0;
|
||||
cursor: pointer;
|
||||
font-size: 0.85em;
|
||||
border-radius: 3px;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.toc-item:hover {
|
||||
background: #f0f0f0;
|
||||
}
|
||||
|
||||
.toc-item.selected {
|
||||
background: #e0e0e0;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
.toc-container {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.page {
|
||||
margin-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 1025px) {
|
||||
.page {
|
||||
margin-left: calc(var(--toc-width) + 20px);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,13 +9,18 @@
|
||||
<script type="module" src="index.mjs"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="toc-container">
|
||||
<div class="toc-list"></div>
|
||||
</div>
|
||||
<script id="example_script"></script>
|
||||
|
||||
<div class="page">
|
||||
<p>
|
||||
<a href="https://github.com/ArthurSonzogni/FTXUI">FTXUI</a> is a simple
|
||||
functional C++ library for terminal user interface. <br/>
|
||||
This showcases the: <a href="https://github.com/ArthurSonzogni/FTXUI/tree/master/examples">./example/</a> folder. <br/>
|
||||
This showcases the: <a
|
||||
href="https://github.com/ArthurSonzogni/FTXUI/tree/master/examples">./example/</a>
|
||||
folder. See <a id="source">source</a>.
|
||||
</p>
|
||||
|
||||
<div id="terminalContainer">
|
||||
|
||||
@@ -55,7 +55,7 @@ const stdout = code => {
|
||||
const stderr = code => {
|
||||
if (code == 0 || code == 10) {
|
||||
console.error(String.fromCodePoint(...stderr_buffer));
|
||||
stderr_buffer = [];
|
||||
stderr_buffer.length = 0;
|
||||
} else {
|
||||
stderr_buffer.push(code)
|
||||
}
|
||||
@@ -89,12 +89,72 @@ window.Module = {
|
||||
const resize_observer = new ResizeObserver(resize_handler);
|
||||
resize_observer.observe(term_element);
|
||||
resize_handler();
|
||||
|
||||
// Disable scrollbar
|
||||
//term.write('\x1b[?47h')
|
||||
},
|
||||
};
|
||||
|
||||
const source = document.querySelector("#source");
|
||||
source.href = "https://github.com/ArthurSonzogni/FTXUI/blob/main/examples/" + example + ".cpp";
|
||||
|
||||
const words = example.split('/')
|
||||
words[1] = "ftxui_example_" + words[1] + ".js"
|
||||
document.querySelector("#example_script").src = words.join('/');
|
||||
|
||||
|
||||
// Table of Contents (TOC) for quick navigation.
|
||||
|
||||
// Get select element
|
||||
const selectEl = document.querySelector('select#selectExample');
|
||||
if (!selectEl) {
|
||||
console.error('select#selectExample not found');
|
||||
} else {
|
||||
// Get TOC container
|
||||
const tocContainer = document.querySelector('.toc-container');
|
||||
const tocList = tocContainer.querySelector('.toc-list');
|
||||
|
||||
// Group options by directory
|
||||
const groupedOptions = Array.from(selectEl.options).reduce((acc, option) => {
|
||||
const [dir, file] = option.text.split('/');
|
||||
if (!acc[dir]) {
|
||||
acc[dir] = [];
|
||||
}
|
||||
acc[dir].push({ option, file });
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
// Generate TOC items
|
||||
for (const dir in groupedOptions) {
|
||||
const dirContainer = document.createElement('div');
|
||||
|
||||
const dirHeader = document.createElement('div');
|
||||
dirHeader.textContent = dir;
|
||||
dirHeader.className = 'toc-title';
|
||||
dirContainer.appendChild(dirHeader);
|
||||
|
||||
groupedOptions[dir].forEach(({ option, file }) => {
|
||||
const tocItem = document.createElement('div');
|
||||
tocItem.textContent = file;
|
||||
tocItem.className = 'toc-item';
|
||||
|
||||
if (selectEl.options[selectEl.selectedIndex].value === option.value) {
|
||||
tocItem.classList.add('selected');
|
||||
}
|
||||
|
||||
// Click handler
|
||||
tocItem.addEventListener('click', () => {
|
||||
for(let i=0; i<selectEl.options.length; ++i) {
|
||||
if (selectEl.options[i].value == option.value) {
|
||||
selectEl.selectedIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
history.pushState({}, "", "?file=" + option.value);
|
||||
location.reload();
|
||||
});
|
||||
|
||||
dirContainer.appendChild(tocItem);
|
||||
});
|
||||
|
||||
tocList.appendChild(dirContainer);
|
||||
}
|
||||
}''
|
||||
|
||||
12
flake.lock
generated
12
flake.lock
generated
@@ -5,11 +5,11 @@
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1694529238,
|
||||
"narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=",
|
||||
"lastModified": 1731533236,
|
||||
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
|
||||
"owner": "numtide",
|
||||
"repo": "flake-utils",
|
||||
"rev": "ff7b65b44d01cf9ba6a71320833626af21126384",
|
||||
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -20,11 +20,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1697915759,
|
||||
"narHash": "sha256-WyMj5jGcecD+KC8gEs+wFth1J1wjisZf8kVZH13f1Zo=",
|
||||
"lastModified": 1765644376,
|
||||
"narHash": "sha256-yqHBL2wYGwjGL2GUF2w3tofWl8qO9tZEuI4wSqbCrtE=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "51d906d2341c9e866e48c2efcaac0f2d70bfd43e",
|
||||
"rev": "23735a82a828372c4ef92c660864e82fbe2f5fbe",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
12
flake.nix
12
flake.nix
@@ -12,15 +12,9 @@
|
||||
let llvm = pkgs.llvmPackages_latest; in
|
||||
{
|
||||
packages = rec {
|
||||
default = pkgs.stdenv.mkDerivation rec {
|
||||
pname = "ftxui";
|
||||
version = "v4.0.0";
|
||||
src = pkgs.fetchFromGitHub {
|
||||
owner = "ArthurSonzogni";
|
||||
repo = "FTXUI";
|
||||
rev = version;
|
||||
sha256 = "sha256-3kAhHDUwzwdvHc8JZAcA14tGqa6w69qrN1JXhSxNBQY=";
|
||||
};
|
||||
default = pkgs.stdenv.mkDerivation {
|
||||
name = "ftxui";
|
||||
src = ./.;
|
||||
|
||||
nativeBuildInputs = [
|
||||
pkgs.cmake
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#include <memory> // for make_shared, shared_ptr
|
||||
#include <utility> // for forward
|
||||
|
||||
#include <ftxui/util/warn_windows_macro.hpp>
|
||||
#include "ftxui/component/component_base.hpp" // for Component, Components
|
||||
#include "ftxui/component/component_options.hpp" // for ButtonOption, CheckboxOption, MenuOption
|
||||
#include "ftxui/dom/elements.hpp" // for Element
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
#include <ftxui/dom/direction.hpp> // for Direction, Direction::Left, Direction::Right, Direction::Down
|
||||
#include <ftxui/dom/elements.hpp> // for Element, separator
|
||||
#include <ftxui/util/ref.hpp> // for Ref, ConstRef, StringRef
|
||||
#include <ftxui/util/warn_windows_macro.hpp>
|
||||
#include <functional> // for function
|
||||
#include <limits> // for numeric_limits
|
||||
#include <string> // for string
|
||||
|
||||
#include "ftxui/component/component_base.hpp" // for Component
|
||||
@@ -216,6 +218,10 @@ struct ResizableSplitOption {
|
||||
(direction() == Direction::Left || direction() == Direction::Right) ? 20
|
||||
: 10;
|
||||
std::function<Element()> separator_func = [] { return ::ftxui::separator(); };
|
||||
|
||||
// Constraints on main_size:
|
||||
Ref<int> min = 0;
|
||||
Ref<int> max = std::numeric_limits<int>::max();
|
||||
};
|
||||
|
||||
// @brief Option for the `Slider` component.
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
#include <ftxui/component/mouse.hpp> // for Mouse
|
||||
#include <string> // for string, operator==
|
||||
#include <string_view>
|
||||
|
||||
namespace ftxui {
|
||||
|
||||
@@ -28,13 +29,13 @@ class ComponentBase;
|
||||
/// @ingroup component
|
||||
struct Event {
|
||||
// --- Constructor section ---------------------------------------------------
|
||||
static Event Character(std::string);
|
||||
static Event Character(std::string_view);
|
||||
static Event Character(char);
|
||||
static Event Character(wchar_t);
|
||||
static Event Special(std::string);
|
||||
static Event Mouse(std::string, Mouse mouse);
|
||||
static Event CursorPosition(std::string, int x, int y); // Internal
|
||||
static Event CursorShape(std::string, int shape); // Internal
|
||||
static Event Special(std::string_view);
|
||||
static Event Mouse(std::string_view, Mouse mouse);
|
||||
static Event CursorPosition(std::string_view, int x, int y); // Internal
|
||||
static Event CursorShape(std::string_view, int shape); // Internal
|
||||
|
||||
// --- Arrow ---
|
||||
static const Event ArrowLeft;
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include <algorithm> // for copy, max
|
||||
#include <atomic> // for atomic, __atomic_base
|
||||
#include <condition_variable> // for condition_variable
|
||||
#include <ftxui/util/warn_windows_macro.hpp>
|
||||
#include <memory> // for unique_ptr, make_unique
|
||||
#include <mutex> // for mutex, unique_lock
|
||||
#include <queue> // for queue
|
||||
@@ -14,6 +15,8 @@
|
||||
|
||||
namespace ftxui {
|
||||
|
||||
// Deprecated
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// Initialization:
|
||||
@@ -39,17 +42,24 @@ namespace ftxui {
|
||||
// Receiver::Receive() returns true when there are no more senders.
|
||||
|
||||
// clang-format off
|
||||
// Deprecated:
|
||||
template<class T> class SenderImpl;
|
||||
// Deprecated:
|
||||
template<class T> class ReceiverImpl;
|
||||
// Deprecated:
|
||||
|
||||
// Deprecated:
|
||||
template<class T> using Sender = std::unique_ptr<SenderImpl<T>>;
|
||||
// Deprecated:
|
||||
template<class T> using Receiver = std::unique_ptr<ReceiverImpl<T>>;
|
||||
// Deprecated:
|
||||
template<class T> Receiver<T> MakeReceiver();
|
||||
// clang-format on
|
||||
|
||||
// ---- Implementation part ----
|
||||
|
||||
template <class T>
|
||||
// Deprecated:
|
||||
class SenderImpl {
|
||||
public:
|
||||
SenderImpl(const SenderImpl&) = delete;
|
||||
|
||||
@@ -5,11 +5,9 @@
|
||||
#define FTXUI_COMPONENT_SCREEN_INTERACTIVE_HPP
|
||||
|
||||
#include <atomic> // for atomic
|
||||
#include <ftxui/component/receiver.hpp> // for Receiver, Sender
|
||||
#include <functional> // for function
|
||||
#include <memory> // for shared_ptr
|
||||
#include <string> // for string
|
||||
#include <thread> // for thread
|
||||
|
||||
#include "ftxui/component/animation.hpp" // for TimePoint
|
||||
#include "ftxui/component/captured_mouse.hpp" // for CapturedMouse
|
||||
@@ -26,6 +24,10 @@ struct Event;
|
||||
using Component = std::shared_ptr<ComponentBase>;
|
||||
class ScreenInteractivePrivate;
|
||||
|
||||
namespace task {
|
||||
class TaskRunner;
|
||||
}
|
||||
|
||||
/// @brief ScreenInteractive is a `Screen` that can handle events, run a main
|
||||
/// loop, and manage components.
|
||||
///
|
||||
@@ -40,8 +42,12 @@ class ScreenInteractive : public Screen {
|
||||
static ScreenInteractive FitComponent();
|
||||
static ScreenInteractive TerminalOutput();
|
||||
|
||||
// Destructor.
|
||||
~ScreenInteractive() override;
|
||||
|
||||
// Options. Must be called before Loop().
|
||||
void TrackMouse(bool enable = true);
|
||||
void HandlePipedInput(bool enable = true);
|
||||
|
||||
// Return the currently active screen, nullptr if none.
|
||||
static ScreenInteractive* Active();
|
||||
@@ -95,8 +101,14 @@ class ScreenInteractive : public Screen {
|
||||
void Draw(Component component);
|
||||
void ResetCursorPosition();
|
||||
|
||||
void InstallPipedInputHandling();
|
||||
|
||||
void Signal(int signal);
|
||||
|
||||
void FetchTerminalEvents();
|
||||
|
||||
void PostAnimationTask();
|
||||
|
||||
ScreenInteractive* suspended_screen_ = nullptr;
|
||||
enum class Dimension {
|
||||
FitComponent,
|
||||
@@ -108,20 +120,16 @@ class ScreenInteractive : public Screen {
|
||||
int dimx,
|
||||
int dimy,
|
||||
bool use_alternative_screen);
|
||||
|
||||
const Dimension dimension_;
|
||||
const bool use_alternative_screen_;
|
||||
|
||||
bool track_mouse_ = true;
|
||||
|
||||
Sender<Task> task_sender_;
|
||||
Receiver<Task> task_receiver_;
|
||||
|
||||
std::string set_cursor_position;
|
||||
std::string reset_cursor_position;
|
||||
|
||||
std::atomic<bool> quit_{false};
|
||||
std::thread event_listener_;
|
||||
std::thread animation_listener_;
|
||||
bool animation_requested_ = false;
|
||||
animation::TimePoint previous_animation_time_;
|
||||
|
||||
@@ -137,6 +145,11 @@ class ScreenInteractive : public Screen {
|
||||
bool force_handle_ctrl_c_ = true;
|
||||
bool force_handle_ctrl_z_ = true;
|
||||
|
||||
// Piped input handling state (POSIX only)
|
||||
bool handle_piped_input_ = true;
|
||||
// File descriptor for /dev/tty, used for piped input handling.
|
||||
int tty_fd_ = -1;
|
||||
|
||||
// The style of the cursor to restore on exit.
|
||||
int cursor_reset_shape_ = 1;
|
||||
|
||||
@@ -156,8 +169,14 @@ class ScreenInteractive : public Screen {
|
||||
std::unique_ptr<Selection> selection_;
|
||||
std::function<void()> selection_on_change_;
|
||||
|
||||
// PIMPL private implementation idiom (Pimpl).
|
||||
struct Internal;
|
||||
std::unique_ptr<Internal> internal_;
|
||||
|
||||
friend class Loop;
|
||||
|
||||
Component component_;
|
||||
|
||||
public:
|
||||
class Private {
|
||||
public:
|
||||
|
||||
@@ -106,9 +106,9 @@ struct Canvas {
|
||||
// Draw using character of size 2x4 at position (x,y)
|
||||
// x is considered to be a multiple of 2.
|
||||
// y is considered to be a multiple of 4.
|
||||
void DrawText(int x, int y, const std::string& value);
|
||||
void DrawText(int x, int y, const std::string& value, const Color& color);
|
||||
void DrawText(int x, int y, const std::string& value, const Stylizer& style);
|
||||
void DrawText(int x, int y, std::string_view value);
|
||||
void DrawText(int x, int y, std::string_view value, const Color& color);
|
||||
void DrawText(int x, int y, std::string_view value, const Stylizer& style);
|
||||
|
||||
// Draw using directly pixels or images --------------------------------------
|
||||
// x is considered to be a multiple of 2.
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
#include <string_view>
|
||||
#include "ftxui/dom/canvas.hpp"
|
||||
#include "ftxui/dom/direction.hpp"
|
||||
#include "ftxui/dom/flexbox_config.hpp"
|
||||
@@ -51,8 +52,8 @@ Elements operator|(Elements, Decorator);
|
||||
Decorator operator|(Decorator, Decorator);
|
||||
|
||||
// --- Widget ---
|
||||
Element text(std::string text);
|
||||
Element vtext(std::string text);
|
||||
Element text(std::string_view text);
|
||||
Element vtext(std::string_view text);
|
||||
Element separator();
|
||||
Element separatorLight();
|
||||
Element separatorDashed();
|
||||
@@ -61,7 +62,7 @@ Element separatorDouble();
|
||||
Element separatorEmpty();
|
||||
Element separatorStyled(BorderStyle);
|
||||
Element separator(Pixel);
|
||||
Element separatorCharacter(std::string);
|
||||
Element separatorCharacter(std::string_view);
|
||||
Element separatorHSelector(float left,
|
||||
float right,
|
||||
Color unselected_color,
|
||||
@@ -89,11 +90,11 @@ Decorator borderStyled(Color);
|
||||
Decorator borderWith(const Pixel&);
|
||||
Element window(Element title, Element content, BorderStyle border = ROUNDED);
|
||||
Element spinner(int charset_index, size_t image_index);
|
||||
Element paragraph(const std::string& text);
|
||||
Element paragraphAlignLeft(const std::string& text);
|
||||
Element paragraphAlignRight(const std::string& text);
|
||||
Element paragraphAlignCenter(const std::string& text);
|
||||
Element paragraphAlignJustify(const std::string& text);
|
||||
Element paragraph(std::string_view text);
|
||||
Element paragraphAlignLeft(std::string_view text);
|
||||
Element paragraphAlignRight(std::string_view text);
|
||||
Element paragraphAlignCenter(std::string_view text);
|
||||
Element paragraphAlignJustify(std::string_view text);
|
||||
Element graph(GraphFunction);
|
||||
Element emptyElement();
|
||||
Element canvas(ConstRef<Canvas>);
|
||||
@@ -120,8 +121,8 @@ Element bgcolor(const LinearGradient&, Element);
|
||||
Decorator focusPosition(int x, int y);
|
||||
Decorator focusPositionRelative(float x, float y);
|
||||
Element automerge(Element child);
|
||||
Decorator hyperlink(std::string link);
|
||||
Element hyperlink(std::string link, Element child);
|
||||
Decorator hyperlink(std::string_view link);
|
||||
Element hyperlink(std::string_view link, Element child);
|
||||
Element selectionStyleReset(Element);
|
||||
Decorator selectionColor(Color foreground);
|
||||
Decorator selectionBackgroundColor(Color foreground);
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
|
||||
namespace ftxui {
|
||||
|
||||
|
||||
/// @brief FlexboxConfig is a configuration structure that defines the layout
|
||||
/// properties for a flexbox container.
|
||||
//
|
||||
|
||||
@@ -30,7 +30,7 @@ class Selection {
|
||||
Selection SaturateVertical(Box box);
|
||||
bool IsEmpty() const { return empty_; }
|
||||
|
||||
void AddPart(const std::string& part, int y, int left, int right);
|
||||
void AddPart(std::string_view part, int y, int left, int right);
|
||||
std::string GetParts() { return parts_.str(); }
|
||||
|
||||
private:
|
||||
|
||||
@@ -5,25 +5,18 @@
|
||||
#define FTXUI_DOM_TAKE_ANY_ARGS_HPP
|
||||
|
||||
// IWYU pragma: private, include "ftxui/dom/elements.hpp"
|
||||
#include <deque>
|
||||
#include <ftxui/dom/node.hpp>
|
||||
#include <queue>
|
||||
#include <stack>
|
||||
#include <vector>
|
||||
|
||||
namespace ftxui {
|
||||
|
||||
template <class T>
|
||||
void Merge(Elements& /*container*/, T /*element*/) {}
|
||||
|
||||
template <>
|
||||
inline void Merge(Elements& container, Element element) {
|
||||
container.push_back(std::move(element));
|
||||
}
|
||||
|
||||
template <>
|
||||
inline void Merge(Elements& container, Elements elements) {
|
||||
for (auto& element : elements) {
|
||||
container.push_back(std::move(element));
|
||||
}
|
||||
}
|
||||
|
||||
// Turn a set of arguments into a vector.
|
||||
template <class... Args>
|
||||
Elements unpack(Args... args) {
|
||||
@@ -32,11 +25,50 @@ Elements unpack(Args... args) {
|
||||
return vec;
|
||||
}
|
||||
|
||||
// Make |container| able to take any number of argments.
|
||||
// Make |container| able to take any number of arguments.
|
||||
#define TAKE_ANY_ARGS(container) \
|
||||
inline Element container(Element child) { \
|
||||
return container(unpack(std::move(child))); \
|
||||
} \
|
||||
\
|
||||
template <class... Args> \
|
||||
Element container(Args... children) { \
|
||||
inline Element container(Args... children) { \
|
||||
return container(unpack(std::forward<Args>(children)...)); \
|
||||
} \
|
||||
\
|
||||
template <class Container> \
|
||||
inline Element container(Container&& children) { \
|
||||
Elements elements; \
|
||||
for (auto& child : children) { \
|
||||
elements.push_back(std::move(child)); \
|
||||
} \
|
||||
return container(std::move(elements)); \
|
||||
} \
|
||||
template <> \
|
||||
inline Element container(std::stack<Element>&& children) { \
|
||||
Elements elements; \
|
||||
while (!children.empty()) { \
|
||||
elements.push_back(std::move(children.top())); \
|
||||
children.pop(); \
|
||||
} \
|
||||
return container(std::move(elements)); \
|
||||
} \
|
||||
template <> \
|
||||
inline Element container(std::queue<Element>&& children) { \
|
||||
Elements elements; \
|
||||
while (!children.empty()) { \
|
||||
elements.push_back(std::move(children.front())); \
|
||||
children.pop(); \
|
||||
} \
|
||||
return container(std::move(elements)); \
|
||||
} \
|
||||
template <> \
|
||||
inline Element container(std::deque<Element>&& children) { \
|
||||
Elements elements; \
|
||||
for (auto& child : children) { \
|
||||
elements.push_back(std::move(child)); \
|
||||
} \
|
||||
return container(std::move(elements)); \
|
||||
}
|
||||
|
||||
TAKE_ANY_ARGS(vbox)
|
||||
|
||||
@@ -20,6 +20,9 @@ class Image {
|
||||
Image() = delete;
|
||||
Image(int dimx, int dimy);
|
||||
|
||||
// Destructor:
|
||||
virtual ~Image() = default;
|
||||
|
||||
// Access a character in the grid at a given position.
|
||||
std::string& at(int x, int y);
|
||||
const std::string& at(int x, int y) const;
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
|
||||
#include "ftxui/screen/image.hpp" // for Pixel, Image
|
||||
#include "ftxui/screen/terminal.hpp" // for Dimensions
|
||||
#include "ftxui/util/autoreset.hpp" // for AutoReset
|
||||
|
||||
namespace ftxui {
|
||||
|
||||
@@ -31,6 +30,9 @@ class Screen : public Image {
|
||||
static Screen Create(Dimensions dimension);
|
||||
static Screen Create(Dimensions width, Dimensions height);
|
||||
|
||||
// Destructor:
|
||||
~Screen() override = default;
|
||||
|
||||
std::string ToString() const;
|
||||
|
||||
// Print the Screen on to the terminal.
|
||||
@@ -58,7 +60,7 @@ class Screen : public Image {
|
||||
BarBlinking = 5,
|
||||
Bar = 6,
|
||||
};
|
||||
Shape shape;
|
||||
Shape shape = Hidden;
|
||||
};
|
||||
|
||||
Cursor cursor() const { return cursor_; }
|
||||
@@ -66,7 +68,7 @@ class Screen : public Image {
|
||||
|
||||
// Store an hyperlink in the screen. Return the id of the hyperlink. The id is
|
||||
// used to identify the hyperlink when the user click on it.
|
||||
uint8_t RegisterHyperlink(const std::string& link);
|
||||
uint8_t RegisterHyperlink(std::string_view link);
|
||||
const std::string& Hyperlink(uint8_t id) const;
|
||||
|
||||
using SelectionStyle = std::function<void(Pixel&)>;
|
||||
|
||||
@@ -5,26 +5,31 @@
|
||||
#define FTXUI_SCREEN_STRING_HPP
|
||||
|
||||
#include <string> // for string, wstring, to_string
|
||||
#include <string_view> // for string_view
|
||||
#include <vector> // for vector
|
||||
|
||||
namespace ftxui {
|
||||
std::string to_string(const std::wstring& s);
|
||||
std::wstring to_wstring(const std::string& s);
|
||||
std::string to_string(std::wstring_view s);
|
||||
std::wstring to_wstring(std::string_view s);
|
||||
|
||||
template <typename T>
|
||||
std::wstring to_wstring(T s) {
|
||||
return to_wstring(std::to_string(s));
|
||||
return to_wstring(std::string_view(std::to_string(s)));
|
||||
}
|
||||
template <>
|
||||
inline std::wstring to_wstring(const char* s) {
|
||||
return to_wstring(std::string_view(s));
|
||||
}
|
||||
|
||||
int string_width(const std::string&);
|
||||
int string_width(std::string_view);
|
||||
|
||||
// Split the string into a its glyphs. An empty one is inserted ater fullwidth
|
||||
// ones.
|
||||
std::vector<std::string> Utf8ToGlyphs(const std::string& input);
|
||||
std::vector<std::string> Utf8ToGlyphs(std::string_view input);
|
||||
|
||||
// Map every cells drawn by |input| to their corresponding Glyphs. Half-size
|
||||
// Glyphs takes one cell, full-size Glyphs take two cells.
|
||||
std::vector<int> CellToGlyphIndex(const std::string& input);
|
||||
std::vector<int> CellToGlyphIndex(std::string_view input);
|
||||
|
||||
} // namespace ftxui
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include <ftxui/screen/string.hpp>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
@@ -17,8 +18,13 @@ template <typename T>
|
||||
class ConstRef {
|
||||
public:
|
||||
ConstRef() = default;
|
||||
|
||||
// Owning constructors:
|
||||
ConstRef(T t) : variant_(std::move(t)) {} // NOLINT
|
||||
|
||||
// Referencing constructors:
|
||||
ConstRef(const T* t) : variant_(t) {} // NOLINT
|
||||
|
||||
ConstRef& operator=(ConstRef&&) noexcept = default;
|
||||
ConstRef(const ConstRef<T>&) = default;
|
||||
ConstRef(ConstRef<T>&&) noexcept = default;
|
||||
@@ -46,8 +52,13 @@ template <typename T>
|
||||
class Ref {
|
||||
public:
|
||||
Ref() = default;
|
||||
|
||||
// Owning constructors:
|
||||
Ref(T t) : variant_(std::move(t)) {} // NOLINT
|
||||
//
|
||||
// Referencing constructors:
|
||||
Ref(T* t) : variant_(t) {} // NOLINT
|
||||
//
|
||||
~Ref() = default;
|
||||
Ref& operator=(Ref&&) noexcept = default;
|
||||
Ref(const Ref<T>&) = default;
|
||||
@@ -83,10 +94,15 @@ class StringRef : public Ref<std::string> {
|
||||
public:
|
||||
using Ref<std::string>::Ref;
|
||||
|
||||
// Owning constructors:
|
||||
StringRef(const wchar_t* ref) // NOLINT
|
||||
: StringRef(to_string(std::wstring(ref))) {}
|
||||
StringRef(const char* ref) // NOLINT
|
||||
: StringRef(std::string(ref)) {}
|
||||
StringRef(std::string_view ref) // NOLINT
|
||||
: StringRef(std::string(ref)) {}
|
||||
StringRef(std::wstring_view ref) // NOLINT
|
||||
: StringRef(to_string(ref)) {}
|
||||
};
|
||||
|
||||
/// @brief An adapter. Own or reference a constant string. For convenience, this
|
||||
@@ -95,14 +111,21 @@ class ConstStringRef : public ConstRef<std::string> {
|
||||
public:
|
||||
using ConstRef<std::string>::ConstRef;
|
||||
|
||||
// Referencing constructors:
|
||||
ConstStringRef(const std::wstring* ref) // NOLINT
|
||||
: ConstStringRef(to_string(*ref)) {}
|
||||
|
||||
// Owning constructors:
|
||||
ConstStringRef(const std::wstring ref) // NOLINT
|
||||
: ConstStringRef(to_string(ref)) {}
|
||||
ConstStringRef(std::wstring_view ref) // NOLINT
|
||||
: ConstStringRef(to_string(ref)) {}
|
||||
ConstStringRef(const wchar_t* ref) // NOLINT
|
||||
: ConstStringRef(to_string(std::wstring(ref))) {}
|
||||
ConstStringRef(const char* ref) // NOLINT
|
||||
: ConstStringRef(std::string(ref)) {}
|
||||
ConstStringRef(std::string_view ref) // NOLINT
|
||||
: ConstStringRef(std::string(ref)) {}
|
||||
};
|
||||
|
||||
/// @brief An adapter. Reference a list of strings.
|
||||
@@ -125,10 +148,12 @@ class ConstStringListRef {
|
||||
Adapter& operator=(Adapter&&) = default;
|
||||
virtual ~Adapter() = default;
|
||||
virtual size_t size() const = 0;
|
||||
virtual std::string operator[](size_t i) const = 0;
|
||||
virtual std::string_view operator[](size_t i) const = 0;
|
||||
};
|
||||
using Variant = std::variant<const std::vector<std::string>, //
|
||||
const std::vector<std::string>*, //
|
||||
const std::vector<std::string_view>, //
|
||||
const std::vector<std::string_view>*, //
|
||||
const std::vector<std::wstring>*, //
|
||||
Adapter*, //
|
||||
std::unique_ptr<Adapter> //
|
||||
@@ -141,25 +166,26 @@ class ConstStringListRef {
|
||||
ConstStringListRef(ConstStringListRef&&) = default;
|
||||
ConstStringListRef(const ConstStringListRef&) = default;
|
||||
|
||||
ConstStringListRef(std::vector<std::string> value) // NOLINT
|
||||
{
|
||||
ConstStringListRef(std::vector<std::string> value) { // NOLINT
|
||||
variant_ = std::make_shared<Variant>(value);
|
||||
}
|
||||
ConstStringListRef(const std::vector<std::string>* value) // NOLINT
|
||||
{
|
||||
ConstStringListRef(const std::vector<std::string>* value) {// NOLINT
|
||||
variant_ = std::make_shared<Variant>(value);
|
||||
}
|
||||
ConstStringListRef(const std::vector<std::wstring>* value) // NOLINT
|
||||
{
|
||||
ConstStringListRef(std::vector<std::string_view> value) { // NOLINT
|
||||
variant_ = std::make_shared<Variant>(value);
|
||||
}
|
||||
ConstStringListRef(Adapter* adapter) // NOLINT
|
||||
{
|
||||
ConstStringListRef(const std::vector<std::string_view>* value) { // NOLINT
|
||||
variant_ = std::make_shared<Variant>(value);
|
||||
}
|
||||
ConstStringListRef(const std::vector<std::wstring>* value) { // NOLINT
|
||||
variant_ = std::make_shared<Variant>(value);
|
||||
}
|
||||
ConstStringListRef(Adapter* adapter) { // NOLINT
|
||||
variant_ = std::make_shared<Variant>(adapter);
|
||||
}
|
||||
template <typename AdapterType>
|
||||
ConstStringListRef(std::unique_ptr<AdapterType> adapter) // NOLINT
|
||||
{
|
||||
ConstStringListRef(std::unique_ptr<AdapterType> adapter) { // NOLINT
|
||||
variant_ = std::make_shared<Variant>(
|
||||
static_cast<std::unique_ptr<Adapter>>(std::move(adapter)));
|
||||
}
|
||||
@@ -168,11 +194,34 @@ class ConstStringListRef {
|
||||
return variant_ ? std::visit(SizeVisitor(), *variant_) : 0;
|
||||
}
|
||||
|
||||
std::string operator[](size_t i) const {
|
||||
return variant_ ? std::visit(IndexedGetter(i), *variant_) : "";
|
||||
std::string_view operator[](size_t i) const {
|
||||
return variant_ ? std::visit(IndexedGetter{i}, *variant_) : "";
|
||||
}
|
||||
|
||||
private:
|
||||
struct IndexedGetter {
|
||||
size_t i;
|
||||
std::string_view operator()(const std::vector<std::string>& v) const {
|
||||
return v[i];
|
||||
}
|
||||
std::string_view operator()(const std::vector<std::string>* v) const {
|
||||
return (*v)[i];
|
||||
}
|
||||
std::string_view operator()(const std::vector<std::string_view>& v) const {
|
||||
return std::string(v[i]);
|
||||
}
|
||||
std::string_view operator()(const std::vector<std::string_view>* v) const {
|
||||
return std::string((*v)[i]);
|
||||
}
|
||||
std::string_view operator()(const std::vector<std::wstring>* v) const {
|
||||
return to_string((*v)[i]);
|
||||
}
|
||||
std::string_view operator()(Adapter* v) const { return std::string((*v)[i]); }
|
||||
std::string_view operator()(const std::unique_ptr<Adapter>& v) const {
|
||||
return (*v)[i];
|
||||
}
|
||||
};
|
||||
|
||||
struct SizeVisitor {
|
||||
size_t operator()(const std::vector<std::string>& v) const {
|
||||
return v.size();
|
||||
@@ -180,6 +229,12 @@ class ConstStringListRef {
|
||||
size_t operator()(const std::vector<std::string>* v) const {
|
||||
return v->size();
|
||||
}
|
||||
size_t operator()(const std::vector<std::string_view>& v) const {
|
||||
return v.size();
|
||||
}
|
||||
size_t operator()(const std::vector<std::string_view>* v) const {
|
||||
return v->size();
|
||||
}
|
||||
size_t operator()(const std::vector<std::wstring>* v) const {
|
||||
return v->size();
|
||||
}
|
||||
@@ -189,25 +244,6 @@ class ConstStringListRef {
|
||||
}
|
||||
};
|
||||
|
||||
struct IndexedGetter {
|
||||
IndexedGetter(size_t index) // NOLINT
|
||||
: index_(index) {}
|
||||
size_t index_;
|
||||
std::string operator()(const std::vector<std::string>& v) const {
|
||||
return v[index_];
|
||||
}
|
||||
std::string operator()(const std::vector<std::string>* v) const {
|
||||
return (*v)[index_];
|
||||
}
|
||||
std::string operator()(const std::vector<std::wstring>* v) const {
|
||||
return to_string((*v)[index_]);
|
||||
}
|
||||
std::string operator()(const Adapter* v) const { return (*v)[index_]; }
|
||||
std::string operator()(const std::unique_ptr<Adapter>& v) const {
|
||||
return (*v)[index_];
|
||||
}
|
||||
};
|
||||
|
||||
std::shared_ptr<Variant> variant_;
|
||||
};
|
||||
|
||||
|
||||
18
include/ftxui/util/warn_windows_macro.hpp
Normal file
18
include/ftxui/util/warn_windows_macro.hpp
Normal file
@@ -0,0 +1,18 @@
|
||||
// Copyright 2025 Arthur Sonzogni. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
|
||||
#ifndef FTXUI_UTIL_WARN_WINDOWS_MACRO_H_
|
||||
#define FTXUI_UTIL_WARN_WINDOWS_MACRO_H_
|
||||
|
||||
#ifdef min
|
||||
#error \
|
||||
"The macro 'min' is defined, which conflicts with the standard C++ library and FTXUI. This is often caused by including <windows.h>. To fix this, add '#define NOMINMAX' before including <windows.h>, or pass '/DNOMINMAX' as a compiler flag."
|
||||
#endif
|
||||
|
||||
#ifdef max
|
||||
#error \
|
||||
"The macro 'max' is defined, which conflicts with the standard C++ library and FTXUI. This is often caused by including <windows.h>. To fix this, add '#define NOMINMAX' before including <windows.h>, or pass '/DNOMINMAX' as a compiler flag."
|
||||
#endif
|
||||
|
||||
#endif // FTXUI_UTIL_WARN_WINDOWS_MACRO_H_
|
||||
@@ -3,14 +3,14 @@
|
||||
|
||||
export module ftxui.component;
|
||||
|
||||
export import ftxui.component.animation;
|
||||
export import ftxui.component.captured_mouse;
|
||||
export import ftxui.component.component;
|
||||
export import ftxui.component.component_base;
|
||||
export import ftxui.component.component_options;
|
||||
export import ftxui.component.event;
|
||||
export import ftxui.component.loop;
|
||||
export import ftxui.component.mouse;
|
||||
export import ftxui.component.receiver;
|
||||
export import ftxui.component.screen_interactive;
|
||||
export import ftxui.component.task;
|
||||
export import :Animation;
|
||||
export import :CapturedMouse;
|
||||
export import :Component;
|
||||
export import :ComponentBase;
|
||||
export import :ComponentOptions;
|
||||
export import :Event;
|
||||
export import :Loop;
|
||||
export import :Mouse;
|
||||
export import :Receiver;
|
||||
export import :ScreenInteractive;
|
||||
export import :Task;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/// @module ftxui.component.animation
|
||||
/// @module ftxui.component:Animation
|
||||
/// @brief C++20 module interface for the Animation namespace of the Component module.
|
||||
///
|
||||
|
||||
@@ -6,7 +6,7 @@ module;
|
||||
|
||||
#include <ftxui/component/animation.hpp>
|
||||
|
||||
export module ftxui.component.animation;
|
||||
export module ftxui.component:Animation;
|
||||
|
||||
/**
|
||||
* @namespace ftxui::animation
|
||||
@@ -23,7 +23,7 @@ export namespace ftxui::animation {
|
||||
|
||||
/**
|
||||
* @namespace easing
|
||||
* @brief The FTXUI sf::animation::easing:: namespace
|
||||
* @brief The FTXUI ftxui::animation::easing:: namespace
|
||||
*/
|
||||
namespace easing {
|
||||
using ftxui::animation::easing::Function;
|
||||
|
||||
@@ -48,7 +48,7 @@ class ButtonBase : public ComponentBase, public ButtonOption {
|
||||
}
|
||||
|
||||
const EntryState state{
|
||||
*label, false, active, focused_or_hover, Index(),
|
||||
std::string(*label), false, active, focused_or_hover, Index(),
|
||||
};
|
||||
|
||||
auto element = (transform ? transform : DefaultTransform) //
|
||||
@@ -139,7 +139,6 @@ class ButtonBase : public ComponentBase, public ButtonOption {
|
||||
private:
|
||||
bool mouse_hover_ = false;
|
||||
Box box_;
|
||||
ButtonOption option_;
|
||||
float animation_background_ = 0;
|
||||
float animation_foreground_ = 0;
|
||||
animation::Animator animator_background_ =
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/// @module ftxui.component.captured_mouse
|
||||
/// @module ftxui.component.CapturedMouse
|
||||
/// @brief Module file for the CapturedMouseInterface class of the Component module
|
||||
|
||||
module;
|
||||
|
||||
#include <ftxui/component/captured_mouse.hpp>
|
||||
|
||||
export module ftxui.component.captured_mouse;
|
||||
export module ftxui.component:CapturedMouse;
|
||||
|
||||
/**
|
||||
* @namespace ftxui
|
||||
|
||||
@@ -27,7 +27,7 @@ class CheckboxBase : public ComponentBase, public CheckboxOption {
|
||||
const bool is_focused = Focused();
|
||||
const bool is_active = Active();
|
||||
auto entry_state = EntryState{
|
||||
*label, *checked, is_active, is_focused || hovered_, -1,
|
||||
std::string(*label), *checked, is_active, is_focused || hovered_, -1,
|
||||
};
|
||||
auto element = (transform ? transform : CheckboxOption::Simple().transform)(
|
||||
entry_state);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/// @module ftxui.component.component
|
||||
/// @module ftxui.component:Component
|
||||
/// @brief Module file for the Component classes of the Component module
|
||||
|
||||
module;
|
||||
|
||||
#include <ftxui/component/component.hpp>
|
||||
|
||||
export module ftxui.component.component;
|
||||
export module ftxui.component:Component;
|
||||
|
||||
/**
|
||||
* @namespace ftxui
|
||||
@@ -28,6 +28,10 @@ export namespace ftxui {
|
||||
using ftxui::operator|;
|
||||
using ftxui::operator|=;
|
||||
|
||||
/**
|
||||
* @namespace Container
|
||||
* @brief The FTXUI ftxui::Container:: namespace
|
||||
*/
|
||||
namespace Container {
|
||||
using ftxui::Container::Vertical;
|
||||
using ftxui::Container::Horizontal;
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/// @module ftxui.component.component_base
|
||||
/// @module ftxui.component:ComponentBase
|
||||
/// @brief Module file for the ComponentBase class of the Component module
|
||||
|
||||
module;
|
||||
|
||||
#include <ftxui/component/component_base.hpp>
|
||||
|
||||
export module ftxui.component.component_base;
|
||||
export module ftxui.component:ComponentBase;
|
||||
|
||||
/**
|
||||
* @namespace ftxui
|
||||
@@ -16,6 +16,10 @@ export namespace ftxui {
|
||||
using ftxui::Focus;
|
||||
using ftxui::Event;
|
||||
|
||||
/**
|
||||
* @namespace animation
|
||||
* @brief The FTXUI ftxui::animation:: namespace
|
||||
*/
|
||||
namespace animation {
|
||||
using ftxui::animation::Params;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
#include <cassert>
|
||||
#include <ftxui/component/event.hpp>
|
||||
#include <vector>
|
||||
#include "ftxui/component/component.hpp"
|
||||
#include "ftxui/component/terminal_input_parser.hpp"
|
||||
@@ -22,8 +23,9 @@ bool GeneratorBool(const char*& data, size_t& size) {
|
||||
|
||||
std::string GeneratorString(const char*& data, size_t& size) {
|
||||
int index = 0;
|
||||
while (index < size && data[index])
|
||||
while (index < size && data[index]) {
|
||||
++index;
|
||||
}
|
||||
|
||||
auto out = std::string(data, data + index);
|
||||
data += index;
|
||||
@@ -39,8 +41,9 @@ std::string GeneratorString(const char*& data, size_t& size) {
|
||||
}
|
||||
|
||||
int GeneratorInt(const char* data, size_t size) {
|
||||
if (size == 0)
|
||||
if (size == 0) {
|
||||
return 0;
|
||||
}
|
||||
auto out = int(data[0]);
|
||||
data++;
|
||||
size--;
|
||||
@@ -112,8 +115,9 @@ Components GeneratorComponents(const char*& data, size_t& size, int depth);
|
||||
Component GeneratorComponent(const char*& data, size_t& size, int depth) {
|
||||
depth--;
|
||||
int value = GeneratorInt(data, size);
|
||||
if (depth <= 0)
|
||||
if (depth <= 0) {
|
||||
return Button(GeneratorString(data, size), [] {});
|
||||
}
|
||||
|
||||
constexpr int value_max = 19;
|
||||
value = (value % value_max + value_max) % value_max;
|
||||
@@ -212,16 +216,17 @@ extern "C" int LLVMFuzzerTestOneInput(const char* data, size_t size) {
|
||||
auto screen =
|
||||
Screen::Create(Dimension::Fixed(width), Dimension::Fixed(height));
|
||||
|
||||
auto event_receiver = MakeReceiver<Task>();
|
||||
{
|
||||
auto parser = TerminalInputParser(event_receiver->MakeSender());
|
||||
for (size_t i = 0; i < size; ++i)
|
||||
// Generate some events.
|
||||
std::vector<Event> events;
|
||||
auto parser =
|
||||
TerminalInputParser([&](const Event& event) { events.push_back(event); });
|
||||
|
||||
for (size_t i = 0; i < size; ++i) {
|
||||
parser.Add(data[i]);
|
||||
}
|
||||
|
||||
Task event;
|
||||
while (event_receiver->Receive(&event)) {
|
||||
component->OnEvent(std::get<Event>(event));
|
||||
for (const auto& event : events) {
|
||||
component->OnEvent(event);
|
||||
auto document = component->Render();
|
||||
Render(screen, document);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/// @module ftxui.component.component_options
|
||||
/// @module ftxui.component:ComponentOptions
|
||||
/// @brief Module file for options for the Component class of the Component module
|
||||
|
||||
module;
|
||||
|
||||
#include <ftxui/component/component_options.hpp>
|
||||
|
||||
export module ftxui.component.component_options;
|
||||
export module ftxui.component:ComponentOptions;
|
||||
|
||||
/**
|
||||
* @namespace ftxui
|
||||
|
||||
@@ -25,9 +25,9 @@ namespace ftxui {
|
||||
/// @brief An event corresponding to a given typed character.
|
||||
/// @param input The character typed by the user.
|
||||
// static
|
||||
Event Event::Character(std::string input) {
|
||||
Event Event::Character(std::string_view input) {
|
||||
Event event;
|
||||
event.input_ = std::move(input);
|
||||
event.input_ = std::string(input);
|
||||
event.type_ = Type::Character;
|
||||
return event;
|
||||
}
|
||||
@@ -50,9 +50,9 @@ Event Event::Character(wchar_t c) {
|
||||
/// @param input The sequence of character send by the terminal.
|
||||
/// @param mouse The mouse state.
|
||||
// static
|
||||
Event Event::Mouse(std::string input, struct Mouse mouse) {
|
||||
Event Event::Mouse(std::string_view input, struct Mouse mouse) {
|
||||
Event event;
|
||||
event.input_ = std::move(input);
|
||||
event.input_ = std::string(input);
|
||||
event.type_ = Type::Mouse;
|
||||
event.data_.mouse = mouse; // NOLINT
|
||||
return event;
|
||||
@@ -60,9 +60,9 @@ Event Event::Mouse(std::string input, struct Mouse mouse) {
|
||||
|
||||
/// @brief An event corresponding to a terminal DCS (Device Control String).
|
||||
// static
|
||||
Event Event::CursorShape(std::string input, int shape) {
|
||||
Event Event::CursorShape(std::string_view input, int shape) {
|
||||
Event event;
|
||||
event.input_ = std::move(input);
|
||||
event.input_ = std::string(input);
|
||||
event.type_ = Type::CursorShape;
|
||||
event.data_.cursor_shape = shape; // NOLINT
|
||||
return event;
|
||||
@@ -71,17 +71,17 @@ Event Event::CursorShape(std::string input, int shape) {
|
||||
/// @brief An custom event whose meaning is defined by the user of the library.
|
||||
/// @param input An arbitrary sequence of character defined by the developer.
|
||||
// static
|
||||
Event Event::Special(std::string input) {
|
||||
Event Event::Special(std::string_view input) {
|
||||
Event event;
|
||||
event.input_ = std::move(input);
|
||||
event.input_ = std::string(input);
|
||||
return event;
|
||||
}
|
||||
|
||||
/// @internal
|
||||
// static
|
||||
Event Event::CursorPosition(std::string input, int x, int y) {
|
||||
Event Event::CursorPosition(std::string_view input, int x, int y) {
|
||||
Event event;
|
||||
event.input_ = std::move(input);
|
||||
event.input_ = std::string(input);
|
||||
event.type_ = Type::CursorPosition;
|
||||
event.data_.cursor = {x, y}; // NOLINT
|
||||
return event;
|
||||
@@ -292,12 +292,12 @@ const Event Event::ArrowLeftCtrl = Event::Special("\x1B[1;5D");
|
||||
const Event Event::ArrowRightCtrl = Event::Special("\x1B[1;5C");
|
||||
const Event Event::ArrowUpCtrl = Event::Special("\x1B[1;5A");
|
||||
const Event Event::ArrowDownCtrl = Event::Special("\x1B[1;5B");
|
||||
const Event Event::Backspace = Event::Special({127});
|
||||
const Event Event::Backspace = Event::Special(std::string({127}));
|
||||
const Event Event::Delete = Event::Special("\x1B[3~");
|
||||
const Event Event::Escape = Event::Special("\x1B");
|
||||
const Event Event::Return = Event::Special({10});
|
||||
const Event Event::Tab = Event::Special({9});
|
||||
const Event Event::TabReverse = Event::Special({27, 91, 90});
|
||||
const Event Event::Return = Event::Special(std::string({10}));
|
||||
const Event Event::Tab = Event::Special(std::string({9}));
|
||||
const Event Event::TabReverse = Event::Special(std::string({27, 91, 90}));
|
||||
|
||||
// See https://invisible-island.net/xterm/xterm-function-keys.html
|
||||
// We follow xterm-new / vterm-xf86-v4 / mgt / screen
|
||||
@@ -315,11 +315,11 @@ const Event Event::F11 = Event::Special("\x1B[23~");
|
||||
const Event Event::F12 = Event::Special("\x1B[24~");
|
||||
|
||||
const Event Event::Insert = Event::Special("\x1B[2~");
|
||||
const Event Event::Home = Event::Special({27, 91, 72});
|
||||
const Event Event::End = Event::Special({27, 91, 70});
|
||||
const Event Event::PageUp = Event::Special({27, 91, 53, 126});
|
||||
const Event Event::PageDown = Event::Special({27, 91, 54, 126});
|
||||
const Event Event::Custom = Event::Special({0});
|
||||
const Event Event::Home = Event::Special(std::string({27, 91, 72}));
|
||||
const Event Event::End = Event::Special(std::string({27, 91, 70}));
|
||||
const Event Event::PageUp = Event::Special(std::string({27, 91, 53, 126}));
|
||||
const Event Event::PageDown = Event::Special(std::string({27, 91, 54, 126}));
|
||||
const Event Event::Custom = Event::Special(std::string({0}));
|
||||
|
||||
const Event Event::a = Event::Character("a");
|
||||
const Event Event::b = Event::Character("b");
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/// @module ftxui.component.event
|
||||
/// @module ftxui.component:Event
|
||||
/// @brief Module file for the Event struct of the Component module
|
||||
|
||||
module;
|
||||
|
||||
#include <ftxui/component/event.hpp>
|
||||
|
||||
export module ftxui.component.event;
|
||||
export module ftxui.component:Event;
|
||||
|
||||
/**
|
||||
* @namespace ftxui
|
||||
|
||||
@@ -173,7 +173,7 @@ class InputBase : public ComponentBase, public InputOption {
|
||||
elements.push_back(element);
|
||||
}
|
||||
|
||||
auto element = vbox(std::move(elements), cursor_line) | frame;
|
||||
auto element = vbox(std::move(elements)) | frame;
|
||||
return transform_func({
|
||||
std::move(element), hovered_, is_focused,
|
||||
false // placeholder
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/// @module ftxui.component.loop
|
||||
/// @module ftxui.component:Loop
|
||||
/// @brief Module file for the Loop class of the Component module
|
||||
|
||||
module;
|
||||
|
||||
#include <ftxui/component/loop.hpp>
|
||||
|
||||
export module ftxui.component.loop;
|
||||
export module ftxui.component:Loop;
|
||||
|
||||
/**
|
||||
* @namespace ftxui
|
||||
|
||||
@@ -123,7 +123,7 @@ class MenuBase : public ComponentBase, public MenuOption {
|
||||
const bool is_selected = (selected() == i);
|
||||
|
||||
const EntryState state = {
|
||||
entries[i], false, is_selected, is_focused, i,
|
||||
std::string(entries[i]), false, is_selected, is_focused, i,
|
||||
};
|
||||
|
||||
Element element = (entries_option.transform ? entries_option.transform
|
||||
@@ -144,9 +144,8 @@ class MenuBase : public ComponentBase, public MenuOption {
|
||||
std::reverse(elements.begin(), elements.end());
|
||||
}
|
||||
|
||||
const Element bar = IsHorizontal()
|
||||
? hbox(std::move(elements), selected_focus_)
|
||||
: vbox(std::move(elements), selected_focus_);
|
||||
const Element bar =
|
||||
IsHorizontal() ? hbox(std::move(elements)) : vbox(std::move(elements));
|
||||
|
||||
if (!underline.enabled) {
|
||||
return bar | reflect(box_);
|
||||
@@ -623,7 +622,7 @@ Component MenuEntry(MenuEntryOption option) {
|
||||
UpdateAnimationTarget();
|
||||
|
||||
const EntryState state{
|
||||
label(), false, hovered_, is_focused, Index(),
|
||||
std::string(label()), false, hovered_, is_focused, Index(),
|
||||
};
|
||||
|
||||
Element element = (transform ? transform : DefaultOptionTransform) //
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/// @module ftxui.component.mouse
|
||||
/// @module ftxui.component:Mouse
|
||||
/// @brief Module file for the Mouse struct of the Component module
|
||||
|
||||
module;
|
||||
|
||||
#include <ftxui/component/mouse.hpp>
|
||||
|
||||
export module ftxui.component.mouse;
|
||||
export module ftxui.component:Mouse;
|
||||
|
||||
/**
|
||||
* @namespace ftxui
|
||||
|
||||
@@ -37,7 +37,7 @@ class RadioboxBase : public ComponentBase, public RadioboxOption {
|
||||
const bool is_focused = (focused_entry() == i) && is_menu_focused;
|
||||
const bool is_selected = (hovered_ == i);
|
||||
auto state = EntryState{
|
||||
entries[i], selected() == i, is_selected, is_focused, i,
|
||||
std::string(entries[i]), selected() == i, is_selected, is_focused, i,
|
||||
};
|
||||
auto element =
|
||||
(transform ? transform : RadioboxOption::Simple().transform)(state);
|
||||
@@ -46,7 +46,7 @@ class RadioboxBase : public ComponentBase, public RadioboxOption {
|
||||
}
|
||||
elements.push_back(element | reflect(boxes_[i]));
|
||||
}
|
||||
return vbox(std::move(elements), hovered_) | reflect(box_);
|
||||
return vbox(std::move(elements)) | reflect(box_);
|
||||
}
|
||||
|
||||
// NOLINTNEXTLINE(readability-function-cognitive-complexity)
|
||||
|
||||
@@ -1,20 +1,26 @@
|
||||
/// @module ftxui.component.receiver
|
||||
/// @module ftxui.component:Receiver
|
||||
/// @brief Module file for the Receiver class of the Component module
|
||||
|
||||
module;
|
||||
|
||||
#include <ftxui/component/receiver.hpp>
|
||||
|
||||
export module ftxui.component.receiver;
|
||||
export module ftxui.component:Receiver;
|
||||
|
||||
/**
|
||||
* @namespace ftxui
|
||||
* @brief The FTXUI ftxui:: namespace
|
||||
*/
|
||||
export namespace ftxui {
|
||||
// Deprecated:
|
||||
using ftxui::SenderImpl;
|
||||
// Deprecated:
|
||||
using ftxui::ReceiverImpl;
|
||||
// Deprecated:
|
||||
using ftxui::Sender;
|
||||
// Deprecated:
|
||||
using ftxui::Receiver;
|
||||
// Deprecated:
|
||||
using ftxui::MakeReceiver;
|
||||
// Deprecated:
|
||||
}
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
// Copyright 2020 Arthur Sonzogni. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
#include <thread> // for thread
|
||||
#include <utility> // for move
|
||||
|
||||
#include "ftxui/component/receiver.hpp"
|
||||
#include "gtest/gtest.h" // for AssertionResult, Message, Test, TestPartResult, EXPECT_EQ, EXPECT_TRUE, EXPECT_FALSE, TEST
|
||||
|
||||
// NOLINTBEGIN
|
||||
namespace ftxui {
|
||||
|
||||
TEST(Receiver, Basic) {
|
||||
auto receiver = MakeReceiver<char>();
|
||||
auto sender = receiver->MakeSender();
|
||||
|
||||
sender->Send('a');
|
||||
sender->Send('b');
|
||||
sender->Send('c');
|
||||
sender.reset();
|
||||
|
||||
char a, b, c, d;
|
||||
EXPECT_TRUE(receiver->Receive(&a));
|
||||
EXPECT_TRUE(receiver->Receive(&b));
|
||||
EXPECT_TRUE(receiver->Receive(&c));
|
||||
EXPECT_FALSE(receiver->Receive(&d));
|
||||
|
||||
EXPECT_EQ(a, 'a');
|
||||
EXPECT_EQ(b, 'b');
|
||||
EXPECT_EQ(c, 'c');
|
||||
}
|
||||
|
||||
TEST(Receiver, BasicWithThread) {
|
||||
auto r1 = MakeReceiver<char>();
|
||||
auto r2 = MakeReceiver<char>();
|
||||
auto r3 = MakeReceiver<char>();
|
||||
|
||||
auto s1 = r1->MakeSender();
|
||||
auto s2 = r2->MakeSender();
|
||||
auto s3 = r3->MakeSender();
|
||||
|
||||
auto s1_bis = r1->MakeSender();
|
||||
|
||||
auto stream = [](Receiver<char> receiver, Sender<char> sender) {
|
||||
char c;
|
||||
while (receiver->Receive(&c))
|
||||
sender->Send(c);
|
||||
};
|
||||
|
||||
// Convert data from a different thread.
|
||||
auto t12 = std::thread(stream, std::move(r1), std::move(s2));
|
||||
auto t23 = std::thread(stream, std::move(r2), std::move(s3));
|
||||
|
||||
// Send some data.
|
||||
s1->Send('1');
|
||||
s1_bis->Send('2');
|
||||
s1->Send('3');
|
||||
s1_bis->Send('4');
|
||||
|
||||
// Close the stream.
|
||||
s1.reset();
|
||||
s1_bis.reset();
|
||||
|
||||
char c;
|
||||
EXPECT_TRUE(r3->Receive(&c));
|
||||
EXPECT_EQ(c, '1');
|
||||
EXPECT_TRUE(r3->Receive(&c));
|
||||
EXPECT_EQ(c, '2');
|
||||
EXPECT_TRUE(r3->Receive(&c));
|
||||
EXPECT_EQ(c, '3');
|
||||
EXPECT_TRUE(r3->Receive(&c));
|
||||
EXPECT_EQ(c, '4');
|
||||
EXPECT_FALSE(r3->Receive(&c));
|
||||
|
||||
// Thread will end at the end of the stream.
|
||||
t12.join();
|
||||
t23.join();
|
||||
}
|
||||
|
||||
} // namespace ftxui
|
||||
// NOLINTEND
|
||||
@@ -1,6 +1,7 @@
|
||||
// Copyright 2021 Arthur Sonzogni. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
#include <algorithm> // for max
|
||||
#include <ftxui/component/component_options.hpp> // for ResizableSplitOption
|
||||
#include <ftxui/dom/direction.hpp> // for Direction, Direction::Down, Direction::Left, Direction::Right, Direction::Up
|
||||
#include <ftxui/util/ref.hpp> // for Ref
|
||||
@@ -18,34 +19,22 @@
|
||||
namespace ftxui {
|
||||
namespace {
|
||||
|
||||
class ResizableSplitBase : public ComponentBase {
|
||||
class ResizableSplitBase : public ComponentBase, public ResizableSplitOption {
|
||||
public:
|
||||
explicit ResizableSplitBase(ResizableSplitOption options)
|
||||
: options_(std::move(options)) {
|
||||
switch (options_->direction()) {
|
||||
: ResizableSplitOption(std::move(options)) {
|
||||
switch (direction()) {
|
||||
case Direction::Left:
|
||||
Add(Container::Horizontal({
|
||||
options_->main,
|
||||
options_->back,
|
||||
}));
|
||||
Add(Container::Horizontal({main, back}));
|
||||
break;
|
||||
case Direction::Right:
|
||||
Add(Container::Horizontal({
|
||||
options_->back,
|
||||
options_->main,
|
||||
}));
|
||||
Add(Container::Horizontal({back, main}));
|
||||
break;
|
||||
case Direction::Up:
|
||||
Add(Container::Vertical({
|
||||
options_->main,
|
||||
options_->back,
|
||||
}));
|
||||
Add(Container::Vertical({main, back}));
|
||||
break;
|
||||
case Direction::Down:
|
||||
Add(Container::Vertical({
|
||||
options_->back,
|
||||
options_->main,
|
||||
}));
|
||||
Add(Container::Vertical({back, main}));
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -75,27 +64,27 @@ class ResizableSplitBase : public ComponentBase {
|
||||
return ComponentBase::OnEvent(event);
|
||||
}
|
||||
|
||||
switch (options_->direction()) {
|
||||
switch (direction()) {
|
||||
case Direction::Left:
|
||||
options_->main_size() = std::max(0, event.mouse().x - box_.x_min);
|
||||
return true;
|
||||
main_size() = std::max(0, event.mouse().x - box_.x_min);
|
||||
break;
|
||||
case Direction::Right:
|
||||
options_->main_size() = std::max(0, box_.x_max - event.mouse().x);
|
||||
return true;
|
||||
main_size() = std::max(0, box_.x_max - event.mouse().x);
|
||||
break;
|
||||
case Direction::Up:
|
||||
options_->main_size() = std::max(0, event.mouse().y - box_.y_min);
|
||||
return true;
|
||||
main_size() = std::max(0, event.mouse().y - box_.y_min);
|
||||
break;
|
||||
case Direction::Down:
|
||||
options_->main_size() = std::max(0, box_.y_max - event.mouse().y);
|
||||
return true;
|
||||
main_size() = std::max(0, box_.y_max - event.mouse().y);
|
||||
break;
|
||||
}
|
||||
|
||||
// NOTREACHED()
|
||||
return false;
|
||||
main_size() = std::clamp(main_size(), min(), max());
|
||||
return true;
|
||||
}
|
||||
|
||||
Element OnRender() final {
|
||||
switch (options_->direction()) {
|
||||
switch (direction()) {
|
||||
case Direction::Left:
|
||||
return RenderLeft();
|
||||
case Direction::Right:
|
||||
@@ -111,46 +100,41 @@ class ResizableSplitBase : public ComponentBase {
|
||||
|
||||
Element RenderLeft() {
|
||||
return hbox({
|
||||
options_->main->Render() |
|
||||
size(WIDTH, EQUAL, options_->main_size()),
|
||||
options_->separator_func() | reflect(separator_box_),
|
||||
options_->back->Render() | xflex,
|
||||
main->Render() | size(WIDTH, EQUAL, main_size()),
|
||||
separator_func() | reflect(separator_box_),
|
||||
back->Render() | xflex,
|
||||
}) |
|
||||
reflect(box_);
|
||||
}
|
||||
|
||||
Element RenderRight() {
|
||||
return hbox({
|
||||
options_->back->Render() | xflex,
|
||||
options_->separator_func() | reflect(separator_box_),
|
||||
options_->main->Render() |
|
||||
size(WIDTH, EQUAL, options_->main_size()),
|
||||
back->Render() | xflex,
|
||||
separator_func() | reflect(separator_box_),
|
||||
main->Render() | size(WIDTH, EQUAL, main_size()),
|
||||
}) |
|
||||
reflect(box_);
|
||||
}
|
||||
|
||||
Element RenderTop() {
|
||||
return vbox({
|
||||
options_->main->Render() |
|
||||
size(HEIGHT, EQUAL, options_->main_size()),
|
||||
options_->separator_func() | reflect(separator_box_),
|
||||
options_->back->Render() | yflex,
|
||||
main->Render() | size(HEIGHT, EQUAL, main_size()),
|
||||
separator_func() | reflect(separator_box_),
|
||||
back->Render() | yflex,
|
||||
}) |
|
||||
reflect(box_);
|
||||
}
|
||||
|
||||
Element RenderBottom() {
|
||||
return vbox({
|
||||
options_->back->Render() | yflex,
|
||||
options_->separator_func() | reflect(separator_box_),
|
||||
options_->main->Render() |
|
||||
size(HEIGHT, EQUAL, options_->main_size()),
|
||||
back->Render() | yflex,
|
||||
separator_func() | reflect(separator_box_),
|
||||
main->Render() | size(HEIGHT, EQUAL, main_size()),
|
||||
}) |
|
||||
reflect(box_);
|
||||
}
|
||||
|
||||
private:
|
||||
Ref<ResizableSplitOption> options_;
|
||||
CapturedMouse captured_mouse_;
|
||||
Box separator_box_;
|
||||
Box box_;
|
||||
|
||||
@@ -233,5 +233,105 @@ TEST(ResizableSplit, NavigationVertical) {
|
||||
EXPECT_FALSE(component_bottom->Active());
|
||||
}
|
||||
|
||||
TEST(ResizableSplit, MinMaxSizeLeft) {
|
||||
int position = 5;
|
||||
auto component = ResizableSplit({
|
||||
.main = BasicComponent(),
|
||||
.back = BasicComponent(),
|
||||
.direction = Direction::Left,
|
||||
.main_size = &position,
|
||||
.separator_func = [] { return separatorDouble(); },
|
||||
.min = 3,
|
||||
.max = 8,
|
||||
});
|
||||
auto screen = Screen(20, 20);
|
||||
Render(screen, component->Render());
|
||||
EXPECT_EQ(position, 5);
|
||||
EXPECT_TRUE(component->OnEvent(MousePressed(5, 1)));
|
||||
EXPECT_EQ(position, 5);
|
||||
// Try to resize below min
|
||||
EXPECT_TRUE(component->OnEvent(MousePressed(2, 1)));
|
||||
EXPECT_EQ(position, 3); // Clamped to min
|
||||
// Try to resize above max
|
||||
EXPECT_TRUE(component->OnEvent(MousePressed(10, 1)));
|
||||
EXPECT_EQ(position, 8); // Clamped to max
|
||||
EXPECT_TRUE(component->OnEvent(MouseReleased(10, 1)));
|
||||
EXPECT_EQ(position, 8);
|
||||
}
|
||||
|
||||
TEST(ResizableSplit, MinMaxSizeRight) {
|
||||
int position = 5;
|
||||
auto component = ResizableSplit({
|
||||
.main = BasicComponent(),
|
||||
.back = BasicComponent(),
|
||||
.direction = Direction::Right,
|
||||
.main_size = &position,
|
||||
.separator_func = [] { return separatorDouble(); },
|
||||
.min = 3,
|
||||
.max = 8,
|
||||
});
|
||||
auto screen = Screen(20, 20);
|
||||
Render(screen, component->Render());
|
||||
EXPECT_EQ(position, 5);
|
||||
EXPECT_TRUE(component->OnEvent(MousePressed(14, 1)));
|
||||
EXPECT_EQ(position, 5);
|
||||
// Try to resize below min
|
||||
EXPECT_TRUE(component->OnEvent(MousePressed(18, 1)));
|
||||
EXPECT_EQ(position, 3); // Clamped to min
|
||||
// Try to resize above max
|
||||
EXPECT_TRUE(component->OnEvent(MousePressed(10, 1)));
|
||||
EXPECT_EQ(position, 8); // Clamped to max
|
||||
EXPECT_TRUE(component->OnEvent(MouseReleased(10, 1)));
|
||||
EXPECT_EQ(position, 8);
|
||||
}
|
||||
|
||||
TEST(ResizableSplit, MinMaxSizeTop) {
|
||||
int position = 5;
|
||||
auto component = ResizableSplit({
|
||||
.main = BasicComponent(),
|
||||
.back = BasicComponent(),
|
||||
.direction = Direction::Up,
|
||||
.main_size = &position,
|
||||
.separator_func = [] { return separatorDouble(); },
|
||||
.min = 2,
|
||||
.max = 10,
|
||||
});
|
||||
auto screen = Screen(20, 20);
|
||||
Render(screen, component->Render());
|
||||
EXPECT_EQ(position, 5);
|
||||
EXPECT_TRUE(component->OnEvent(MousePressed(1, 5)));
|
||||
EXPECT_EQ(position, 5);
|
||||
// Try to resize below min
|
||||
EXPECT_TRUE(component->OnEvent(MousePressed(1, 1)));
|
||||
EXPECT_EQ(position, 2); // Clamped to min
|
||||
// Try to resize above max
|
||||
EXPECT_TRUE(component->OnEvent(MousePressed(1, 15)));
|
||||
EXPECT_EQ(position, 10); // Clamped to max
|
||||
}
|
||||
|
||||
TEST(ResizableSplit, MinMaxSizeBottom) {
|
||||
int position = 5;
|
||||
auto component = ResizableSplit({
|
||||
.main = BasicComponent(),
|
||||
.back = BasicComponent(),
|
||||
.direction = Direction::Down,
|
||||
.main_size = &position,
|
||||
.separator_func = [] { return separatorDouble(); },
|
||||
.min = 3,
|
||||
.max = 12,
|
||||
});
|
||||
auto screen = Screen(20, 20);
|
||||
Render(screen, component->Render());
|
||||
EXPECT_EQ(position, 5);
|
||||
EXPECT_TRUE(component->OnEvent(MousePressed(1, 14)));
|
||||
EXPECT_EQ(position, 5);
|
||||
// Try to resize below min
|
||||
EXPECT_TRUE(component->OnEvent(MousePressed(1, 18)));
|
||||
EXPECT_EQ(position, 3); // Clamped to min
|
||||
// Try to resize above max
|
||||
EXPECT_TRUE(component->OnEvent(MousePressed(1, 5)));
|
||||
EXPECT_EQ(position, 12); // Clamped to max
|
||||
}
|
||||
|
||||
} // namespace ftxui
|
||||
// NOLINTEND
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
#include <string>
|
||||
#include <thread> // for thread, sleep_for
|
||||
#include <tuple> // for _Swallow_assign, ignore
|
||||
#include <type_traits> // for decay_t
|
||||
#include <utility> // for move, swap
|
||||
#include <variant> // for visit, variant
|
||||
#include <vector> // for vector
|
||||
@@ -28,13 +27,12 @@
|
||||
#include "ftxui/component/component_base.hpp" // for ComponentBase
|
||||
#include "ftxui/component/event.hpp" // for Event
|
||||
#include "ftxui/component/loop.hpp" // for Loop
|
||||
#include "ftxui/component/receiver.hpp" // for ReceiverImpl, Sender, MakeReceiver, SenderImpl, Receiver
|
||||
#include "ftxui/component/task_runner.hpp"
|
||||
#include "ftxui/component/terminal_input_parser.hpp" // for TerminalInputParser
|
||||
#include "ftxui/dom/node.hpp" // for Node, Render
|
||||
#include "ftxui/dom/requirement.hpp" // for Requirement
|
||||
#include "ftxui/screen/pixel.hpp" // for Pixel
|
||||
#include "ftxui/screen/terminal.hpp" // for Dimensions, Size
|
||||
#include "ftxui/screen/util.hpp" // for util::clamp
|
||||
#include "ftxui/util/autoreset.hpp" // for AutoReset
|
||||
|
||||
#if defined(_WIN32)
|
||||
#define DEFINE_CONSOLEV2_PROPERTIES
|
||||
@@ -47,9 +45,11 @@
|
||||
#error Must be compiled in UNICODE mode
|
||||
#endif
|
||||
#else
|
||||
#include <fcntl.h>
|
||||
#include <sys/select.h> // for select, FD_ISSET, FD_SET, FD_ZERO, fd_set, timeval
|
||||
#include <termios.h> // for tcsetattr, termios, tcgetattr, TCSANOW, cc_t, ECHO, ICANON, VMIN, VTIME
|
||||
#include <unistd.h> // for STDIN_FILENO, read
|
||||
#include <cerrno>
|
||||
#endif
|
||||
|
||||
// Quick exit is missing in standard CLang headers
|
||||
@@ -59,6 +59,20 @@
|
||||
|
||||
namespace ftxui {
|
||||
|
||||
struct ScreenInteractive::Internal {
|
||||
// Convert char to Event.
|
||||
TerminalInputParser terminal_input_parser;
|
||||
|
||||
task::TaskRunner task_runner;
|
||||
|
||||
// The last time a character was received.
|
||||
std::chrono::time_point<std::chrono::steady_clock> last_char_time =
|
||||
std::chrono::steady_clock::now();
|
||||
|
||||
explicit Internal(std::function<void(Event)> out)
|
||||
: terminal_input_parser(std::move(out)) {}
|
||||
};
|
||||
|
||||
namespace animation {
|
||||
void RequestAnimationFrame() {
|
||||
auto* screen = ScreenInteractive::Active();
|
||||
@@ -82,73 +96,9 @@ constexpr int timeout_milliseconds = 20;
|
||||
timeout_milliseconds * 1000;
|
||||
#if defined(_WIN32)
|
||||
|
||||
void EventListener(std::atomic<bool>* quit, Sender<Task> out) {
|
||||
auto console = GetStdHandle(STD_INPUT_HANDLE);
|
||||
auto parser = TerminalInputParser(out->Clone());
|
||||
while (!*quit) {
|
||||
// Throttle ReadConsoleInput by waiting 250ms, this wait function will
|
||||
// return if there is input in the console.
|
||||
auto wait_result = WaitForSingleObject(console, timeout_milliseconds);
|
||||
if (wait_result == WAIT_TIMEOUT) {
|
||||
parser.Timeout(timeout_milliseconds);
|
||||
continue;
|
||||
}
|
||||
|
||||
DWORD number_of_events = 0;
|
||||
if (!GetNumberOfConsoleInputEvents(console, &number_of_events))
|
||||
continue;
|
||||
if (number_of_events <= 0)
|
||||
continue;
|
||||
|
||||
std::vector<INPUT_RECORD> records{number_of_events};
|
||||
DWORD number_of_events_read = 0;
|
||||
ReadConsoleInput(console, records.data(), (DWORD)records.size(),
|
||||
&number_of_events_read);
|
||||
records.resize(number_of_events_read);
|
||||
|
||||
for (const auto& r : records) {
|
||||
switch (r.EventType) {
|
||||
case KEY_EVENT: {
|
||||
auto key_event = r.Event.KeyEvent;
|
||||
// ignore UP key events
|
||||
if (key_event.bKeyDown == FALSE)
|
||||
continue;
|
||||
std::wstring wstring;
|
||||
wstring += key_event.uChar.UnicodeChar;
|
||||
for (auto it : to_string(wstring)) {
|
||||
parser.Add(it);
|
||||
}
|
||||
} break;
|
||||
case WINDOW_BUFFER_SIZE_EVENT:
|
||||
out->Send(Event::Special({0}));
|
||||
break;
|
||||
case MENU_EVENT:
|
||||
case FOCUS_EVENT:
|
||||
case MOUSE_EVENT:
|
||||
// TODO(mauve): Implement later.
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#elif defined(__EMSCRIPTEN__)
|
||||
#include <emscripten.h>
|
||||
|
||||
// Read char from the terminal.
|
||||
void EventListener(std::atomic<bool>* quit, Sender<Task> out) {
|
||||
auto parser = TerminalInputParser(std::move(out));
|
||||
|
||||
char c;
|
||||
while (!*quit) {
|
||||
while (read(STDIN_FILENO, &c, 1), c)
|
||||
parser.Add(c);
|
||||
|
||||
emscripten_sleep(1);
|
||||
parser.Timeout(1);
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE
|
||||
void ftxui_on_resize(int columns, int rows) {
|
||||
@@ -162,33 +112,15 @@ void ftxui_on_resize(int columns, int rows) {
|
||||
|
||||
#else // POSIX (Linux & Mac)
|
||||
|
||||
int CheckStdinReady(int usec_timeout) {
|
||||
timeval tv = {0, usec_timeout}; // NOLINT
|
||||
int CheckStdinReady(int fd) {
|
||||
timeval tv = {0, 0}; // NOLINT
|
||||
fd_set fds;
|
||||
FD_ZERO(&fds); // NOLINT
|
||||
FD_SET(STDIN_FILENO, &fds); // NOLINT
|
||||
select(STDIN_FILENO + 1, &fds, nullptr, nullptr, &tv); // NOLINT
|
||||
return FD_ISSET(STDIN_FILENO, &fds); // NOLINT
|
||||
FD_SET(fd, &fds); // NOLINT
|
||||
select(fd + 1, &fds, nullptr, nullptr, &tv); // NOLINT
|
||||
return FD_ISSET(fd, &fds); // NOLINT
|
||||
}
|
||||
|
||||
// Read char from the terminal.
|
||||
void EventListener(std::atomic<bool>* quit, Sender<Task> out) {
|
||||
auto parser = TerminalInputParser(std::move(out));
|
||||
|
||||
while (!*quit) {
|
||||
if (!CheckStdinReady(timeout_microseconds)) {
|
||||
parser.Timeout(timeout_milliseconds);
|
||||
continue;
|
||||
}
|
||||
|
||||
const size_t buffer_size = 100;
|
||||
std::array<char, buffer_size> buffer; // NOLINT;
|
||||
size_t l = read(fileno(stdin), buffer.data(), buffer_size); // NOLINT
|
||||
for (size_t i = 0; i < l; ++i) {
|
||||
parser.Add(buffer[i]); // NOLINT
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
std::stack<Closure> on_exit_functions; // NOLINT
|
||||
@@ -335,15 +267,6 @@ class CapturedMouseImpl : public CapturedMouseInterface {
|
||||
std::function<void(void)> callback_;
|
||||
};
|
||||
|
||||
void AnimationListener(std::atomic<bool>* quit, Sender<Task> out) {
|
||||
// Animation at around 60fps.
|
||||
const auto time_delta = std::chrono::milliseconds(15);
|
||||
while (!*quit) {
|
||||
out->Send(AnimationTask());
|
||||
std::this_thread::sleep_for(time_delta);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ScreenInteractive::ScreenInteractive(Dimension dimension,
|
||||
@@ -353,7 +276,8 @@ ScreenInteractive::ScreenInteractive(Dimension dimension,
|
||||
: Screen(dimx, dimy),
|
||||
dimension_(dimension),
|
||||
use_alternative_screen_(use_alternative_screen) {
|
||||
task_receiver_ = MakeReceiver<Task>();
|
||||
internal_ = std::make_unique<Internal>(
|
||||
[&](Event event) { PostEvent(std::move(event)); });
|
||||
}
|
||||
|
||||
// static
|
||||
@@ -414,6 +338,8 @@ ScreenInteractive ScreenInteractive::TerminalOutput() {
|
||||
};
|
||||
}
|
||||
|
||||
ScreenInteractive::~ScreenInteractive() = default;
|
||||
|
||||
/// Create a ScreenInteractive whose width and height match the component being
|
||||
/// drawn.
|
||||
// static
|
||||
@@ -446,16 +372,24 @@ void ScreenInteractive::TrackMouse(bool enable) {
|
||||
track_mouse_ = enable;
|
||||
}
|
||||
|
||||
/// @brief Enable or disable automatic piped input handling.
|
||||
/// When enabled, FTXUI will detect piped input and redirect stdin from /dev/tty
|
||||
/// for keyboard input, allowing applications to read piped data while still
|
||||
/// receiving interactive keyboard events.
|
||||
/// @param enable Whether to enable piped input handling. Default is true.
|
||||
/// @note This must be called before Loop().
|
||||
/// @note This feature is enabled by default.
|
||||
/// @note This feature is only available on POSIX systems (Linux/macOS).
|
||||
void ScreenInteractive::HandlePipedInput(bool enable) {
|
||||
handle_piped_input_ = enable;
|
||||
}
|
||||
|
||||
/// @brief Add a task to the main loop.
|
||||
/// It will be executed later, after every other scheduled tasks.
|
||||
void ScreenInteractive::Post(Task task) {
|
||||
// Task/Events sent toward inactive screen or screen waiting to become
|
||||
// inactive are dropped.
|
||||
if (!task_sender_) {
|
||||
return;
|
||||
}
|
||||
|
||||
task_sender_->Send(std::move(task));
|
||||
internal_->task_runner.PostTask([this, task = std::move(task)]() mutable {
|
||||
HandleTask(component_, task);
|
||||
});
|
||||
}
|
||||
|
||||
/// @brief Add an event to the main loop.
|
||||
@@ -499,7 +433,7 @@ void ScreenInteractive::Loop(Component component) { // NOLINT
|
||||
|
||||
/// @brief Return whether the main loop has been quit.
|
||||
bool ScreenInteractive::HasQuitted() {
|
||||
return task_receiver_->HasQuitted();
|
||||
return quit_;
|
||||
}
|
||||
|
||||
// private
|
||||
@@ -605,6 +539,8 @@ void ScreenInteractive::Install() {
|
||||
// https://github.com/ArthurSonzogni/FTXUI/issues/846
|
||||
Flush();
|
||||
|
||||
InstallPipedInputHandling();
|
||||
|
||||
// After uninstalling the new configuration, flush it to the terminal to
|
||||
// ensure it is fully applied:
|
||||
on_exit_functions.emplace([] { Flush(); });
|
||||
@@ -656,15 +592,24 @@ void ScreenInteractive::Install() {
|
||||
|
||||
SetConsoleMode(stdin_handle, in_mode);
|
||||
SetConsoleMode(stdout_handle, out_mode);
|
||||
#else
|
||||
#else // POSIX (Linux & Mac)
|
||||
// #if defined(__EMSCRIPTEN__)
|
||||
//// Reading stdin isn't blocking.
|
||||
// int flags = fcntl(0, F_GETFL, 0);
|
||||
// fcntl(0, F_SETFL, flags | O_NONBLOCK);
|
||||
|
||||
//// Restore the terminal configuration on exit.
|
||||
// on_exit_functions.emplace([flags] { fcntl(0, F_SETFL, flags); });
|
||||
// #endif
|
||||
for (const int signal : {SIGWINCH, SIGTSTP}) {
|
||||
InstallSignalHandler(signal);
|
||||
}
|
||||
|
||||
struct termios terminal; // NOLINT
|
||||
tcgetattr(STDIN_FILENO, &terminal);
|
||||
on_exit_functions.emplace(
|
||||
[=] { tcsetattr(STDIN_FILENO, TCSANOW, &terminal); });
|
||||
tcgetattr(tty_fd_, &terminal);
|
||||
on_exit_functions.emplace([terminal = terminal, tty_fd_ = tty_fd_] {
|
||||
tcsetattr(tty_fd_, TCSANOW, &terminal);
|
||||
});
|
||||
|
||||
// Enabling raw terminal input mode
|
||||
terminal.c_iflag &= ~IGNBRK; // Disable ignoring break condition
|
||||
@@ -692,7 +637,7 @@ void ScreenInteractive::Install() {
|
||||
// read.
|
||||
terminal.c_cc[VTIME] = 0; // Timeout in deciseconds for non-canonical read.
|
||||
|
||||
tcsetattr(STDIN_FILENO, TCSANOW, &terminal);
|
||||
tcsetattr(tty_fd_, TCSANOW, &terminal);
|
||||
|
||||
#endif
|
||||
|
||||
@@ -729,40 +674,88 @@ void ScreenInteractive::Install() {
|
||||
Flush();
|
||||
|
||||
quit_ = false;
|
||||
task_sender_ = task_receiver_->MakeSender();
|
||||
event_listener_ =
|
||||
std::thread(&EventListener, &quit_, task_receiver_->MakeSender());
|
||||
animation_listener_ =
|
||||
std::thread(&AnimationListener, &quit_, task_receiver_->MakeSender());
|
||||
|
||||
PostAnimationTask();
|
||||
}
|
||||
|
||||
void ScreenInteractive::InstallPipedInputHandling() {
|
||||
#if !defined(_WIN32) && !defined(__EMSCRIPTEN__)
|
||||
tty_fd_ = STDIN_FILENO;
|
||||
// Handle piped input redirection if explicitly enabled by the application.
|
||||
// This allows applications to read data from stdin while still receiving
|
||||
// keyboard input from the terminal for interactive use.
|
||||
if (!handle_piped_input_) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If stdin is a terminal, we don't need to open /dev/tty.
|
||||
if (isatty(STDIN_FILENO)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Open /dev/tty for keyboard input.
|
||||
tty_fd_ = open("/dev/tty", O_RDONLY);
|
||||
if (tty_fd_ < 0) {
|
||||
// Failed to open /dev/tty (containers, headless systems, etc.)
|
||||
tty_fd_ = STDIN_FILENO; // Fallback to stdin.
|
||||
return;
|
||||
}
|
||||
|
||||
// Close the /dev/tty file descriptor on exit.
|
||||
on_exit_functions.emplace([this] {
|
||||
close(tty_fd_);
|
||||
tty_fd_ = -1;
|
||||
});
|
||||
#endif
|
||||
}
|
||||
|
||||
// private
|
||||
void ScreenInteractive::Uninstall() {
|
||||
ExitNow();
|
||||
event_listener_.join();
|
||||
animation_listener_.join();
|
||||
OnExit();
|
||||
}
|
||||
|
||||
// private
|
||||
// NOLINTNEXTLINE
|
||||
void ScreenInteractive::RunOnceBlocking(Component component) {
|
||||
ExecuteSignalHandlers();
|
||||
Task task;
|
||||
if (task_receiver_->Receive(&task)) {
|
||||
HandleTask(component, task);
|
||||
}
|
||||
// Set FPS to 60 at most.
|
||||
const auto time_per_frame = std::chrono::microseconds(16666); // 1s / 60fps
|
||||
|
||||
auto time = std::chrono::steady_clock::now();
|
||||
size_t executed_task = internal_->task_runner.ExecutedTasks();
|
||||
|
||||
// Wait for at least one task to execute.
|
||||
while (executed_task == internal_->task_runner.ExecutedTasks() &&
|
||||
!HasQuitted()) {
|
||||
RunOnce(component);
|
||||
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
const auto delta = now - time;
|
||||
time = now;
|
||||
|
||||
if (delta < time_per_frame) {
|
||||
const auto sleep_duration = time_per_frame - delta;
|
||||
std::this_thread::sleep_for(sleep_duration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// private
|
||||
void ScreenInteractive::RunOnce(Component component) {
|
||||
Task task;
|
||||
while (task_receiver_->ReceiveNonBlocking(&task)) {
|
||||
HandleTask(component, task);
|
||||
AutoReset set_component(&component_, component);
|
||||
ExecuteSignalHandlers();
|
||||
FetchTerminalEvents();
|
||||
|
||||
// Execute the pending tasks from the queue.
|
||||
const size_t executed_task = internal_->task_runner.ExecutedTasks();
|
||||
internal_->task_runner.RunUntilIdle();
|
||||
// If no executed task, we can return early without redrawing the screen.
|
||||
if (executed_task == internal_->task_runner.ExecutedTasks()) {
|
||||
return;
|
||||
}
|
||||
Draw(std::move(component));
|
||||
|
||||
ExecuteSignalHandlers();
|
||||
Draw(component);
|
||||
|
||||
if (selection_data_previous_ != selection_data_) {
|
||||
selection_data_previous_ = selection_data_;
|
||||
@@ -783,6 +776,7 @@ void ScreenInteractive::HandleTask(Component component, Task& task) {
|
||||
// clang-format off
|
||||
// Handle Event.
|
||||
if constexpr (std::is_same_v<T, Event>) {
|
||||
|
||||
if (arg.is_cursor_position()) {
|
||||
cursor_x_ = arg.cursor_x();
|
||||
cursor_y_ = arg.cursor_y();
|
||||
@@ -1034,7 +1028,6 @@ void ScreenInteractive::Exit() {
|
||||
// private:
|
||||
void ScreenInteractive::ExitNow() {
|
||||
quit_ = true;
|
||||
task_sender_.reset();
|
||||
}
|
||||
|
||||
// private:
|
||||
@@ -1061,12 +1054,130 @@ void ScreenInteractive::Signal(int signal) {
|
||||
}
|
||||
|
||||
if (signal == SIGWINCH) {
|
||||
Post(Event::Special({0}));
|
||||
Post(Event::Special(std::string({0})));
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void ScreenInteractive::FetchTerminalEvents() {
|
||||
#if defined(_WIN32)
|
||||
auto get_input_records = [&]() -> std::vector<INPUT_RECORD> {
|
||||
// Check if there is input in the console.
|
||||
auto console = GetStdHandle(STD_INPUT_HANDLE);
|
||||
DWORD number_of_events = 0;
|
||||
if (!GetNumberOfConsoleInputEvents(console, &number_of_events)) {
|
||||
return std::vector<INPUT_RECORD>();
|
||||
}
|
||||
if (number_of_events <= 0) {
|
||||
// No input, return.
|
||||
return std::vector<INPUT_RECORD>();
|
||||
}
|
||||
// Read the input events.
|
||||
std::vector<INPUT_RECORD> records(number_of_events);
|
||||
DWORD number_of_events_read = 0;
|
||||
if (!ReadConsoleInput(console, records.data(), (DWORD)records.size(),
|
||||
&number_of_events_read)) {
|
||||
return std::vector<INPUT_RECORD>();
|
||||
}
|
||||
records.resize(number_of_events_read);
|
||||
return records;
|
||||
};
|
||||
|
||||
auto records = get_input_records();
|
||||
if (records.size() == 0) {
|
||||
const auto timeout =
|
||||
std::chrono::steady_clock::now() - internal_->last_char_time;
|
||||
const size_t timeout_microseconds =
|
||||
std::chrono::duration_cast<std::chrono::microseconds>(timeout).count();
|
||||
internal_->terminal_input_parser.Timeout(timeout_microseconds);
|
||||
return;
|
||||
}
|
||||
internal_->last_char_time = std::chrono::steady_clock::now();
|
||||
|
||||
// Convert the input events to FTXUI events.
|
||||
// For each event, we call the terminal input parser to convert it to
|
||||
// Event.
|
||||
std::wstring wstring;
|
||||
for (const auto& r : records) {
|
||||
switch (r.EventType) {
|
||||
case KEY_EVENT: {
|
||||
auto key_event = r.Event.KeyEvent;
|
||||
// ignore UP key events
|
||||
if (key_event.bKeyDown == FALSE) {
|
||||
continue;
|
||||
}
|
||||
const wchar_t wc = key_event.uChar.UnicodeChar;
|
||||
wstring += wc;
|
||||
if (wc >= 0xd800 && wc <= 0xdbff) {
|
||||
// Wait for the Low Surrogate to arrive in the next record.
|
||||
continue;
|
||||
}
|
||||
for (auto it : to_string(wstring)) {
|
||||
internal_->terminal_input_parser.Add(it);
|
||||
}
|
||||
wstring.clear();
|
||||
} break;
|
||||
case WINDOW_BUFFER_SIZE_EVENT:
|
||||
Post(Event::Special({0}));
|
||||
break;
|
||||
case MENU_EVENT:
|
||||
case FOCUS_EVENT:
|
||||
case MOUSE_EVENT:
|
||||
// TODO(mauve): Implement later.
|
||||
break;
|
||||
}
|
||||
}
|
||||
#elif defined(__EMSCRIPTEN__)
|
||||
// Read chars from the terminal.
|
||||
// We configured it to be non blocking.
|
||||
std::array<char, 128> out{};
|
||||
size_t l = read(STDIN_FILENO, out.data(), out.size());
|
||||
if (l == 0) {
|
||||
const auto timeout =
|
||||
std::chrono::steady_clock::now() - internal_->last_char_time;
|
||||
const size_t timeout_microseconds =
|
||||
std::chrono::duration_cast<std::chrono::microseconds>(timeout).count();
|
||||
internal_->terminal_input_parser.Timeout(timeout_microseconds);
|
||||
return;
|
||||
}
|
||||
internal_->last_char_time = std::chrono::steady_clock::now();
|
||||
|
||||
// Convert the chars to events.
|
||||
for (size_t i = 0; i < l; ++i) {
|
||||
internal_->terminal_input_parser.Add(out[i]);
|
||||
}
|
||||
#else // POSIX (Linux & Mac)
|
||||
if (!CheckStdinReady(tty_fd_)) {
|
||||
const auto timeout =
|
||||
std::chrono::steady_clock::now() - internal_->last_char_time;
|
||||
const size_t timeout_ms =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count();
|
||||
internal_->terminal_input_parser.Timeout(timeout_ms);
|
||||
return;
|
||||
}
|
||||
internal_->last_char_time = std::chrono::steady_clock::now();
|
||||
|
||||
// Read chars from the terminal.
|
||||
std::array<char, 128> out{};
|
||||
size_t l = read(tty_fd_, out.data(), out.size());
|
||||
|
||||
// Convert the chars to events.
|
||||
for (size_t i = 0; i < l; ++i) {
|
||||
internal_->terminal_input_parser.Add(out[i]);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void ScreenInteractive::PostAnimationTask() {
|
||||
Post(AnimationTask());
|
||||
|
||||
// Repeat the animation task every 15ms. This correspond to a frame rate
|
||||
// of around 66fps.
|
||||
internal_->task_runner.PostDelayedTask([this] { PostAnimationTask(); },
|
||||
std::chrono::milliseconds(15));
|
||||
}
|
||||
|
||||
bool ScreenInteractive::SelectionData::operator==(
|
||||
const ScreenInteractive::SelectionData& other) const {
|
||||
if (empty && other.empty) {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/// @module ftxui.component.screen_interactive
|
||||
/// @module ftxui.component:ScreenInteractive
|
||||
/// @brief Module file for the ScreenInteractive class of the Component module
|
||||
|
||||
module;
|
||||
|
||||
#include <ftxui/component/screen_interactive.hpp>
|
||||
|
||||
export module ftxui.component.screen_interactive;
|
||||
export module ftxui.component:ScreenInteractive;
|
||||
|
||||
/**
|
||||
* @namespace ftxui
|
||||
|
||||
222
src/ftxui/component/screen_interactive_piped_input_test.cpp
Normal file
222
src/ftxui/component/screen_interactive_piped_input_test.cpp
Normal file
@@ -0,0 +1,222 @@
|
||||
// Copyright 2025 Arthur Sonzogni. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
#include <fcntl.h>
|
||||
#include <gtest/gtest.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <cstdio>
|
||||
|
||||
#include "ftxui/component/component.hpp"
|
||||
#include "ftxui/component/screen_interactive.hpp"
|
||||
#include "ftxui/dom/elements.hpp"
|
||||
|
||||
#if !defined(_WIN32) && !defined(__EMSCRIPTEN__)
|
||||
|
||||
namespace ftxui {
|
||||
|
||||
namespace {
|
||||
|
||||
// Test fixture for piped input functionality
|
||||
class PipedInputTest : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
// Save original stdin for restoration
|
||||
original_stdin_ = dup(STDIN_FILENO);
|
||||
}
|
||||
|
||||
void TearDown() override {
|
||||
// Restore original stdin
|
||||
if (original_stdin_ >= 0) {
|
||||
dup2(original_stdin_, STDIN_FILENO);
|
||||
close(original_stdin_);
|
||||
}
|
||||
}
|
||||
|
||||
// Create a pipe and redirect stdin to read from it
|
||||
void SetupPipedStdin() {
|
||||
if (pipe(pipe_fds_) == 0) {
|
||||
dup2(pipe_fds_[0], STDIN_FILENO);
|
||||
close(pipe_fds_[0]);
|
||||
// Keep write end open for writing test data
|
||||
piped_stdin_setup_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Write test data to the piped stdin
|
||||
void WriteToPipedStdin(const std::string& data) {
|
||||
if (piped_stdin_setup_) {
|
||||
write(pipe_fds_[1], data.c_str(), data.length());
|
||||
close(pipe_fds_[1]); // Close write end to signal EOF
|
||||
}
|
||||
}
|
||||
|
||||
// Check if /dev/tty is available (not available in some CI environments)
|
||||
bool IsTtyAvailable() {
|
||||
struct stat st;
|
||||
return stat("/dev/tty", &st) == 0;
|
||||
}
|
||||
|
||||
private:
|
||||
int original_stdin_ = -1;
|
||||
int pipe_fds_[2] = {-1, -1};
|
||||
bool piped_stdin_setup_ = false;
|
||||
};
|
||||
|
||||
TEST_F(PipedInputTest, DefaultBehaviorEnabled) {
|
||||
// Test that HandlePipedInput is enabled by default
|
||||
if (!IsTtyAvailable()) {
|
||||
GTEST_SKIP() << "/dev/tty not available in this environment";
|
||||
}
|
||||
|
||||
auto screen = ScreenInteractive::TerminalOutput();
|
||||
auto component = Renderer([] { return text("test"); });
|
||||
|
||||
SetupPipedStdin();
|
||||
WriteToPipedStdin("test data\n");
|
||||
|
||||
// Install should redirect stdin since HandlePipedInput is on by default
|
||||
screen.Install();
|
||||
|
||||
// Stdin should be the tty
|
||||
EXPECT_TRUE(isatty(STDIN_FILENO));
|
||||
|
||||
screen.Uninstall();
|
||||
}
|
||||
|
||||
TEST_F(PipedInputTest, ExplicitlyDisabled) {
|
||||
// Test that explicitly disabling works
|
||||
auto screen = ScreenInteractive::TerminalOutput();
|
||||
screen.HandlePipedInput(false);
|
||||
auto component = Renderer([] { return text("test"); });
|
||||
|
||||
SetupPipedStdin();
|
||||
WriteToPipedStdin("test data\n");
|
||||
|
||||
screen.Install();
|
||||
|
||||
// Stdin should still be the pipe since feature is disabled
|
||||
EXPECT_FALSE(isatty(STDIN_FILENO));
|
||||
|
||||
screen.Uninstall();
|
||||
}
|
||||
|
||||
TEST_F(PipedInputTest, ExplicitlyEnabled) {
|
||||
if (!IsTtyAvailable()) {
|
||||
GTEST_SKIP() << "/dev/tty not available in this environment";
|
||||
}
|
||||
|
||||
auto screen = ScreenInteractive::TerminalOutput();
|
||||
screen.HandlePipedInput(true); // Explicitly enable
|
||||
auto component = Renderer([] { return text("test"); });
|
||||
|
||||
SetupPipedStdin();
|
||||
WriteToPipedStdin("test data\n");
|
||||
|
||||
// Before install: stdin should be piped
|
||||
EXPECT_FALSE(isatty(STDIN_FILENO));
|
||||
|
||||
screen.Install();
|
||||
|
||||
// After install with piped input handling: stdin should be redirected to tty
|
||||
EXPECT_TRUE(isatty(STDIN_FILENO));
|
||||
|
||||
screen.Uninstall();
|
||||
|
||||
// After uninstall: stdin should be restored to original state
|
||||
// Note: This will be the pipe we set up, so it should be non-tty
|
||||
EXPECT_FALSE(isatty(STDIN_FILENO));
|
||||
}
|
||||
|
||||
TEST_F(PipedInputTest, NormalStdinUnchanged) {
|
||||
// Test that normal stdin (not piped) is not affected
|
||||
auto screen = ScreenInteractive::TerminalOutput();
|
||||
auto component = Renderer([] { return text("test"); });
|
||||
|
||||
// Don't setup piped stdin - use normal stdin
|
||||
bool original_isatty = isatty(STDIN_FILENO);
|
||||
|
||||
screen.Install();
|
||||
|
||||
// Stdin should remain unchanged
|
||||
EXPECT_EQ(original_isatty, isatty(STDIN_FILENO));
|
||||
|
||||
screen.Uninstall();
|
||||
|
||||
// Stdin should still be unchanged
|
||||
EXPECT_EQ(original_isatty, isatty(STDIN_FILENO));
|
||||
}
|
||||
|
||||
TEST_F(PipedInputTest, MultipleInstallUninstallCycles) {
|
||||
if (!IsTtyAvailable()) {
|
||||
GTEST_SKIP() << "/dev/tty not available in this environment";
|
||||
}
|
||||
|
||||
auto screen = ScreenInteractive::TerminalOutput();
|
||||
auto component = Renderer([] { return text("test"); });
|
||||
|
||||
SetupPipedStdin();
|
||||
WriteToPipedStdin("test data\n");
|
||||
|
||||
// First cycle
|
||||
screen.Install();
|
||||
EXPECT_TRUE(isatty(STDIN_FILENO));
|
||||
screen.Uninstall();
|
||||
EXPECT_FALSE(isatty(STDIN_FILENO));
|
||||
|
||||
// Second cycle should work the same
|
||||
screen.Install();
|
||||
EXPECT_TRUE(isatty(STDIN_FILENO));
|
||||
screen.Uninstall();
|
||||
EXPECT_FALSE(isatty(STDIN_FILENO));
|
||||
}
|
||||
|
||||
TEST_F(PipedInputTest, HandlePipedInputMethodBehavior) {
|
||||
auto screen = ScreenInteractive::TerminalOutput();
|
||||
|
||||
// Test method can be called multiple times
|
||||
screen.HandlePipedInput(true);
|
||||
screen.HandlePipedInput(false);
|
||||
screen.HandlePipedInput(true);
|
||||
|
||||
// Should be enabled after last call
|
||||
SetupPipedStdin();
|
||||
WriteToPipedStdin("test data\n");
|
||||
|
||||
if (IsTtyAvailable()) {
|
||||
screen.Install();
|
||||
EXPECT_TRUE(isatty(STDIN_FILENO));
|
||||
screen.Uninstall();
|
||||
}
|
||||
}
|
||||
|
||||
// Test the graceful fallback when /dev/tty is not available
|
||||
// This test simulates environments like containers where /dev/tty might not
|
||||
// exist
|
||||
TEST_F(PipedInputTest, GracefulFallbackWhenTtyUnavailable) {
|
||||
auto screen = ScreenInteractive::TerminalOutput();
|
||||
auto component = Renderer([] { return text("test"); });
|
||||
|
||||
SetupPipedStdin();
|
||||
WriteToPipedStdin("test data\n");
|
||||
|
||||
// This test doesn't directly mock /dev/tty unavailability since that's hard
|
||||
// to do in a unit test environment, but the code path handles freopen()
|
||||
// failure gracefully
|
||||
screen.Install();
|
||||
|
||||
// The behavior depends on whether /dev/tty is available
|
||||
// If available, stdin gets redirected; if not, it remains piped
|
||||
// Both behaviors are correct
|
||||
|
||||
screen.Uninstall();
|
||||
|
||||
// After uninstall, stdin should be restored
|
||||
EXPECT_FALSE(isatty(STDIN_FILENO)); // Should still be our test pipe
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
} // namespace ftxui
|
||||
|
||||
#endif // !defined(_WIN32) && !defined(__EMSCRIPTEN__)
|
||||
@@ -27,9 +27,10 @@ namespace {
|
||||
// Capture the standard output (stdout) to a string.
|
||||
class StdCapture {
|
||||
public:
|
||||
explicit StdCapture(std::string* captured)
|
||||
: captured_(captured) {
|
||||
if (pipe(pipefd_) != 0) return;
|
||||
explicit StdCapture(std::string* captured) : captured_(captured) {
|
||||
if (pipe(pipefd_) != 0) {
|
||||
return;
|
||||
}
|
||||
old_stdout_ = dup(fileno(stdout));
|
||||
fflush(stdout);
|
||||
dup2(pipefd_[1], fileno(stdout));
|
||||
@@ -188,14 +189,14 @@ TEST(ScreenInteractive, FixedSizeInitialFrame) {
|
||||
auto capture = StdCapture(&output);
|
||||
|
||||
auto screen = ScreenInteractive::FixedSize(2, 2);
|
||||
auto component = Renderer([&] {
|
||||
return text("AB");
|
||||
});
|
||||
auto component = Renderer([&] { return text("AB"); });
|
||||
|
||||
Loop loop(&screen, component);
|
||||
loop.RunOnce();
|
||||
}
|
||||
ASSERT_EQ(
|
||||
using namespace std::string_view_literals;
|
||||
|
||||
auto expected =
|
||||
// Install the ScreenInteractive.
|
||||
"\0" // Flush stdout.
|
||||
"\x1BP$q q" // Set cursor shape to 1 (block).
|
||||
@@ -236,10 +237,9 @@ TEST(ScreenInteractive, FixedSizeInitialFrame) {
|
||||
"\0" // Flush stdout.
|
||||
|
||||
// Skip one line to avoid the prompt to be printed over the last drawing.
|
||||
"\r\n",
|
||||
output);
|
||||
"\r\n"sv;
|
||||
ASSERT_EQ(expected, output);
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
} // namespace ftxui
|
||||
|
||||
@@ -33,6 +33,20 @@ Decorator flexDirection(Direction direction) {
|
||||
return xflex; // NOT_REACHED()
|
||||
}
|
||||
|
||||
Direction Opposite(Direction d) {
|
||||
switch (d) {
|
||||
case Direction::Up:
|
||||
return Direction::Down;
|
||||
case Direction::Down:
|
||||
return Direction::Up;
|
||||
case Direction::Left:
|
||||
return Direction::Right;
|
||||
case Direction::Right:
|
||||
return Direction::Left;
|
||||
}
|
||||
return d; // NOT_REACHED()
|
||||
}
|
||||
|
||||
template <class T>
|
||||
class SliderBase : public SliderOption<T>, public ComponentBase {
|
||||
public:
|
||||
@@ -47,59 +61,15 @@ class SliderBase : public SliderOption<T>, public ComponentBase {
|
||||
flexDirection(this->direction) | reflect(gauge_box_) | gauge_color;
|
||||
}
|
||||
|
||||
void OnLeft() {
|
||||
switch (this->direction) {
|
||||
case Direction::Right:
|
||||
this->value() -= this->increment();
|
||||
break;
|
||||
case Direction::Left:
|
||||
void OnDirection(Direction pressed) {
|
||||
if (pressed == this->direction) {
|
||||
this->value() += this->increment();
|
||||
break;
|
||||
case Direction::Up:
|
||||
case Direction::Down:
|
||||
break;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
void OnRight() {
|
||||
switch (this->direction) {
|
||||
case Direction::Right:
|
||||
this->value() += this->increment();
|
||||
break;
|
||||
case Direction::Left:
|
||||
if (pressed == Opposite(this->direction)) {
|
||||
this->value() -= this->increment();
|
||||
break;
|
||||
case Direction::Up:
|
||||
case Direction::Down:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void OnUp() {
|
||||
switch (this->direction) {
|
||||
case Direction::Up:
|
||||
this->value() -= this->increment();
|
||||
break;
|
||||
case Direction::Down:
|
||||
this->value() += this->increment();
|
||||
break;
|
||||
case Direction::Left:
|
||||
case Direction::Right:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void OnDown() {
|
||||
switch (this->direction) {
|
||||
case Direction::Down:
|
||||
this->value() += this->increment();
|
||||
break;
|
||||
case Direction::Up:
|
||||
this->value() -= this->increment();
|
||||
break;
|
||||
case Direction::Left:
|
||||
case Direction::Right:
|
||||
break;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,16 +80,16 @@ class SliderBase : public SliderOption<T>, public ComponentBase {
|
||||
|
||||
T old_value = this->value();
|
||||
if (event == Event::ArrowLeft || event == Event::Character('h')) {
|
||||
OnLeft();
|
||||
OnDirection(Direction::Left);
|
||||
}
|
||||
if (event == Event::ArrowRight || event == Event::Character('l')) {
|
||||
OnRight();
|
||||
OnDirection(Direction::Right);
|
||||
}
|
||||
if (event == Event::ArrowUp || event == Event::Character('k')) {
|
||||
OnDown();
|
||||
OnDirection(Direction::Up);
|
||||
}
|
||||
if (event == Event::ArrowDown || event == Event::Character('j')) {
|
||||
OnUp();
|
||||
OnDirection(Direction::Down);
|
||||
}
|
||||
|
||||
this->value() = std::max(this->min(), std::min(this->max(), this->value()));
|
||||
|
||||
19
src/ftxui/component/task.cpp
Normal file
19
src/ftxui/component/task.cpp
Normal file
@@ -0,0 +1,19 @@
|
||||
// Copyright 2024 Arthur Sonzogni. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
#include "ftxui/component/task_internal.hpp"
|
||||
|
||||
namespace ftxui::task {
|
||||
bool PendingTask::operator<(const PendingTask& other) const {
|
||||
if (!time && !other.time) {
|
||||
return false;
|
||||
}
|
||||
if (!time) {
|
||||
return true;
|
||||
}
|
||||
if (!other.time) {
|
||||
return false;
|
||||
}
|
||||
return time.value() > other.time.value();
|
||||
}
|
||||
} // namespace ftxui::task
|
||||
@@ -1,11 +1,11 @@
|
||||
/// @module ftxui.component.task
|
||||
/// @module ftxui.component:Task
|
||||
/// @brief Module file for the Task class of the Component module
|
||||
|
||||
module;
|
||||
|
||||
#include <ftxui/component/task.hpp>
|
||||
|
||||
export module ftxui.component.task;
|
||||
export module ftxui.component:Task;
|
||||
|
||||
/**
|
||||
* @namespace ftxui
|
||||
|
||||
40
src/ftxui/component/task_internal.hpp
Normal file
40
src/ftxui/component/task_internal.hpp
Normal file
@@ -0,0 +1,40 @@
|
||||
// Copyright 2024 Arthur Sonzogni. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
#ifndef TASK_HPP
|
||||
#define TASK_HPP
|
||||
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
|
||||
namespace ftxui::task {
|
||||
|
||||
/// A task represents a unit of work.
|
||||
using Task = std::function<void()>;
|
||||
|
||||
/// A PendingTask represents a task that is scheduled to be executed at a
|
||||
/// specific time, or as soon as possible.
|
||||
struct PendingTask {
|
||||
// Immediate task:
|
||||
PendingTask(Task t) : task(std::move(t)) {} // NOLINT
|
||||
|
||||
// Delayed task with a duration
|
||||
PendingTask(Task t, std::chrono::steady_clock::duration duration)
|
||||
: task(std::move(t)), time(std::chrono::steady_clock::now() + duration) {}
|
||||
|
||||
/// The task to be executed.
|
||||
Task task;
|
||||
|
||||
/// The time when the task should be executed. If the time is empty, the task
|
||||
/// should be executed as soon as possible.
|
||||
std::optional<std::chrono::steady_clock::time_point> time;
|
||||
|
||||
/// Compare two PendingTasks by their time.
|
||||
/// If both tasks have no time, they are considered equal.
|
||||
bool operator<(const PendingTask& other) const;
|
||||
};
|
||||
|
||||
} // namespace ftxui::task
|
||||
|
||||
#endif // TASK_HPP_
|
||||
53
src/ftxui/component/task_queue.cpp
Normal file
53
src/ftxui/component/task_queue.cpp
Normal file
@@ -0,0 +1,53 @@
|
||||
// Copyright 2024 Arthur Sonzogni. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
#include "ftxui/component/task_queue.hpp"
|
||||
|
||||
namespace ftxui::task {
|
||||
|
||||
auto TaskQueue::PostTask(PendingTask task) -> void {
|
||||
if (!task.time) {
|
||||
immediate_tasks_.push(task);
|
||||
return;
|
||||
}
|
||||
|
||||
if (task.time.value() < std::chrono::steady_clock::now()) {
|
||||
immediate_tasks_.push(task);
|
||||
return;
|
||||
}
|
||||
|
||||
delayed_tasks_.push(task);
|
||||
}
|
||||
|
||||
auto TaskQueue::Get() -> MaybeTask {
|
||||
// Attempt to execute a task immediately.
|
||||
if (!immediate_tasks_.empty()) {
|
||||
auto task = immediate_tasks_.front();
|
||||
immediate_tasks_.pop();
|
||||
return task.task;
|
||||
}
|
||||
|
||||
// Move all tasks that can be executed to the immediate queue.
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
while (!delayed_tasks_.empty() && delayed_tasks_.top().time.value() <= now) {
|
||||
immediate_tasks_.push(delayed_tasks_.top());
|
||||
delayed_tasks_.pop();
|
||||
}
|
||||
|
||||
// Attempt to execute a task immediately.
|
||||
if (!immediate_tasks_.empty()) {
|
||||
auto task = immediate_tasks_.front();
|
||||
immediate_tasks_.pop();
|
||||
return task.task;
|
||||
}
|
||||
|
||||
// If there are no tasks to execute, return the delay until the next task.
|
||||
if (!delayed_tasks_.empty()) {
|
||||
return delayed_tasks_.top().time.value() - now;
|
||||
}
|
||||
|
||||
// If there are no tasks to execute, return the maximum duration.
|
||||
return std::monostate{};
|
||||
}
|
||||
|
||||
} // namespace ftxui::task
|
||||
37
src/ftxui/component/task_queue.hpp
Normal file
37
src/ftxui/component/task_queue.hpp
Normal file
@@ -0,0 +1,37 @@
|
||||
// Copyright 2024 Arthur Sonzogni. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
#ifndef TASK_QUEUE_HPP
|
||||
#define TASK_QUEUE_HPP
|
||||
|
||||
#include <queue>
|
||||
#include <variant>
|
||||
|
||||
#include "ftxui/component/task_internal.hpp" // for PendingTask, Task
|
||||
|
||||
namespace ftxui::task {
|
||||
|
||||
/// A task queue that schedules tasks to be executed in the future. Tasks can be
|
||||
/// scheduled to be executed immediately, or after a certain duration.
|
||||
/// - The tasks are executed in the order they were scheduled.
|
||||
/// - If multiple tasks are scheduled to be executed at the same time, they are
|
||||
/// executed in the order they were scheduled.
|
||||
/// - If a task is scheduled to be executed in the past, it is executed
|
||||
/// immediately.
|
||||
struct TaskQueue {
|
||||
auto PostTask(PendingTask task) -> void;
|
||||
|
||||
using MaybeTask =
|
||||
std::variant<Task, std::chrono::steady_clock::duration, std::monostate>;
|
||||
auto Get() -> MaybeTask;
|
||||
|
||||
bool HasImmediateTasks() const { return !immediate_tasks_.empty(); }
|
||||
|
||||
private:
|
||||
std::queue<PendingTask> immediate_tasks_;
|
||||
std::priority_queue<PendingTask> delayed_tasks_;
|
||||
};
|
||||
|
||||
} // namespace ftxui::task
|
||||
|
||||
#endif
|
||||
75
src/ftxui/component/task_runner.cpp
Normal file
75
src/ftxui/component/task_runner.cpp
Normal file
@@ -0,0 +1,75 @@
|
||||
// Copyright 2024 Arthur Sonzogni. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
#include "ftxui/component/task_runner.hpp"
|
||||
|
||||
#include <cassert>
|
||||
#include <thread>
|
||||
|
||||
namespace ftxui::task {
|
||||
|
||||
static thread_local TaskRunner* current_task_runner = nullptr; // NOLINT
|
||||
|
||||
TaskRunner::TaskRunner() {
|
||||
assert(!previous_task_runner_);
|
||||
previous_task_runner_ = current_task_runner;
|
||||
current_task_runner = this;
|
||||
}
|
||||
|
||||
TaskRunner::~TaskRunner() {
|
||||
current_task_runner = previous_task_runner_;
|
||||
}
|
||||
|
||||
// static
|
||||
auto TaskRunner::Current() -> TaskRunner* {
|
||||
assert(current_task_runner);
|
||||
return current_task_runner;
|
||||
}
|
||||
|
||||
auto TaskRunner::PostTask(Task task) -> void {
|
||||
queue_.PostTask(PendingTask{std::move(task)});
|
||||
}
|
||||
|
||||
auto TaskRunner::PostDelayedTask(Task task,
|
||||
std::chrono::steady_clock::duration duration)
|
||||
-> void {
|
||||
queue_.PostTask(PendingTask{std::move(task), duration});
|
||||
}
|
||||
|
||||
/// Runs the tasks in the queue.
|
||||
auto TaskRunner::RunUntilIdle()
|
||||
-> std::optional<std::chrono::steady_clock::duration> {
|
||||
while (true) {
|
||||
auto maybe_task = queue_.Get();
|
||||
if (std::holds_alternative<std::monostate>(maybe_task)) {
|
||||
// No more tasks to execute, exit the loop.
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
if (std::holds_alternative<Task>(maybe_task)) {
|
||||
executed_tasks_++;
|
||||
std::get<Task>(maybe_task)();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (std::holds_alternative<std::chrono::steady_clock::duration>(
|
||||
maybe_task)) {
|
||||
return std::get<std::chrono::steady_clock::duration>(maybe_task);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto TaskRunner::Run() -> void {
|
||||
while (true) {
|
||||
auto duration = RunUntilIdle();
|
||||
if (!duration) {
|
||||
// No more tasks to execute, exit the loop.
|
||||
return;
|
||||
}
|
||||
|
||||
// Sleep for the duration until the next task can be executed.
|
||||
std::this_thread::sleep_for(duration.value());
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace ftxui::task
|
||||
46
src/ftxui/component/task_runner.hpp
Normal file
46
src/ftxui/component/task_runner.hpp
Normal file
@@ -0,0 +1,46 @@
|
||||
// Copyright 2024 Arthur Sonzogni. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
#ifndef TASK_RUNNER_HPP
|
||||
#define TASK_RUNNER_HPP
|
||||
|
||||
#include "ftxui/component/task_internal.hpp"
|
||||
#include "ftxui/component/task_queue.hpp"
|
||||
|
||||
namespace ftxui::task {
|
||||
|
||||
class TaskRunner {
|
||||
public:
|
||||
TaskRunner();
|
||||
~TaskRunner();
|
||||
|
||||
// Returns the task runner for the current thread.
|
||||
static auto Current() -> TaskRunner*;
|
||||
|
||||
/// Schedules a task to be executed immediately.
|
||||
auto PostTask(Task task) -> void;
|
||||
|
||||
/// Schedules a task to be executed after a certain duration.
|
||||
auto PostDelayedTask(Task task, std::chrono::steady_clock::duration duration)
|
||||
-> void;
|
||||
|
||||
/// Runs the tasks in the queue, return the delay until the next delayed task
|
||||
/// can be executed.
|
||||
auto RunUntilIdle() -> std::optional<std::chrono::steady_clock::duration>;
|
||||
|
||||
// Runs the tasks in the queue, blocking until all tasks are executed.
|
||||
auto Run() -> void;
|
||||
|
||||
bool HasImmediateTasks() const { return queue_.HasImmediateTasks(); }
|
||||
|
||||
size_t ExecutedTasks() const { return executed_tasks_; }
|
||||
|
||||
private:
|
||||
TaskRunner* previous_task_runner_ = nullptr;
|
||||
TaskQueue queue_;
|
||||
size_t executed_tasks_ = 0;
|
||||
};
|
||||
|
||||
} // namespace ftxui::task
|
||||
|
||||
#endif // TASK_RUNNER_HPP
|
||||
94
src/ftxui/component/task_test.cpp
Normal file
94
src/ftxui/component/task_test.cpp
Normal file
@@ -0,0 +1,94 @@
|
||||
// Copyright 2024 Arthur Sonzogni. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
// Copyright 2024 Arthur Sonzogni. All rights reserved.
|
||||
// Use of this source code is governed by the MIT license that can be found in
|
||||
// the LICENSE file.
|
||||
#include "ftxui/component/task_internal.hpp"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <thread> // for sleep_for
|
||||
#include "ftxui/component/task_runner.hpp"
|
||||
|
||||
namespace ftxui::task {
|
||||
|
||||
TEST(TaskTest, Basic) {
|
||||
std::vector<int> values;
|
||||
|
||||
auto task_1 = [&values] { values.push_back(1); };
|
||||
auto task_2 = [&values] { values.push_back(2); };
|
||||
auto task_3 = [&values] { values.push_back(3); };
|
||||
|
||||
auto runner = TaskRunner();
|
||||
|
||||
runner.PostTask(task_1);
|
||||
runner.PostTask(task_2);
|
||||
runner.PostTask(task_3);
|
||||
while (true) {
|
||||
auto duration = runner.RunUntilIdle();
|
||||
if (!duration) {
|
||||
break;
|
||||
}
|
||||
std::this_thread::sleep_for(duration.value());
|
||||
}
|
||||
|
||||
EXPECT_EQ(values, (std::vector<int>{1, 2, 3}));
|
||||
}
|
||||
|
||||
TEST(TaskTest, PostedWithinTask) {
|
||||
std::vector<int> values;
|
||||
|
||||
auto task_1 = [&values] {
|
||||
values.push_back(1);
|
||||
auto task_2 = [&values] { values.push_back(5); };
|
||||
TaskRunner::Current()->PostTask(std::move(task_2));
|
||||
values.push_back(2);
|
||||
};
|
||||
|
||||
auto task_2 = [&values] {
|
||||
values.push_back(3);
|
||||
auto task_2 = [&values] { values.push_back(6); };
|
||||
TaskRunner::Current()->PostTask(std::move(task_2));
|
||||
values.push_back(4);
|
||||
};
|
||||
|
||||
auto runner = TaskRunner();
|
||||
|
||||
runner.PostTask(task_1);
|
||||
runner.PostTask(task_2);
|
||||
while (true) {
|
||||
auto duration = runner.RunUntilIdle();
|
||||
if (!duration) {
|
||||
break;
|
||||
}
|
||||
std::this_thread::sleep_for(duration.value());
|
||||
}
|
||||
|
||||
EXPECT_EQ(values, (std::vector<int>{1, 2, 3, 4, 5, 6}));
|
||||
}
|
||||
|
||||
TEST(TaskTest, RunDelayedTask) {
|
||||
std::vector<int> values;
|
||||
|
||||
auto task_1 = [&values] { values.push_back(1); };
|
||||
auto task_2 = [&values] { values.push_back(2); };
|
||||
auto task_3 = [&values] { values.push_back(3); };
|
||||
|
||||
auto runner = TaskRunner();
|
||||
|
||||
runner.PostDelayedTask(task_3, std::chrono::milliseconds(300));
|
||||
runner.PostDelayedTask(task_1, std::chrono::milliseconds(100));
|
||||
runner.PostDelayedTask(task_2, std::chrono::milliseconds(200));
|
||||
while (true) {
|
||||
auto duration = runner.RunUntilIdle();
|
||||
if (!duration) {
|
||||
break;
|
||||
}
|
||||
std::this_thread::sleep_for(duration.value());
|
||||
}
|
||||
|
||||
EXPECT_EQ(values, (std::vector<int>{1, 2, 3}));
|
||||
}
|
||||
|
||||
} // namespace ftxui::task
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user