mirror of
https://github.com/ArthurSonzogni/FTXUI.git
synced 2025-12-16 01:48:56 +08:00
Compare commits
26 Commits
copilot/fi
...
d9c62b3678
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
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
|
||||||
16
.github/workflows/documentation.yaml
vendored
16
.github/workflows/documentation.yaml
vendored
@@ -12,6 +12,10 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: "Checkout repository"
|
- name: "Checkout repository"
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
fetch-depth: 0 # Need full history.
|
||||||
|
fetch-tags: true # Need tags.
|
||||||
|
|
||||||
|
|
||||||
- name: "Install cmake"
|
- name: "Install cmake"
|
||||||
uses: lukka/get-cmake@latest
|
uses: lukka/get-cmake@latest
|
||||||
@@ -30,7 +34,12 @@ jobs:
|
|||||||
sudo apt-get install graphviz;
|
sudo apt-get install graphviz;
|
||||||
|
|
||||||
- name: "Build documentation"
|
- name: "Build documentation"
|
||||||
|
run: |
|
||||||
|
python3 ./tools/build_multiversion_doc.py
|
||||||
|
|
||||||
|
- name: "Build examples"
|
||||||
run: >
|
run: >
|
||||||
|
mkdir -p multiversion_docs/main/examples;
|
||||||
mkdir build;
|
mkdir build;
|
||||||
cd build;
|
cd build;
|
||||||
emcmake cmake ..
|
emcmake cmake ..
|
||||||
@@ -41,8 +50,7 @@ jobs:
|
|||||||
-DFTXUI_BUILD_TESTS_FUZZER=OFF
|
-DFTXUI_BUILD_TESTS_FUZZER=OFF
|
||||||
-DFTXUI_ENABLE_INSTALL=OFF
|
-DFTXUI_ENABLE_INSTALL=OFF
|
||||||
-DFTXUI_DEV_WARNINGS=OFF;
|
-DFTXUI_DEV_WARNINGS=OFF;
|
||||||
cmake --build . --target doc;
|
cmake --build .;
|
||||||
cmake --build . ;
|
|
||||||
rsync -amv
|
rsync -amv
|
||||||
--include='*/'
|
--include='*/'
|
||||||
--include='*.html'
|
--include='*.html'
|
||||||
@@ -52,13 +60,13 @@ jobs:
|
|||||||
--include='*.wasm'
|
--include='*.wasm'
|
||||||
--exclude='*'
|
--exclude='*'
|
||||||
examples
|
examples
|
||||||
doc/doxygen/html;
|
../multiversion_docs/
|
||||||
|
|
||||||
- name: "Deploy"
|
- name: "Deploy"
|
||||||
uses: peaceiris/actions-gh-pages@v3
|
uses: peaceiris/actions-gh-pages@v3
|
||||||
with:
|
with:
|
||||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
publish_dir: build/doc/doxygen/html/
|
publish_dir: multiversion_docs
|
||||||
enable_jekyll: false
|
enable_jekyll: false
|
||||||
allow_empty_commit: false
|
allow_empty_commit: false
|
||||||
force_orphan: true
|
force_orphan: true
|
||||||
|
|||||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -28,6 +28,7 @@ out/
|
|||||||
# .github directory:
|
# .github directory:
|
||||||
!.github/**/*.yaml
|
!.github/**/*.yaml
|
||||||
!.github/**/*.yml
|
!.github/**/*.yml
|
||||||
|
!.github/**/*.md
|
||||||
|
|
||||||
# cmake directory:
|
# cmake directory:
|
||||||
!cmake/**/*.in
|
!cmake/**/*.in
|
||||||
@@ -44,6 +45,7 @@ out/
|
|||||||
!doc/**/*.html
|
!doc/**/*.html
|
||||||
!doc/**/*.xml
|
!doc/**/*.xml
|
||||||
!doc/**/*.md
|
!doc/**/*.md
|
||||||
|
!doc/*.md
|
||||||
|
|
||||||
# examples directory:
|
# examples directory:
|
||||||
!examples/**/*.cpp
|
!examples/**/*.cpp
|
||||||
@@ -69,4 +71,6 @@ out/
|
|||||||
|
|
||||||
# tools directory:
|
# tools directory:
|
||||||
!tools/**/*.sh
|
!tools/**/*.sh
|
||||||
|
!tools/**/*.py
|
||||||
!tools/**/*.cpp
|
!tools/**/*.cpp
|
||||||
|
build/
|
||||||
|
|||||||
11
CHANGELOG.md
11
CHANGELOG.md
@@ -27,11 +27,22 @@ Next
|
|||||||
- Remove dependency on 'pthread'.
|
- Remove dependency on 'pthread'.
|
||||||
|
|
||||||
### Component
|
### 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
|
- Fix ScreenInteractive::FixedSize screen stomps on the preceding terminal
|
||||||
output. Thanks @zozowell in #1064.
|
output. Thanks @zozowell in #1064.
|
||||||
- Fix vertical `ftxui::Slider`. The "up" key was previously decreasing the
|
- Fix vertical `ftxui::Slider`. The "up" key was previously decreasing the
|
||||||
value. Thanks @its-pablo in #1093 for reporting the issue.
|
value. Thanks @its-pablo in #1093 for reporting 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)
|
6.1.9 (2025-05-07)
|
||||||
------------
|
------------
|
||||||
|
|||||||
15
README.md
15
README.md
@@ -22,6 +22,12 @@
|
|||||||
<a href="https://arthursonzogni.github.io/FTXUI/examples/">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/issues">Request Feature</a> ·
|
||||||
<a href="https://github.com/ArthurSonzogni/FTXUI/pulls">Send a Pull Request</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>
|
</p>
|
||||||
|
|
||||||
@@ -365,6 +371,7 @@ Feel free to add your projects here:
|
|||||||
- [SHOOT!](https://github.com/ShingZhanho/ENGG1340-Project-25Spring)
|
- [SHOOT!](https://github.com/ShingZhanho/ENGG1340-Project-25Spring)
|
||||||
- [VerifySN (Fast Hash Tool)](https://github.com/d06i/verifySN)
|
- [VerifySN (Fast Hash Tool)](https://github.com/d06i/verifySN)
|
||||||
- [tic-tac-toe](https://github.com/birland/tic-tac-toe)
|
- [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)
|
### [cpp-best-practices/game_jam](https://github.com/cpp-best-practices/game_jam)
|
||||||
|
|
||||||
@@ -381,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)
|
- [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)
|
- [Consu](https://github.com/cpp-best-practices/game_jam/blob/main/Jam1_April_2022/consu.md)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
## Build using CMake
|
## 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.
|
It is **highly** recommended to use CMake FetchContent to depend on FTXUI so you may specify which commit you would like to depend on.
|
||||||
@@ -416,9 +425,9 @@ cc_binary(
|
|||||||
name = "your_target",
|
name = "your_target",
|
||||||
srcs = ["your_source.cc"],
|
srcs = ["your_source.cc"],
|
||||||
deps = [
|
deps = [
|
||||||
"@ftxui//:ftxui_component",
|
"@ftxui//:component",
|
||||||
"@ftxui//:ftxui_dom",
|
"@ftxui//:dom",
|
||||||
"@ftxui//:ftxui_screen",
|
"@ftxui//:screen",
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ include(FetchContent)
|
|||||||
|
|
||||||
FetchContent_Declare(googletest
|
FetchContent_Declare(googletest
|
||||||
GIT_REPOSITORY "https://github.com/google/googletest"
|
GIT_REPOSITORY "https://github.com/google/googletest"
|
||||||
GIT_TAG 23ef29555ef4789f555f1ba8c51b4c52975f0907
|
GIT_TAG 52eb8108c5bdec04579160ae17225d66034bd723 # v1.17.0
|
||||||
GIT_PROGRESS TRUE
|
GIT_PROGRESS TRUE
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ include(CMakePackageConfigHelpers)
|
|||||||
install(
|
install(
|
||||||
TARGETS screen dom component
|
TARGETS screen dom component
|
||||||
EXPORT ftxui-targets
|
EXPORT ftxui-targets
|
||||||
|
ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
|
||||||
|
LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}"
|
||||||
|
RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
|
||||||
)
|
)
|
||||||
|
|
||||||
install(
|
install(
|
||||||
|
|||||||
@@ -4,15 +4,15 @@
|
|||||||
> [!WARNING]
|
> [!WARNING]
|
||||||
> This feature is still in development, and the API may change in future releases.
|
> 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
|
> 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.
|
> please open an issue.
|
||||||
|
|
||||||
FTXUI experimentally supports
|
FTXUI experimentally supports
|
||||||
[C++20 modules](https://en.cppreference.com/w/cpp/language/modules) to reduce
|
[C++20 modules](https://en.cppreference.com/w/cpp/language/modules) to reduce
|
||||||
compilation times and improve code organization. Each header has a
|
compilation times and improve code organization. Each part of the library has a
|
||||||
corresponding module.
|
corresponding module, split into partitions per each header.
|
||||||
|
|
||||||
Use the FTXUI_BUILD_MODULES option to build the FTXUI project itself to provide C++ 20 modules,
|
Use the FTXUI_BUILD_MODULES option to build the FTXUI project itself to provide C++20 modules,
|
||||||
for example with CMake and Ninja:
|
for example with CMake and Ninja:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -25,7 +25,7 @@ ninja
|
|||||||
```
|
```
|
||||||
|
|
||||||
> [!NOTE]
|
> [!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
|
> higher, and use a compatible generator like Ninja. Note that Makefile
|
||||||
> generators **do not support modules**.
|
> generators **do not support modules**.
|
||||||
|
|
||||||
@@ -34,9 +34,12 @@ Then, in your own code you can consume the modules and code as normal:
|
|||||||
```cpp
|
```cpp
|
||||||
import ftxui;
|
import ftxui;
|
||||||
|
|
||||||
|
using ftxui::Button;
|
||||||
|
using ftxui::ScreenInteractive;
|
||||||
|
|
||||||
int main() {
|
int main() {
|
||||||
auto screen = ftxui::ScreenInteractive::TerminalOutput();
|
auto screen = ScreenInteractive::TerminalOutput();
|
||||||
auto button = ftxui::Button("Click me", screen.QuitClosure());
|
auto button = Button("Click me", screen.QuitClosure());
|
||||||
screen.Loop(button);
|
screen.Loop(button);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -70,38 +73,6 @@ are available:
|
|||||||
|
|
||||||
- `ftxui`
|
- `ftxui`
|
||||||
- `ftxui.component`
|
- `ftxui.component`
|
||||||
- `ftxui.component.Animation`
|
- `ftxui.dom`
|
||||||
- `ftxui.component.CapturedMouse`
|
- `ftxui.screen`
|
||||||
- `ftxui.component.Component`
|
- `ftxui.util`
|
||||||
- `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`
|
|
||||||
|
|||||||
@@ -2,16 +2,9 @@
|
|||||||
<!-- start footer part -->
|
<!-- start footer part -->
|
||||||
<!--BEGIN GENERATE_TREEVIEW-->
|
<!--BEGIN GENERATE_TREEVIEW-->
|
||||||
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
|
<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>
|
</div>
|
||||||
<!--END GENERATE_TREEVIEW-->
|
<!--END GENERATE_TREEVIEW-->
|
||||||
<!--BEGIN !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-->
|
<!--END !GENERATE_TREEVIEW-->
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -92,6 +92,24 @@
|
|||||||
|
|
||||||
</script>
|
</script>
|
||||||
<script type="module">
|
<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
|
// Click on the navtree, except for the main page where this is already done
|
||||||
// automatically.
|
// automatically.
|
||||||
let delay = 0;
|
let delay = 0;
|
||||||
|
|||||||
@@ -91,7 +91,7 @@ add_executable(demo demo.cpp)
|
|||||||
target_link_libraries(demo PRIVATE ftxui::component)
|
target_link_libraries(demo PRIVATE ftxui::component)
|
||||||
```
|
```
|
||||||
|
|
||||||
@todo 考虑到中国多数地区使用Conan很有可能遇到各种网络问题,我想做一个定制的版本说明,但是我对conan的了解有限再加上没有找到合适的资料,因此这个计划短暂的被搁置了,如果您知道方法,欢迎在[中文版本](xiaoditx.girhub.io/public/docs/ftxui%E4%B8%AD%E6%96%87%E7%BF%BB%E8%AF%91/installation/conan/)的下方留下评论以提醒我
|
@todo 中国大陆在这方面的下载可能会受限制,需要一个替代的方案
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ Clone and build the project using CMake:
|
|||||||
```bash
|
```bash
|
||||||
git clone https://github.com/ArthurSonzogni/FTXUI.git
|
git clone https://github.com/ArthurSonzogni/FTXUI.git
|
||||||
cd FTXUI
|
cd FTXUI
|
||||||
cmake -S . -B build -DFTXUI_ENABLE_INSTALL=ON -D
|
cmake -S . -B build -D FTXUI_ENABLE_INSTALL=ON
|
||||||
cmake --build build -j
|
cmake --build build -j
|
||||||
sudo cmake --install build
|
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);
|
||||||
|
```
|
||||||
@@ -39,6 +39,7 @@ example(radiobox)
|
|||||||
example(radiobox_in_frame)
|
example(radiobox_in_frame)
|
||||||
example(renderer)
|
example(renderer)
|
||||||
example(resizable_split)
|
example(resizable_split)
|
||||||
|
example(resizable_split_clamp)
|
||||||
example(scrollbar)
|
example(scrollbar)
|
||||||
example(selection)
|
example(selection)
|
||||||
example(slider)
|
example(slider)
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
// the LICENSE file.
|
// the LICENSE file.
|
||||||
#include <memory> // for shared_ptr, allocator, __shared_ptr_access
|
#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.hpp" // for Renderer, ResizableSplitBottom, ResizableSplitLeft, ResizableSplitRight, ResizableSplitTop
|
||||||
#include "ftxui/component/component_base.hpp" // for ComponentBase
|
#include "ftxui/component/component_base.hpp" // for ComponentBase
|
||||||
#include "ftxui/component/screen_interactive.hpp" // for ScreenInteractive
|
#include "ftxui/component/screen_interactive.hpp" // for ScreenInteractive
|
||||||
@@ -14,17 +13,24 @@ using namespace ftxui;
|
|||||||
int main() {
|
int main() {
|
||||||
auto screen = ScreenInteractive::Fullscreen();
|
auto screen = ScreenInteractive::Fullscreen();
|
||||||
|
|
||||||
auto middle = Renderer([] { return text("middle") | center; });
|
// State:
|
||||||
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; });
|
|
||||||
|
|
||||||
int left_size = 20;
|
int left_size = 20;
|
||||||
int right_size = 20;
|
int right_size = 20;
|
||||||
int top_size = 10;
|
int top_size = 10;
|
||||||
int bottom_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;
|
auto container = middle;
|
||||||
container = ResizableSplitLeft(left, container, &left_size);
|
container = ResizableSplitLeft(left, container, &left_size);
|
||||||
container = ResizableSplitRight(right, container, &right_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);
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@
|
|||||||
#include <ftxui/util/ref.hpp> // for Ref, ConstRef, StringRef
|
#include <ftxui/util/ref.hpp> // for Ref, ConstRef, StringRef
|
||||||
#include <ftxui/util/warn_windows_macro.hpp>
|
#include <ftxui/util/warn_windows_macro.hpp>
|
||||||
#include <functional> // for function
|
#include <functional> // for function
|
||||||
|
#include <limits> // for numeric_limits
|
||||||
#include <string> // for string
|
#include <string> // for string
|
||||||
|
|
||||||
#include "ftxui/component/component_base.hpp" // for Component
|
#include "ftxui/component/component_base.hpp" // for Component
|
||||||
@@ -217,6 +218,10 @@ struct ResizableSplitOption {
|
|||||||
(direction() == Direction::Left || direction() == Direction::Right) ? 20
|
(direction() == Direction::Left || direction() == Direction::Right) ? 20
|
||||||
: 10;
|
: 10;
|
||||||
std::function<Element()> separator_func = [] { return ::ftxui::separator(); };
|
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.
|
// @brief Option for the `Slider` component.
|
||||||
|
|||||||
@@ -4,14 +4,14 @@
|
|||||||
#ifndef FTXUI_COMPONENT_RECEIVER_HPP_
|
#ifndef FTXUI_COMPONENT_RECEIVER_HPP_
|
||||||
#define FTXUI_COMPONENT_RECEIVER_HPP_
|
#define FTXUI_COMPONENT_RECEIVER_HPP_
|
||||||
|
|
||||||
#include <ftxui/util/warn_windows_macro.hpp>
|
|
||||||
#include <algorithm> // for copy, max
|
#include <algorithm> // for copy, max
|
||||||
#include <atomic> // for atomic, __atomic_base
|
#include <atomic> // for atomic, __atomic_base
|
||||||
#include <condition_variable> // for condition_variable
|
#include <condition_variable> // for condition_variable
|
||||||
#include <memory> // for unique_ptr, make_unique
|
#include <ftxui/util/warn_windows_macro.hpp>
|
||||||
#include <mutex> // for mutex, unique_lock
|
#include <memory> // for unique_ptr, make_unique
|
||||||
#include <queue> // for queue
|
#include <mutex> // for mutex, unique_lock
|
||||||
#include <utility> // for move
|
#include <queue> // for queue
|
||||||
|
#include <utility> // for move
|
||||||
|
|
||||||
namespace ftxui {
|
namespace ftxui {
|
||||||
|
|
||||||
|
|||||||
@@ -43,10 +43,11 @@ class ScreenInteractive : public Screen {
|
|||||||
static ScreenInteractive TerminalOutput();
|
static ScreenInteractive TerminalOutput();
|
||||||
|
|
||||||
// Destructor.
|
// Destructor.
|
||||||
~ScreenInteractive();
|
~ScreenInteractive() override;
|
||||||
|
|
||||||
// Options. Must be called before Loop().
|
// Options. Must be called before Loop().
|
||||||
void TrackMouse(bool enable = true);
|
void TrackMouse(bool enable = true);
|
||||||
|
void HandlePipedInput(bool enable = true);
|
||||||
|
|
||||||
// Return the currently active screen, nullptr if none.
|
// Return the currently active screen, nullptr if none.
|
||||||
static ScreenInteractive* Active();
|
static ScreenInteractive* Active();
|
||||||
@@ -100,6 +101,8 @@ class ScreenInteractive : public Screen {
|
|||||||
void Draw(Component component);
|
void Draw(Component component);
|
||||||
void ResetCursorPosition();
|
void ResetCursorPosition();
|
||||||
|
|
||||||
|
void InstallPipedInputHandling();
|
||||||
|
|
||||||
void Signal(int signal);
|
void Signal(int signal);
|
||||||
|
|
||||||
void FetchTerminalEvents();
|
void FetchTerminalEvents();
|
||||||
@@ -117,6 +120,7 @@ class ScreenInteractive : public Screen {
|
|||||||
int dimx,
|
int dimx,
|
||||||
int dimy,
|
int dimy,
|
||||||
bool use_alternative_screen);
|
bool use_alternative_screen);
|
||||||
|
|
||||||
const Dimension dimension_;
|
const Dimension dimension_;
|
||||||
const bool use_alternative_screen_;
|
const bool use_alternative_screen_;
|
||||||
|
|
||||||
@@ -141,6 +145,11 @@ class ScreenInteractive : public Screen {
|
|||||||
bool force_handle_ctrl_c_ = true;
|
bool force_handle_ctrl_c_ = true;
|
||||||
bool force_handle_ctrl_z_ = 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.
|
// The style of the cursor to restore on exit.
|
||||||
int cursor_reset_shape_ = 1;
|
int cursor_reset_shape_ = 1;
|
||||||
|
|
||||||
|
|||||||
@@ -5,25 +5,18 @@
|
|||||||
#define FTXUI_DOM_TAKE_ANY_ARGS_HPP
|
#define FTXUI_DOM_TAKE_ANY_ARGS_HPP
|
||||||
|
|
||||||
// IWYU pragma: private, include "ftxui/dom/elements.hpp"
|
// IWYU pragma: private, include "ftxui/dom/elements.hpp"
|
||||||
|
#include <deque>
|
||||||
#include <ftxui/dom/node.hpp>
|
#include <ftxui/dom/node.hpp>
|
||||||
|
#include <queue>
|
||||||
|
#include <stack>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
namespace ftxui {
|
namespace ftxui {
|
||||||
|
|
||||||
template <class T>
|
|
||||||
void Merge(Elements& /*container*/, T /*element*/) {}
|
|
||||||
|
|
||||||
template <>
|
|
||||||
inline void Merge(Elements& container, Element element) {
|
inline void Merge(Elements& container, Element element) {
|
||||||
container.push_back(std::move(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.
|
// Turn a set of arguments into a vector.
|
||||||
template <class... Args>
|
template <class... Args>
|
||||||
Elements unpack(Args... args) {
|
Elements unpack(Args... args) {
|
||||||
@@ -32,11 +25,50 @@ Elements unpack(Args... args) {
|
|||||||
return vec;
|
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) \
|
#define TAKE_ANY_ARGS(container) \
|
||||||
|
inline Element container(Element child) { \
|
||||||
|
return container(unpack(std::move(child))); \
|
||||||
|
} \
|
||||||
|
\
|
||||||
template <class... Args> \
|
template <class... Args> \
|
||||||
Element container(Args... children) { \
|
inline Element container(Args... children) { \
|
||||||
return container(unpack(std::forward<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)
|
TAKE_ANY_ARGS(vbox)
|
||||||
|
|||||||
@@ -3,14 +3,14 @@
|
|||||||
|
|
||||||
export module ftxui.component;
|
export module ftxui.component;
|
||||||
|
|
||||||
export import ftxui.component.animation;
|
export import :Animation;
|
||||||
export import ftxui.component.captured_mouse;
|
export import :CapturedMouse;
|
||||||
export import ftxui.component.component;
|
export import :Component;
|
||||||
export import ftxui.component.component_base;
|
export import :ComponentBase;
|
||||||
export import ftxui.component.component_options;
|
export import :ComponentOptions;
|
||||||
export import ftxui.component.event;
|
export import :Event;
|
||||||
export import ftxui.component.loop;
|
export import :Loop;
|
||||||
export import ftxui.component.mouse;
|
export import :Mouse;
|
||||||
export import ftxui.component.receiver;
|
export import :Receiver;
|
||||||
export import ftxui.component.screen_interactive;
|
export import :ScreenInteractive;
|
||||||
export import ftxui.component.task;
|
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.
|
/// @brief C++20 module interface for the Animation namespace of the Component module.
|
||||||
///
|
///
|
||||||
|
|
||||||
@@ -6,7 +6,7 @@ module;
|
|||||||
|
|
||||||
#include <ftxui/component/animation.hpp>
|
#include <ftxui/component/animation.hpp>
|
||||||
|
|
||||||
export module ftxui.component.animation;
|
export module ftxui.component:Animation;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui::animation
|
* @namespace ftxui::animation
|
||||||
@@ -23,7 +23,7 @@ export namespace ftxui::animation {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace easing
|
* @namespace easing
|
||||||
* @brief The FTXUI sf::animation::easing:: namespace
|
* @brief The FTXUI ftxui::animation::easing:: namespace
|
||||||
*/
|
*/
|
||||||
namespace easing {
|
namespace easing {
|
||||||
using ftxui::animation::easing::Function;
|
using ftxui::animation::easing::Function;
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.component.captured_mouse
|
/// @module ftxui.component.CapturedMouse
|
||||||
/// @brief Module file for the CapturedMouseInterface class of the Component module
|
/// @brief Module file for the CapturedMouseInterface class of the Component module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/component/captured_mouse.hpp>
|
#include <ftxui/component/captured_mouse.hpp>
|
||||||
|
|
||||||
export module ftxui.component.captured_mouse;
|
export module ftxui.component:CapturedMouse;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.component.component
|
/// @module ftxui.component:Component
|
||||||
/// @brief Module file for the Component classes of the Component module
|
/// @brief Module file for the Component classes of the Component module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/component/component.hpp>
|
#include <ftxui/component/component.hpp>
|
||||||
|
|
||||||
export module ftxui.component.component;
|
export module ftxui.component:Component;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
@@ -28,6 +28,10 @@ export namespace ftxui {
|
|||||||
using ftxui::operator|;
|
using ftxui::operator|;
|
||||||
using ftxui::operator|=;
|
using ftxui::operator|=;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @namespace Container
|
||||||
|
* @brief The FTXUI ftxui::Container:: namespace
|
||||||
|
*/
|
||||||
namespace Container {
|
namespace Container {
|
||||||
using ftxui::Container::Vertical;
|
using ftxui::Container::Vertical;
|
||||||
using ftxui::Container::Horizontal;
|
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
|
/// @brief Module file for the ComponentBase class of the Component module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/component/component_base.hpp>
|
#include <ftxui/component/component_base.hpp>
|
||||||
|
|
||||||
export module ftxui.component.component_base;
|
export module ftxui.component:ComponentBase;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
@@ -16,6 +16,10 @@ export namespace ftxui {
|
|||||||
using ftxui::Focus;
|
using ftxui::Focus;
|
||||||
using ftxui::Event;
|
using ftxui::Event;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @namespace animation
|
||||||
|
* @brief The FTXUI ftxui::animation:: namespace
|
||||||
|
*/
|
||||||
namespace animation {
|
namespace animation {
|
||||||
using ftxui::animation::Params;
|
using ftxui::animation::Params;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
/// @brief Module file for options for the Component class of the Component module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/component/component_options.hpp>
|
#include <ftxui/component/component_options.hpp>
|
||||||
|
|
||||||
export module ftxui.component.component_options;
|
export module ftxui.component:ComponentOptions;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.component.event
|
/// @module ftxui.component:Event
|
||||||
/// @brief Module file for the Event struct of the Component module
|
/// @brief Module file for the Event struct of the Component module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/component/event.hpp>
|
#include <ftxui/component/event.hpp>
|
||||||
|
|
||||||
export module ftxui.component.event;
|
export module ftxui.component:Event;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -173,7 +173,7 @@ class InputBase : public ComponentBase, public InputOption {
|
|||||||
elements.push_back(element);
|
elements.push_back(element);
|
||||||
}
|
}
|
||||||
|
|
||||||
auto element = vbox(std::move(elements), cursor_line) | frame;
|
auto element = vbox(std::move(elements)) | frame;
|
||||||
return transform_func({
|
return transform_func({
|
||||||
std::move(element), hovered_, is_focused,
|
std::move(element), hovered_, is_focused,
|
||||||
false // placeholder
|
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
|
/// @brief Module file for the Loop class of the Component module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/component/loop.hpp>
|
#include <ftxui/component/loop.hpp>
|
||||||
|
|
||||||
export module ftxui.component.loop;
|
export module ftxui.component:Loop;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -145,8 +145,8 @@ class MenuBase : public ComponentBase, public MenuOption {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const Element bar = IsHorizontal()
|
const Element bar = IsHorizontal()
|
||||||
? hbox(std::move(elements), selected_focus_)
|
? hbox(std::move(elements))
|
||||||
: vbox(std::move(elements), selected_focus_);
|
: vbox(std::move(elements));
|
||||||
|
|
||||||
if (!underline.enabled) {
|
if (!underline.enabled) {
|
||||||
return bar | reflect(box_);
|
return bar | reflect(box_);
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.component.mouse
|
/// @module ftxui.component:Mouse
|
||||||
/// @brief Module file for the Mouse struct of the Component module
|
/// @brief Module file for the Mouse struct of the Component module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/component/mouse.hpp>
|
#include <ftxui/component/mouse.hpp>
|
||||||
|
|
||||||
export module ftxui.component.mouse;
|
export module ftxui.component:Mouse;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ class RadioboxBase : public ComponentBase, public RadioboxOption {
|
|||||||
}
|
}
|
||||||
elements.push_back(element | reflect(boxes_[i]));
|
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)
|
// NOLINTNEXTLINE(readability-function-cognitive-complexity)
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.component.receiver
|
/// @module ftxui.component:Receiver
|
||||||
/// @brief Module file for the Receiver class of the Component module
|
/// @brief Module file for the Receiver class of the Component module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/component/receiver.hpp>
|
#include <ftxui/component/receiver.hpp>
|
||||||
|
|
||||||
export module ftxui.component.receiver;
|
export module ftxui.component:Receiver;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// Copyright 2021 Arthur Sonzogni. All rights reserved.
|
// Copyright 2021 Arthur Sonzogni. All rights reserved.
|
||||||
// Use of this source code is governed by the MIT license that can be found in
|
// Use of this source code is governed by the MIT license that can be found in
|
||||||
// the LICENSE file.
|
// the LICENSE file.
|
||||||
|
#include <algorithm> // for max
|
||||||
#include <ftxui/component/component_options.hpp> // for ResizableSplitOption
|
#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/dom/direction.hpp> // for Direction, Direction::Down, Direction::Left, Direction::Right, Direction::Up
|
||||||
#include <ftxui/util/ref.hpp> // for Ref
|
#include <ftxui/util/ref.hpp> // for Ref
|
||||||
@@ -18,34 +19,22 @@
|
|||||||
namespace ftxui {
|
namespace ftxui {
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
class ResizableSplitBase : public ComponentBase {
|
class ResizableSplitBase : public ComponentBase, public ResizableSplitOption {
|
||||||
public:
|
public:
|
||||||
explicit ResizableSplitBase(ResizableSplitOption options)
|
explicit ResizableSplitBase(ResizableSplitOption options)
|
||||||
: options_(std::move(options)) {
|
: ResizableSplitOption(std::move(options)) {
|
||||||
switch (options_->direction()) {
|
switch (direction()) {
|
||||||
case Direction::Left:
|
case Direction::Left:
|
||||||
Add(Container::Horizontal({
|
Add(Container::Horizontal({main, back}));
|
||||||
options_->main,
|
|
||||||
options_->back,
|
|
||||||
}));
|
|
||||||
break;
|
break;
|
||||||
case Direction::Right:
|
case Direction::Right:
|
||||||
Add(Container::Horizontal({
|
Add(Container::Horizontal({back, main}));
|
||||||
options_->back,
|
|
||||||
options_->main,
|
|
||||||
}));
|
|
||||||
break;
|
break;
|
||||||
case Direction::Up:
|
case Direction::Up:
|
||||||
Add(Container::Vertical({
|
Add(Container::Vertical({main, back}));
|
||||||
options_->main,
|
|
||||||
options_->back,
|
|
||||||
}));
|
|
||||||
break;
|
break;
|
||||||
case Direction::Down:
|
case Direction::Down:
|
||||||
Add(Container::Vertical({
|
Add(Container::Vertical({back, main}));
|
||||||
options_->back,
|
|
||||||
options_->main,
|
|
||||||
}));
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -75,27 +64,27 @@ class ResizableSplitBase : public ComponentBase {
|
|||||||
return ComponentBase::OnEvent(event);
|
return ComponentBase::OnEvent(event);
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (options_->direction()) {
|
switch (direction()) {
|
||||||
case Direction::Left:
|
case Direction::Left:
|
||||||
options_->main_size() = std::max(0, event.mouse().x - box_.x_min);
|
main_size() = std::max(0, event.mouse().x - box_.x_min);
|
||||||
return true;
|
break;
|
||||||
case Direction::Right:
|
case Direction::Right:
|
||||||
options_->main_size() = std::max(0, box_.x_max - event.mouse().x);
|
main_size() = std::max(0, box_.x_max - event.mouse().x);
|
||||||
return true;
|
break;
|
||||||
case Direction::Up:
|
case Direction::Up:
|
||||||
options_->main_size() = std::max(0, event.mouse().y - box_.y_min);
|
main_size() = std::max(0, event.mouse().y - box_.y_min);
|
||||||
return true;
|
break;
|
||||||
case Direction::Down:
|
case Direction::Down:
|
||||||
options_->main_size() = std::max(0, box_.y_max - event.mouse().y);
|
main_size() = std::max(0, box_.y_max - event.mouse().y);
|
||||||
return true;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// NOTREACHED()
|
main_size() = std::clamp(main_size(), min(), max());
|
||||||
return false;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
Element OnRender() final {
|
Element OnRender() final {
|
||||||
switch (options_->direction()) {
|
switch (direction()) {
|
||||||
case Direction::Left:
|
case Direction::Left:
|
||||||
return RenderLeft();
|
return RenderLeft();
|
||||||
case Direction::Right:
|
case Direction::Right:
|
||||||
@@ -111,46 +100,41 @@ class ResizableSplitBase : public ComponentBase {
|
|||||||
|
|
||||||
Element RenderLeft() {
|
Element RenderLeft() {
|
||||||
return hbox({
|
return hbox({
|
||||||
options_->main->Render() |
|
main->Render() | size(WIDTH, EQUAL, main_size()),
|
||||||
size(WIDTH, EQUAL, options_->main_size()),
|
separator_func() | reflect(separator_box_),
|
||||||
options_->separator_func() | reflect(separator_box_),
|
back->Render() | xflex,
|
||||||
options_->back->Render() | xflex,
|
|
||||||
}) |
|
}) |
|
||||||
reflect(box_);
|
reflect(box_);
|
||||||
}
|
}
|
||||||
|
|
||||||
Element RenderRight() {
|
Element RenderRight() {
|
||||||
return hbox({
|
return hbox({
|
||||||
options_->back->Render() | xflex,
|
back->Render() | xflex,
|
||||||
options_->separator_func() | reflect(separator_box_),
|
separator_func() | reflect(separator_box_),
|
||||||
options_->main->Render() |
|
main->Render() | size(WIDTH, EQUAL, main_size()),
|
||||||
size(WIDTH, EQUAL, options_->main_size()),
|
|
||||||
}) |
|
}) |
|
||||||
reflect(box_);
|
reflect(box_);
|
||||||
}
|
}
|
||||||
|
|
||||||
Element RenderTop() {
|
Element RenderTop() {
|
||||||
return vbox({
|
return vbox({
|
||||||
options_->main->Render() |
|
main->Render() | size(HEIGHT, EQUAL, main_size()),
|
||||||
size(HEIGHT, EQUAL, options_->main_size()),
|
separator_func() | reflect(separator_box_),
|
||||||
options_->separator_func() | reflect(separator_box_),
|
back->Render() | yflex,
|
||||||
options_->back->Render() | yflex,
|
|
||||||
}) |
|
}) |
|
||||||
reflect(box_);
|
reflect(box_);
|
||||||
}
|
}
|
||||||
|
|
||||||
Element RenderBottom() {
|
Element RenderBottom() {
|
||||||
return vbox({
|
return vbox({
|
||||||
options_->back->Render() | yflex,
|
back->Render() | yflex,
|
||||||
options_->separator_func() | reflect(separator_box_),
|
separator_func() | reflect(separator_box_),
|
||||||
options_->main->Render() |
|
main->Render() | size(HEIGHT, EQUAL, main_size()),
|
||||||
size(HEIGHT, EQUAL, options_->main_size()),
|
|
||||||
}) |
|
}) |
|
||||||
reflect(box_);
|
reflect(box_);
|
||||||
}
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
Ref<ResizableSplitOption> options_;
|
|
||||||
CapturedMouse captured_mouse_;
|
CapturedMouse captured_mouse_;
|
||||||
Box separator_box_;
|
Box separator_box_;
|
||||||
Box box_;
|
Box box_;
|
||||||
|
|||||||
@@ -233,5 +233,105 @@ TEST(ResizableSplit, NavigationVertical) {
|
|||||||
EXPECT_FALSE(component_bottom->Active());
|
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
|
} // namespace ftxui
|
||||||
// NOLINTEND
|
// NOLINTEND
|
||||||
|
|||||||
@@ -112,13 +112,13 @@ void ftxui_on_resize(int columns, int rows) {
|
|||||||
|
|
||||||
#else // POSIX (Linux & Mac)
|
#else // POSIX (Linux & Mac)
|
||||||
|
|
||||||
int CheckStdinReady() {
|
int CheckStdinReady(int fd) {
|
||||||
timeval tv = {0, 0}; // NOLINT
|
timeval tv = {0, 0}; // NOLINT
|
||||||
fd_set fds;
|
fd_set fds;
|
||||||
FD_ZERO(&fds); // NOLINT
|
FD_ZERO(&fds); // NOLINT
|
||||||
FD_SET(STDIN_FILENO, &fds); // NOLINT
|
FD_SET(fd, &fds); // NOLINT
|
||||||
select(STDIN_FILENO + 1, &fds, nullptr, nullptr, &tv); // NOLINT
|
select(fd + 1, &fds, nullptr, nullptr, &tv); // NOLINT
|
||||||
return FD_ISSET(STDIN_FILENO, &fds); // NOLINT
|
return FD_ISSET(fd, &fds); // NOLINT
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
@@ -372,6 +372,18 @@ void ScreenInteractive::TrackMouse(bool enable) {
|
|||||||
track_mouse_ = 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.
|
/// @brief Add a task to the main loop.
|
||||||
/// It will be executed later, after every other scheduled tasks.
|
/// It will be executed later, after every other scheduled tasks.
|
||||||
void ScreenInteractive::Post(Task task) {
|
void ScreenInteractive::Post(Task task) {
|
||||||
@@ -527,6 +539,8 @@ void ScreenInteractive::Install() {
|
|||||||
// https://github.com/ArthurSonzogni/FTXUI/issues/846
|
// https://github.com/ArthurSonzogni/FTXUI/issues/846
|
||||||
Flush();
|
Flush();
|
||||||
|
|
||||||
|
InstallPipedInputHandling();
|
||||||
|
|
||||||
// After uninstalling the new configuration, flush it to the terminal to
|
// After uninstalling the new configuration, flush it to the terminal to
|
||||||
// ensure it is fully applied:
|
// ensure it is fully applied:
|
||||||
on_exit_functions.emplace([] { Flush(); });
|
on_exit_functions.emplace([] { Flush(); });
|
||||||
@@ -592,9 +606,10 @@ void ScreenInteractive::Install() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
struct termios terminal; // NOLINT
|
struct termios terminal; // NOLINT
|
||||||
tcgetattr(STDIN_FILENO, &terminal);
|
tcgetattr(tty_fd_, &terminal);
|
||||||
on_exit_functions.emplace(
|
on_exit_functions.emplace([terminal = terminal, tty_fd_ = tty_fd_] {
|
||||||
[=] { tcsetattr(STDIN_FILENO, TCSANOW, &terminal); });
|
tcsetattr(tty_fd_, TCSANOW, &terminal);
|
||||||
|
});
|
||||||
|
|
||||||
// Enabling raw terminal input mode
|
// Enabling raw terminal input mode
|
||||||
terminal.c_iflag &= ~IGNBRK; // Disable ignoring break condition
|
terminal.c_iflag &= ~IGNBRK; // Disable ignoring break condition
|
||||||
@@ -622,7 +637,7 @@ void ScreenInteractive::Install() {
|
|||||||
// read.
|
// read.
|
||||||
terminal.c_cc[VTIME] = 0; // Timeout in deciseconds for non-canonical read.
|
terminal.c_cc[VTIME] = 0; // Timeout in deciseconds for non-canonical read.
|
||||||
|
|
||||||
tcsetattr(STDIN_FILENO, TCSANOW, &terminal);
|
tcsetattr(tty_fd_, TCSANOW, &terminal);
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
@@ -663,6 +678,37 @@ void ScreenInteractive::Install() {
|
|||||||
PostAnimationTask();
|
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
|
// private
|
||||||
void ScreenInteractive::Uninstall() {
|
void ScreenInteractive::Uninstall() {
|
||||||
ExitNow();
|
ExitNow();
|
||||||
@@ -1096,7 +1142,7 @@ void ScreenInteractive::FetchTerminalEvents() {
|
|||||||
internal_->terminal_input_parser.Add(out[i]);
|
internal_->terminal_input_parser.Add(out[i]);
|
||||||
}
|
}
|
||||||
#else // POSIX (Linux & Mac)
|
#else // POSIX (Linux & Mac)
|
||||||
if (!CheckStdinReady()) {
|
if (!CheckStdinReady(tty_fd_)) {
|
||||||
const auto timeout =
|
const auto timeout =
|
||||||
std::chrono::steady_clock::now() - internal_->last_char_time;
|
std::chrono::steady_clock::now() - internal_->last_char_time;
|
||||||
const size_t timeout_ms =
|
const size_t timeout_ms =
|
||||||
@@ -1108,7 +1154,7 @@ void ScreenInteractive::FetchTerminalEvents() {
|
|||||||
|
|
||||||
// Read chars from the terminal.
|
// Read chars from the terminal.
|
||||||
std::array<char, 128> out{};
|
std::array<char, 128> out{};
|
||||||
size_t l = read(fileno(stdin), out.data(), out.size());
|
size_t l = read(tty_fd_, out.data(), out.size());
|
||||||
|
|
||||||
// Convert the chars to events.
|
// Convert the chars to events.
|
||||||
for (size_t i = 0; i < l; ++i) {
|
for (size_t i = 0; i < l; ++i) {
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.component.screen_interactive
|
/// @module ftxui.component:ScreenInteractive
|
||||||
/// @brief Module file for the ScreenInteractive class of the Component module
|
/// @brief Module file for the ScreenInteractive class of the Component module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/component/screen_interactive.hpp>
|
#include <ftxui/component/screen_interactive.hpp>
|
||||||
|
|
||||||
export module ftxui.component.screen_interactive;
|
export module ftxui.component:ScreenInteractive;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @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__)
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.component.task
|
/// @module ftxui.component:Task
|
||||||
/// @brief Module file for the Task class of the Component module
|
/// @brief Module file for the Task class of the Component module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/component/task.hpp>
|
#include <ftxui/component/task.hpp>
|
||||||
|
|
||||||
export module ftxui.component.task;
|
export module ftxui.component:Task;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -21,8 +21,8 @@ class TaskRunner {
|
|||||||
auto PostTask(Task task) -> void;
|
auto PostTask(Task task) -> void;
|
||||||
|
|
||||||
/// Schedules a task to be executed after a certain duration.
|
/// Schedules a task to be executed after a certain duration.
|
||||||
auto PostDelayedTask(Task task, std::chrono::steady_clock::duration duration)
|
auto PostDelayedTask(Task task,
|
||||||
-> void;
|
std::chrono::steady_clock::duration duration) -> void;
|
||||||
|
|
||||||
/// Runs the tasks in the queue, return the delay until the next delayed task
|
/// Runs the tasks in the queue, return the delay until the next delayed task
|
||||||
/// can be executed.
|
/// can be executed.
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
/// @module ftxui.dom
|
/// @module ftxui.dom
|
||||||
/// @brief Module file for FTXUI main operations.
|
/// @brief Module file for FTXUI DOM operations.
|
||||||
|
|
||||||
export module ftxui.dom;
|
export module ftxui.dom;
|
||||||
|
|
||||||
export import ftxui.dom.canvas;
|
export import :Canvas;
|
||||||
export import ftxui.dom.deprecated;
|
export import :Deprecated;
|
||||||
export import ftxui.dom.direction;
|
export import :Direction;
|
||||||
export import ftxui.dom.elements;
|
export import :Elements;
|
||||||
export import ftxui.dom.flexbox_config;
|
export import :FlexboxConfig;
|
||||||
export import ftxui.dom.linear_gradient;
|
export import :LinearGradient;
|
||||||
export import ftxui.dom.node;
|
export import :Node;
|
||||||
export import ftxui.dom.requirement;
|
export import :Requirement;
|
||||||
export import ftxui.dom.selection;
|
export import :Selection;
|
||||||
export import ftxui.dom.table;
|
export import :Table;
|
||||||
|
|||||||
@@ -4,11 +4,18 @@
|
|||||||
#include "ftxui/dom/box_helper.hpp"
|
#include "ftxui/dom/box_helper.hpp"
|
||||||
|
|
||||||
#include <algorithm> // for max
|
#include <algorithm> // for max
|
||||||
#include <vector> // for vector
|
#include <cstdint>
|
||||||
|
#include <vector> // for vector
|
||||||
|
|
||||||
namespace ftxui::box_helper {
|
namespace ftxui::box_helper {
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
|
int SafeRatio(int value, int numerator, int denominator) {
|
||||||
|
return static_cast<int64_t>(value) * static_cast<int64_t>(numerator) /
|
||||||
|
std::max(static_cast<int64_t>(denominator), static_cast<int64_t>(1));
|
||||||
|
}
|
||||||
|
|
||||||
// Called when the size allowed is greater than the requested size. This
|
// Called when the size allowed is greater than the requested size. This
|
||||||
// distributes the extra spaces toward the flexible elements, in relative
|
// distributes the extra spaces toward the flexible elements, in relative
|
||||||
// proportions.
|
// proportions.
|
||||||
@@ -17,7 +24,7 @@ void ComputeGrow(std::vector<Element>* elements,
|
|||||||
int flex_grow_sum) {
|
int flex_grow_sum) {
|
||||||
for (Element& element : *elements) {
|
for (Element& element : *elements) {
|
||||||
const int added_space =
|
const int added_space =
|
||||||
extra_space * element.flex_grow / std::max(flex_grow_sum, 1);
|
SafeRatio(extra_space, element.flex_grow, flex_grow_sum);
|
||||||
extra_space -= added_space;
|
extra_space -= added_space;
|
||||||
flex_grow_sum -= element.flex_grow;
|
flex_grow_sum -= element.flex_grow;
|
||||||
element.size = element.min_size + added_space;
|
element.size = element.min_size + added_space;
|
||||||
@@ -31,8 +38,8 @@ void ComputeShrinkEasy(std::vector<Element>* elements,
|
|||||||
int extra_space,
|
int extra_space,
|
||||||
int flex_shrink_sum) {
|
int flex_shrink_sum) {
|
||||||
for (Element& element : *elements) {
|
for (Element& element : *elements) {
|
||||||
const int added_space = extra_space * element.min_size *
|
const int added_space = SafeRatio(
|
||||||
element.flex_shrink / std::max(flex_shrink_sum, 1);
|
extra_space, element.min_size * element.flex_shrink, flex_shrink_sum);
|
||||||
extra_space -= added_space;
|
extra_space -= added_space;
|
||||||
flex_shrink_sum -= element.flex_shrink * element.min_size;
|
flex_shrink_sum -= element.flex_shrink * element.min_size;
|
||||||
element.size = element.min_size + added_space;
|
element.size = element.min_size + added_space;
|
||||||
@@ -40,7 +47,7 @@ void ComputeShrinkEasy(std::vector<Element>* elements,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Called when the size allowed is lower than the requested size, and the
|
// Called when the size allowed is lower than the requested size, and the
|
||||||
// shrinkable element can not absorbe the (negative) extra_space. This assign
|
// shrinkable element can not absorb the (negative) extra_space. This assigns
|
||||||
// zero to shrinkable elements and distribute the remaining (negative)
|
// zero to shrinkable elements and distribute the remaining (negative)
|
||||||
// extra_space toward the other non shrinkable elements.
|
// extra_space toward the other non shrinkable elements.
|
||||||
void ComputeShrinkHard(std::vector<Element>* elements,
|
void ComputeShrinkHard(std::vector<Element>* elements,
|
||||||
@@ -52,7 +59,8 @@ void ComputeShrinkHard(std::vector<Element>* elements,
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const int added_space = extra_space * element.min_size / std::max(1, size);
|
const int added_space = SafeRatio(extra_space, element.min_size, size);
|
||||||
|
|
||||||
extra_space -= added_space;
|
extra_space -= added_space;
|
||||||
size -= element.min_size;
|
size -= element.min_size;
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.dom.canvas
|
/// @module ftxui.dom:Canvas
|
||||||
/// @brief Module file for the Canvas struct of the Dom module
|
/// @brief Module file for the Canvas struct of the DOM module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/dom/canvas.hpp>
|
#include <ftxui/dom/canvas.hpp>
|
||||||
|
|
||||||
export module ftxui.dom.canvas;
|
export module ftxui.dom:Canvas;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.dom.deprecated
|
/// @module ftxui.dom:Deprecated
|
||||||
/// @brief Module file for deprecated parts of the Dom module
|
/// @brief Module file for deprecated parts of the DOM module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/dom/deprecated.hpp>
|
#include <ftxui/dom/deprecated.hpp>
|
||||||
|
|
||||||
export module ftxui.dom.deprecated;
|
export module ftxui.dom:Deprecated;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.dom.direction
|
/// @module ftxui.dom:Direction
|
||||||
/// @brief Module file for the Direction enum of the Dom module
|
/// @brief Module file for the Direction enum of the Dom module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/dom/direction.hpp>
|
#include <ftxui/dom/direction.hpp>
|
||||||
|
|
||||||
export module ftxui.dom.direction;
|
export module ftxui.dom:Direction;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.dom.elements
|
/// @module ftxui.dom:Elements
|
||||||
/// @brief Module file for the Element classes and functions of the Dom module
|
/// @brief Module file for the Element classes and functions of the DOM module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/dom/elements.hpp>
|
#include <ftxui/dom/elements.hpp>
|
||||||
|
|
||||||
export module ftxui.dom.elements;
|
export module ftxui.dom:Elements;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.dom.flexbox_config
|
/// @module ftxui.dom:FlexboxConfig
|
||||||
/// @brief Module file for the FlexboxConfig struct of the Dom module
|
/// @brief Module file for the FlexboxConfig struct of the DOM module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/dom/flexbox_config.hpp>
|
#include <ftxui/dom/flexbox_config.hpp>
|
||||||
|
|
||||||
export module ftxui.dom.flexbox_config;
|
export module ftxui.dom:FlexboxConfig;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -2,9 +2,13 @@
|
|||||||
// Use of this source code is governed by the MIT license that can be found in
|
// Use of this source code is governed by the MIT license that can be found in
|
||||||
// the LICENSE file.
|
// the LICENSE file.
|
||||||
#include <gtest/gtest.h> // for Test, TestInfo (ptr only), EXPECT_EQ, Message, TEST, TestPartResult
|
#include <gtest/gtest.h> // for Test, TestInfo (ptr only), EXPECT_EQ, Message, TEST, TestPartResult
|
||||||
#include <cstddef> // for size_t
|
#include <array> // for array
|
||||||
#include <string> // for allocator, basic_string, string
|
#include <cstddef> // for size_t
|
||||||
#include <vector> // for vector
|
#include <queue>
|
||||||
|
#include <stack> // for stack
|
||||||
|
#include <string> // for allocator, basic_string, string
|
||||||
|
#include <unordered_set> // for unordered_set
|
||||||
|
#include <vector> // for vector
|
||||||
|
|
||||||
#include "ftxui/dom/elements.hpp" // for text, operator|, Element, flex_grow, flex_shrink, hbox
|
#include "ftxui/dom/elements.hpp" // for text, operator|, Element, flex_grow, flex_shrink, hbox
|
||||||
#include "ftxui/dom/node.hpp" // for Render
|
#include "ftxui/dom/node.hpp" // for Render
|
||||||
@@ -358,5 +362,39 @@ TEST(HBoxTest, FlexGrow_NoFlex_FlewShrink) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST(HBoxTest, FromElementsContainer) {
|
||||||
|
Elements elements_vector{text("0"), text("1")};
|
||||||
|
|
||||||
|
std::array<Element, 2> elements_array{text("0"), text("1")};
|
||||||
|
|
||||||
|
std::deque<Element> elements_deque{text("0"), text("1")};
|
||||||
|
|
||||||
|
std::stack<Element> elements_stack;
|
||||||
|
elements_stack.push(text("1"));
|
||||||
|
elements_stack.push(text("0"));
|
||||||
|
|
||||||
|
std::queue<Element> elements_queue;
|
||||||
|
elements_queue.emplace(text("0"));
|
||||||
|
elements_queue.emplace(text("1"));
|
||||||
|
|
||||||
|
const std::vector<Element> collection_hboxes{
|
||||||
|
hbox(std::move(elements_vector)), hbox(std::move(elements_array)),
|
||||||
|
hbox(std::move(elements_stack)), hbox(std::move(elements_deque)),
|
||||||
|
hbox(std::move(elements_queue)),
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const Element& collection_hbox : collection_hboxes) {
|
||||||
|
Screen screen(2, 1);
|
||||||
|
Render(screen, collection_hbox);
|
||||||
|
EXPECT_EQ("01", screen.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exception: unordered set, which has no guaranteed order.
|
||||||
|
std::unordered_set<Element> elements_set{text("0"), text("0")};
|
||||||
|
Screen screen(2, 1);
|
||||||
|
Render(screen, hbox(elements_set));
|
||||||
|
EXPECT_EQ("00", screen.ToString());
|
||||||
|
};
|
||||||
|
|
||||||
} // namespace ftxui
|
} // namespace ftxui
|
||||||
// NOLINTEND
|
// NOLINTEND
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.dom.linear_gradient
|
/// @module ftxui.dom:LinearGradient
|
||||||
/// @brief Module file for the LinearGradient struct of the Dom module
|
/// @brief Module file for the LinearGradient struct of the DOM module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/dom/linear_gradient.hpp>
|
#include <ftxui/dom/linear_gradient.hpp>
|
||||||
|
|
||||||
export module ftxui.dom.linear_gradient;
|
export module ftxui.dom:LinearGradient;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.dom.node
|
/// @module ftxui.dom:Node
|
||||||
/// @brief Module file for the Node class of the Dom module
|
/// @brief Module file for the Node class of the DOM module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/dom/node.hpp>
|
#include <ftxui/dom/node.hpp>
|
||||||
|
|
||||||
export module ftxui.dom.node;
|
export module ftxui.dom:Node;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.dom.requirement
|
/// @module ftxui.dom:Requirement
|
||||||
/// @brief Module file for the Requirement struct of the Dom module
|
/// @brief Module file for the Requirement struct of the DOM module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/dom/requirement.hpp>
|
#include <ftxui/dom/requirement.hpp>
|
||||||
|
|
||||||
export module ftxui.dom.requirement;
|
export module ftxui.dom:Requirement;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.dom.selection
|
/// @module ftxui.dom:Selection
|
||||||
/// @brief Module file for the Selection class of the Dom module
|
/// @brief Module file for the Selection class of the DOM module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/dom/selection.hpp>
|
#include <ftxui/dom/selection.hpp>
|
||||||
|
|
||||||
export module ftxui.dom.selection;
|
export module ftxui.dom:Selection;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.dom.table
|
/// @module ftxui.dom:Table
|
||||||
/// @brief Module file for the Table class of the Dom module
|
/// @brief Module file for the Table class of the DOM module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/dom/table.hpp>
|
#include <ftxui/dom/table.hpp>
|
||||||
|
|
||||||
export module ftxui.dom.table;
|
export module ftxui.dom:Table;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -3,12 +3,12 @@
|
|||||||
|
|
||||||
export module ftxui.screen;
|
export module ftxui.screen;
|
||||||
|
|
||||||
export import ftxui.screen.box;
|
export import :Box;
|
||||||
export import ftxui.screen.color;
|
export import :Color;
|
||||||
export import ftxui.screen.color_info;
|
export import :ColorInfo;
|
||||||
export import ftxui.screen.deprecated;
|
export import :Deprecated;
|
||||||
export import ftxui.screen.image;
|
export import :Image;
|
||||||
export import ftxui.screen.pixel;
|
export import :Pixel;
|
||||||
export import ftxui.screen.screen;
|
export import :Screen;
|
||||||
export import ftxui.screen.string;
|
export import :String;
|
||||||
export import ftxui.screen.terminal;
|
export import :Terminal;
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.screen.box
|
/// @module ftxui.screen:Box
|
||||||
/// @brief Module file for the Box struct of the Screen module
|
/// @brief Module file for the Box struct of the Screen module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/screen/box.hpp>
|
#include <ftxui/screen/box.hpp>
|
||||||
|
|
||||||
export module ftxui.screen.box;
|
export module ftxui.screen:Box;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.screen.color
|
/// @module ftxui.screen:Color
|
||||||
/// @brief Module file for the Color class of the Screen module
|
/// @brief Module file for the Color class of the Screen module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/screen/color.hpp>
|
#include <ftxui/screen/color.hpp>
|
||||||
|
|
||||||
export module ftxui.screen.color;
|
export module ftxui.screen:Color;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
@@ -14,6 +14,10 @@ export module ftxui.screen.color;
|
|||||||
export namespace ftxui {
|
export namespace ftxui {
|
||||||
using ftxui::Color;
|
using ftxui::Color;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @namespace literals
|
||||||
|
* @brief The FTXUI ftxui::literals:: namespace
|
||||||
|
*/
|
||||||
inline namespace literals {
|
inline namespace literals {
|
||||||
using ftxui::literals::operator""_rgb;
|
using ftxui::literals::operator""_rgb;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.screen.color_info
|
/// @module ftxui.screen:ColorInfo
|
||||||
/// @brief Module file for the ColorInfo struct of the Screen module
|
/// @brief Module file for the ColorInfo struct of the Screen module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/screen/color_info.hpp>
|
#include <ftxui/screen/color_info.hpp>
|
||||||
|
|
||||||
export module ftxui.screen.color_info;
|
export module ftxui.screen:ColorInfo;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.screen.deprecated
|
/// @module ftxui.screen:Deprecated
|
||||||
/// @brief Module file for the deprecated parts of the Screen module
|
/// @brief Module file for the deprecated parts of the Screen module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/screen/deprecated.hpp>
|
#include <ftxui/screen/deprecated.hpp>
|
||||||
|
|
||||||
export module ftxui.screen.deprecated;
|
export module ftxui.screen:Deprecated;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.screen.image
|
/// @module ftxui.screen:Image
|
||||||
/// @brief Module file for the Image class of the Screen module
|
/// @brief Module file for the Image class of the Screen module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/screen/image.hpp>
|
#include <ftxui/screen/image.hpp>
|
||||||
|
|
||||||
export module ftxui.screen.image;
|
export module ftxui.screen:Image;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.screen.pixel
|
/// @module ftxui.screen:Pixel
|
||||||
/// @brief Module file for the Pixel struct of the Screen module
|
/// @brief Module file for the Pixel struct of the Screen module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/screen/pixel.hpp>
|
#include <ftxui/screen/pixel.hpp>
|
||||||
|
|
||||||
export module ftxui.screen.pixel;
|
export module ftxui.screen:Pixel;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,17 +1,21 @@
|
|||||||
/// @module ftxui.screen.screen
|
/// @module ftxui.screen:Screen
|
||||||
/// @brief Module file for the Screen class of the Screen module
|
/// @brief Module file for the Screen class of the Screen module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/screen/screen.hpp>
|
#include <ftxui/screen/screen.hpp>
|
||||||
|
|
||||||
export module ftxui.screen.screen;
|
export module ftxui.screen:Screen;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
* @brief The FTXUI ftxui:: namespace
|
* @brief The FTXUI ftxui:: namespace
|
||||||
*/
|
*/
|
||||||
export namespace ftxui {
|
export namespace ftxui {
|
||||||
|
/**
|
||||||
|
* @namespace Dimension
|
||||||
|
* @brief The FTXUI ftxui::Dimension:: namespace
|
||||||
|
*/
|
||||||
namespace Dimension {
|
namespace Dimension {
|
||||||
using ftxui::Dimension::Fixed;
|
using ftxui::Dimension::Fixed;
|
||||||
using ftxui::Dimension::Full;
|
using ftxui::Dimension::Full;
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.screen.string
|
/// @module ftxui.screen:String
|
||||||
/// @brief Module file for string functions of the Screen module
|
/// @brief Module file for string functions of the Screen module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/screen/string.hpp>
|
#include <ftxui/screen/string.hpp>
|
||||||
|
|
||||||
export module ftxui.screen.string;
|
export module ftxui.screen:String;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.screen.terminal
|
/// @module ftxui.screen:Terminal
|
||||||
/// @brief Module file for the Terminal namespace of the Screen module
|
/// @brief Module file for the Terminal namespace of the Screen module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/screen/terminal.hpp>
|
#include <ftxui/screen/terminal.hpp>
|
||||||
|
|
||||||
export module ftxui.screen.terminal;
|
export module ftxui.screen:Terminal;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
@@ -14,6 +14,10 @@ export module ftxui.screen.terminal;
|
|||||||
export namespace ftxui {
|
export namespace ftxui {
|
||||||
using ftxui::Dimensions;
|
using ftxui::Dimensions;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @namespace Terminal
|
||||||
|
* @brief The FTXUI ftxui::Terminal:: namespace
|
||||||
|
*/
|
||||||
namespace Terminal {
|
namespace Terminal {
|
||||||
using ftxui::Terminal::Size;
|
using ftxui::Terminal::Size;
|
||||||
using ftxui::Terminal::SetFallbackSize;
|
using ftxui::Terminal::SetFallbackSize;
|
||||||
|
|||||||
@@ -3,5 +3,5 @@
|
|||||||
|
|
||||||
export module ftxui.util;
|
export module ftxui.util;
|
||||||
|
|
||||||
export import ftxui.util.autoreset;
|
export import :AutoReset;
|
||||||
export import ftxui.util.ref;
|
export import :Ref;
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.util.autoreset
|
/// @module ftxui.util:AutoReset
|
||||||
/// @brief Module file for the AutoReset class of the Util module
|
/// @brief Module file for the AutoReset class of the Util module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/util/autoreset.hpp>
|
#include <ftxui/util/autoreset.hpp>
|
||||||
|
|
||||||
export module ftxui.util.autoreset;
|
export module ftxui.util:AutoReset;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
/// @module ftxui.util.ref
|
/// @module ftxui.util:Ref
|
||||||
/// @brief Module file for the Ref classes of the Util module
|
/// @brief Module file for the Ref classes of the Util module
|
||||||
|
|
||||||
module;
|
module;
|
||||||
|
|
||||||
#include <ftxui/util/ref.hpp>
|
#include <ftxui/util/ref.hpp>
|
||||||
|
|
||||||
export module ftxui.util.ref;
|
export module ftxui.util:Ref;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @namespace ftxui
|
* @namespace ftxui
|
||||||
|
|||||||
489
tools/build_multiversion_doc.py
Executable file
489
tools/build_multiversion_doc.py
Executable file
@@ -0,0 +1,489 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import shutil
|
||||||
|
import tempfile
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Dict
|
||||||
|
|
||||||
|
# --- Configuration ---
|
||||||
|
# URL for the translations repository. This is where other language branches reside.
|
||||||
|
TRANSLATIONS_REPO_URL = "https://github.com/ArthurSonzogni/ftxui-translations"
|
||||||
|
# --- End Configuration ---
|
||||||
|
|
||||||
|
# Mapping of language codes to their display names for the dropdown menu.
|
||||||
|
# Key: Standard BCP 47/ISO 639-1 Code
|
||||||
|
# Value: [Native Name, Doxygen Name]
|
||||||
|
LANG_NAME_MAP = {
|
||||||
|
"af": ["Afrikaans", "Afrikaans"],
|
||||||
|
"ar": ["العربية", "Arabic"],
|
||||||
|
"bg": ["Български", "Bulgarian"],
|
||||||
|
"ca": ["Català", "Catalan"],
|
||||||
|
"cs": ["Čeština", "Czech"],
|
||||||
|
"da": ["Dansk", "Danish"],
|
||||||
|
"de": ["Deutsch", "German"],
|
||||||
|
"el": ["Ελληνικά", "Greek"],
|
||||||
|
"en": ["English", "English"],
|
||||||
|
"eo": ["Esperanto", "Esperanto"],
|
||||||
|
"es": ["Español", "Spanish"],
|
||||||
|
"fi": ["Suomi", "Finnish"],
|
||||||
|
"fr": ["Français", "French"],
|
||||||
|
"hi": ["हिन्दी", "Hindi"],
|
||||||
|
"hr": ["Hrvatski", "Croatian"],
|
||||||
|
"hu": ["Magyar", "Hungarian"],
|
||||||
|
"hy": ["Հայերեն", "Armenian"],
|
||||||
|
"id": ["Bahasa Indonesia", "Indonesian"],
|
||||||
|
"it": ["Italiano", "Italian"],
|
||||||
|
"ja": ["日本語", "Japanese-en"],
|
||||||
|
"ko": ["한국어", "Korean-en"],
|
||||||
|
"lt": ["Lietuvių", "Lithuanian"],
|
||||||
|
"lv": ["Latviešu", "Latvian"],
|
||||||
|
"mk": ["Македонски", "Macedonian"],
|
||||||
|
"nl": ["Nederlands", "Dutch"],
|
||||||
|
"no": ["Norsk", "Norwegian"],
|
||||||
|
"pl": ["Polski", "Polish"],
|
||||||
|
"pt": ["Português", "Portuguese"],
|
||||||
|
"ro": ["Română", "Romanian"],
|
||||||
|
"ru": ["Русский", "Russian"],
|
||||||
|
"sk": ["Slovenčina", "Slovak"],
|
||||||
|
"sl": ["Slovenščina", "Slovene"],
|
||||||
|
"sr": ["Српски", "Serbian"],
|
||||||
|
"sv": ["Svenska", "Swedish"],
|
||||||
|
"tr": ["Türkçe", "Turkish"],
|
||||||
|
"uk": ["Українська", "Ukrainian"],
|
||||||
|
"vi": ["Tiếng Việt", "Vietnamese"],
|
||||||
|
"zh-CH": ["中文 (简体)", "Chinese"],
|
||||||
|
"zh-TW": ["中文 (繁體)", "Chinese-Traditional"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class DocInfo:
|
||||||
|
"""A structure to hold all information about a single documentation build."""
|
||||||
|
def __init__(self, lang: str, version_name: str, is_main_version: bool, output_root: Path, is_primary_lang: bool = True):
|
||||||
|
self.lang = lang
|
||||||
|
self.version_name = version_name # e.g., "main", "v6.1.9"
|
||||||
|
self.is_main_version = is_main_version
|
||||||
|
self.is_primary_lang = is_primary_lang
|
||||||
|
|
||||||
|
if self.is_primary_lang:
|
||||||
|
if self.is_main_version:
|
||||||
|
# English Main: Deployed to the root directory
|
||||||
|
self.dest_dir = output_root
|
||||||
|
else:
|
||||||
|
# English Versions: Deployed to /en/<version_name>
|
||||||
|
self.dest_dir = output_root / "en" / version_name
|
||||||
|
else:
|
||||||
|
# Translated Docs (only 'main' version for now): Deployed to /<lang_code>/
|
||||||
|
self.dest_dir = output_root / lang
|
||||||
|
|
||||||
|
# The path to this version's index.html, relative to the output root.
|
||||||
|
self.index_path_from_root = self.dest_dir / "index.html"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def key(self) -> str:
|
||||||
|
"""A unique key for this documentation set (e.g., 'en-main', 'fr-main', 'en-v6.1.9')."""
|
||||||
|
return f"{self.lang}-{self.version_name}"
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return f"DocInfo(lang='{self.lang}', version='{self.version_name}', dest_dir='{self.dest_dir}')"
|
||||||
|
|
||||||
|
def run_command(command: List[str], check: bool = True, cwd: Path = None):
|
||||||
|
"""
|
||||||
|
Runs a command, prints its output, and handles errors.
|
||||||
|
"""
|
||||||
|
command_str = ' '.join(command)
|
||||||
|
print(f"Executing: {command_str} in {cwd or Path.cwd()}")
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
command,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
check=check,
|
||||||
|
cwd=cwd
|
||||||
|
)
|
||||||
|
if result.stdout:
|
||||||
|
print(result.stdout)
|
||||||
|
if result.stderr:
|
||||||
|
print(result.stderr)
|
||||||
|
return result
|
||||||
|
except subprocess.CalledProcessError as e:
|
||||||
|
print(f"ERROR: Command failed with exit code {e.returncode}")
|
||||||
|
print(f"Command: {command_str}")
|
||||||
|
if e.stdout:
|
||||||
|
print("--- STDOUT ---")
|
||||||
|
print(e.stdout)
|
||||||
|
if e.stderr:
|
||||||
|
print("--- STDERR ---")
|
||||||
|
print(e.stderr)
|
||||||
|
raise # Re-raise the exception to halt the script
|
||||||
|
|
||||||
|
def get_switchers_js(
|
||||||
|
current_doc: DocInfo,
|
||||||
|
all_docs: List[DocInfo],
|
||||||
|
current_html_file: Path
|
||||||
|
) -> str:
|
||||||
|
"""
|
||||||
|
Generates the JavaScript for both the version and language switcher dropdowns.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# 1. Prepare Language Data (Links to the main version/entry point of each language)
|
||||||
|
language_map: Dict[str, str] = {}
|
||||||
|
language_display_names: Dict[str, str] = {}
|
||||||
|
language_doxygen_names: Dict[str, str] = {}
|
||||||
|
|
||||||
|
# Filter for the main entry point of each language (e.g., /fr/, /en/ and /)
|
||||||
|
main_language_docs = {}
|
||||||
|
for doc in all_docs:
|
||||||
|
# Use the main version for its language as the entry point
|
||||||
|
if doc.is_main_version or (doc.is_primary_lang and doc.version_name == 'main'):
|
||||||
|
if doc.lang not in main_language_docs:
|
||||||
|
main_language_docs[doc.lang] = doc
|
||||||
|
|
||||||
|
# Calculate relative paths for the language switcher
|
||||||
|
for lang_code, doc in main_language_docs.items():
|
||||||
|
relative_path = os.path.relpath(doc.index_path_from_root, current_html_file.parent)
|
||||||
|
language_map[lang_code] = relative_path
|
||||||
|
# Use the map for display name, fall back to code if not found
|
||||||
|
language_display_names[lang_code] = LANG_NAME_MAP.get(lang_code,
|
||||||
|
lang_code)[0]
|
||||||
|
language_doxygen_names[lang_code] = LANG_NAME_MAP.get(lang_code,
|
||||||
|
lang_code)[1]
|
||||||
|
|
||||||
|
language_names = list(language_map.keys())
|
||||||
|
# Sort languages: 'en' first, then others alphabetically.
|
||||||
|
language_names.sort(key=lambda x: (x != 'en', x))
|
||||||
|
|
||||||
|
|
||||||
|
# 2. Prepare Version Data (Only versions for the current language)
|
||||||
|
version_docs = [doc for doc in all_docs if doc.lang == current_doc.lang]
|
||||||
|
version_names = [v.version_name for v in version_docs]
|
||||||
|
version_paths: Dict[str, str] = {}
|
||||||
|
|
||||||
|
# Calculate relative paths for the version switcher
|
||||||
|
for version_doc in version_docs:
|
||||||
|
relative_path = os.path.relpath(version_doc.index_path_from_root, current_html_file.parent)
|
||||||
|
version_paths[version_doc.version_name] = relative_path
|
||||||
|
|
||||||
|
# Use json.dumps for safe serialization of data into JavaScript.
|
||||||
|
langs_json = json.dumps(language_names)
|
||||||
|
lang_paths_json = json.dumps(language_map)
|
||||||
|
lang_display_json = json.dumps(language_display_names)
|
||||||
|
versions_json = json.dumps(version_names)
|
||||||
|
version_paths_json = json.dumps(version_paths)
|
||||||
|
current_lang_json = json.dumps(current_doc.lang)
|
||||||
|
current_version_json = json.dumps(current_doc.version_name)
|
||||||
|
|
||||||
|
# Note: We are using Doxygen's #projectnumber container to inject both switchers.
|
||||||
|
# We will wrap the original element with a new container.
|
||||||
|
return f"""
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {{
|
||||||
|
const projectNumber = document.getElementById('projectname');
|
||||||
|
|
||||||
|
if (!projectNumber) {{
|
||||||
|
console.warn('Doxygen element with ID "projectnumber" not found. Cannot add version switcher.');
|
||||||
|
return;
|
||||||
|
}}
|
||||||
|
|
||||||
|
const langs = {langs_json};
|
||||||
|
const lang_paths = {lang_paths_json};
|
||||||
|
const lang_display = {lang_display_json};
|
||||||
|
const versions = {versions_json};
|
||||||
|
const version_paths = {version_paths_json};
|
||||||
|
const currentLang = {current_lang_json};
|
||||||
|
const currentVersion = {current_version_json};
|
||||||
|
|
||||||
|
// Helper function to create a styled select element
|
||||||
|
const createSelect = (options, current, paths, label, displayMap = null) => {{
|
||||||
|
const select = document.createElement('select');
|
||||||
|
select.title = label;
|
||||||
|
select.onchange = function() {{
|
||||||
|
const selectedValue = this.value;
|
||||||
|
if (selectedValue in paths) {{
|
||||||
|
window.location.href = paths[selectedValue];
|
||||||
|
}}
|
||||||
|
}};
|
||||||
|
|
||||||
|
// Sort versions: 'main' first, then others numerically descending.
|
||||||
|
options.sort((a, b) => {{
|
||||||
|
if (a === 'main') return -1;
|
||||||
|
if (b === 'main') return 1;
|
||||||
|
return b.localeCompare(a, undefined, {{ numeric: true, sensitivity: 'base' }});
|
||||||
|
}});
|
||||||
|
|
||||||
|
options.forEach(v => {{
|
||||||
|
const option = document.createElement('option');
|
||||||
|
option.value = v;
|
||||||
|
// Use the displayMap if provided, otherwise default to the value (v)
|
||||||
|
option.textContent = displayMap ? displayMap[v] : v;
|
||||||
|
if (v === current) {{
|
||||||
|
option.selected = true;
|
||||||
|
}}
|
||||||
|
select.appendChild(option);
|
||||||
|
}});
|
||||||
|
|
||||||
|
// Apply some styling to make it look good.
|
||||||
|
Object.assign(select.style, {{
|
||||||
|
backgroundColor: 'rgba(0, 0, 0, 0.8)',
|
||||||
|
color: 'white',
|
||||||
|
border: '1px solid rgba(255, 255, 255, 0.2)',
|
||||||
|
padding: '5px',
|
||||||
|
borderRadius: '5px',
|
||||||
|
fontSize: '14px',
|
||||||
|
fontFamily: 'inherit',
|
||||||
|
margin: '0 5px 0 0',
|
||||||
|
cursor: 'pointer'
|
||||||
|
}});
|
||||||
|
return select;
|
||||||
|
}};
|
||||||
|
|
||||||
|
// 1. Create Language Switcher, passing the language display names map
|
||||||
|
const langSelect = createSelect(langs, currentLang, lang_paths, 'Select Language', lang_display);
|
||||||
|
|
||||||
|
// 2. Create Version Switcher
|
||||||
|
const versionSelect = createSelect(versions, currentVersion, version_paths, 'Select Version');
|
||||||
|
|
||||||
|
// 3. Create FTXUI title.
|
||||||
|
const ftxuiTitle = document.createElement('span');
|
||||||
|
ftxuiTitle.textContent = 'FTXUI: ';
|
||||||
|
Object.assign(ftxuiTitle.style, {{
|
||||||
|
color: 'white',
|
||||||
|
fontSize: '20px',
|
||||||
|
fontWeight: 'bold',
|
||||||
|
marginRight: '10px'
|
||||||
|
}});
|
||||||
|
|
||||||
|
// 3. Create a container to hold both selectors
|
||||||
|
const container = document.createElement('div');
|
||||||
|
container.id = 'version-lang-switchers';
|
||||||
|
Object.assign(container.style, {{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'flex-end',
|
||||||
|
width: 'auto'
|
||||||
|
}});
|
||||||
|
container.appendChild(ftxuiTitle);
|
||||||
|
container.appendChild(langSelect);
|
||||||
|
container.appendChild(versionSelect);
|
||||||
|
|
||||||
|
Object.assign(container.style, {{
|
||||||
|
backgroundColor: 'rgba(0, 0, 0, 0.5)',
|
||||||
|
padding: '5px 10px',
|
||||||
|
borderRadius: '8px'
|
||||||
|
}});
|
||||||
|
|
||||||
|
|
||||||
|
// Replace the Doxygen project number element with our container.
|
||||||
|
projectNumber.replaceWith(container);
|
||||||
|
|
||||||
|
// Clean up the original Doxygen project number text if it still exists nearby
|
||||||
|
const parent = container.parentElement;
|
||||||
|
if (parent) {{
|
||||||
|
const textNode = Array.from(parent.childNodes).find(n => n.nodeType === 3 && n.textContent.trim() !== '');
|
||||||
|
if (textNode) {{
|
||||||
|
textNode.remove();
|
||||||
|
}}
|
||||||
|
}}
|
||||||
|
}});
|
||||||
|
"""
|
||||||
|
|
||||||
|
def build_doc_from_git(doc_info: DocInfo, build_root: Path, repo_url: str, branch_or_tag: str, temp_repo_dir: Path):
|
||||||
|
"""
|
||||||
|
Handles checking out the source from a git reference, running the build,
|
||||||
|
and copying the output to the final destination.
|
||||||
|
|
||||||
|
:param doc_info: The DocInfo object for the build.
|
||||||
|
:param build_root: The temporary root directory for all builds.
|
||||||
|
:param repo_url: The URL or path to the git repository.
|
||||||
|
:param branch_or_tag: The git reference (branch or tag) to check out.
|
||||||
|
:param temp_repo_dir: The path to the temporary cloned repository directory.
|
||||||
|
"""
|
||||||
|
print(f"--- Building {doc_info.key} (Source: {branch_or_tag} from {repo_url}) ---")
|
||||||
|
|
||||||
|
# 1. Archive the source code from the repository reference.
|
||||||
|
version_src_dir = build_root / f"src_{doc_info.key}"
|
||||||
|
version_src_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
archive_path = version_src_dir / "source.tar"
|
||||||
|
|
||||||
|
# Determine the directory to run git archive from (it needs to be the root of the git repo)
|
||||||
|
git_run_dir = temp_repo_dir if temp_repo_dir.is_dir() else Path.cwd()
|
||||||
|
|
||||||
|
run_command([
|
||||||
|
"git", "archive", branch_or_tag,
|
||||||
|
"--format=tar", f"--output={archive_path}"
|
||||||
|
], cwd=git_run_dir)
|
||||||
|
|
||||||
|
run_command(["tar", "-xf", str(archive_path)], cwd=version_src_dir)
|
||||||
|
archive_path.unlink()
|
||||||
|
|
||||||
|
# 2. Configure and build the docs using CMake.
|
||||||
|
version_build_dir = build_root / f"build_{doc_info.key}"
|
||||||
|
version_build_dir.mkdir()
|
||||||
|
|
||||||
|
# 2.a Update doc/Doxyfile.in to set the correct language.
|
||||||
|
doxyfile_in_path = version_src_dir / "doc" / "Doxyfile.in"
|
||||||
|
if not doxyfile_in_path.is_file():
|
||||||
|
print(f"FATAL: Doxyfile.in not found at {doxyfile_in_path} for {doc_info.key}")
|
||||||
|
exit(1)
|
||||||
|
doxyfile_content = doxyfile_in_path.read_text(encoding='utf-8')
|
||||||
|
# Replace the keyword "English" with the appropriate Doxygen language name.
|
||||||
|
lang_doxygen_name = LANG_NAME_MAP.get(doc_info.lang, [doc_info.lang,
|
||||||
|
doc_info.lang])[1]
|
||||||
|
doxyfile_content = doxyfile_content.replace("English", lang_doxygen_name)
|
||||||
|
|
||||||
|
|
||||||
|
# Assuming CMakeLists.txt is in the root of the extracted source
|
||||||
|
run_command([
|
||||||
|
"cmake", str(version_src_dir),
|
||||||
|
"-DFTXUI_BUILD_DOCS=ON",
|
||||||
|
'-DFTXUI_BUILD_EXAMPLES=ON' # Required for the Doxygen build target
|
||||||
|
], cwd=version_build_dir)
|
||||||
|
|
||||||
|
run_command(["make", "doc"], cwd=version_build_dir)
|
||||||
|
|
||||||
|
# 3. Copy the generated HTML files to the final destination.
|
||||||
|
doxygen_html_dir = version_build_dir / "doc" / "doxygen" / "html"
|
||||||
|
if not doxygen_html_dir.is_dir():
|
||||||
|
print(f"FATAL: Doxygen HTML output not found for {doc_info.key} at {doxygen_html_dir}")
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
print(f"Copying files to: {doc_info.dest_dir}")
|
||||||
|
shutil.copytree(doxygen_html_dir, doc_info.dest_dir, dirs_exist_ok=True)
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""Main function to build multi-version and multi-language documentation."""
|
||||||
|
root_dir = Path.cwd()
|
||||||
|
output_dir = root_dir / "multiversion_docs"
|
||||||
|
|
||||||
|
print("--- 1. Cleaning up old documentation ---")
|
||||||
|
if output_dir.exists():
|
||||||
|
shutil.rmtree(output_dir)
|
||||||
|
output_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
all_docs: List[DocInfo] = []
|
||||||
|
|
||||||
|
# --- 2. Gather English (Primary) Versions from the current repository ---
|
||||||
|
print("--- 2a. Getting English versions (main repo) ---")
|
||||||
|
|
||||||
|
# Get all tags that start with 'v' for versioning
|
||||||
|
git_tags_result = run_command(["git", "tag", "--list", "v*"])
|
||||||
|
|
||||||
|
# Start with 'main', then add sorted tags (reverse numerical order)
|
||||||
|
english_versions = ["main"] + sorted(
|
||||||
|
git_tags_result.stdout.splitlines(),
|
||||||
|
reverse=True
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"English versions to build: {', '.join(english_versions)}")
|
||||||
|
|
||||||
|
for name in english_versions:
|
||||||
|
is_main = name == "main"
|
||||||
|
all_docs.append(DocInfo("en", name, is_main, output_dir, is_primary_lang=True))
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as build_dir_str:
|
||||||
|
build_dir = Path(build_dir_str)
|
||||||
|
temp_translations_repo = build_dir / "translations_repo"
|
||||||
|
|
||||||
|
# --- 2b. Gather Translated Language Branches ---
|
||||||
|
print("\n--- 2b. Cloning translations repo and getting language branches (excluding 'main') ---")
|
||||||
|
try:
|
||||||
|
# Clone the translations repository
|
||||||
|
run_command(["git", "clone", TRANSLATIONS_REPO_URL, str(temp_translations_repo)])
|
||||||
|
|
||||||
|
# Get remote branches (e.g., origin/fr, origin/zh-CH) and map them to lang codes
|
||||||
|
translation_branches_result = run_command(
|
||||||
|
["git", "branch", "-r", "--list", "origin/*"],
|
||||||
|
cwd=temp_translations_repo
|
||||||
|
)
|
||||||
|
|
||||||
|
# Filter and map to language codes
|
||||||
|
language_branches = []
|
||||||
|
for line in translation_branches_result.stdout.splitlines():
|
||||||
|
branch_name = line.strip()
|
||||||
|
|
||||||
|
# Ignore lines that are references (like 'origin/HEAD -> origin/main')
|
||||||
|
if '->' in branch_name:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Extract the language code (e.g., 'fr' from 'origin/fr')
|
||||||
|
if branch_name.startswith('origin/'):
|
||||||
|
# The name after 'origin/'
|
||||||
|
lang_code = branch_name.split('origin/')[1]
|
||||||
|
|
||||||
|
# Explicitly exclude 'main' as requested by the user
|
||||||
|
if lang_code != 'main':
|
||||||
|
language_branches.append(lang_code)
|
||||||
|
|
||||||
|
print(f"Translation languages to build: {', '.join(language_branches)}")
|
||||||
|
|
||||||
|
for lang in language_branches:
|
||||||
|
# For translations, we treat them as the 'main' version for that language
|
||||||
|
# The branch name is the language code (e.g., 'fr' branch)
|
||||||
|
all_docs.append(DocInfo(lang, "main", True, output_dir, is_primary_lang=False))
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Warning: Could not clone or process translations repository: {e}")
|
||||||
|
# Continue with English docs if translation cloning fails
|
||||||
|
|
||||||
|
# --- 3. Build documentation for each DocInfo ---
|
||||||
|
for doc in all_docs:
|
||||||
|
if doc.is_primary_lang:
|
||||||
|
# English docs are archived from the current directory (root_dir)
|
||||||
|
build_doc_from_git(doc, build_dir, "origin", doc.version_name, root_dir)
|
||||||
|
else:
|
||||||
|
# Translated docs are archived from the cloned translation repo
|
||||||
|
# FIX: Use 'origin/<lang>' as the git reference because 'git archive'
|
||||||
|
# inside the repository only knows remote-tracking branches.
|
||||||
|
translation_git_ref = f"origin/{doc.lang}"
|
||||||
|
build_doc_from_git(doc, build_dir, TRANSLATIONS_REPO_URL, translation_git_ref, temp_translations_repo)
|
||||||
|
|
||||||
|
# --- 4. Inject version and language switchers into all HTML files ---
|
||||||
|
print("\n--- Injecting version and language switcher JavaScript ---")
|
||||||
|
|
||||||
|
# A set to keep track of processed directories
|
||||||
|
processed_dirs = set()
|
||||||
|
|
||||||
|
for doc in all_docs:
|
||||||
|
if not doc.dest_dir.exists() or doc.dest_dir in processed_dirs:
|
||||||
|
continue
|
||||||
|
|
||||||
|
print(f"Processing HTML files in: {doc.dest_dir}")
|
||||||
|
|
||||||
|
# For the main 'en' directory, we need to handle the structure carefully
|
||||||
|
# as it contains the root, but we only want to inject once per file.
|
||||||
|
html_files: List[Path] = []
|
||||||
|
# We need all language branch names for exclusion, including 'en'.
|
||||||
|
all_lang_dirs = [d.lang for d in all_docs if not d.is_primary_lang] + ['en']
|
||||||
|
|
||||||
|
if doc.is_main_version and doc.is_primary_lang:
|
||||||
|
# This is the root level ('/')
|
||||||
|
# Find all HTML files, but explicitly exclude the language subdirectories ('en', 'fr', etc.)
|
||||||
|
html_files.extend(doc.dest_dir.glob("*.html"))
|
||||||
|
for subdir in doc.dest_dir.iterdir():
|
||||||
|
if subdir.is_dir() and subdir.name not in all_lang_dirs:
|
||||||
|
html_files.extend(subdir.rglob("*.html"))
|
||||||
|
else:
|
||||||
|
# This handles /en/vX.Y.Z/ or /fr/
|
||||||
|
html_files = list(doc.dest_dir.rglob("*.html"))
|
||||||
|
|
||||||
|
# Since multiple DocInfos might point to the same file (e.g., index.html),
|
||||||
|
# we inject the script relative to that specific file's context.
|
||||||
|
for html_file in html_files:
|
||||||
|
js_script = get_switchers_js(doc, all_docs, html_file)
|
||||||
|
script_tag = f'<script>{js_script}</script>'
|
||||||
|
|
||||||
|
content = html_file.read_text(encoding='utf-8')
|
||||||
|
# Inject the script right before the closing body tag.
|
||||||
|
new_content = content.replace("</body>", f"{script_tag}\n</body>")
|
||||||
|
html_file.write_text(new_content, encoding='utf-8')
|
||||||
|
|
||||||
|
processed_dirs.add(doc.dest_dir)
|
||||||
|
|
||||||
|
print("\n--- 5. Finalizing ---")
|
||||||
|
print("Multi-version and multi-language documentation generated successfully!")
|
||||||
|
print(f"Output located in: {output_dir.resolve()}")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
516
tools/build_translations.py
Normal file
516
tools/build_translations.py
Normal file
@@ -0,0 +1,516 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
FTXUI → translations translator, v2.9 (Full Rich Console Output).
|
||||||
|
- Diff-aware and cost-optimized.
|
||||||
|
- AGGRESSIVE Throttling for Free Tier (max ~5-6 RPM).
|
||||||
|
- Parses JSON streams (Robust) for accurate token usage tracking.
|
||||||
|
- DEBUG: Prints the full raw output stream as formatted, syntax-highlighted YAML using 'rich'.
|
||||||
|
- CONSOLE: All logging and output now uses rich markup and styling.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
import sys
|
||||||
|
from collections import deque
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
# If 'rich' or 'pyyaml' is not installed, install them via: pip install rich pyyaml
|
||||||
|
from rich.console import Console
|
||||||
|
from rich.syntax import Syntax
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
# Initialize rich console once for colored printing
|
||||||
|
# Using style="dark_sea_green4" for a pleasant terminal default color
|
||||||
|
console = Console()
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Config & Constants
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
FTXUI_REPO_URL = "git@github.com:ArthurSonzogni/FTXUI.git"
|
||||||
|
TRANSLATIONS_REPO_URL = "git@github.com:ArthurSonzogni/ftxui-translations.git"
|
||||||
|
MODEL = "gemini-2.5-flash"
|
||||||
|
|
||||||
|
# --- FREE TIER LIMITS (Conservative) ---
|
||||||
|
LIMIT_RPM = 1_000 # Max requests per minute
|
||||||
|
LIMIT_TPM = 1_000_000 # Tokens per minute
|
||||||
|
POST_REQUEST_DELAY = 2 # Seconds to SLEEP after every request.
|
||||||
|
|
||||||
|
CPP_EXT = {".cppm", ".cpp", ".hpp", ".h", ".ipp"}
|
||||||
|
MD_EXT = {".md"}
|
||||||
|
TRANSLATABLE_EXT = CPP_EXT | MD_EXT
|
||||||
|
|
||||||
|
ALLOWED_TOOLS = ",".join([
|
||||||
|
"list_directory",
|
||||||
|
"read_file",
|
||||||
|
"write_file",
|
||||||
|
"glob",
|
||||||
|
"search_file_content",
|
||||||
|
"replace",
|
||||||
|
"read_many_files",
|
||||||
|
])
|
||||||
|
|
||||||
|
LANG_NAMES = {
|
||||||
|
"fr": "French",
|
||||||
|
"it": "Italian",
|
||||||
|
"zh-CN": "Simplified Chinese",
|
||||||
|
"zh-TW": "Traditional Chinese",
|
||||||
|
"zh-HK": "Hong Kong Chinese",
|
||||||
|
"ja": "Japanese",
|
||||||
|
"es": "Spanish",
|
||||||
|
"pt": "Portuguese",
|
||||||
|
"de": "German",
|
||||||
|
"ru": "Russian",
|
||||||
|
"ko": "Korean",
|
||||||
|
}
|
||||||
|
|
||||||
|
CACHE_FILE = "translation_cache.json"
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Rich Console Helpers
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def print_step(msg: str):
|
||||||
|
# Big, bold step indicator
|
||||||
|
console.print(f"\n[bold deep_sky_blue1]==> {msg}[/]", highlight=False)
|
||||||
|
|
||||||
|
def print_info(msg: str):
|
||||||
|
# Standard informational message
|
||||||
|
console.print(f"[cyan] -> {msg}[/cyan]", highlight=False)
|
||||||
|
|
||||||
|
def print_success(msg: str):
|
||||||
|
# Successful outcome
|
||||||
|
console.print(f"[green] ✓ {msg}[/green]", highlight=False)
|
||||||
|
|
||||||
|
def print_warn(msg: str):
|
||||||
|
# Warning message
|
||||||
|
console.print(f"[yellow] ! {msg}[/yellow]", highlight=False)
|
||||||
|
|
||||||
|
def print_err(msg: str):
|
||||||
|
# Critical error message with reverse styling
|
||||||
|
console.print(f"[bold white on red] X {msg}[/]", highlight=False)
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Rate Limiter
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class RateLimiter:
|
||||||
|
def __init__(self, rpm_limit: int, tpm_limit: int):
|
||||||
|
self.rpm_limit = rpm_limit
|
||||||
|
self.tpm_limit = tpm_limit
|
||||||
|
self.requests: deque[float] = deque()
|
||||||
|
self.tokens: deque[tuple[float, int]] = deque()
|
||||||
|
self.session_requests = 0
|
||||||
|
|
||||||
|
def _cleanup(self, now: float):
|
||||||
|
"""Remove entries older than 60 seconds."""
|
||||||
|
window_start = now - 60.0
|
||||||
|
while self.requests and self.requests[0] < window_start:
|
||||||
|
self.requests.popleft()
|
||||||
|
while self.tokens and self.tokens[0][0] < window_start:
|
||||||
|
self.tokens.popleft()
|
||||||
|
|
||||||
|
def wait_for_capacity(self, estimated_tokens: int = 1000):
|
||||||
|
while True:
|
||||||
|
now = time.time()
|
||||||
|
self._cleanup(now)
|
||||||
|
|
||||||
|
if len(self.requests) >= self.rpm_limit:
|
||||||
|
wait_time = 60.0 - (now - self.requests[0]) + 1.0
|
||||||
|
print_warn(f"RPM limit reached ({self.rpm_limit}). Cooling down for {wait_time:.1f}s...")
|
||||||
|
time.sleep(wait_time)
|
||||||
|
continue
|
||||||
|
|
||||||
|
current_tpm = sum(count for _, count in self.tokens)
|
||||||
|
if current_tpm + estimated_tokens > self.tpm_limit:
|
||||||
|
if self.tokens:
|
||||||
|
wait_time = 60.0 - (now - self.tokens[0][0]) + 1.0
|
||||||
|
print_warn(f"TPM limit saturation ({current_tpm}/{self.tpm_limit}). Cooling down for {wait_time:.1f}s...")
|
||||||
|
time.sleep(wait_time)
|
||||||
|
continue
|
||||||
|
|
||||||
|
break
|
||||||
|
|
||||||
|
def record_usage(self, input_tok: int, output_tok: int):
|
||||||
|
now = time.time()
|
||||||
|
total = input_tok + output_tok
|
||||||
|
self.requests.append(now)
|
||||||
|
self.tokens.append((now, total))
|
||||||
|
print_info(f"Usage recorded: {total} tokens (In: {input_tok}, Out: {output_tok})")
|
||||||
|
|
||||||
|
def increment_session_counter(self):
|
||||||
|
self.session_requests += 1
|
||||||
|
|
||||||
|
limiter = RateLimiter(LIMIT_RPM, LIMIT_TPM)
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Prompts
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
AGENT_NEW_FILE_PROMPT = """\
|
||||||
|
You are an autonomous documentation translator.
|
||||||
|
|
||||||
|
GOAL
|
||||||
|
- Translate a single, NEW file to {lang_name} ("{lang_code}").
|
||||||
|
- The file at {tx_root}/{rel_path} is currently a copy of the English source.
|
||||||
|
- Translate IN-PLACE.
|
||||||
|
|
||||||
|
WORKFLOW
|
||||||
|
1. Read {tx_root}/{rel_path}
|
||||||
|
2. Translate ONLY documentation:
|
||||||
|
* C++ comments (//, /* ... */)
|
||||||
|
* Doxygen comments (///, /** ... */).
|
||||||
|
* Prose in Markdown.
|
||||||
|
3. DO NOT translate/modify:
|
||||||
|
* C/C++ code, identifiers, includes, macros.
|
||||||
|
* Doxygen commands/params.
|
||||||
|
* Markdown code fences/URLs.
|
||||||
|
4. Overwrite {tx_root}/{rel_path} with the translation.
|
||||||
|
|
||||||
|
TOOLS: {allowed_tools}.
|
||||||
|
"""
|
||||||
|
|
||||||
|
AGENT_DIFF_FILE_PROMPT = """\
|
||||||
|
You are an autonomous documentation translator.
|
||||||
|
|
||||||
|
GOAL
|
||||||
|
- Update existing translation: {tx_root}/{rel_path}
|
||||||
|
- Target: "{lang_name}" ("{lang_code}").
|
||||||
|
|
||||||
|
CONTEXT: SOURCE DIFF
|
||||||
|
The English source has changed. `git diff`:
|
||||||
|
```diff
|
||||||
|
{diff}
|
||||||
|
```
|
||||||
|
|
||||||
|
WORKFLOW
|
||||||
|
1. Read {tx_root}/{rel_path}
|
||||||
|
2. Analyze the `diff`.
|
||||||
|
3. For each changed English section:
|
||||||
|
a. Find corresponding old translation.
|
||||||
|
b. Generate new translation for the new English text.
|
||||||
|
c. Update the file using `replace`.
|
||||||
|
4. ONLY update text where the source changed.
|
||||||
|
5. DO NOT translate code.
|
||||||
|
|
||||||
|
TOOLS: {allowed_tools}.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Helpers
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def run(cmd: List[str], cwd: Path | None = None, check: bool = True) -> str:
|
||||||
|
proc = subprocess.run(cmd, cwd=cwd, text=True, capture_output=True)
|
||||||
|
if check and proc.returncode != 0:
|
||||||
|
raise RuntimeError(f"Command failed: {' '.join(cmd)}\nStderr: {proc.stderr}")
|
||||||
|
return proc.stdout.strip()
|
||||||
|
|
||||||
|
def ensure_repo(path: Path, url: str) -> None:
|
||||||
|
if path.exists() and (path / ".git").is_dir():
|
||||||
|
run(["git", "fetch", "--all", "--prune"], cwd=path)
|
||||||
|
return
|
||||||
|
if path.exists():
|
||||||
|
shutil.rmtree(path)
|
||||||
|
run(["git", "clone", url, str(path)])
|
||||||
|
|
||||||
|
def update_to_head(path: Path) -> None:
|
||||||
|
try:
|
||||||
|
ref = run(["git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD"], cwd=path)
|
||||||
|
default_branch = ref.split("/")[-1]
|
||||||
|
except Exception:
|
||||||
|
default_branch = "main"
|
||||||
|
run(["git", "checkout", default_branch], cwd=path)
|
||||||
|
run(["git", "pull", "--ff-only"], cwd=path)
|
||||||
|
|
||||||
|
def checkout_or_create_branch(repo: Path, branch: str) -> None:
|
||||||
|
if run(["git", "branch", "--list", branch], cwd=repo):
|
||||||
|
run(["git", "checkout", branch], cwd=repo)
|
||||||
|
run(["git", "pull", "--ff-only"], cwd=repo, check=False)
|
||||||
|
elif run(["git", "ls-remote", "--heads", "origin", branch], cwd=repo):
|
||||||
|
run(["git", "checkout", "-t", f"origin/{branch}"], cwd=repo)
|
||||||
|
run(["git", "pull", "--ff-only"], cwd=repo)
|
||||||
|
else:
|
||||||
|
run(["git", "checkout", "-b", branch], cwd=repo)
|
||||||
|
|
||||||
|
def ensure_gemini() -> None:
|
||||||
|
if not shutil.which("gemini"):
|
||||||
|
print_err("gemini CLI not found. Install it and set GEMINI_API_KEY.")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
def parse_and_accumulate_usage(line_str: str) -> bool:
|
||||||
|
"""
|
||||||
|
Parses a JSON line from the gemini CLI stream.
|
||||||
|
Updates the global limiter if usage data is found, checking for both
|
||||||
|
'usageMetadata' (standard) and 'stats' (error summary) formats.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
data = json.loads(line_str)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 1. Look for standard usage keys (camelCase or snake_case)
|
||||||
|
usage = data.get("usageMetadata") or data.get("usage_metadata")
|
||||||
|
|
||||||
|
# 2. Look for nested usage (e.g. inside 'result' or 'candidates')
|
||||||
|
if not usage and "result" in data and isinstance(data["result"], dict):
|
||||||
|
usage = data["result"].get("usageMetadata") or data["result"].get("usage_metadata")
|
||||||
|
|
||||||
|
# 3. CRITICAL: Check for 'stats' key in error/result chunks (CLI-specific format)
|
||||||
|
if not usage:
|
||||||
|
usage = data.get("stats")
|
||||||
|
|
||||||
|
# If found, record it
|
||||||
|
if usage:
|
||||||
|
# Prioritize standard keys, fall back to 'stats' snake_case keys if needed.
|
||||||
|
prompt_tok = usage.get("promptTokenCount") or usage.get("prompt_token_count") or usage.get("input_tokens") or 0
|
||||||
|
cand_tok = usage.get("candidatesTokenCount") or usage.get("candidates_token_count") or usage.get("output_tokens") or 0
|
||||||
|
total_tok = usage.get("totalTokenCount") or usage.get("total_token_count") or usage.get("total_tokens") or 0
|
||||||
|
|
||||||
|
if total_tok > 0:
|
||||||
|
console.print() # Newline before recording usage for clean output
|
||||||
|
limiter.record_usage(prompt_tok, cand_tok)
|
||||||
|
|
||||||
|
if "error" in data:
|
||||||
|
console.print()
|
||||||
|
print_err(f"API Error: {data['error']}")
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
def run_gemini_agent(workdir: Path, prompt: str) -> None:
|
||||||
|
limiter.wait_for_capacity(estimated_tokens=500)
|
||||||
|
limiter.increment_session_counter()
|
||||||
|
|
||||||
|
cmd = [
|
||||||
|
"gemini",
|
||||||
|
"--model", MODEL,
|
||||||
|
f"--allowed-tools={ALLOWED_TOOLS}",
|
||||||
|
"--output-format", "stream-json",
|
||||||
|
"--approval-mode", "auto_edit",
|
||||||
|
prompt,
|
||||||
|
]
|
||||||
|
|
||||||
|
print_info(f"Invoking Agent ({MODEL})...")
|
||||||
|
|
||||||
|
process = subprocess.Popen(
|
||||||
|
cmd,
|
||||||
|
cwd=workdir,
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
text=True,
|
||||||
|
bufsize=1
|
||||||
|
)
|
||||||
|
|
||||||
|
if process.stdout:
|
||||||
|
for line in process.stdout:
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Load the JSON data
|
||||||
|
data = json.loads(line)
|
||||||
|
|
||||||
|
# Convert Python object (from JSON) to YAML string for readability
|
||||||
|
# Use safe_dump for security and sort_keys=False to maintain streaming order
|
||||||
|
yaml_output = yaml.safe_dump(data, indent=2, sort_keys=False)
|
||||||
|
|
||||||
|
console.print("--- Agent Stream Chunk (YAML) ---", style="bold magenta")
|
||||||
|
# Use rich.syntax.Syntax for colored YAML output with monokai theme
|
||||||
|
syntax = Syntax(yaml_output, "yaml", theme="monokai", word_wrap=True)
|
||||||
|
console.print(syntax, justify="left")
|
||||||
|
|
||||||
|
# Still run the usage tracking logic on the raw line string
|
||||||
|
parse_and_accumulate_usage(line)
|
||||||
|
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
# Handle non-JSON output (e.g., occasional non-stream lines from the CLI)
|
||||||
|
print(f" [Agent Non-JSON Output] {line}")
|
||||||
|
|
||||||
|
_, stderr_str = process.communicate()
|
||||||
|
|
||||||
|
# No final print() needed, as usage recording handles the newlines.
|
||||||
|
|
||||||
|
if process.returncode != 0:
|
||||||
|
print_err("Gemini Agent failed.")
|
||||||
|
console.print(stderr_str)
|
||||||
|
raise RuntimeError("Agent execution failed")
|
||||||
|
|
||||||
|
print_success("Agent finished task.")
|
||||||
|
|
||||||
|
if POST_REQUEST_DELAY > 0:
|
||||||
|
print_info(f"Cooling down for {POST_REQUEST_DELAY}s ...")
|
||||||
|
time.sleep(POST_REQUEST_DELAY)
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Filesystem
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def is_hidden(rel: Path) -> bool:
|
||||||
|
return any(p.startswith(".") for p in rel.parts)
|
||||||
|
|
||||||
|
def list_repo_files(root: Path) -> List[Path]:
|
||||||
|
out: List[Path] = []
|
||||||
|
for p in root.rglob("*"):
|
||||||
|
if p.is_dir(): continue
|
||||||
|
rel = p.relative_to(root)
|
||||||
|
if is_hidden(rel): continue
|
||||||
|
out.append(rel)
|
||||||
|
return out
|
||||||
|
|
||||||
|
def load_cache(path: Path) -> Dict[str, Any]:
|
||||||
|
if path.exists():
|
||||||
|
try:
|
||||||
|
with open(path, "r") as f: return json.load(f)
|
||||||
|
except: pass
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def save_cache(path: Path, data: Dict[str, Any]) -> None:
|
||||||
|
with open(path, "w") as f: json.dump(data, f, indent=2)
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Main
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("--langs", nargs="+", required=True, help="Language codes")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
ensure_gemini()
|
||||||
|
|
||||||
|
root_dir = Path.cwd()
|
||||||
|
build_dir = root_dir / "build_translation"
|
||||||
|
build_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
ftxui_dir = build_dir / "ftxui"
|
||||||
|
tx_dir = build_dir / "translations"
|
||||||
|
|
||||||
|
print_step("Ensuring source repo (FTXUI)...")
|
||||||
|
ensure_repo(ftxui_dir, FTXUI_REPO_URL)
|
||||||
|
update_to_head(ftxui_dir)
|
||||||
|
ftxui_head = run(["git", "rev-parse", "HEAD"], cwd=ftxui_dir)
|
||||||
|
print_info(f"FTXUI HEAD: {ftxui_head[:8]}")
|
||||||
|
|
||||||
|
print_step("Ensuring translations repo...")
|
||||||
|
ensure_repo(tx_dir, TRANSLATIONS_REPO_URL)
|
||||||
|
update_to_head(tx_dir)
|
||||||
|
|
||||||
|
print_step("Scanning files...")
|
||||||
|
all_files = list_repo_files(ftxui_dir)
|
||||||
|
source_set = {str(p) for p in all_files}
|
||||||
|
all_files.sort()
|
||||||
|
|
||||||
|
for lang_code in args.langs:
|
||||||
|
lang_name = LANG_NAMES.get(lang_code, lang_code)
|
||||||
|
print_step(f"Processing Language: {lang_name} ({lang_code})")
|
||||||
|
|
||||||
|
checkout_or_create_branch(tx_dir, lang_code)
|
||||||
|
|
||||||
|
cache_path = tx_dir / CACHE_FILE
|
||||||
|
cache = load_cache(cache_path)
|
||||||
|
last_hash = cache.get("last_processed_ftxui_commit")
|
||||||
|
|
||||||
|
if last_hash == ftxui_head:
|
||||||
|
print_success("Up to date. Skipping.")
|
||||||
|
continue
|
||||||
|
|
||||||
|
changed_set = set()
|
||||||
|
if last_hash:
|
||||||
|
diff_files = run(["git", "diff", "--name-only", last_hash, ftxui_head], cwd=ftxui_dir, check=False)
|
||||||
|
changed_set = set(diff_files.splitlines())
|
||||||
|
print_info(f"Changes detected: {len(changed_set)} files changed since {last_hash[:8]}")
|
||||||
|
else:
|
||||||
|
print_info("No history found. Full scan.")
|
||||||
|
|
||||||
|
for p in tx_dir.rglob("*"):
|
||||||
|
if p.is_dir(): continue
|
||||||
|
rel = p.relative_to(tx_dir)
|
||||||
|
if is_hidden(rel) or str(rel) == CACHE_FILE: continue
|
||||||
|
if str(rel) not in source_set:
|
||||||
|
print_warn(f"Removing orphan: {rel}")
|
||||||
|
p.unlink()
|
||||||
|
|
||||||
|
processed_count = 0
|
||||||
|
total_files = len(all_files)
|
||||||
|
|
||||||
|
for idx, rel in enumerate(all_files, 1):
|
||||||
|
src = ftxui_dir / rel
|
||||||
|
dst = tx_dir / rel
|
||||||
|
rel_s = str(rel)
|
||||||
|
dst.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
is_translatable = rel.suffix.lower() in TRANSLATABLE_EXT
|
||||||
|
is_changed = rel_s in changed_set
|
||||||
|
dst_exists = dst.exists()
|
||||||
|
|
||||||
|
prefix = f"[{idx}/{total_files}] {rel_s}"
|
||||||
|
|
||||||
|
if not is_translatable:
|
||||||
|
if is_changed or not dst_exists:
|
||||||
|
print_info(f"{prefix} -> Copying (Asset)")
|
||||||
|
shutil.copy2(src, dst)
|
||||||
|
processed_count += 1
|
||||||
|
continue
|
||||||
|
|
||||||
|
if dst_exists and last_hash and not is_changed:
|
||||||
|
continue
|
||||||
|
|
||||||
|
console.print("-" * 60, style="dim")
|
||||||
|
|
||||||
|
if not dst_exists or not last_hash:
|
||||||
|
print_info(f"{prefix} -> New Translation")
|
||||||
|
shutil.copy2(src, dst)
|
||||||
|
prompt = AGENT_NEW_FILE_PROMPT.format(
|
||||||
|
tx_root="translations", rel_path=rel_s,
|
||||||
|
lang_code=lang_code, lang_name=lang_name,
|
||||||
|
allowed_tools=ALLOWED_TOOLS
|
||||||
|
)
|
||||||
|
run_gemini_agent(build_dir, prompt)
|
||||||
|
processed_count += 1
|
||||||
|
|
||||||
|
elif is_changed:
|
||||||
|
print_info(f"{prefix} -> Updating (Diff-based)")
|
||||||
|
diff_out = run(["git", "diff", last_hash, ftxui_head, "--", rel_s], cwd=ftxui_dir)
|
||||||
|
|
||||||
|
if len(diff_out) > 20_000:
|
||||||
|
print_warn(f"Diff too large ({len(diff_out)} chars). Copying source for full re-translation.")
|
||||||
|
shutil.copy2(src, dst)
|
||||||
|
prompt = AGENT_NEW_FILE_PROMPT.format(
|
||||||
|
tx_root="translations", rel_path=rel_s,
|
||||||
|
lang_code=lang_code, lang_name=lang_name,
|
||||||
|
allowed_tools=ALLOWED_TOOLS
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
prompt = AGENT_DIFF_FILE_PROMPT.format(
|
||||||
|
tx_root="translations", rel_path=rel_s,
|
||||||
|
lang_code=lang_code, lang_name=lang_name,
|
||||||
|
allowed_tools=ALLOWED_TOOLS,
|
||||||
|
diff=diff_out
|
||||||
|
)
|
||||||
|
|
||||||
|
run_gemini_agent(build_dir, prompt)
|
||||||
|
processed_count += 1
|
||||||
|
|
||||||
|
if processed_count > 0:
|
||||||
|
cache["last_processed_ftxui_commit"] = ftxui_head
|
||||||
|
save_cache(cache_path, cache)
|
||||||
|
|
||||||
|
status = run(["git", "status", "--porcelain"], cwd=tx_dir, check=False)
|
||||||
|
if status.strip():
|
||||||
|
print_step("Committing changes...")
|
||||||
|
run(["git", "add", "-A"], cwd=tx_dir)
|
||||||
|
run(["git", "commit", "-m", f"{lang_name}: update translations to {ftxui_head[:8]}"], cwd=tx_dir, check=False)
|
||||||
|
run(["git", "push", "--set-upstream", "origin", lang_code], cwd=tx_dir)
|
||||||
|
print_success("Pushed.")
|
||||||
|
else:
|
||||||
|
print_success("No file changes detected after processing.")
|
||||||
|
else:
|
||||||
|
print_success("Nothing to process.")
|
||||||
|
|
||||||
|
print_step("All Done.")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user