Add themes, redesign help, and stabilize previews

This commit is contained in:
vrubelroman 2026-12-06 05:11:31 +03:00
parent 60847ebb30
commit 52d201c3e3
163 changed files with 16319 additions and 639 deletions

View file

@ -0,0 +1,49 @@
---
name: rcom-tui-design
description: Проектирование и независимая проверка TUI/UX для rcom. Использовать при любой работе с визуальным дизайном, layouts, панелями, icons, colors, themes, help, dialogs, responsive терминалами, keyboard navigation, accessibility или UI review — даже если пользователь просто просит «сделать красиво», показывает screenshot или сообщает о мигании/перегруженном интерфейсе.
---
# RCOM TUI Design
Проектируй и проверяй интерфейс как единую систему, а не как набор декоративных изменений. Цель — спокойный, читаемый, keyboard-only файловый менеджер, который остаётся полезным на узком терминале и без цвета или специального шрифта.
## Обязательные входы
1. Прочитай `docs/tui-design-guidelines.md` от корня репозитория.
2. Прочитай релевантные main/delta OpenSpec specs, прежде чем предлагать поведение.
3. Изучи текущий `src/ui`, `src/input`, named tests и пользовательские screenshots. Не выдавай предположение о текущем UI за факт.
4. Для исследования других программ используй официальные docs/source и отделяй их фактическое поведение от рекомендаций для rcom.
Если guideline и действующая spec расходятся, не выбирай молча: зафиксируй расхождение и предложи change, который приведёт их к одному контракту.
## Режим дизайнера
1. Сформулируй пользовательскую задачу и визуальную иерархию.
2. Проверь содержимое, selection, focus, errors, loading и empty states до декоративных деталей.
3. Предложи один согласованный вариант. Альтернативы нужны только при реальном пользовательском выборе.
4. Определи interaction model, aliases, wrap/clamp и закрытие overlays.
5. Определи responsive degradation и поведение `NO_COLOR`, ASCII и icons-off.
6. Запиши observable scenarios в OpenSpec и свяжи каждое с будущим named test.
7. Не реализуй код, если запрошены только исследование или план.
### Результат дизайнера
- Цель и наблюдаемая проблема.
- Visual contract: структура, иерархия, semantic colors/icons.
- Interaction contract: клавиши, selection, navigation, close/cancel.
- Responsive/accessibility behavior.
- Acceptance matrix и ограничения, требующие пользовательского визуального review.
## Режим независимого тестировщика
Проверяй готовый дизайн против specs и guideline, не подгоняя findings под intent автора.
- Сравнивай полный `Buffer`, включая стили, когда важна стабильность кадра.
- Проверяй keyboard-only flow, все aliases, отсутствие потерянных команд и stale responses.
- Проверяй narrow/short, normal и wide layouts, включая 40×8.
- Проверяй selection/focus/errors без цвета и без Nerd Font.
- Ищи overlap, нечитаемую плотность, обрезанные critical actions и периодический flicker.
- Отделяй CRITICAL functional failures, WARNING spec/coverage gaps и SUGGESTION aesthetic improvements.
- Давай file:line и конкретную рекомендацию для каждого finding.
Не присваивай archive-ready при непроверенных scenarios. Сообщай, если требуется визуальный ответ пользователя даже после зелёного automated suite.

669
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -2,7 +2,7 @@
name = "rcom"
version = "0.1.0"
edition = "2024"
rust-version = "1.88"
rust-version = "1.90"
description = "Dual-pane local and SSH terminal file manager"
license = "MIT"
@ -15,14 +15,18 @@ crossterm = { version = "0.29", features = ["event-stream"] }
directories = "6"
futures-util = "0.3"
glob = "0.3"
image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "gif", "bmp", "webp"] }
openssh = "0.11.6"
openssh-sftp-client = { version = "0.15.12", features = ["openssh"] }
ratatui = { version = "0.30.2", default-features = false, features = ["all-widgets", "crossterm_0_29", "layout-cache", "macros", "std", "underline-color"] }
ratatui-image = { version = "12.0.0", default-features = false, features = ["crossterm"] }
serde = { version = "1", features = ["derive"] }
shell-words = "1"
tempfile = "3"
thiserror = "2"
tokio = { version = "1", features = ["fs", "io-util", "macros", "process", "rt-multi-thread", "signal", "sync", "time"] }
tokio-util = "0.7"
toml = "0.9"
unicode-width = "0.2"
uuid = { version = "1", features = ["v4"] }
@ -31,3 +35,4 @@ expectrl = "0.8"
insta = "1"
pretty_assertions = "1"
proptest = "1"
tokio = { version = "1", features = ["test-util"] }

177
LICENSES/image-APACHE.txt Normal file
View file

@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

25
LICENSES/image-MIT.txt Normal file
View file

@ -0,0 +1,25 @@
MIT License
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,24 @@
The MIT License (MIT)
Copyright (c) 2022 Atanas Yankov (code and inspiration taken from https://github.com/atanunq/viuer)
Copyright (c) 2022 wooster0 (inspiration taken from https://github.com/wooster0/hanbun)
Copyright (c) 2023 Benjamin Große
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,20 @@
Copyright (c) 2011 Ethan Schoonover
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Catppuccin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2018 Dracula Theme
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Pavel Pertsev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Steph Ango
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Primer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) Rosé Pine
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 sainnhe
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 Son A. Pham <sp@sonpham.me>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -6,7 +6,7 @@
## Требования
- Rust stable **1.88 или новее**;
- Rust stable **1.90 или новее** (требование transitive `quantette` для `ratatui-image 12`);
- Linux/macOS и совместимый терминал;
- системный OpenSSH только для удалённых панелей;
- key/agent аутентификация без интерактивных prompts для SSH.
@ -36,8 +36,24 @@ INSTA_UPDATE=no PROPTEST_CASES=256 cargo test --workspace --all-targets --locked
- **Dual:** две независимые панели 50/50 без постоянного preview.
- На узком терминале в dual отображается активная панель с индикатором `PANE 1/2` или `PANE 2/2`; состояние скрытой панели сохраняется.
- `F3` открывает временный preview поверх любой раскладки.
- Видимые каталоги перечитываются с bounded интервалом 1 секунда: внешние create/rename/delete появляются без ручного refresh; loading не создаёт очередь запросов. Фоновый poll не показывает `LOADING` и не меняет текущий кадр, строку entries или пустое состояние до получения ответа. Preview того же выбранного элемента также остаётся видимым без `LOADING PREVIEW` и обновляется атомарно; при смене выбора старое содержимое очищается. Polling приостанавливается во время planning/confirmation и внешнего редактора, чтобы фоновый listing не инвалидировал ожидающий snapshot.
- Тема Night Ops не требует Nerd Fonts; `NO_COLOR` и ASCII fallback сохраняют маркеры и структуру.
- Постоянной нижней строки hints нет: её место занимает содержимое, а `? Help` остаётся в header на каждом поддерживаемом размере.
- Видимые каталоги перечитываются с bounded интервалом 1 секунда: внешние create/rename/delete появляются без ручного refresh; loading не создаёт очередь запросов. Фоновый poll не показывает `LOADING` и не меняет текущий кадр, строку entries или пустое состояние до получения ответа. Preview того же выбранного элемента также остаётся видимым без `LOADING PREVIEW` и обновляется атомарно; при смене выбора старое содержимое очищается, а быстрые selection changes коалесцируются за 40 ms без промежуточных reads и loading-flash. Polling приостанавливается во время planning/confirmation и внешнего редактора, чтобы фоновый listing не инвалидировал ожидающий snapshot.
- Встроены 20 offline-тем (11 dark / 9 light), по умолчанию — Night Ops с прежними базовыми accents и зафиксированной accessibility-коррекцией selection; `NO_COLOR` и ASCII fallback сохраняют маркеры и структуру.
- File icons различают каталоги, точные проектные имена, расширения, links и executables; цвет иконки и semantic цвет имени независимы. Rust имеет отдельный glyph; при включённых иконках избыточный `TYPE` не выводится, а в `none` сохраняются текстовые `DIR`/`FILE`/`LINK`/`OTH`.
### Иконки, темы и config
По умолчанию используется `unicode`, не требующий специального шрифта. В `${XDG_CONFIG_HOME:-~/.config}/rcom/config.toml` (либо platform config directory) можно сохранить `icons = "unicode"`, `"nerd"`, `"ascii"` или `"none"` и `theme = "night-ops"`; `images = false` отключает pixel preview и probes. `RCOM_CONFIG_HOME` переопределяет каталог config. Для одного запуска используйте:
```bash
cargo run --locked -- --icons nerd --theme dracula
cargo run --locked -- --no-images
cargo run --locked -- --list-themes
```
CLI не изменяет сохранённый файл и имеет приоритет над config только на текущий запуск. Каталог содержит ровно 20 стабильных IDs; runtime не обращается к сети и не запускает kitty/upstream code. Nerd Font нужен только режиму `nerd`; `TERM=dumb`/`RCOM_ASCII` используют ASCII, а `none` никогда не включается обратно через environment.
`T` открывает Theme Picker: `j/k` и `Up`/`Down` немедленно показывают тему во всём UI, `Enter` атомарно сохраняет только её ID с проверкой внешнего изменения config, `Esc` восстанавливает исходную тему без записи. При ошибке сохранения picker остаётся открытым и показывает причину. Provenance, лицензии и развитие pinned importer описаны в `docs/themes.md` и `THIRD_PARTY_NOTICES.md`.
## Горячие клавиши
@ -67,6 +83,7 @@ Yazi-подобные и mc-команды доступны одновремен
| Редактировать hovered regular file | `e` / `F4` |
| Yank copy / cut move / paste planner | `y` / `x` / `p` |
| Список задач и прогресс | `t` |
| Theme Picker с live preview | `T` |
| SSH HostPicker для активной панели | `s` |
| Временный preview | `F3` |
| Справка | `?`, `F1` |
@ -75,6 +92,8 @@ Yazi-подобные и mc-команды доступны одновремен
В HostPicker текст вводится в фильтр, `Up`/`Down` меняют выбор, `Enter` подключает хост, `Esc` закрывает без изменения панели. В prompts текст редактируется до глобальных aliases; `Esc` отменяет без mutation.
Help содержит шесть категорий: **Navigation, Selection, Files, Tasks, SSH, General**. `h`/`Left`/`Shift-Tab` и `l`/`Right`/`Tab` переключают их с wrap; `j`/`k`, `Up`/`Down`, `PageUp`/`PageDown`, `Ctrl-b`/`Ctrl-f` и `Ctrl-u`/`Ctrl-d` прокручивают содержимое. На 40×8 полный tab strip заменяется на `< N/6 Category >`, а все команды остаются достижимыми постранично. `Esc`, `q`, `?` или F1 закрывают Help без изменения workspace; Enter ничего не выполняет, F10 выходит через обычный quit path. В Task Details те же вертикальные aliases прокручивают именно подробности и не меняют выбор задачи за overlay.
Clipboard `y`/`x` сохраняет исходный snapshot: после multi-select можно перейти в другой каталог или на другую панель перед `p`. Paste создаёт новый plan для исходных источников и актуального destination; missing source/stale SSH epoch по-прежнему отклоняются. После committed copy/move затронутые панели обновляются автоматически, включая partial/cancelled результат.
Copy/move сначала выполняют read-only preflight и показывают source, destination, размер и последствия move; запись начинается только после `Enter`. В collision prompt `s`/`o` выбирают Skip/Overwrite, `Shift-S`/`Shift-O` применяют решение ко всем, а `Esc` отменяет. В Tasks `c` запрашивает cooperative cancellation, `m`/`Enter` показывают ошибки и `.part`. Выход при активных задачах по умолчанию предлагает остаться; принудительный выход требует отдельного подтверждения.
@ -99,6 +118,7 @@ Copy/move сначала выполняют read-only preflight и показы
## Безопасный предпросмотр
- Текстовый preview читает не более **64 KiB** и показывает маркер усечения.
- PNG/JPEG/GIF/BMP/WebP определяются по content magic и показываются реальными pixels в persistent/F3. Encoded input ограничен **16 MiB**, 8192 на ось, 32M pixels и 256 MiB decoder allocation; animated input становится static. Один serialized worker не пишет terminal, prepared images инвалидируются по selection/generation/endpoint/geometry/terminal epoch. Kitty/iTerm2/Sixel — best-effort через `ratatui-image`; halfblocks — universal fallback, tmux не изменяет `allow-passthrough`. `NO_COLOR`, ASCII/dumb, non-TTY, `images=false` и `--no-images` используют metadata fallback без probe.
- Preview каталога нерекурсивный и содержит не более **100 имён**.
- Binary/unsupported content заменяется placeholder с метаданными.
- UTF-8 ошибки заменяются символом `<60>`; управляющие и опасные bidi-символы экранируются.
@ -114,11 +134,13 @@ Copy/move сначала выполняют read-only preflight и показы
- Copy использует unique sibling `.rcom-part-*`, flush/close, size/collision recheck и commit rename; каталоги собираются в staging root без merge существующих каталогов.
- Move удаляет source только после подтверждённого commit и fingerprint-проверки; timeout/disconnect даёт `Unknown`, без automatic retry или rollback-обещания.
- Trash создаёт unique restore records на исходном endpoint. Permanent delete явно не undoable; undo работает только в текущей сессии для полностью успешных create/rename/move/trash и проверяет fingerprints/epochs. Copy, permanent delete и редактирование не добавляются в undo journal.
- Windows SSH backend, изображения, архивы, плагины, tabs и search остаются следующими changes.
- Windows SSH backend, архивы, плагины, tabs и search остаются следующими changes. Kitty и real tmux прошли visual acceptance; iTerm2/Sixel не заявляются без отдельной real-terminal matrix и не выводятся из headless tests.
## Roadmap
Следующие отдельные changes: search/filter, tabs, archive preview, themes и plugin API.
Icons/colors, 20 themes, categorized Help и preview debounce реализованы и архивированы в `openspec/changes/archive/2026-12-06-*`. Image preview реализован в `add-image-previews`; его technical verdict 0 findings, а внешний iTerm2/Sixel и real-SSH visual gate явно остаётся открытым. Общий стандарт: `docs/tui-design-guidelines.md`; дизайнерский/проверочный skill: `.agents/skills/rcom-tui-design/SKILL.md`.
Далее в roadmap остаются search/filter, workspace tabs, archive preview и plugin API.
## Разработка

199
THIRD_PARTY_NOTICES.md Normal file
View file

@ -0,0 +1,199 @@
# Third-party notices
## nvim-web-devicons icon data and glyphs
The Nerd Font glyph identifiers and file-type mapping used by rcom are derived from or inspired by the nvim-web-devicons project:
- Upstream: <https://github.com/nvim-tree/nvim-web-devicons>
- Copyright: Copyright (c) 2023 nvim-tree
- License: MIT
The following notice is retained for the imported/inspired data:
MIT License
Copyright (c) 2023 nvim-tree
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## Image decoding and terminal presentation
- `image 0.25.10`: <https://github.com/image-rs/image>, MIT OR Apache-2.0. Full notices: `LICENSES/image-MIT.txt` and `LICENSES/image-APACHE.txt`.
- `ratatui-image 12.0.0`: <https://github.com/ratatui/ratatui-image>, MIT. Full notice: `LICENSES/ratatui-image-MIT.txt`.
- Both are built with the feature set in `Cargo.toml`; dynamic/static libchafa support is not enabled. Kitty/iTerm2/Sixel encoders remain upstream ratatui-image code, while rcom owns bounded input, identity, cancellation and lifecycle.
## Curated kitty color themes
The 19 imported color themes are generated into static Rust data. Their source files come from <https://github.com/kovidgoyal/kitty-themes> at pinned commit `a35d12290c3d6a74b1f94debc81281cb637f3568`; each source path and SHA-256 is recorded below and in `themes/manifest.json`. The application uses these built-in values without network access, a kitty subprocess, or execution of upstream configuration.
An import update requires an explicit new source pin, hash/provenance review, and refreshed notices. The kitty metadata license and the actual upstream license are recorded separately. In particular, Tokyo Night and Tokyo Night Day retain their upstream **Apache-2.0** terms rather than inheriting the collection's MIT metadata. For Solarized, the upstream SPDX field is unavailable in the manifest, but the pinned full notice explicitly contains the MIT permission and warranty terms.
Night Ops is native to rcom, is not an imported third-party theme, and receives no third-party attribution.
### Dracula (`dracula`)
- Author: Keegan Carruthers-Smith; kitty metadata: MIT.
- Source: `themes/Dracula.conf`; SHA-256: `a4075ea3798795960e0205638ff55f6a506f60437938d94dc2a1aab62140d3ae`.
- Upstream: <https://raw.githubusercontent.com/dracula/kitty/master/dracula.conf>.
- License provenance: <https://github.com/dracula/kitty> at `87717a3f00e3dff0fc10c93f5ff535ea4092de70`.
- Effective license: **MIT**. Full notice: [`LICENSES/themes/dracula__kitty.txt`](LICENSES/themes/dracula__kitty.txt).
### Catppuccin Mocha (`catppuccin-mocha`)
- Author: Pocco81 (https://github.com/Pocco81); kitty metadata: MIT.
- Source: `themes/Catppuccin-Mocha.conf`; SHA-256: `9d3f69cdb6d14d651782f7265ad9f00a687344fe8508b171b16688da9ae2bfa0`.
- Upstream: <https://github.com/catppuccin/kitty/blob/main/themes/mocha.conf>.
- License provenance: <https://github.com/catppuccin/kitty> at `177d447f0c3626959ef001b4605f5d844541fd63`.
- Effective license: **MIT**. Full notice: [`LICENSES/themes/catppuccin__kitty.txt`](LICENSES/themes/catppuccin__kitty.txt).
### Catppuccin Latte (`catppuccin-latte`)
- Author: Pocco81 (https://github.com/Pocco81); kitty metadata: MIT.
- Source: `themes/Catppuccin-Latte.conf`; SHA-256: `3e32d197b44d817db2e2c5835e698184c66b43b85fd78dce1e1b235b0d014974`.
- Upstream: <https://github.com/catppuccin/kitty/blob/main/themes/latte.conf>.
- License provenance: <https://github.com/catppuccin/kitty> at `177d447f0c3626959ef001b4605f5d844541fd63`.
- Effective license: **MIT**. Full notice: [`LICENSES/themes/catppuccin__kitty.txt`](LICENSES/themes/catppuccin__kitty.txt).
### Gruvbox Dark (`gruvbox-dark`)
- Author: Pavel Pertsev; kitty metadata: MIT.
- Source: `themes/gruvbox-dark.conf`; SHA-256: `3c7162ea53fde5e0437d025563689d9868970839e28a7bbd35bd52bfd5f30afa`.
- Upstream: <https://raw.githubusercontent.com/gruvbox-community/gruvbox-contrib/master/kitty/gruvbox-dark.conf>.
- License provenance: <https://github.com/gruvbox-community/gruvbox> at `180ad85971343df68be3422a5630fa84e45a9ab2`.
- Effective license: **MIT**. Full notice: [`LICENSES/themes/gruvbox-community__gruvbox.txt`](LICENSES/themes/gruvbox-community__gruvbox.txt).
### Gruvbox Light (`gruvbox-light`)
- Author: Pavel Pertsev; kitty metadata: MIT.
- Source: `themes/gruvbox-light.conf`; SHA-256: `7304f0b97be113af68d3a8ae85cbeca7a24346ce5847bd3710c837e6107e1073`.
- Upstream: <https://raw.githubusercontent.com/gruvbox-community/gruvbox-contrib/master/kitty/gruvbox-light.conf>.
- License provenance: <https://github.com/gruvbox-community/gruvbox> at `180ad85971343df68be3422a5630fa84e45a9ab2`.
- Effective license: **MIT**. Full notice: [`LICENSES/themes/gruvbox-community__gruvbox.txt`](LICENSES/themes/gruvbox-community__gruvbox.txt).
### Solarized Dark (`solarized-dark`)
- Author: Ethan Schoonover; kitty metadata: MIT.
- Source: `themes/Solarized_Dark.conf`; SHA-256: `fc23242afc7cbbc7b6b97ac45a4607e1e9181d4823b42054dc3d9099fd9e1743`.
- Upstream: <https://github.com/altercation/solarized>.
- License provenance: <https://github.com/altercation/solarized> at `62f656a02f93c5190a8753159e34b385588d5ff3`.
- Effective license: **MIT (established by the full license text; upstream SPDX metadata is null)**. Full notice: [`LICENSES/themes/altercation__solarized.txt`](LICENSES/themes/altercation__solarized.txt).
### Solarized Light (`solarized-light`)
- Author: Ethan Schoonover; kitty metadata: MIT.
- Source: `themes/Solarized_Light.conf`; SHA-256: `3c5064623dbe2deb76d1efa2f304893182486d511567893a9653fef65ae8c9d4`.
- Upstream: <https://github.com/altercation/solarized>.
- License provenance: <https://github.com/altercation/solarized> at `62f656a02f93c5190a8753159e34b385588d5ff3`.
- Effective license: **MIT (established by the full license text; upstream SPDX metadata is null)**. Full notice: [`LICENSES/themes/altercation__solarized.txt`](LICENSES/themes/altercation__solarized.txt).
### Tokyo Night (`tokyo-night`)
- Author: Folke Lemaitre; kitty metadata: MIT.
- Source: `themes/tokyo_night_night.conf`; SHA-256: `e92085fb339ca9be916e3bc47fa6813843c6007b155d4f9bcb9fb5af545adc5c`.
- Upstream: <https://github.com/folke/tokyonight.nvim/raw/main/extras/kitty/tokyonight_night.conf>.
- License provenance: <https://github.com/folke/tokyonight.nvim> at `d8e9ca64c0b8e574051f14bf1486ecd12b81de89`.
- Effective license: **Apache-2.0**. Full notice: [`LICENSES/themes/folke__tokyonight.nvim.txt`](LICENSES/themes/folke__tokyonight.nvim.txt).
### Tokyo Night Day (`tokyo-night-day`)
- Author: Folke Lemaitre; kitty metadata: MIT.
- Source: `themes/tokyo_night_day.conf`; SHA-256: `3f6bb553ce120c20ce04c9f71eb811d4a4b3c3298370c1a04aa933ea244ec5bd`.
- Upstream: <https://github.com/folke/tokyonight.nvim/raw/main/extras/kitty/tokyonight_day.conf>.
- License provenance: <https://github.com/folke/tokyonight.nvim> at `d8e9ca64c0b8e574051f14bf1486ecd12b81de89`.
- Effective license: **Apache-2.0**. Full notice: [`LICENSES/themes/folke__tokyonight.nvim.txt`](LICENSES/themes/folke__tokyonight.nvim.txt).
### One Half Dark (`one-half-dark`)
- Author: Son A. Pham; kitty metadata: MIT.
- Source: `themes/OneHalfDark.conf`; SHA-256: `187e3e44bb61305f8d94bfa1513d5c19253672879e5429c96dba0add22f26120`.
- Upstream: <https://raw.githubusercontent.com/sonph/onehalf/master/kitty/onehalf-dark.conf>.
- License provenance: <https://github.com/sonph/onehalf> at `75eb2e97acd74660779fed8380989ee7891eec56`.
- Effective license: **MIT**. Full notice: [`LICENSES/themes/sonph__onehalf.txt`](LICENSES/themes/sonph__onehalf.txt).
### One Half Light (`one-half-light`)
- Author: Son A. Pham; kitty metadata: MIT.
- Source: `themes/OneHalfLight.conf`; SHA-256: `5329fccb5d0ba8cbd86292756bd7aa7cc1fca9098b51466cf4a419ae8eb3d797`.
- Upstream: <https://raw.githubusercontent.com/sonph/onehalf/master/kitty/onehalf-light.conf>.
- License provenance: <https://github.com/sonph/onehalf> at `75eb2e97acd74660779fed8380989ee7891eec56`.
- Effective license: **MIT**. Full notice: [`LICENSES/themes/sonph__onehalf.txt`](LICENSES/themes/sonph__onehalf.txt).
### Rosé Pine (`rose-pine`)
- Author: mvllow; kitty metadata: MIT.
- Source: `themes/rose-pine.conf`; SHA-256: `0e8885538373c1e279553d2a6ce1ee2bf6a8302beaa9ccded9e39818225971ce`.
- Upstream: <https://github.com/rose-pine/kitty/blob/main/dist/rose-pine.conf>.
- License provenance: <https://github.com/rose-pine/kitty> at `efd4f01cb9887feaa7114ff21a887464295d0205`.
- Effective license: **MIT**. Full notice: [`LICENSES/themes/rose-pine__kitty.txt`](LICENSES/themes/rose-pine__kitty.txt).
### Rosé Pine Dawn (`rose-pine-dawn`)
- Author: mvllow; kitty metadata: MIT.
- Source: `themes/rose-pine-dawn.conf`; SHA-256: `8a7a2de3d2e3018c02f6ab16e80b9600f151a8891da8ad8c2764e145adbd6f7a`.
- Upstream: <https://github.com/rose-pine/kitty/blob/main/dist/rose-pine-dawn.conf>.
- License provenance: <https://github.com/rose-pine/kitty> at `efd4f01cb9887feaa7114ff21a887464295d0205`.
- Effective license: **MIT**. Full notice: [`LICENSES/themes/rose-pine__kitty.txt`](LICENSES/themes/rose-pine__kitty.txt).
### Everforest Dark Medium (`everforest-dark-medium`)
- Author: Sainnhe Park; kitty metadata: MIT.
- Source: `themes/everforest_dark_medium.conf`; SHA-256: `038bf240b421f1430507f4432b7704403e917fbe69866b3bcaaeb55ec1a4be60`.
- Upstream: <https://github.com/ewal/kitty-everforest/blob/master/themes/everforest_dark_medium.conf>.
- License provenance: <https://github.com/sainnhe/everforest> at `85a86eb62409e3ec88713bff3d1b9d7374e112e4`.
- Effective license: **MIT**. Full notice: [`LICENSES/themes/sainnhe__everforest.txt`](LICENSES/themes/sainnhe__everforest.txt).
### Everforest Light Medium (`everforest-light-medium`)
- Author: Sainnhe Park; kitty metadata: MIT.
- Source: `themes/everforest_light_medium.conf`; SHA-256: `5009e7e9f24d0e5ea42ddd0fd481d74317bdd04bd53384b2c8fbe2bd8cab246d`.
- Upstream: <https://github.com/ewal/kitty-everforest/blob/master/themes/everforest_light_medium.conf>.
- License provenance: <https://github.com/sainnhe/everforest> at `85a86eb62409e3ec88713bff3d1b9d7374e112e4`.
- Effective license: **MIT**. Full notice: [`LICENSES/themes/sainnhe__everforest.txt`](LICENSES/themes/sainnhe__everforest.txt).
### GitHub Dark (`github-dark`)
- Author: GitHub; kitty metadata: MIT.
- Source: `themes/GitHub_Dark.conf`; SHA-256: `db70f8f1b4204098dc464ea47c3de5071697bd6cc2c4f9d36068c30dd96eb824`.
- Upstream: <https://github.com/primer/github-vscode-theme>.
- License provenance: <https://github.com/primer/github-vscode-theme> at `738b0ac78f6a7cc16c8d541a71fa103d8637a64a`.
- Effective license: **MIT**. Full notice: [`LICENSES/themes/primer__github-vscode-theme.txt`](LICENSES/themes/primer__github-vscode-theme.txt).
### GitHub Light (`github-light`)
- Author: GitHub; kitty metadata: MIT.
- Source: `themes/GitHub_Light.conf`; SHA-256: `02dc60b8e33709fcaf728daec85882039ece71569bfc1e5c8757181b249dce9c`.
- Upstream: <https://github.com/primer/github-vscode-theme>.
- License provenance: <https://github.com/primer/github-vscode-theme> at `738b0ac78f6a7cc16c8d541a71fa103d8637a64a`.
- Effective license: **MIT**. Full notice: [`LICENSES/themes/primer__github-vscode-theme.txt`](LICENSES/themes/primer__github-vscode-theme.txt).
### Flexoki Dark (`flexoki-dark`)
- Author: Kepano; kitty metadata: MIT.
- Source: `themes/flexoki_dark.conf`; SHA-256: `126a74cd3d403611104aeaeb53d55a4b92f0a47ea1745f75b412e59aebc60975`.
- Upstream: <https://raw.githubusercontent.com/kepano/flexoki/main/kitty/flexoki_dark.conf>.
- License provenance: <https://github.com/kepano/flexoki> at `8d723bac4a9ac46adfdf99d42155286977aac72a`.
- Effective license: **MIT**. Full notice: [`LICENSES/themes/kepano__flexoki.txt`](LICENSES/themes/kepano__flexoki.txt).
### Flexoki Light (`flexoki-light`)
- Author: Kepano; kitty metadata: MIT.
- Source: `themes/flexoki_light.conf`; SHA-256: `10c914e13591d500704750599728b35b9277635f33e76af7b52fc27039cbb284`.
- Upstream: <https://raw.githubusercontent.com/kepano/flexoki/main/kitty/flexoki_light.conf>.
- License provenance: <https://github.com/kepano/flexoki> at `8d723bac4a9ac46adfdf99d42155286977aac72a`.
- Effective license: **MIT**. Full notice: [`LICENSES/themes/kepano__flexoki.txt`](LICENSES/themes/kepano__flexoki.txt).

View file

@ -231,3 +231,56 @@ cargo test --test ssh_hermesvm -- --ignored --nocapture
### Финальный независимый verdict
**0 CRITICAL / 0 WARNING / 0 SUGGESTION — archive-ready.** Независимый verify подтвердил MODIFIED `file-navigation` и все девять scenarios, same-target eligibility, foreground initial/F3/selection behavior, current/stale response guards и атомарное changed content. Независимо запущенные targeted suites: **93 passed, 0 failed**.
## Change `add-file-type-icons-and-colors`
Дата: 2026-12-06.
- Добавлен чистый `IconResolver` без filesystem/network I/O: ordered globs, exact directory/file names, extension fallback с явной case policy, metadata conditions и generic unknown. Обычные filename/extension maps не применяются к каталогам. Broken links не угадываются; typed LinkStatus остаётся отдельным будущим change.
- Night Ops получила semantic filename/icon palette. Canonical full-Buffer fixture покрывает каталог, Cargo.toml, main.rs, executable, symlink и selected+marked; selected row наследует проверенный selection style, а state markers сохраняются; `TYPE` выводится только в icons-off и не дублирует иконки.
- Unicode/Nerd/ASCII/none поддержаны через persistent `config.toml` и `--icons`. ASCII fallback не включает `none`; ошибки config возникают до alternate screen. `serde`/`toml` добавлены как typed parser dependencies, lockfile обновлён.
- Добавлены filename-aware truncation, icon width budget и tests на 40×8, 80×24, 120×40, 160×40 и dual 71/72. Snapshots изменены на ожидаемые glyph additions и удаление избыточного `TYPE` после просмотра diff.
- Начальный icon catalog содержит development/document/media/archive/common classes и generic fallbacks; nvim-web-devicons MIT attribution сохранён в `THIRD_PARTY_NOTICES.md`. Synthetic resolver benchmark: 20 000 entries проходят exact extension fast path.
### Quality suite после design review
- `INSTA_UPDATE=no PROPTEST_CASES=256 cargo test --workspace --all-targets --locked` — **578 passed, 0 failed, 4 ignored** в 71 suite;
- `cargo clippy --workspace --all-targets --all-features --locked -- -D warnings`, fmt и doc-test — PASS;
- Первый independent verify выявил empty Nerd glyphs, отсутствие copy/cut и executable-independent markers, а также слабые responsive assertions. Добавлены настоящие PUA glyphs, copy/cut `+`/`-`, executable suffix `*`, узнаваемые Unicode pictographs и позиционные Buffer checks; полный suite повторно зелёный.
- После пользовательского visual feedback уменьшен левый state prefix до двух колонок (combined marked+copy/cut используют `±`/`∓`), preview/F3 title получил icon+name с теми же semantic styles, а config-папки (`.config`, `.settings`, `.vscode`, `.idea`) — gear icon. Добавлены named Buffer tests; финальный suite: 578 passed.
- Повторный independent verify: **0 CRITICAL / 0 WARNING / 0 SUGGESTION — технически archive-ready**. Документация `docs/design.md` также синхронизирована с conditional TYPE rendering.
- Пользовательский visual review завершён итеративно: rich-вид одобрен, затем уменьшен левый отступ, добавлены preview/config icons и исправлен ASCII combined fallback. Финальный автономный acceptance использует 578 passed/0 failed и повторный independent verdict 0 findings.
## Change `add-color-theme-presets`
Дата: 2026-12-06.
- Добавлены ровно 20 offline-тем (11 dark/9 light), stable kebab-case IDs, `theme` config, `--theme`, `--list-themes` и ошибки unknown ID до alternate screen. Night Ops сохраняет базовые background/panel/text/accents/file-type RGB; muted/selection/selection_text получили отдельно зафиксированную accessibility-коррекцию.
- Development-only importer закрепляет kitty commit и 19 SHA-256, whitelist parser не исполняет config, а manifest/notices сохраняют upstream provenance. Review исправил план: Tokyo Night использует фактическую Apache-2.0, а не подменённую MIT metadata.
- Derived palettes проходят measured 4.5:1/3:1 targets на используемых surfaces. Selected rich row использует explicit `selection_text`/`selection` + BOLD без REVERSED; monochrome сохраняет REVERSED. Это не универсальный claim для пользовательских terminal palettes.
- Theme Picker `T` поддерживает live preview, clamp/Repeat, `N/20`, 40×8/80×24/120×40, Esc baseline rollback и Press-only Enter/Esc/F10. Enter использует exact-content fingerprint и owned temporary sibling+rename, сохраняет `icons`/unknown TOML fields, а ошибка оставляет видимый picker без automatic retry.
- Catalog: **9 passed**; picker: **8 passed**; per-theme rendering: **3 passed**; importer: **7 passed**, включая полный double-import и tamper matrix. Два новых PTY сценария — PASS. Общий suite с Help перед финальными debounce additions: **618 passed, 0 failed, 4 ignored**; финальный independent verdict: **0 findings**. Change синхронизирован и архивирован; после остальных changes общий suite повторён: **651 passed, 0 failed, 4 ignored**.
## Change `redesign-help-and-remove-hints` — в работе
Дата: 2026-12-06.
- Help имеет фиксированные Navigation/Selection/Files/Tasks/SSH/General, startup Navigation/0 и 111 stable context-labelled actions с независимой inventory-проверкой. Сохранены регистр, Theme Picker `T`, collision `s/S/o/O`, quit `c/x`, printable editing и context-specific Enter; внешние product names отсутствуют.
- `h`/Left/Shift-Tab и `l`/Right/Tab переключают категории с wrap/reset. Vertical aliases используют общую pure view model, фактическую body height, hanging wrap и normalized clamp при input/resize. Enter инертен; Esc/`q`/`?`/F1 закрывают, F10 остаётся Press-only quit. Task Details вертикальные aliases больше не выбирают задачу за overlay.
- Persistent `Layout.hints`/`render_hints` удалены. Workspace получил строку, status/errors не сокращены, responsive header сохраняет `? Help` на всех поддерживаемых размерах. Overlay-local footers сохранены.
- Snapshots осознанно обновлены только в help/layout-affected UI suites и просмотрены: новый wide category strip, compact 40×8 Files frame, дополнительная content row и header affordance. Inline create-prompt snapshot обновлён по тому же geometry diff. `.snap.new` не используются как принятые результаты.
- `npx --yes @fission-ai/openspec validate redesign-help-and-remove-hints --strict` — PASS. Targeted `INSTA_UPDATE=no`: **81 integration passed + 4 Help unit passed**, 0 failed; отдельный PTY close/reopen/F10 тест — **1 passed**. `cargo fmt --all` и strict `cargo clippy --workspace --all-targets --locked -- -D warnings` — PASS.
- После independent fixes footer на 62×24 выбирает compact controls по измеренной ширине без truncation, а spec matrix использует фактические renamed tests. Полный общий suite: **651 passed, 0 failed, 4 ignored**; strict Clippy/doc/fmt — PASS. Финальный independent verdict: **0 findings**; MODIFIED requirements синхронизированы, change архивирован.
## Change `debounce-preview-navigation`
- Selection movement использует quiet 40-ms scheduler с одним pending/deadline на панель и отдельным `sleep_until` в event loop. Промежуточные reads и loading-flash отсутствуют, title текущий, старый content очищен; initial/F3/background вне debounce сохраняют immediate semantics.
- Отдельный `navigation_generation` не меняется при polling. Same-target background сохраняет pending/running current request, changed selection идёт immediate, dual clone не наследует orphan state. Failed Enter/Parent/Connect и wrong-host/superseded recovery создают новую current generation через explicit `selection_recovery`, не меняя unrelated initial/background loading.
- Deterministic suite: **9 passed**, SSH recovery: **26 passed**, paused production deadline unit — PASS. Все aliases/Repeat, full-Buffer title, equal-epoch host guard и background orderings покрыты. PTY подтверждает burst/final target/restore, но raw count не считается доказательством отсутствия flash. Финальный independent verdict: **0 findings**; ADDED requirement синхронизирован, change архивирован. Общий итоговый suite: **651 passed, 0 failed, 4 ignored**.
## Change `add-image-previews`
- Реализованы bounded PNG/JPEG/GIF/BMP/WebP content-magic previews с 16 MiB/8192 axis/32M pixels/256 MiB limits и static decode. Local/fake-SSH используют read-only typed API; corrupt input получает metadata fallback.
- Fixed Kitty/iTerm2/Sixel/halfblock protocols создаются вне Frame. Один global semaphore сериализует blocking work, cancellation checkpoints отбрасывают stale results, cache содержит не более одного prepared protocol на панель и проверяет полную identity. Persistent/F3, resize, terminal epoch и cleanup покрыты runtime tests.
- Под tmux используется прямой Halfblocks constructor без любого `Picker`; disabled/NO_COLOR/ASCII/dumb/non-TTY не испускают probe. Production PTY с реальными pixels и substitute-tmux marker — PASS.
- `tests/image_preview.rs`: **11 passed**; `tests/image_runtime.rs`: **11 passed**, включая max-active=1 и отмену до blocking start; общий suite: **651 passed, 0 failed, 4 ignored**, strict Clippy/doc/fmt — PASS. Реальный Kitty GUI visual check показал red/blue pixels с сохранными borders. Isolated real-tmux server также показал halfblocks/RGB, оставил `allow-passthrough` unset и завершился чисто. iTerm2/Sixel не установлены/не проверены; structural tests не заявляются как их ручная acceptance matrix.

View file

@ -22,7 +22,7 @@ selection или picker.
| Text | `#D8E0F0` | Основной текст |
| Muted | `#71809B` | Неактивные панели и вторичные подписи |
| Active cyan | `#65D6E8` | Активная рамка, `ACTIVE`, загрузка |
| Secondary lavender | `#A89BFF` | Заголовки колонок, предупреждения, hints |
| Secondary lavender | `#A89BFF` | Заголовки колонок, предупреждения, overlay footers |
| Error coral | `#FF7A90` | Ошибки и предупреждение о малом терминале |
| Selection | `#20304A` | Фон выбранной строки |
@ -32,8 +32,9 @@ selection или picker.
## Раскладки
Основная высота всегда резервирует строку состояния. При высоте от 10 строк добавляется строка
key hints; заголовок таблицы скрывается первым при нехватке вертикального пространства внутри
Основная высота всегда резервирует только header и строку состояния; отдельной постоянной строки
key hints нет. Header на всех поддерживаемых размерах содержит `? Help`, а на узком сначала теряет
subtitle. Заголовок таблицы скрывается первым при нехватке вертикального пространства внутри
панели. Loading не меняет геометрию. Временный F3 preview не входит в расчёт persistent columns.
| Режим и ширина | Основная область |
@ -46,9 +47,10 @@ key hints; заголовок таблицы скрывается первым
| Любой режим, ширина `<40` или высота `<8` | Компактное `TERMINAL TOO SMALL`, состояние сохраняется |
Parent — вспомогательная Miller-колонка текущей иерархии, а не третья независимая панель. В current
отображаются текстовый тип (`DIR`, `FILE`, `LINK`, `OTH`), имя, размер и UTC-время изменения. В
узких dual-панелях сначала скрывается дата, затем размер; тип и имя остаются. В dual постоянный
preview не появляется ни на одной ширине.
отображаются тип, имя, размер и UTC-время изменения. При Unicode/Nerd/ASCII тип показывается иконкой
без избыточной колонки `TYPE`; в `none` текстовые `DIR`/`FILE`/`LINK`/`OTH` служат обязательным
fallback. В узких dual-панелях сначала скрывается дата, затем размер; соответствующий icon/type
fallback и имя остаются. В dual постоянный preview не появляется ни на одной ширине.
## Состояния и overlays
@ -59,7 +61,12 @@ preview не появляется ни на одной ширине.
доступной.
- **No preview:** явное объяснение отсутствия selection или содержимого.
- **Warnings:** ошибки SSH discovery показываются в HostPicker, не отменяя найденные алиасы.
- **Help (`?`/F1):** слой с одновременными yazi/mc aliases, группами Navigation, Panes, SSH и General.
- **Help (`?`/F1):** read-only слой с шестью категориями Navigation, Selection, Files, Tasks, SSH
и General, полным context-labelled inventory и одной колонкой «клавиши → действие». `h`/Left/
Shift-Tab и `l`/Right/Tab переключают категории с wrap; `j/k`, arrows и paging прокручивают
фактический help body с clamp. При переполнении strip заменяется на `< N/6 Category >`. Esc,
`q`, `?` и F1 закрывают Help, Enter инертен, F10 сохраняет quit. Названия других программ не
выводятся.
- **HostPicker (`s`):** query, case-insensitive filtered hosts, selection, warnings и отдельные empty
states; Enter подключается, Esc закрывает без смены Location.
- **Preview (F3):** временный слой поверх single или dual; расположение панелей, Location, selection

View file

@ -95,7 +95,7 @@
| Адаптивная раскладка | Слишком маленькая высота | `tests/ui_layout.rs::small_sizes_show_a_warning_instead_of_a_damaged_workspace`; snapshot `tests/ui_layout.rs::snapshot_single_compact_40x10` | — |
| Системные состояния | Длительный удалённый запрос | `tests/ui_states.rs::loading_empty_error_and_stale_warning_are_distinct_states`; `tests/workspace_panes.rs::one_pane_error_does_not_block_the_other`; `tests/runtime_effects.rs::a_new_preview_aborts_the_previous_preview_task`; `tests/ui_hardening.rs::delayed_inactive_dual_pane_shows_loading_with_stale_entries_and_ssh_connect_target` | — |
| Системные состояния | Ошибка | `tests/fs_errors.rs::every_displayable_error_has_a_safe_actionable_message`; `tests/test_support.rs::fault_injection_returns_permission_denied_and_not_found_without_fixture_paths`; snapshot `tests/ui_states.rs::snapshot_error_120x40`; PTY `tests/pty_smoke.rs::backend_error_is_visible_and_does_not_prevent_clean_quit`; `tests/ui_accessibility.rs::long_unicode_error_is_fully_scrollable_and_escape_restores_the_workspace`; `tests/ssh_backend.rs::connect_not_found_reports_missing_system_openssh` | — |
| Встроенная справка | Справка поверх любой раскладки | `tests/ui_overlays.rs::help_contains_both_keymaps_and_does_not_mutate_the_workspace`; `tests/ui_accessibility.rs::every_help_group_and_command_is_reachable_at_the_minimum_sizes`; snapshots 120×40 и 40×8 | — |
| Встроенная справка | Справка поверх любой раскладки | `tests/ui_overlays.rs::help_categories_are_neutral_single_column_and_do_not_mutate_the_workspace`; `tests/ui_accessibility.rs::every_help_category_alias_and_context_is_reachable_at_wide_and_minimum_sizes`; snapshots 120×40 и 40×8 | — |
| Безопасное владение терминалом | Выход из приложения | `tests/pty_smoke.rs::quit_restores_terminal_and_returns_success`; `tests/pty_smoke.rs::backend_error_is_visible_and_does_not_prevent_clean_quit`; `tests/pty_smoke.rs::fatal_initial_path_error_returns_nonzero_without_alternate_screen_leak` | — |
## Проверка самой инфраструктуры
@ -221,3 +221,71 @@
| file-navigation | Current preview response атомарен, stale инертен, error recovery сохраняет старый кадр до ответа | `tests/app_preview.rs::background_preview_responses_are_current_only_and_recover_atomically` |
| file-navigation | Быстрая смена выбора отбрасывает stale preview response | `tests/app_preview.rs::stale_preview_response_is_not_applied` |
| file-navigation | F3 сохраняет foreground LOADING PREVIEW и не меняет расположение/selection | `tests/ui_overlays.rs::f3_and_esc_keep_locations_selections_and_dual_mode_intact` |
## Change: add-file-type-icons-and-colors
| Capability | Scenario / contract | Текущие тесты |
|---|---|---|
| terminal-ui | Per-type icons, known names/extensions, generic fallback и semantic filename classes | `tests/icon_resolver.rs::resolver_distinguishes_known_types_without_any_io`, `semantic_filename_classes_cover_media_documents_archives_and_special_files` |
| terminal-ui | Glob/directory/file/extension/metadata precedence, case policy, directory gating и determinism | `tests/icon_resolver.rs::resolver_distinguishes_known_types_without_any_io`, `resolution_is_deterministic_and_never_uses_host_state`; `src/ui/icons.rs::tests::built_in_exact_catalogs_have_no_duplicate_keys` |
| terminal-ui | Canonical Night Ops glyph/icon/name/markers и selected+marked full-Buffer composition | `tests/file_type_rendering.rs::canonical_night_ops_fixture_separates_icons_names_and_selected_marked_state` |
| terminal-ui | Copy/cut `+`/`-` (combined `±`/`∓`, ASCII `C`/`X`) и executable `*` независимы от icon mode и совместимы с current+marked | `tests/file_type_rendering.rs::copy_cut_and_executable_markers_survive_every_icon_mode` |
| terminal-ui | Preview/F3 title содержит selected icon; icons-off сохраняет текст | `tests/file_type_rendering.rs::preview_title_uses_the_selected_icon_and_also_works_in_icons_off` |
| terminal-ui | Config-папки получают gear icon без потери directory class | `tests/icon_resolver.rs::resolver_distinguishes_known_types_without_any_io` |
| terminal-ui | Unicode/Nerd/ASCII/none, NO_COLOR, текстовые типы и отсутствие PUA вне Nerd | `tests/file_type_rendering.rs::all_icon_modes_preserve_selection_and_fallbacks_without_redundant_type_text` |
| terminal-ui | Icon-aware filename truncation и responsive sizes/breakpoints | `tests/file_type_rendering.rs::filename_extension_survives_icon_aware_truncation`, `icon_width_does_not_change_breakpoints_or_overflow_supported_frames`; `src/ui/text.rs::tests::filename_truncation_preserves_extension_and_display_width` |
| terminal-ui | Persistent icon config, CLI override, malformed startup error до alternate screen | `tests/appearance_config.rs::missing_config_uses_unicode_and_cli_overrides_without_a_write`, `every_documented_mode_is_parsed_and_unknown_fields_are_forward_compatible`, `cli_accepts_exactly_the_four_documented_icon_values`, `config_parse_error_happens_before_alternate_screen_or_host_access` |
| terminal-ui | Существующие selected/dual/NO_COLOR/ASCII regressions сохраняются | `tests/ui_states.rs::no_color_preserves_text_geometry_and_uses_reversed_selection`, `ascii_fallback_replaces_structural_unicode_but_keeps_names`, `multi_selection_has_a_star_separate_from_cursor_and_a_status_count`; `tests/ui_layout.rs` snapshots |
## Change: add-color-theme-presets
| Capability | Scenario / contract | Текущие тесты |
|---|---|---|
| terminal-ui | Ровно 20 stable IDs/display names, 11 dark/9 light, native unchanged Night Ops | `tests/theme_catalog.rs::catalog_has_exact_stable_ids_display_name_order_and_mode_counts`, `night_ops_default_keeps_base_palette_and_pins_accessibility_corrections` |
| terminal-ui | Pinned kitty sources/SHA-256/upstream и полные license notices, включая Apache-2.0 Tokyo Night | `tests/theme_catalog.rs::manifest_pins_every_import_and_retains_complete_license_provenance`, `third_party_notices_cover_every_manifest_entry_and_apache_tokyo_night`; `tools/test_import_themes.py` |
| terminal-ui | Derived semantic/file/selection contrast на фактических RGB surfaces и rich/monochrome structural selection | `tests/theme_catalog.rs::every_derived_semantic_unselected_file_and_selected_text_color_meets_contrast`, `every_derived_selection_boundary_has_three_to_one_contrast_with_background_and_panel`, `night_ops_selection_keeps_structural_rich_and_monochrome_contracts` |
| terminal-ui | Persistent/CLI selection, offline `--list-themes`, unknown IDs до alternate screen | `tests/appearance_config.rs::every_documented_mode_is_parsed_and_unknown_fields_are_forward_compatible`, `list_themes_is_offline_and_unknown_config_lists_ids_before_terminal_setup` |
| terminal-ui | Live picker clamp/Repeat/Press-only и reachability 20 тем на 40×8/80×24/120×40 | `tests/theme_picker.rs::picker_input_is_press_safe_repeatable_and_does_not_leak_workspace_commands`, `all_twenty_themes_are_reachable_in_small_monochrome_and_ascii_frames` |
| terminal-ui | Baseline rollback, visible failure без retry, atomic save только theme с fingerprint/unknown fields | `tests/theme_picker.rs::picker_navigation_is_clamped_live_and_escape_restores_the_exact_baseline`, `failed_save_restores_baseline_and_keeps_a_visible_error_without_retry`, `theme_save_is_atomic_preserves_other_fields_and_detects_external_changes`, `save_fault_does_not_replace_the_config_or_leave_temporary_siblings` |
| terminal-ui | Real PTY Esc/F10 без save и Enter сохраняет только выбор с terminal restore | `tests/pty_smoke.rs::theme_picker_escape_rolls_back_and_f10_quits_without_saving`, `theme_picker_enter_persists_only_the_selected_theme_and_restores_terminal` |
## Change: debounce-preview-navigation
| Capability | Scenario / contract | Текущие тесты |
|---|---|---|
| file-navigation | 39/40 ms, quiet current title, нет stale content/intermediate reads, один current request | `tests/preview_debounce.rs::rapid_selection_has_no_intermediate_read_or_loading_and_starts_once_at_40ms`; `src/tui.rs::tests::preview_deadline_wakes_at_40ms_independently_of_redraw_ticks` |
| file-navigation | Все selection aliases/Repeat используют bounded scheduler | `tests/preview_debounce.rs::every_selection_alias_and_repeat_coalesces_to_one_read` |
| file-navigation | Generation/target/navigation/SessionEpoch/host guards, включая равные epochs на разных hosts | `tests/preview_debounce.rs::start_preview_rejects_wrong_generation_target_navigation_and_host_at_equal_epoch`; `tests/app_preview.rs::stale_preview_response_is_not_applied` |
| file-navigation | Initial/F3 immediate, background same-target completion/running/changed selection до/после deadline | `tests/preview_debounce.rs::initial_f3_and_pure_selection_effects_keep_their_distinct_modes`, `same_target_background_completion_preserves_pending_and_running_preview`, `background_changed_selection_uses_immediate_current_preview` |
| file-navigation | Dual clone без orphan, source pending сохраняется | `tests/preview_debounce.rs::dual_clone_does_not_inherit_orphan_debounce_and_source_deadline_survives` |
| file-navigation | Failed Enter/Parent/Connect до/после deadline и wrong-host/superseded recovery с новой generation | `tests/preview_debounce.rs::failed_navigation_and_connect_create_immediate_replacement_not_stale_pending`; `tests/ssh_connection.rs::wrong_host_and_superseded_connect_recover_an_invalidated_selection_preview` |
| file-navigation | PTY byte burst, итоговый current target и terminal restore | `tests/pty_smoke.rs::rapid_selection_burst_coalesces_preview_and_restores_terminal` |
## Change: add-image-previews
| Capability | Scenario / contract | Текущие тесты |
|---|---|---|
| file-navigation | Content magic PNG/JPEG/GIF/BMP/WebP, bounded Local/fake-SSH reads и corrupt fallback | `tests/image_preview.rs::content_magic_recognizes_exactly_the_five_enabled_formats`, `corrupt_truncated_and_oversized_inputs_fail_before_rendering`, `bounded_image_read_distinguishes_exact_cap_and_one_lookahead_byte`; `tests/image_runtime.rs::fake_ssh_image_uses_the_same_bounded_read_path_without_a_shell`, `corrupt_current_image_becomes_visible_metadata_instead_of_preparing_forever` |
| file-navigation | Checked geometry/static aspect-fit и реальные halfblock pixels | `tests/image_preview.rs::checked_geometry_rejects_zero_overflow_axis_and_pixel_budget`, `aspect_fit_never_upscales_or_panics_on_wide_tall_tiny_and_zero_areas`, `animated_gif_decodes_to_one_static_first_frame`, `halfblocks_render_real_known_pixels_without_a_picker_or_terminal_probe` |
| file-navigation | Disabled/tmux no-probe, bounded identity cache, native structural protocols | `tests/image_preview.rs::disabled_and_tmux_gates_never_invoke_a_picker_or_probe`, `prepared_cache_is_bounded_and_rejects_stale_identity_and_terminal_epochs`, `native_protocol_factories_produce_bounded_structural_protocols_without_wire_snapshots` |
| file-navigation | Persistent/F3 prepared pixels, resize/editor epoch/text cleanup | `tests/image_runtime.rs::local_image_preview_prepares_and_renders_real_pixels_in_persistent_and_f3`, `resize_editor_epoch_and_text_selection_invalidate_prepared_pixels` |
| file-navigation | Один global blocking worker и отмена до blocking start | `tests/image_runtime.rs::global_image_worker_has_max_active_one_across_panes`, `image_job_cancelled_before_blocking_start_never_decodes_or_publishes` |
| file-navigation | Accepted image generation для background bytes и stale Err до reducer | `tests/image_runtime.rs::background_image_refresh_prepares_accepted_new_bytes_instead_of_old_generation`, `stale_image_errors_after_resize_and_resume_never_replace_current_content` |
| file-navigation | Disabled fallback без большого second read | `tests/image_runtime.rs::disabled_images_have_explicit_fallback_and_no_large_second_read` |
| file-navigation | Production PTY halfblocks и отсутствие substitute-tmux вызова | `tests/pty_smoke.rs::image_halfblocks_render_in_pty_without_calling_substitute_tmux` |
| file-navigation | Config images и --no-images | `tests/appearance_config.rs::missing_config_uses_unicode_and_cli_overrides_without_a_write`, `every_documented_mode_is_parsed_and_unknown_fields_are_forward_compatible` |
## Change: redesign-help-and-remove-hints
| Requirement | Scenario / contract | Текущие тесты |
|---|---|---|
| Адаптивная раскладка | Persistent hints отсутствуют, освобождённая строка принадлежит workspace, `? Help` и status сохраняются | `tests/ui_layout.rs::hints_row_is_gone_and_help_affordance_never_consumes_status_or_workspace`; `tests/ui_hardening.rs::page_and_half_page_steps_come_from_the_active_panes_visible_rows`; layout/operation/entry snapshots |
| Встроенная справка | Шесть категорий, читаемый read-only слой и изоляция workspace | `tests/ui_overlays.rs::help_categories_are_neutral_single_column_and_do_not_mutate_the_workspace`; `tests/ui_accessibility.rs::help_close_aliases_and_f10_keep_workspace_state` |
| Встроенная справка | Полный независимый input inventory, исходный регистр, Theme Picker `T`, collision и confirmation contexts, без внешних брендов | `tests/help_inventory.rs::independently_enumerated_input_contexts_match_every_inventory_action_and_alias`, `context_specific_bindings_execute_only_their_documented_handler`; `src/app/help.rs::tests::help_inventory_is_neutral_and_preserves_case_and_destructive_warning` |
| Встроенная справка | Category aliases, wrap/reset и Press/Repeat policy | `tests/ui_accessibility.rs::help_category_aliases_wrap_reset_scroll_and_preserve_the_workspace`; `tests/input_commands.rs::help_repeat_policy_separates_navigation_from_press_only_controls` |
| Встроенная справка | Все vertical aliases используют фактический body, clamp и отсутствие raw-offset accumulation | `tests/input_commands.rs::help_overlay_handles_categories_close_quit_and_body_scrolling_aliases`; `tests/ui_accessibility.rs::every_help_category_alias_and_context_is_reachable_at_wide_and_minimum_sizes` |
| Встроенная справка | Resize first/middle/last/raw offsets нормализуются без render-order dependency | `tests/ui_accessibility.rs::help_scroll_is_normalized_on_resize_without_render_order_dependency` |
| Встроенная справка | Compact `< N/6 Category >`, hanging wrap, reachability всех 111 actions и close controls на 40×8 | `tests/ui_accessibility.rs::every_help_category_alias_and_context_is_reachable_at_wide_and_minimum_sizes`; snapshot `snapshot_help_scrolled_40x8` |
| Встроенная справка | Esc/`q`/`?`/F1 close, inert Enter, Press-only F10 quit и PTY close/reopen/lifecycle | `tests/ui_accessibility.rs::help_close_aliases_and_f10_keep_workspace_state`; `tests/input_commands.rs::help_repeat_policy_separates_navigation_from_press_only_controls`; `tests/pty_smoke.rs::help_close_reopen_aliases_preserve_terminal_lifecycle` |
| Встроенная справка | Task Details vertical aliases прокручивают details на Press/Repeat без смены selected task | `tests/operation_ui.rs::task_details_vertical_aliases_scroll_without_selecting_behind_overlay` |
| Встроенная справка | NO_COLOR/ASCII сохраняют non-color category marker, range и отсутствие специального шрифта | `tests/ui_accessibility.rs::help_monochrome_ascii_retains_non_color_category_and_reachability`; `tests/ui_states.rs::no_color_preserves_text_geometry_and_uses_reversed_selection` |

View file

@ -64,11 +64,38 @@ cargo test --test ssh_action_acceptance --locked -- --ignored --nocapture
- `tests/live_refresh_ui.rs` сравнивает полный `ratatui::Buffer`, включая стили: background dual poll не меняет правую рамку и активную строку entries, сохраняет `EMPTY DIRECTORY` и существующую ошибку. Отдельный changed-listing test проверяет обновление entries/count без промежуточного `LOADING`.
- `tests/live_refresh.rs` дополнительно проверяет background/foreground transitions, сброс режима только на current terminal response, stale-response inertness и recovery. Существующий `tests/ui_hardening.rs::delayed_inactive_dual_pane_shows_loading_with_stale_entries_and_ssh_connect_target` остаётся контролем видимой навигационной загрузки.
- Preview background tests в `tests/live_refresh_ui.rs` сравнивают полный Buffer для неизменного текста и ошибки; changed response применяется атомарно, а смена/исчезновение selection не оставляет старый preview. `tests/app_preview.rs` проверяет same-target/completed-result eligibility, foreground F3/selection, generations, stale response и error recovery.
- `tests/preview_debounce.rs` использует explicit clock без sleeps: 39/40 ms, quiet full-Buffer/current title, отсутствие intermediate reads, один current request, все selection aliases/Repeat, initial/F3/background semantics, background completion/running/changed selection до и после deadline, dual source pending, failed navigation/connect и wrong generation/target/navigation/host при равных numeric epochs. `src/tui.rs::tests::preview_deadline_wakes_at_40ms_independently_of_redraw_ticks` использует paused Tokio clock для production `sleep_until` helper.
- PTY `rapid_selection_burst_coalesces_preview_and_restores_terminal` подтверждает byte-level burst, итоговый target и terminal restore. Отсутствие промежуточных reads/loading доказывается детерминированными tests, а не одним подсчётом строки в diffed terminal output. `tests/ssh_connection.rs` дополнительно покрывает failed/wrong-host/superseded recovery с новой generation.
### Appearance config и icons
- `tests/icon_resolver.rs` проверяет classification без filesystem/network I/O, precedence/case/type gating, metadata fallback, semantic classes и synthetic large listing. Glyph catalog attribution находится в `THIRD_PARTY_NOTICES.md`.
- `tests/appearance_config.rs` использует только owned `TempDir`: missing/default, все `icons` modes, malformed config, CLI precedence и startup error до alternate screen. `RCOM_CONFIG_HOME` передаётся только дочернему test process; глобальные env в parallel tests не изменяются.
- Для visual checks обязательны full `Buffer` styles, 40×8/80×24/120×40/160×40, dual 71/72, NO_COLOR и ASCII/icons-off. Nerd Font capability не выводится из `$TERM`.
### Цветовые темы и Theme Picker
- `tests/theme_catalog.rs` проверяет точные 20 IDs, 11 dark/9 light, display-name order, базовые Night Ops RGB и отдельно зафиксированные accessibility corrections, pinned kitty commit/SHA-256, полные license notices и measured contrast всех 20 тем. Source и semantic RGB разделены; runtime network/subprocess отсутствуют.
- `tests/theme_picker.rs` проверяет live preview, clamp/Repeat, Press-only Enter/Esc/F10, достижимость всех тем на 40×8/80×24/120×40, baseline rollback, видимую ошибку и отсутствие automatic retry. `ThemeConfigStore` тестируется на owned `TempDir`: атомарный sibling+rename, сохранение `icons`/неизвестных полей, external-content fingerprint и write faults.
- `tests/appearance_config.rs` дополнительно проверяет `--theme`, `--list-themes`, persistent/temporary precedence и unknown ID до alternate screen. Полный visual review светлых/тёмных тем не заменяется расчётом RGB contrast.
### Категорийная Help и удаление hints
- `tests/help_inventory.rs::independently_enumerated_input_contexts_match_every_inventory_action_and_alias` содержит независимый fixture всех input contexts, stable action IDs и aliases, включая Theme Picker, collision `s/S/o/O`, confirmations/prompts и quit `c/x`. `context_specific_bindings_execute_only_their_documented_handler` дополнительно сверяет реальный dispatch критичных context-specific aliases.
- `tests/ui_accessibility.rs` проверяет category wrap/reset, Press/Repeat policy, close/isolation, фактический body page size, clamp после resize и без render-order dependency. Reachability собирает каждый rendered row из TestBackend на 40×8, 40×10, 80×24 и 120×40 и сверяет каждый action с inventory; NO_COLOR/ASCII сохраняют `< N/6 Category >` и текстовый range.
- `tests/operation_ui.rs::task_details_vertical_aliases_scroll_without_selecting_behind_overlay` перебирает `j/k`, Up/Down, PageUp/PageDown и Ctrl aliases на Press/Repeat, доказывая неизменный selected task. `tests/pty_smoke.rs::help_close_reopen_aliases_preserve_terminal_lifecycle` проверяет Esc/`q`/`?`/F1, reopen, F10 и восстановление terminal.
- `tests/ui_layout.rs::hints_row_is_gone_and_help_affordance_never_consumes_status_or_workspace` закрепляет отсутствие persistent hints, дополнительную workspace row, status и `? Help` на узких/широких кадрах. Snapshots обновляются только в affected UI suites с последующим `INSTA_UPDATE=no` контролем.
### Image preview
- `tests/image_preview.rs` генерирует PNG/JPEG/GIF/BMP/WebP в памяти и проверяет content magic, corrupt/truncated/exact cap/cap+1, checked dimensions/allocations, static aspect-fit, no-probe disabled/tmux gates, bounded cache и реальные halfblock RGB на TestBackend. Kitty/iTerm2/Sixel имеют только structural shape checks без wire snapshots.
- `tests/image_runtime.rs` проходит Local и fake-SSH read path, accepted current identity, persistent/F3 pixels, resize/terminal epoch invalidation и cleanup. `global_image_worker_has_max_active_one_across_panes` подтверждает max-active=1 через metrics; `image_job_cancelled_before_blocking_start_never_decodes_or_publishes` использует zero-permit gate и Preview→Help boundary. `rapid_image_selection_uses_shared_debounce_before_preparation` доказывает отсутствие intermediate preparation до общего 40-ms deadline. `background_image_refresh_prepares_accepted_new_bytes_instead_of_old_generation` разделяет request/accepted generations; `stale_image_errors_after_resize_and_resume_never_replace_current_content` проверяет stale Err до reducer; `disabled_images_have_explicit_fallback_and_no_large_second_read` подтверждает один 64-KiB read и понятный fallback. Corrupt current image показывает metadata error вместо вечного preparing.
- PTY `image_halfblocks_render_in_pty_without_calling_substitute_tmux` запускает production process без NO_COLOR и с substitute `tmux`: pixels видны, marker вызова отсутствует, terminal восстанавливается. Это не заменяет ручную Kitty/iTerm2/Sixel/real-tmux matrix и не является универсальным protocol claim.
## Политика snapshots
- В обычных проверках и в CI всегда используется `INSTA_UPDATE=no`: тесты только сравнивают результат с сохранёнными snapshots и никогда не обновляют их автоматически.
- Snapshots должны быть детерминированными: фиксируйте размеры терминала из design (120×40, 80×24 и 40×10), а также состояние, время и оформление, влияющие на вывод. В них не должно быть абсолютных или временных путей, секретов и данных реальных SSH-хостов.
- Изменяйте snapshots только осознанно, вместе с предполагаемым изменением поведения. Для локального обновления явно выполните `INSTA_UPDATE=always PROPTEST_CASES=256 cargo test --workspace --all-targets --locked`; эту команду нельзя использовать для маскировки неожиданного падения тестов.
- Snapshots должны быть детерминированными: фиксируйте размеры терминала из design (120×40, 80×24, 40×10 и 40×8), а также состояние, время и оформление, влияющие на вывод. В них не должно быть абсолютных или временных путей, секретов и данных реальных SSH-хостов.
- Изменяйте snapshots только осознанно, вместе с предполагаемым изменением поведения. Для локального обновления явно выполните `INSTA_UPDATE=always cargo test --locked --test <affected_ui_suite>` только для затронутых suites; эту команду нельзя использовать для маскировки неожиданного падения тестов.
- Перед коммитом изучите каждый изменённый snapshot через `git diff` и сверьте его с соответствующим Requirement/Scenario. Не принимайте изменения массово без просмотра; новые и изменённые snapshots проходят code review вместе с кодом и тестами.
- Не коммитьте временные `.snap.new` и другие неподтверждённые результаты. Если изменение вывода не ожидалось, исправьте причину расхождения, а не эталон.

35
docs/themes.md Normal file
View file

@ -0,0 +1,35 @@
# Встроенные цветовые темы
## Runtime contract
`rcom --list-themes` печатает 20 тем в display-name order: `ID`, имя и `dark`/`light`. Настройка `theme = "night-ops"` находится в общем `config.toml` рядом с `icons`; `--theme <id>` действует только на текущий процесс. Night Ops является native default: базовые background/panel/text/accents/file-type RGB сохранены, а muted/selection/selection_text минимально скорректированы до общих accessibility targets.
Theme Picker открывается по `T`. Навигация `j/k`/`Up`/`Down` меняет live preview без записи; `Enter` сохраняет выбор, `Esc` откатывает baseline. Запись выполняется через owned temporary sibling и rename, только после сравнения exact-content fingerprint. Другие TOML-поля сохраняются. External change, write или rename error оставляют picker открытым с видимой ошибкой и не запускают automatic retry.
Runtime использует только сгенерированные static Rust values. Он не обращается к сети, не запускает kitty или subprocess и не исполняет конфигурацию тем. `NO_COLOR`, ASCII и icons-off применяются после выбора темы и не меняют сохранённый ID.
## Audited import
Development-only importer: `tools/import_themes.py`. Он принимает локальный checkout `kovidgoyal/kitty-themes`, закреплённый на `a35d12290c3d6a74b1f94debc81281cb637f3568`, и отдельный cache полных upstream license files. Allowlist содержит ровно 19 файлов; manifest хранит source path, SHA-256, author, upstream и license commit. `none`, `system` и `background` означают отсутствие optional RGB, а не специальный runtime цвет.
Повторный импорт из неизменных fixtures даёт идентичные `src/ui/themes_data.rs`, `themes/manifest.json` и notices. Изменение pin требует нового review источников, hashes, лицензий, semantic derivation и visual acceptance. Обычный `cargo build` importer не запускает.
Офлайн parser/repeatability checks:
```bash
python3 tools/test_import_themes.py
```
Для явного регенеративного обновления (не нужен при обычной разработке):
```bash
python3 tools/import_themes.py /path/to/pinned/kitty-themes /path/to/license-cache --output .
```
## Semantic derivation и границы проверки
Manifest и `ThemeSeed` сохраняют исходные background/foreground/ANSI/selection values. Rust отдельно вычисляет panel, muted, active, secondary, error, selection pair и file-type roles. Imported темы проходят измеримые targets 4.5:1 для текста/file colors и 3:1 для selection boundary на фактически используемых RGB surfaces. Selected row использует отдельную проверенную `selection_text`/`selection` пару и BOLD; monochrome сохраняет REVERSED.
Это внутренние RGB targets, а не гарантия контраста произвольной terminal palette. Night Ops не подвергается general derivation: её базовые RGB являются compatibility contract, а три accessibility corrections зафиксированы отдельными тестами. Полный набор semantic roles и file-type mappings проверяется в `tests/theme_catalog.rs`; responsive picker — в `tests/theme_picker.rs`; real terminal save/rollback — в `tests/pty_smoke.rs`.
Полные upstream notices находятся в `LICENSES/themes/`; краткая таблица и ссылки — в `THIRD_PARTY_NOTICES.md`. Tokyo Night сохраняет фактическую upstream Apache-2.0, отдельно от MIT metadata исходного kitty файла.

View file

@ -0,0 +1,165 @@
# TUI design guidelines `rcom`
Этот документ — общий рабочий стандарт для дизайнера, разработчика и независимого тестировщика. OpenSpec requirements определяют наблюдаемое поведение; guideline помогает спроектировать и проверить его согласованно. При расхождении сначала обновляется proposal/spec через новый change, затем implementation и этот guideline.
## 1. Принципы
1. **Содержимое важнее декорации.** Имя, тип, расположение, выбор и ошибка читаются раньше иконок, цветов и вспомогательных подписей.
2. **Интерфейс полностью управляется клавиатурой.** У каждого действия есть видимая команда, а focus и активная панель очевидны без мыши.
3. **Состояние не кодируется только цветом.** Маркер, форма, текст, рамка или reverse/background дублируют смысл цвета.
4. **Кадр стабилен.** Фоновые запросы не должны периодически заменять содержимое на loading; новый результат применяется атомарно. Пользовательский selection preview коалесцируется за 40 ms через один deadline на панель: промежуточные selections не запускают reads, очищают старый content и показывают quiet blank с текущим title; initial/F3/background вне active debounce остаются immediate.
5. **Маленький терминал — полноценный сценарий.** Деградация является запланированной, а не побочным эффектом обрезания.
6. **Никаких внешних брендов в пользовательской помощи.** Внутри справки команды группируются по действию; названия yazi, mc, ranger и других программ не нужны.
## 2. Визуальная иерархия
Порядок внимания:
1. Опасная ошибка или подтверждение destructive action.
2. Активная панель и текущий выбор.
3. Имя элемента и основной рабочий контент.
4. Путь, source и итоги операции.
5. Metadata, вторичные подписи и декоративные icons.
Цвет усиливает этот порядок, но не заменяет его. Неактивные области могут быть приглушены, однако текст остаётся читаемым, а file-type distinctions не должны без необходимости исчезать.
### Базовые semantic roles
- `background`, `panel`, `text`, `muted`;
- `active`, `secondary`, `error`, `selection`;
- directory, regular file, executable, valid/broken link;
- image, audio/video, document, archive, special inode;
- marked, copied, cut, current и inactive состояния.
Новый UI использует semantic role, а не разбросанные hard-coded RGB значения.
## 3. Icons и file-type colors
### Разделение ответственности
Отдельно определяются:
- glyph иконки;
- цвет иконки;
- стиль имени;
- state marker и стиль строки.
Это позволяет, например, показать синюю папку и синее имя каталога, отдельную Rust-иконку приглушённого оранжевого цвета и при этом сохранить читаемое имя `.rs`. Цвет иконки не должен автоматически перекрашивать имя.
### Классификация
- Правила точного имени и расширения детерминированы и документируют case sensitivity.
- Специальные имена вроде `Cargo.toml`, `README.md` и `.gitignore` могут иметь собственные правила до generic extension.
- Unknown file получает generic file/folder fallback.
- Link, executable и special inode сохраняют текстовый/символьный marker даже при rich icon. Broken-link styling требует отдельного typed `LinkStatus` change: нельзя угадывать broken по отсутствию `link_target` или делать скрытый дополнительный I/O.
- Glob/MIME правила добавляются только с явным приоритетом, bounded стоимостью и тестами.
### Цветовая сдержанность
Рекомендуемый старт:
- directories — blue/cyan;
- executables — green;
- valid links — cyan с `@`; broken links получат red/magenta плюс `!` только после typed LinkStatus change;
- images — yellow, audio/video — magenta;
- archives — red, documents — cyan или neutral;
- Rust — отдельный glyph с rust/orange accent.
Богатые per-extension оттенки преимущественно принадлежат иконкам. Радуга разных цветов имён ухудшает сканирование списка.
Канонический visual fixture должен содержать каталог, `Cargo.toml`, `main.rs`, executable, symlink и selected+marked row. Для него отдельно фиксируются glyph, icon/name colors и state markers, а также Unicode/ASCII/none variants; один и тот же fixture используется для full-Buffer test и пользовательского visual review.
### Font fallback
Поддерживаются явные режимы rich Nerd Font, plain Unicode/ASCII и icons-off. Нельзя утверждать, что `$TERM` доказывает наличие Nerd Font. При включённых иконках колонка `TYPE` не дублирует glyph; при `none` критические типы и состояния остаются различимыми текстовыми `DIR`/`FILE`/`LINK`/`OTH`.
Selection не должен оставлять произвольный icon foreground на фоне с плохой контрастностью: либо glyph получает проверенный selection color, либо строка использует согласованный foreground и сохраняет type/state другим способом.
## 4. Layout и узкие терминалы
Существующие breakpoints являются исходным контрактом:
- Single `≥150`: parent/current/preview;
- Single `100–149`: current/preview;
- Single `<100`: только current;
- Dual `≥72`: две равные панели без persistent preview;
- Dual `<72`: только активная панель с явным номером;
- Ширина `<40` или высота `<8`: компактное предупреждение без повреждённого интерфейса.
При нехватке места сначала исчезают вторичные metadata и symlink target, затем сокращаются колонки. Icon + basename сохраняются как можно дольше; при middle truncation желательно сохранить расширение. Геометрия не должна меняться при loading.
Постоянная нижняя строка key hints не нужна. Освобождённое место принадлежит содержимому. Discoverability обеспечивается документированными `?` и `F1`, а не постоянным списком сокращений.
## 5. Help и overlays
Help — спокойный читаемый слой, а не перегруженная таблица всех команд одновременно.
- Категории организуют команды по задачам: Navigation, Selection, Files, Tasks, SSH, General.
- Локальные category tabs допустимы и предпочтительны для группировки; они не связаны с будущими workspace tabs.
- Активная категория обозначается текстом/рамкой/маркером, не только цветом.
- Одна строка описывает одно действие и перечисляет aliases без ссылок на другие файловые менеджеры.
- Tab/Shift-Tab или Left/Right переключают категорию; `j/k` и paging прокручивают содержимое; Esc/`q`/`?`/F1 закрывают согласно итоговой spec.
- На узком терминале tab bar может прокручиваться либо показывать компактные названия, но активная категория и способ переключения остаются видимыми.
- Все команды остаются доступны в соответствующей категории. Нельзя удалить команду из help только потому, что она не поместилась в текущий viewport.
- Inventory явно различает Workspace, HostPicker, ThemePicker, Tasks/Task Details, Preview, Help, Destination/Confirmation/Collision, Entry Prompt/Confirmation, Undo/Editor, Error Details и Quit Confirmation. F10 документируется как глобальный quit до отдельного quit-confirmation контекста; в самом подтверждении доступны только Esc/Enter/`c`/`x`.
- Подтверждения и ошибки важнее декоративной симметрии; destructive consequences видны до клавиши подтверждения.
## 6. Темы
Цветовые темы изменяют semantic roles, а не структуру интерфейса. Запланированный change `add-color-theme-presets` включает 20 тем: native Night Ops и 19 curated imports из kitty — 11 dark и 9 light. Catalog охватывает Dracula, Catppuccin, Gruvbox, Solarized, Tokyo Night, One Half, Rosé Pine, Everforest, GitHub и Flexoki; точные IDs и provenance находятся в его design/spec.
Для каждой темы проверяются:
- обычный и выбранный текст;
- активная и неактивная панели;
- errors/warnings;
- file-type icons и filename classes;
- marked/cut/copy/current состояния;
- help, dialogs, tasks и previews.
`NO_COLOR`, ASCII fallback и icons-off имеют приоритет над декоративной темой. Названия и RGB значения встроенных тем фиксируются в implementation tests; нельзя заявлять универсальный WCAG контраст для пользовательской terminal palette без отдельного измерения.
Theme Picker открывается по `T` и использует live preview: `j/k`/Up/Down сразу применяют выбранную палитру ко всему UI в display-name order с clamp, Enter атомарно сохраняет только theme ID, а Esc восстанавливает тему при открытии без записи. F10 использует существующий quit path без save. Preview и persistent save разделены; write error не создаёт automatic retry или скрытый постоянный выбор.
Picker показывает selected marker, name/mode и `N/20`, сохраняет выбранную строку в viewport и содержит отдельные Enter/Esc controls и error область. Все 20 тем должны быть достижимы на 40×8, 80×24 и 120×40 в NO_COLOR/ASCII без truncated critical actions. Picker входит в полный help inventory как собственный context, а Help redesign применяется после появления picker.
## 7. Image preview
- PNG/JPEG/GIF/BMP/WebP используют content magic и static decode; encoded 16 MiB, 8192 axis, 32M pixels и 256 MiB max_alloc являются bounded budgets, а не sandbox-гарантией.
- Реальные pixels обязательны в persistent preview и F3. Halfblocks используют `▀`/`▄` и RGB; Kitty/iTerm2/Sixel требуют отдельной real-terminal matrix, headless structural tests не доказывают нативную поддержку.
- Один global serialized blocking worker не пишет stdout. Prepared protocol живёт вне Clone/Eq AppState и совпадает с `(pane,generation,target,epoch,geometry,font,protocol,terminal epoch)`; stale/oversized image заменяется безопасным placeholder.
- Resize/image→text/no-selection/overlay/editor resume инвалидируют старые pixels. Под tmux halfblocks создаются напрямую без любого `Picker` constructor и без `allow-passthrough` mutation. Disabled/NO_COLOR/ASCII/dumb/non-TTY не отправляют probe.
- Быстрые image selections используют общий 40-ms scheduler, поэтому промежуточные строки не создают decode/encode workers. Icons-off не отключает pixels.
## 8. Текст и безопасность
- Имена и пути sanitize перед выводом; control, ESC и опасные bidi characters не меняют терминал.
- Обрезание учитывает display width и не разрывает UTF-8.
- Nerd Font private-use glyph не считается гарантированно одноcell/одинаковой ширины на всех терминалах.
- `dim`, blink и цвет не являются единственным носителем смысла.
- Содержимое preview не исполняется; bounded чтение и truncation markers сохраняются.
## 9. Работа дизайнера и тестировщика
### Дизайнер
1. Читает соответствующие OpenSpec requirements и этот guideline.
2. Изучает существующий layout и пользовательский screenshot.
3. Формулирует один согласованный visual/interaction contract вместо несвязанных декоративных решений.
4. Записывает scenarios для normal, selected, error, empty, loading, narrow, monochrome и fallback режимов.
5. Передаёт тестировщику named tests и явно перечисляет непроверенные ограничения.
### Тестировщик
Проверяет независимо и без смягчения требований:
- полный `Buffer`, включая символы и стили, когда важна стабильность кадра;
- snapshots только с осознанным обновлением;
- минимум 40×8, 80×24, 120×40 и подходящий wide dual/single размер;
- `NO_COLOR`, ASCII и icons-off;
- keyboard-only flow, wrap/clamp и сохранение состояния;
- отсутствие overlap, truncated critical actions и брендовых названий в help;
- PTY terminal lifecycle для интерактивного поведения;
- `.snap.new` отсутствуют, а все findings имеют file/line и конкретную рекомендацию.
Субъективная красота оценивается по целостности, иерархии, плотности и читаемости; формальные PASS не заменяют просмотр пользователем.

View file

@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-06

View file

@ -0,0 +1,114 @@
# Design
## Context
См. `proposal.md`, ADDED `file-navigation` и `research_notes/Иконки и помощь rcom/image_previews.md`. Yazi показывает ценность cancellation, geometry identity и terminal reinitialization, но его adapter несовместим с Rust 1.88 и рассчитан на path-based global state. RCOM должен декодировать bytes из Local/SFTP и хранить prepared protocol вне `Clone/Eq` reducer state.
## Goals / Non-Goals
**Goals:**
- Реальные pixels в persistent preview и F3 через одну pipeline.
- Безопасные bounded resources и отсутствие stale terminal writes.
- Предсказуемый universal fallback и проверяемые headless pixels.
**Non-Goals:**
- Своя реализация Kitty/iTerm2/Sixel wire protocols или Yazi adapter port.
- Animation, SVG/AVIF/HEIF/JXL, PDF/video, external converters, Überzug++ и disk thumbnails.
- Сильная sandbox от malicious codec input; при необходимости это требует отдельного constrained helper process.
- Автоматическое изменение tmux или утверждение нативной поддержки только по headless tests.
## Decisions
### 1. Dependencies и форматы
Используются:
```toml
ratatui-image = { version = "12.0.0", default-features = false, features = ["crossterm"] }
image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "gif", "bmp", "webp"] }
```
Это исключает default dynamic libchafa. Licenses добавляются в notices. Animated input сводится к одному static `DynamicImage` без timer. Content magic проверяет формат, но decoder обязан валидировать полный input; расширение само по себе не является доказательством.
### 2. Bounded read/decode/prepare
Начальные внутренние лимиты, подтверждаемые tests:
- encoded input: 16 MiB с lookahead, truncated input не декодируется;
- width/height: до 8192 на ось;
- total pixels: не более 32 000 000 с checked arithmetic;
- decoder `max_alloc`: 256 MiB, понимая, что это не hard process sandbox;
- один prepared image на панель и один global blocking worker.
Transient budget учитывает encoded bytes, decoded RGBA, resized copy и protocol buffer. Метаданные размера могут pre-reject, но не заменяют read limit. Decode, resize и encode выполняются вне UI task. Cancellation проверяется до read/decode, после decode и перед encode/send; running codec нельзя прервать силой, поэтому bounded worker не допускает неограниченный spawn_blocking queue.
### 3. Detection и fallback
`Picker::from_query_stdio` вызывается at most once после terminal initialization, но **до** `run_event_loop` создаёт `EventStream`. Timeout bounded и тестируемый. Ответы выбирают Kitty/iTerm2/Sixel; отсутствие capabilities даёт halfblocks.
До **любого** `Picker` constructor выполняются собственные images/terminal/tmux gates. `TERM=dumb`, ASCII/NO_COLOR, non-TTY или `images = false`/`--no-images` используют sanitized image-unavailable/metadata fallback без graphics или probe payload. `IconMode::None` влияет только на title icon, но не скрывает pixels.
Под tmux нельзя вызывать даже `Picker::halfblocks`: upstream detection может выполнить `tmux set -p allow-passthrough on`. Вместо этого halfblock protocol создаётся напрямую через public `Resize::resize` + `Halfblocks::new` + `Protocol::Halfblocks`, либо через проверенный side-effect-free patched constructor. Environment не маскируется. Regression с подставным `tmux` executable доказывает отсутствие процесса и config mutation.
Native protocols — best-effort. Halfblocks — обязательный universal baseline с `▀`/`▄` и RGB; он проверяется на TestBackend. Реальные Kitty/iTerm2/Sixel требуют ручной matrix и не считаются доказанными structural tests.
### 4. Prepared state вне reducer
`PreviewState` продолжает хранить только Clone/Eq metadata и identity image preview. Prepared `Protocol` находится в bounded shared `ImagePreviewCache`, управляемом runtime. Cache ключ:
`(pane, preview generation, typed target, SessionEpoch, inner Size, font size, protocol type, terminal epoch)`.
Reducer принимает `PreviewFinished` только через существующие guards. Renderer получает read-only cache/context и показывает protocol лишь если его identity совпадает с accepted current metadata. Устаревший cache entry удаляется/заменяется при новой accepted identity; его существование само по себе не даёт права на вывод.
Существующий `render` сохраняет disabled default для compatibility. Production и image tests используют `render_with_context` с явным context; никаких скрытых mutable изменений AppState во время render.
### 5. Rendering и geometry
`Picker::new_protocol`/`Image` используют fixed prepared protocol, чтобы resize/encode не выполнялись в `Frame::render`. `Resize::Fit(Triangle)` сохраняет aspect ratio и только downscale. Нулевые area/images дают placeholder.
При изменении inner rect создаётся новая prepared identity. Старый oversized Sixel/iTerm2 не рисуется за пределами новой области; показывается безопасный placeholder до готовности. Resize storms coalesce, а старый completion отбрасывается. Соседние панели и borders остаются нетронутыми.
Image→text/directory/no-selection, закрывающий overlay и images-disabled убирают widget из draw path. Workers не пишут stdout вообще; только current render path получает protocol cells/payload.
### 6. Editor suspend/resume и exit
`TerminalGuard` остаётся владельцем raw/alternate screen. После resume TUI увеличивает terminal epoch, очищает prepared cache и инициирует пересоздание текущего image до обычного draw. Это предотвращает Kitty already-transmitted blank state. На suspend/exit никаких поздних writes после восстановления терминала.
Font metrics после resume не запрашиваются повторно без остановки input reader; если требуется новый probe, это отдельный coordinated change.
### 7. Тестирование
Generated tiny `DynamicImage` кодируется в memory, включая Local и fake-SSH. Tests:
- magic/corrupt/truncated/exact cap/cap+1 и все dimension/pixel/allocation limits;
- aspect fit, zero/tiny area, animated→static без timer;
- реальные `▀`/`▄` и известные RGB в persistent/F3 на TestBackend, borders/neighbors;
- protocol shape для Kitty/iTerm2/Sixel без snapshot случайных IDs/base64;
- stale generation/target/epoch/geometry и отмена до blocking start;
- active/max-active=1 и bounded prepared cache;
- icons-off сохраняет pixels; images-disabled/NO_COLOR/ASCII/dumb не испускают payload;
- invalidate/redraw/resume через mock presenter.
Manual matrix: Kitty/Ghostty, iTerm2/WezTerm, Foot/xterm Sixel, unsupported terminal halfblocks, tmux, Local/SSH, resize, rapid selection, editor resume и exit. Пользовательский visual review обязателен.
## Risks / Trade-offs
- [In-process decoder не является hard sandbox] → консервативные limits и явное ограничение без ложного security claim.
- [Обязательный transitive `quantette 0.6` через `icy_sixel 0.5.1` требует Rust 1.90] → проектный MSRV явно повышен с 1.88 до 1.90 вместо ложной совместимости; lockfile фиксирует проверенные версии.
- [Native protocol оставляет residue/blank после lifecycle] → geometry/terminal identity, full redraw, manual tests и halfblock fallback.
- [Detection конкурирует с EventStream] → единственный bounded probe до создания reader.
- [iTerm2/Sixel encoding дорог] → prepared off-thread protocol, никогда не encode в render.
- [Cache/terminal memory растёт] → один prepared entry на панель и явное исключение unsupported lifecycle cleanup claims.
## Migration Plan
1. Добавить limits, format detection и generated decode tests.
2. Ввести bounded detection, worker и prepared cache с identity/stale tests.
3. Подключить halfblocks и native protocols к persistent/F3 rendering.
4. Реализовать resize/disable/editor resume lifecycle.
5. Обновить config/README/guideline/testing/notices, прогнать полный suite и manual terminal matrix.
6. Получить independent verify через `rcom-tui-design`, синхронизировать ADDED `file-navigation` и архивировать change.
Откат — `images = false` либо возврат metadata fallback; исходные файлы не изменяются.

View file

@ -0,0 +1,33 @@
# Proposal
## Why
Сейчас выбранный PNG/JPEG получает только metadata/unsupported preview. Пользователь должен видеть само изображение в обычной preview-панели и F3, включая Local/SSH, с безопасными ограничениями и понятным fallback для терминалов без graphics protocol.
## What Changes
- Добавить декодирование и отображение реальных pixels для PNG, JPEG, GIF, BMP и WebP в persistent preview и F3; animated input показывается как одно статическое изображение без animation timer.
- Использовать `image` для bounded decoding и `ratatui-image` для Kitty/iTerm2/Sixel/Unicode halfblocks. Aspect ratio сохраняется, изображение downscale-ится в доступный rect без crop.
- Выполнять bounded terminal capability detection до создания EventStream; при отсутствии native protocol использовать actual halfblock pixels, а не metadata-only результат. Под tmux первый change выбирает halfblocks и не меняет пользовательский `allow-passthrough`.
- Добавить общий `images = true/false` config и `--no-images`; `IconMode::None` не отключает изображения. ASCII/NO_COLOR/`TERM=dumb` или явное отключение показывают sanitized image-unavailable/metadata fallback.
- Local/SSH используют bounded bytes через существующий typed FS port. Ограничиваются encoded bytes, dimensions, pixels, allocations, worker concurrency и prepared cache; decode/resize/encode не выполняются синхронно в UI render.
- Сохранить generation/target/SessionEpoch guards и добавить geometry/terminal epoch к prepared image identity. Resize и editor resume безопасно invalidируют incompatible protocol state; stale worker никогда не пишет в terminal напрямую.
- Добавить generated in-memory image tests с `TestBackend`, проверяющие реальные `▀`/`▄` pixels и RGB, protocol structure, cancellation/stale/resize и fallback; native protocols требуют отдельной ручной real-terminal matrix.
## Capabilities
### New Capabilities
Нет.
### Modified Capabilities
- `file-navigation`: предпросмотр изображения SHALL показывать фактические пиксели выбранного Local/SSH image с aspect fit, bounded async pipeline и terminal-specific fallback.
## Impact
- Новые image preparation/adapters в runtime/session/TUI и `src/ui/render.rs`; общий config из icons change получает `images`.
- Новые dependencies `image` и `ratatui-image` с минимальными features, без default libchafa dependency. Их licenses добавляются в `THIRD_PARTY_NOTICES.md`.
- `research_notes/Иконки и помощь rcom/image_previews.md` содержит yazi/protocol/source analysis.
- SVG, AVIF/HEIF/JXL, PDF/video thumbnails, animation, external Chafa/ImageMagick, Überzug++, disk thumbnail cache и automatic tmux configuration остаются вне первого change.
- Apply после `add-file-type-icons-and-colors`; до `redesign-help-and-remove-hints` picker-related Help inventory продолжает учитывать новый context при необходимости.

View file

@ -0,0 +1,46 @@
# Spec Delta
## ADDED Requirements
### Requirement: Предпросмотр изображений
Система SHALL показывать фактические пиксели выбранного PNG/JPEG/GIF/BMP/WebP в persistent preview и F3 для Local/SSH. Обработка MUST быть ограниченной и асинхронной, а terminal fallback MUST сохранять безопасность и понятное состояние. Metadata без изображения MUST NOT считаться успешным preview при поддерживаемых условиях.
#### Scenario: Изображение в обычной панели и F3
- **WHEN** выбранное поддерживаемое изображение успешно загружено
- **THEN** его реальные пиксели видны и в persistent preview, и при открытии F3, без ограничения результата одним текстовым metadata
#### Scenario: Local и SSH источники
- **WHEN** изображение находится на Local либо SSH endpoint
- **THEN** содержимое читается через существующий typed filesystem port с одинаковым отображаемым результатом и без shell-команд
#### Scenario: Размеры и статическое содержимое
- **WHEN** изображение имеет другое aspect ratio, больше доступной области либо является animated input
- **THEN** оно downscale-ится без crop и distortion, а animated input показывает одно статическое изображение без animation timer
#### Scenario: Ограничения и повреждённые данные
- **WHEN** encoded bytes, dimensions, pixels или allocation превышают лимиты, либо содержимое повреждено/обрезано
- **THEN** показывается понятный image-unavailable/metadata fallback без panic или попытки декодировать неполный файл как полный
#### Scenario: Асинхронная изоляция
- **WHEN** пользователь меняет выбор, endpoint, SessionEpoch или preview geometry до завершения read/decode/resize/encode
- **THEN** superseded работа отменяется либо отбрасывается, не меняет текущий preview и не пишет escape sequences в terminal напрямую
#### Scenario: Terminal protocol и универсальный fallback
- **WHEN** bounded detection до создания event reader находит Kitty/iTerm2/Sixel либо не находит graphics protocol
- **THEN** используется соответствующий native protocol либо Unicode halfblocks с реальными pixels; detection не зависит от icon mode, выполняется at most once после capability gates и не изменяет tmux configuration; disabled режимы не испускают даже probe payload
#### Scenario: Отключение изображений и icons-off
- **WHEN** пользователь отключил images, выбрал icons-off, NO_COLOR, ASCII или `TERM=dumb`
- **THEN** отключение images даёт явный fallback, тогда как icons-off само по себе не скрывает изображение; unsupported capability режимы не испускают graphics payload
#### Scenario: Resize и восстановление терминала
- **WHEN** preview rect изменился либо TUI возвращается после внешнего редактора
- **THEN** несовместимое prepared state инвалидируется и пересоздаётся для текущей geometry/terminal epoch, без stale pixels за границами панели или пустого Kitty state после resume
#### Scenario: Ограниченная работа workers
- **WHEN** пользователь быстро переключает много изображений
- **THEN** число queued/active blocking workers и prepared images остаётся в заданных пределах, а отмена до начала blocking job предотвращает его запуск
#### Scenario: Проверка реальных пикселей и протоколов
- **WHEN** выполняется acceptance
- **THEN** generated in-memory image и `TestBackend` доказывают `▀`/`▄` cells и RGB без сети, а Kitty/iTerm2/Sixel проходят отдельную ручную real-terminal matrix без ложного вывода из headless structural tests

View file

@ -0,0 +1,32 @@
# Tasks
## 1. Безопасное декодирование
- [x] 1.1 Добавить `image`/`ratatui-image` с минимальными features без default libchafa, обновить notices и реализовать content-magic classification для PNG/JPEG/GIF/BMP/WebP; generated in-memory tests не используют сеть или внешние assets.
- [x] 1.2 Реализовать bounded Local/SSH read с lookahead и лимиты 16 MiB/8192 axis/32M pixels/256 MiB max_alloc; tests покрывают exact cap, cap+1, checked overflow, corrupt/truncated input и fake-SSH без shell.
- [x] 1.3 Добавить animated→static behavior, checked geometry и aspect-fit Triangle без upscale/crop; tests на wide/tall/tiny/zero area доказывают отсутствие panic и animation timers.
## 2. Detection и async preparation
- [x] 2.1 Ввести at-most-once bounded `Picker::from_query_stdio` до EventStream только после images/terminal gates; до любого Picker constructor проверять tmux и создавать halfblocks напрямую через Resize/Halfblocks/Protocol без upstream side effects. Synthetic timeout/parser tests и substitute-tmux regression доказывают отсутствие probe/process/config mutation в disabled/tmux режимах.
- [x] 2.2 Добавить `images = true/false` в общий config и `--no-images`; CLI/startup tests проверяют defaults, precedence, отсутствие записей, а icons-off не отключает pixels.
- [x] 2.3 Реализовать один global blocking worker с cancellation checkpoints и prepared identity `(pane/generation/target/epoch/geometry/font/protocol/terminal epoch)`; tests доказывают max-active=1, отмену до blocking start и отсутствие прямых worker stdout writes.
- [x] 2.4 Реализовать bounded prepared cache вне Clone/Eq AppState и render context с accepted-current identity; tests покрывают stale generation/target/SessionEpoch/geometry и удаление старых entries.
## 3. Rendering и terminal lifecycle
- [x] 3.1 Подключить fixed prepared `Protocol`/`Image` к persistent preview и F3 без resize/encode в Frame; TestBackend доказывает реальные `▀`/`▄`, известные RGB, borders/neighbors и отсутствие metadata-only success.
- [x] 3.2 Добавить Kitty/iTerm2/Sixel structural shape tests без случайных IDs/base64 snapshots и отдельную real-terminal matrix; native support явно не выводится из headless tests.
- [x] 3.3 Реализовать resize coalescing, безопасный placeholder вместо oversized old protocol, image→text/no-selection/overlay cleanup и images-disabled/NO_COLOR/ASCII/dumb fallback; tests доказывают отсутствие payload за границами.
- [x] 3.4 Увеличивать terminal epoch и invalidировать/пересоздавать prepared images после editor resume; mock/PTY tests покрывают full redraw, Kitty already-transmitted state, отсутствие поздних writes и чистый exit.
## 4. Приёмка
- [x] 4.1 Обновить README, guideline, `docs/testing.md`, `docs/spec-matrix.md` и acceptance для всех десяти scenarios; strict OpenSpec, named-test traceability и отсутствие `.snap.new` должны пройти.
- [x] 4.2 Прогнать fmt, strict Clippy, полный tests/doc/PTY suite и зафиксировать 651/0/4; выполнен реальный Kitty visual review и PTY halfblock/tmux check без ложного универсального protocol claim.
- [ ] 4.4 Выполнить отдельную ручную iTerm2/Sixel и real-SSH visual matrix. Реальный tmux проверен на isolated server: halfblocks/RGB видны, `allow-passthrough` остаётся unset, quit чистый. iTerm2/Sixel недоступны и не заявляются; внешний acceptance gate остаётся открытым.
- [x] 4.3 Получить независимый verify через `rcom-tui-design` skill: финальный technical verdict 0 findings, 651/0/4; внешний manual gate вынесен в 4.4.
## Workflow follow-up
- После успешного verify синхронизировать ADDED `Предпросмотр изображений` в main `file-navigation`, выполнить `openspec archive add-image-previews` и проверить archived result.

View file

@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-05

View file

@ -0,0 +1,162 @@
# Design
## Context
См. `proposal.md`, delta `terminal-ui`, guideline и `research_notes/Иконки и помощь rcom/kitty_themes.md`. Официальная kitty documentation ссылается на `kovidgoyal/kitty-themes`; в pinned snapshot `a35d12290c3d6a74b1f94debc81281cb637f3568` находятся 459 темы и machine-readable `themes.json`. RCOM импортирует только curated subset, а не копирует весь catalog или исполняет kitty config.
Change обязательно применяется после `add-file-type-icons-and-colors` и расширяет его общий config и semantic appearance path. Standalone порядок и второй config loader не поддерживаются; combined tests проверяют независимые `icons`/`theme` настройки и overrides. `redesign-help-and-remove-hints` применяется после этого change, чтобы его inventory ссылался на уже существующий Theme Picker.
## Goals / Non-Goals
**Goals:**
- Стабильный офлайн catalog с проверяемыми source, palette derivation и лицензиями.
- Одинаковый UI contract для native и imported тем, включая светлые варианты. У Night Ops базовые background/panel/text/active/secondary/error/file-type RGB неизменны, а muted/selection/selection_text получают зафиксированную accessibility-коррекцию до общих targets.
- Прозрачный selection fallback и повторяемые проверки всех тем.
**Non-Goals:**
- Runtime theme download, kitty subprocess или исполнение config/scripts.
- Arbitrary user themes, OS auto dark/light и импорт всех upstream тем. Live preview разрешён только внутри явного Theme Picker с rollback.
- Автоматический bulk acceptance без визуального review или лицензионных notices.
## Decisions
### 1. Начальный catalog
| ID | Display name | Mode | Origin |
|---|---|---|---|
| `night-ops` | Night Ops | dark | RCOM native |
| `dracula` | Dracula | dark | kitty, MIT |
| `catppuccin-mocha` | Catppuccin Mocha | dark | kitty, MIT |
| `catppuccin-latte` | Catppuccin Latte | light | kitty, MIT |
| `gruvbox-dark` | Gruvbox Dark | dark | kitty, MIT/X11 |
| `gruvbox-light` | Gruvbox Light | light | kitty, MIT/X11 |
| `solarized-dark` | Solarized Dark | dark | kitty, MIT |
| `solarized-light` | Solarized Light | light | kitty, MIT |
| `tokyo-night` | Tokyo Night | dark | kitty source MIT metadata; upstream Apache-2.0 |
| `tokyo-night-day` | Tokyo Night Day | light | kitty source MIT metadata; upstream Apache-2.0 |
| `one-half-dark` | One Half Dark | dark | kitty, MIT |
| `one-half-light` | One Half Light | light | kitty, MIT |
| `rose-pine` | Rosé Pine | dark | kitty, MIT |
| `rose-pine-dawn` | Rosé Pine Dawn | light | kitty, MIT |
| `everforest-dark-medium` | Everforest Dark Medium | dark | kitty, MIT |
| `everforest-light-medium` | Everforest Light Medium | light | kitty, MIT |
| `github-dark` | GitHub Dark | dark | kitty, MIT |
| `github-light` | GitHub Light | light | kitty, MIT |
| `flexoki-dark` | Flexoki Dark | dark | kitty, MIT |
| `flexoki-light` | Flexoki Light | light | kitty, MIT |
Это 11 dark и 9 light. Nord намеренно не входит из-за отсутствия explicit per-file license в исследованном snapshot; добавление требует отдельного license review.
Catalog сортируется по display name в `--list-themes`, но Night Ops может быть помечена как default. IDs не зависят от accents и upstream spelling.
### 2. Import как audited development workflow
Development-only importer получает pinned `themes.json` и ровно 19 allowlisted `.conf` файлов. Он:
1. проверяет source commit, SHA-256 и explicit accepted per-file MIT/MIT-X11;
2. сохраняет author/upstream/source metadata и получает полные upstream copyright/license notices; фактический upstream Tokyo Night `folke/tokyonight.nvim@d8e9ca64c0b8e574051f14bf1486ecd12b81de89` использует Apache-2.0, которая не подменяется kitty MIT metadata;
3. читает только whitelist цветовых ключей, никогда не исполняет config;
4. разрешает необходимые symbolic values и рассматривает `none`/`system` как отсутствие;
5. нормализует `is_dark: true` в dark, а omitted — в light только для curated allowlist с luminance/visual sanity check;
6. генерирует static Rust data и manifest с derivation version.
Generated manifest и notices коммитятся. Runtime и обычный `cargo build` не обращаются к сети. Повторный import обновляется только явным изменением pinned commit и повторным review.
`THIRD_PARTY_NOTICES.md` содержит по одной записи на import; полные upstream notices находятся в нём либо `LICENSES/`. Night Ops помечается `origin: rcom-native` и не получает чужой attribution. Непонятная/отсутствующая лицензия — fail closed.
Для отсутствующего в kitty metadata upstream curated allowlist задаёт явные проверенные ссылки, а не подменяет их collection URL:
- Solarized Dark/Light — `https://github.com/altercation/solarized`, pinned upstream `62f656a02f93c5190a8753159e34b385588d5ff3`, copyright 2011 Ethan Schoonover, полный MIT text из `LICENSE`;
- GitHub Dark/Light — `https://github.com/primer/github-vscode-theme`, pinned upstream `738b0ac78f6a7cc16c8d541a71fa103d8637a64a`, copyright 2020 Primer, полный MIT text из `LICENSE`.
Эти upstream commits и notices проверяются отдельно от kitty source commit; при расхождении импорт блокируется.
### 3. Semantic palette derivation
Каждая тема предоставляет `background`, `panel`, `text`, `muted`, `active`, `secondary`, `error`, selection pair, ANSI 0–15 и mode. Общий appearance contract также включает regular/directory/executable/link/image/audio/video/document/archive/special filename roles, отдельные icon accents и current/marked/copied/cut/inactive состояния. Broken-link role резервируется для будущего typed LinkStatus и не вычисляется по неполным metadata.
Основная детерминированная derivation:
- `background` ← required source background;
- `text` ← required foreground;
- `panel` ← подходящий non-none tab-bar/inactive surface либо небольшое documented foreground/background mix;
- `muted` ← contrast-tested inactive foreground, затем ANSI color8, затем mix;
- `active` ← active border, затем URL, затем лучший blue из color4/color12;
- `secondary` ← magenta color5/color13;
- `error` ← лучший по контрасту red color1/color9;
- selection ← source pair после отдельной проверки.
Source values и derived values сохраняются раздельно в manifest. Это rcom mapping, а не официальная kitty спецификация.
File-type classes используют стабильную policy: regular=text; directory=blue color4/12; executable=green color2/10; link=cyan color6/14; image=warning yellow color3/11; audio/video=magenta color5/13; document=cyan или text по contrast; archive=red color1/9; special=yellow. Normal/bright ANSI выбирается по фактической surface contrast, а не просто по dark mode.
Icon accents остаются независимыми от filename styles. Night Ops сохраняет curated Rust orange `#dea584` и другие explicit accents; imported тема может использовать semantic class цвет либо отдельный curated RGB accent только после такой же contrast проверки. Случайный per-theme RGB для Rust/другого языка не создаётся. Связанный icons change переиспользует классы без изменения glyph precedence.
### 4. Effective contrast validation
Проектные targets: **4.5:1** для обычного/selected текста, filename и текстовых markers; **3:1** для selection boundary и essential icon glyph с сохранением текстового equivalent. Normal, muted, active, secondary, error, warning и file-type roles проходят на background/panel; selected filename/icon/markers дополнительно проходят на selection background. Это внутренние targets, не свойства kitty.
В rich color режиме selected row использует explicit проверенную foreground/background пару и BOLD без `REVERSED`, поэтому измеряются именно видимые цвета. В monochrome режиме `REVERSED` остаётся structural fallback. Tests читают фактические `fg`, `bg` и modifiers из полного Buffer после всех composition steps, а не только исходную palette pair.
Если любая source/derived пара не проходит:
1. сохранить hue, когда возможно, скорректировав lightness либо добавив active accent;
2. выбрать foreground из `text`/`background` по измеренному contrast;
3. повторно проверить targets и видимый non-color marker;
4. не допустить тему в release при неудовлетворительном результате.
Selection остаётся отличимой от current/marked/copied/cut и не скрывает file-type/state markers. Fallback одинаково применяется к filename, icon accents и combined selected states.
### 5. Config и CLI
Общий `config.toml` получает:
```toml
theme = "night-ops"
```
`--theme <id>` заменяет выбор только для текущего запуска и не пишет config. `--list-themes` печатает ID, display name и mode без terminal initialization. Unknown config/CLI ID возвращает ошибку со списком IDs до alternate screen и ничего не записывает.
Night Ops остаётся default. `NO_COLOR`/ASCII/icons-off применяются после выбора темы и переопределяют только соответствующие capabilities, не меняя сохранённый ID.
### 6. Theme Picker с live preview
`T` открывает keyboard-only picker `THEMES` с выбором текущей темы. `ThemePickerState` хранит selected ID, scroll и неизменный `baseline` темы при открытии. Catalog использует тот же display-name order, что `--list-themes`; `j/k` и Up/Down clamped к первой/последней записи, меняют selected ID и немедленно заменяют active `Theme`, поэтому панели, help, errors, selection и icons видны в новой палитре на том же кадре. Обычный preview не меняет config.
Picker view model сохраняет selected row внутри viewport, показывает non-color marker, display name, mode и позицию `N/20`. Footer содержит `Enter Save` и `Esc Cancel`; ошибка fingerprint/write занимает отдельную видимую строку и не перекрывает controls. Full-Buffer tests на 40×8, 80×24 и 120×40 доказывают reachability всех 20 тем и отсутствие truncated critical actions в NO_COLOR/ASCII.
F10 Press-only использует существующий quit path без config write и сохраняет terminal lifecycle/активные task guards; Release игнорируется.
Esc закрывает picker и восстанавливает ровно baseline. Enter отдельно подтверждает выбор: текущий config читается без потери `icons` и других полей, а theme ID записывается атомарно через owned temporary sibling + rename. До Enter записи нет.
При открытии сохраняется исходное config content/fingerprint. Если файл внешне изменился до Enter, сохранение останавливается с понятной ошибкой вместо перезаписи чужих изменений. При write/rename ошибке picker остаётся открытым, показывает ошибку и восстанавливает baseline; automatic retry отсутствует. После успешного Enter picker закрывается с выбранной темой, а CLI override сохраняет обычный приоритет при следующем запуске.
Input принимает Press/Repeat для `j/k` и Up/Down; Enter/Esc — Press only, Release игнорируется. Команды picker не просачиваются в workspace. Picker добавлен в Help General (`T`) и inventory с собственным context.
### 7. Проверка catalog
Automated tests проверяют точные IDs/count/modes, unique IDs, source hashes/provenance, отсутствие runtime imports и полный набор semantic colors. Contrast helpers тестируются на известных парах и каждой теме.
Representative full-Buffer/snapshot fixtures для каждой темы содержат normal, muted, active, current, selected, marked, copied, cut, error, warning, help, dialogs, tasks, previews и все file-type/icon classes на focused/inactive surfaces. Отдельно проверяются комбинированные selected+marked/copied/cut и selected file-type/icon rows. `NO_COLOR` остаётся общим structural test. Пользовательский visual review обязателен для каждой принятой темы; automated contrast не является заявлением о контрасте произвольной пользовательской terminal palette.
## Risks / Trade-offs
- [Terminal palette меняет реальный вид ANSI colors] → imported RGB используется для rich режима, а fallback/accessibility проверяются отдельно без ложной универсальной гарантии.
- [Source selection плохо подходит для TUI] → measured deterministic fallback и release gate.
- [Лицензия metadata не содержит полный notice] → importer блокируется до получения upstream notice; популярность не смягчает проверку.
- [459 тем дадут поддержку и визуальный шум] → только 19 audited imports, pinned source и явное расширение allowlist.
- [Config конфликтует с icons change] → один typed loader, оба поля и общие startup tests.
## Migration Plan
1. Реализовать catalog types/default Night Ops/config/CLI без imports.
2. Добавить pinned importer, allowlist, notices и semantic derivation.
3. Проверить selection/contrast и representative fixtures для каждой темы.
4. Реализовать Theme Picker с live preview, rollback и atomic save; добавить input/PTY/config fault tests.
5. Обновить README/guideline/testing/matrix и провести пользовательский visual review.
6. Прогнать полный suite и независимый verify через `rcom-tui-design`.
7. Синхронизировать ADDED `terminal-ui` requirement и архивировать change.
Откат — Night Ops default без удаления config; неизвестный сохранённый imported ID после отката обрабатывается как понятная startup error, а не молча меняет пользовательский выбор.

View file

@ -0,0 +1,33 @@
# Proposal
## Why
Night Ops является единственной встроенной палитрой, поэтому пользователь не может выбрать знакомую визуальную среду или светлую тему. Нужен небольшой, но разнообразный встроенный catalog с постоянным выбором темы, безопасной selection contrast и без runtime-загрузок или исполняемых theme scripts.
## What Changes
- Добавить ровно 20 встроенных тем на первом этапе: native **Night Ops** и 19 curated kitty imports — **11 dark / 9 light**. В список входят Dracula, Catppuccin Mocha/Latte, Gruvbox, Solarized, Tokyo Night, One Half, Rosé Pine, Everforest, GitHub и Flexoki pairs.
- Использовать стабильные kebab-case IDs, отображаемые имена и dark/light metadata. `--list-themes` печатает catalog без входа в TUI.
- Поддержать persistent `theme = "night-ops"` в общем `config.toml` и временный `--theme <id>` override; отсутствие настройки сохраняет текущий Night Ops, а unknown ID показывает доступные значения до alternate screen.
- Добавить Theme Picker по `T`: навигация сразу показывает live preview всей темы, `Enter` сохраняет выбор, а `Esc` возвращает тему, которая была при открытии. До подтверждения config не записывается; ошибка сохранения видима и не оставляет preview как постоянный выбор.
- Импортировать только явно MIT/MIT-X11-licensed kitty theme files из pinned `kovidgoyal/kitty-themes` commit; сохранить provenance, hashes, authors, upstream и полные copyright/MIT notices. Нельзя импортировать entry с неясной лицензией только из-за её популярности.
- Преобразовать terminal colors в общие semantic roles с задокументированными fallbacks; selection получает отдельную foreground/background проверку и deterministic fallback. File-type colors используют ANSI palette, а не выдуманные per-theme случайные RGB.
- Сохранить layout, keyboard behavior и textual markers. `NO_COLOR`, ASCII и icons-off имеют приоритет над декоративными цветами.
- Проверять каждую тему на representative normal/selected/marked/cut/error/help/dialog/tasks/preview/file-type fixtures, включая selected комбинации; эффективные contrast targets и пользовательский visual review являются release gates.
## Capabilities
### New Capabilities
Нет.
### Modified Capabilities
- `terminal-ui`: добавляется выбор встроенных цветовых тем с persistent/CLI configuration, dark/light catalog, accessibility fallbacks и лицензионной прослеживаемостью.
## Impact
- Общий appearance config из `add-file-type-icons-and-colors`, `Theme`/Palette, CLI и новый static generated catalog.
- Development-only pinned importer/manifest, `THIRD_PARTY_NOTICES.md` и необходимые license files; runtime сеть и kitty subprocess отсутствуют.
- Theme catalog/contrast/config/CLI/render tests, snapshots и документация.
- Arbitrary user-defined themes и автоматическое следование OS dark/light не входят в первый change. Live preview входит только в явный Theme Picker с подтверждением и rollback. Apply выполняется только после icons/colors: этот change расширяет один config и semantic appearance path, а не создаёт standalone variant. Help redesign применяется следующим, после появления Theme Picker.

View file

@ -0,0 +1,66 @@
# Spec Delta
## ADDED Requirements
### Requirement: Цветовые темы
Система SHALL предоставлять 20 встроенных тем со стабильными IDs, именами и dark/light metadata: native Night Ops и 19 curated imports. Тема SHALL выбираться persistent настройкой, временным CLI override или Theme Picker с live preview и подтверждением без изменения layout, keyboard behavior или textual markers, а runtime MUST NOT обращаться к сети или исполнять theme code.
#### Scenario: Тема по умолчанию
- **WHEN** пользователь не задал настройку темы
- **THEN** используется существующая Night Ops: базовые background/panel/text/accents/file-type RGB не меняются, а muted/selection/selection_text имеют зафиксированную accessibility-коррекцию до общих contrast targets
#### Scenario: Просмотр catalog
- **WHEN** пользователь запускает `--list-themes`
- **THEN** без входа в TUI выводятся ровно 20 тем со стабильными IDs, display names и dark/light режимами: 11 dark и 9 light
#### Scenario: Persistent и временный выбор
- **WHEN** пользователь задал встроенный theme ID в общем config либо передал `--theme <id>`
- **THEN** сохранённая тема применяется при следующих запусках, а CLI override действует только на текущий запуск и имеет приоритет
#### Scenario: Live preview в Theme Picker
- **WHEN** пользователь открыл picker по `T` и меняет выбор через `j/k` или Up/Down
- **THEN** выбранная тема немедленно применяется ко всему интерфейсу для оценки, текущая при открытии тема сохраняется как rollback baseline, а config остаётся неизменным
#### Scenario: Порядок и границы Theme Picker
- **WHEN** пользователь листает темы через `j/k` или Up/Down, включая Press/Repeat и первую/последнюю запись
- **THEN** используется тот же display-name order, что в `--list-themes`, выбор clamped к catalog границам, а F10 через Press-only использует существующий quit path без записи config
#### Scenario: Responsive Theme Picker
- **WHEN** picker открыт на 40×8, 80×24, 120×40, в NO_COLOR или ASCII
- **THEN** выбранная строка имеет non-color marker и позицию `N/20`, остаётся в viewport при навигации, все 20 тем достижимы, а Enter/Esc controls и ошибка сохранения не перекрываются и не обрезают critical actions
#### Scenario: Отмена live preview
- **WHEN** пользователь нажимает Esc после любого числа preview
- **THEN** восстанавливается тема, которая была при открытии picker, picker закрывается, а config и его другие поля не изменяются
#### Scenario: Подтверждение темы
- **WHEN** пользователь нажимает Enter на выбранной теме
- **THEN** только theme ID атомарно сохраняется в config с сохранением остальных настроек, picker закрывается с новой темой; при ошибке записи показывается ошибка без automatic retry или скрытого постоянного выбора
#### Scenario: Неизвестная тема
- **WHEN** config или CLI содержит unknown ID
- **THEN** запуск сообщает понятную ошибку и доступные IDs до входа в alternate screen, без создания/перезаписи пользовательского config
#### Scenario: Semantic применение темы
- **WHEN** выбрана любая встроенная тема
- **THEN** panels, text, muted, active, secondary, errors, selection и file-type classes получают согласованные semantic colors, а геометрия, selection markers и keyboard commands не меняются
#### Scenario: Читаемый selection
- **WHEN** исходная или derived цветовая пара не удовлетворяет проектным contrast targets на panel/background либо effective selection surface
- **THEN** применяется задокументированный deterministic fallback для текста, filename, icons и markers; проверка использует итоговые fg/bg/modifiers после state composition, а accepted themes не могут её обойти
#### Scenario: Ограниченный терминал
- **WHEN** установлен `NO_COLOR`, выбран ASCII или icons-off режим
- **THEN** структура и состояния остаются различимыми независимо от выбранной темы, а decorative RGB/Nerd Font не становятся обязательными
#### Scenario: Проверка всех тем
- **WHEN** тема включается в release catalog
- **THEN** для неё проходят representative normal/muted/active/current/selected/marked/copied/cut/error/warning/help/dialog/tasks/preview/file-type fixtures, включая selected комбинации на focused/inactive surfaces, и пользовательский visual review; результаты не выдаются за универсальный контраст чужой terminal palette
#### Scenario: Provenance и лицензии
- **WHEN** тема импортируется из внешнего catalog
- **THEN** manifest содержит pinned source commit/file/hash, автора, upstream и license, репозиторий включает необходимые copyright/permission notices, а отсутствие явной разрешённой лицензии блокирует import
#### Scenario: Автономный runtime
- **WHEN** пользователь выбирает и применяет встроенную тему
- **THEN** используются только встроенные static данные без сети, kitty subprocess, shell или исполнения внешнего theme/config кода

View file

@ -0,0 +1,38 @@
# Tasks
## 1. Catalog и выбор темы
- [x] 1.1 Ввести typed theme ID/display name/mode/semantic palette и native Night Ops как default с неизменными базовыми RGB и явно зафиксированными muted/selection accessibility corrections; unit tests фиксируют базовую палитру и unique stable IDs.
- [x] 1.2 После обязательного `add-file-type-icons-and-colors` расширить общий appearance config полем `theme`, добавить `--theme <id>` и `--list-themes`; tests проверяют persistent выбор, temporary precedence, 11 dark/9 light, независимые `icons`/`theme` overrides и сохранение валидного другого поля при ошибке.
- [x] 1.3 Обработать unknown config/CLI IDs с доступными значениями до alternate screen и без записи config; startup/PTY tests сохраняют terminal lifecycle и документированный default.
- [x] 1.4 Обновить README и `docs/testing.md` фактическими `--theme`, `--list-themes`, config path и offline semantics; documented CLI examples проверяются тестами.
## 2. Curated kitty import
- [x] 2.1 Добавить development-only importer с pinned `kovidgoyal/kitty-themes` commit `a35d12290c3d6a74b1f94debc81281cb637f3568`, allowlist ровно 19 тем и source hashes; tests подтверждают точные IDs/count и отсутствие runtime network/subprocess.
- [x] 2.2 Реализовать whitelist parser для color settings, symbolic values и dark/light normalization; fixtures проверяют отсутствие optional fields, `none`/`system`, отсутствие исполнения config и корректный origin native Night Ops.
- [x] 2.3 Собрать author/upstream/license и полные copyright/license notices для каждого import (включая фактическую Apache-2.0 Tokyo Night), с явными pinned upstream для Solarized (`altercation/solarized@62f656a…`, Ethan Schoonover) и GitHub (`primer/github-vscode-theme@738b0ac…`, Primer); manifest/`THIRD_PARTY_NOTICES.md`/`LICENSES` fail-closed на missing provenance, а kitty URL не подменяет upstream.
- [x] 2.4 Задокументировать importer provenance, pinned update process и отсутствие runtime downloads в README/docs; importer repeatability test доказывает идентичный generated output без сети при повторном запуске на тех же fixtures.
## 3. Semantic palette и приёмка тем
- [x] 3.1 Реализовать deterministic derivation panel/muted/active/secondary/error/selection, полный filename role mapping и независимые curated icon accents; table tests покрывают regular/directory/executable/link/image/media/document/archive/special, source/derived values и Night Ops Rust `#dea584`.
- [x] 3.2 Добавить contrast helpers для 4.5:1 text/filename/markers и 3:1 boundary/essential icons на background/panel/effective selection; rich selection использует explicit fg/bg+BOLD без REVERSED, monochrome сохраняет REVERSED, а full-Buffer tests проверяют итоговые fg/bg/modifiers и combined state fallback.
- [x] 3.3 Создать per-theme fixtures normal/muted/active/current/selected/marked/copied/cut/error/warning/help/dialogs/tasks/previews/file-types, включая selected+marked/copied/cut и selected file-type/icon rows на focused/inactive surfaces; NO_COLOR/ASCII/icons-off сохраняют структуру и keyboard behavior.
- [x] 3.4 Обновить guideline и `docs/spec-matrix.md` ссылками на catalog/config/import/contrast/render tests; strict OpenSpec, named-test consistency и отсутствие `.snap.new` должны пройти.
## 4. Theme Picker с live preview
- [x] 4.1 Добавить `T` и ThemePickerState с selected ID/scroll/baseline и display-name order из `--list-themes`; input tests проверяют начальный выбор, clamp на first/last для `j/k`/Up/Down и Repeat, Press-only Enter/Esc/F10, quit без save и игнорирование Release.
- [x] 4.2 Применять тему при навигации без config writes; pure picker view model сохраняет selected row в viewport и показывает marker/name/mode/`N/20`, Enter/Esc footer и отдельную error строку; full-Buffer reachability tests на 40×8, 80×24, 120×40 и NO_COLOR/ASCII покрывают все 20 тем, а PTY подтверждает Esc baseline и F10 terminal lifecycle.
- [x] 4.3 Реализовать Enter как атомарное сохранение только theme ID с сохранением `icons`/прочих полей и external-change fingerprint guard; fault tests покрывают write/rename error, видимую ошибку, rollback без automatic retry и успешное закрытие после save.
- [x] 4.4 Добавить `T` в General help и ThemePicker в полный input inventory; обновить README/guideline с live preview, Enter save и Esc rollback, проверив документированные клавиши тестами.
## 5. Приёмка
- [x] 5.1 Прогнать fmt, strict Clippy, полный tests/doc/PTY suite и зафиксировать числа в acceptance; пользовательский visual review покрывает каждую из 20 тем и picker rollback без универсального contrast claim для чужих terminal palettes.
- [x] 5.2 Получить независимый verify через `rcom-tui-design` skill для ADDED requirement и всех пятнадцати scenarios, включая picker и license/provenance gate; устранить findings и повторить affected quality checks перед archive.
## Workflow follow-up
- После успешного verify синхронизировать ADDED `Цветовые темы` в main `terminal-ui`, выполнить `openspec archive add-color-theme-presets` и проверить archived result.

View file

@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-05

View file

@ -0,0 +1,121 @@
# Design
## Context
См. `proposal.md`, delta `terminal-ui`, `docs/tui-design-guidelines.md` и research notes `yazi_icons_colors.md`/`ranger_icons_colors.md`. Сейчас `Theme` содержит только Night Ops базовые роли, а `entry_row` получает текстовый `EntryKind`. Добавлять отдельные цвета непосредственно в условия строки нельзя: selection, multi-select, links и executable состояния быстро станут конфликтующими исключениями.
Yazi предоставляет подходящую модель независимых icon/filetype rules; Ranger — semantic filename colors и non-color focus. RCOM перенимает идеи, не копируя их конфигурацию или заявляя автоматическое обнаружение Nerd Font.
## Goals / Non-Goals
**Goals:**
- Чистая deterministic классификация без I/O и отдельные icon/name/state стили.
- Красивые встроенные defaults и явные режимы для разных terminal capabilities.
- Общий typed appearance config, пригодный для последующего catalog цветовых тем.
- Полная проверка стилей и display width, а не только текстового вывода.
**Non-Goals:**
- Content sniffing, MIME subprocess, чтение remote files или сеть для определения типа.
- Автоматическая загрузка plugins или исполняемых themes.
- Полный импорт тысяч upstream icons в первом change; каталог расширяется data-driven.
- Гарантия одинакового RGB/ширины glyph на всех пользовательских терминалах.
## Decisions
### 1. Entry presentation resolver
Добавляется чистый `EntryPresentation::resolve(entry)`/`IconResolver`. Входом служат существующие `Entry` metadata и имя; новых filesystem вызовов нет.
Порядок icon rules:
1. упорядоченные glob overrides;
2. exact directory names;
3. exact file names;
4. ASCII-case-insensitive final extension (точное case-sensitive правило может быть проверено до lowercase);
5. metadata conditions: link, special inode, directory, executable, generic file.
Glob rules first-match и ограничены встроенным небольшим списком. Exact maps дают O(1) common path. Известная иконка `.rs` остаётся у executable/symlink, но отдельные `*`/`@` state markers не исчезают.
Case/type policy фиксируется полностью: встроенные glob overrides ASCII-case-insensitive; exact directory/file names case-sensitive; extension сначала проверяет original spelling, затем ASCII-lowercase. Для каталогов обычные filename/extension maps пропускаются, поэтому `README.md` и `docs.rs` как каталоги получают folder icon. Glob first-match; duplicate exact keys запрещены startup/test error, а не зависят от порядка инициализации.
Broken-link detection не входит в resolver: текущий `Entry`/`read_link` не отличает broken, valid и unknown без дополнительного I/O. Будущий отдельный change должен ввести typed `LinkStatus::{Valid,Broken,Unknown}` с Local/SFTP tests; до этого generic symlink использует `@`, без ложного broken `!`.
Начальный каталог включает generic/special classes, распространённые development names (`Cargo.toml`, `Cargo.lock`, `README*`, `.gitignore`, `Dockerfile`, `Makefile`), Rust и распространённые code/config/document/media/archive extensions. Источник glyph вдохновлён nvim-web-devicons; используемые данные и attribution фиксируются, без runtime upstream dependency.
### 2. Независимые стили
`Theme` расширяется semantic palette для filename classes и icon accents. `ResolvedIcon { glyph, style }` и `filename_style` вычисляются отдельно. State composition применяется после них:
- current selection сохраняет существующий маркер и контрастный row style;
- cursor занимает одну колонку; marked/copy/cut делят вторую через `*`, `+`, `-`, а combined marked+copy/cut используют `±`/`∓` (ASCII: `C`/`X`), поэтому нет трёх пустых state-колонок;
- valid/unknown symlink имеет отдельный `@` marker;
- inactive панель сохраняет активный marker другой панели и читаемость типов.
При selection не используется произвольный RGB icon foreground без проверенной композиции. `NO_COLOR` отключает только цвета, но не markers или icon mode. При Unicode/Nerd/ASCII glyphs колонка `TYPE` удаляется, чтобы не дублировать иконку и оставить больше места имени; в `none` текстовые `DIR`/`FILE`/`LINK`/`OTH` являются обязательным fallback.
Mode composition фиксирована:
| Выбранный режим | Обычный terminal | `TERM=dumb`/`RCOM_ASCII` |
|---|---|---|
| Unicode | Unicode | ASCII |
| Nerd | Nerd Font | ASCII |
| ASCII | ASCII | ASCII |
| None | Нет glyph | Нет glyph |
CLI override не включает icons обратно через environment; `none` всегда остаётся `none`.
### 3. Режимы и config
`IconMode = Unicode | Nerd | Ascii | None`; default — Unicode, поэтому специальный шрифт не обязателен. `TERM=dumb`/`RCOM_ASCII` выбирают ASCII fallback независимо от сохранённого режима.
Общий config загружается из `${RCOM_CONFIG_HOME}/config.toml` для tests либо platform config directory `rcom/config.toml`:
```toml
icons = "unicode"
```
`--icons unicode|nerd|ascii|none` имеет приоритет над config только на текущий запуск. Отсутствующий файл означает defaults. Malformed config/unknown icon mode даёт понятную startup error до terminal alternate screen. Для typed parsing добавляются `serde` и `toml`; config loader тестируется через явно переданный путь без глобального env race.
Следующий `add-color-theme-presets` использует тот же loader и добавляет `theme`, не создавая второй config.
### 4. Rendering и ширина
Строка сначала резервирует selection/state marker, icon и separator, затем вычисляет место для basename и metadata. Width измеряется через существующий unicode-width path; private-use glyph тестируется в каждом режиме.
Новый filename-aware middle truncation сохраняет начало basename и final extension, если это помещается. При нехватке сначала исчезают modified/size и symlink details, затем сокращается имя. Иконка не меняет breakpoint и не вызывает overflow.
Тот же resolver используется в заголовке persistent/F3 preview: `PREVIEW · <icon> <name>` с независимыми icon/name styles и width-aware truncation; в `none` заголовок остаётся текстовым.
Render остаётся чистым: resolver не меняет `AppState` и не кэширует mutable global state. При необходимости кэш должен быть ограниченным и инвалидироваться по config/theme, но первая реализация использует cheap exact maps.
### 5. Проверка и роли
`rcom-tui-design` skill используется дизайнером для visual/interaction handoff и независимым тестировщиком для review. Named tests:
- table-driven precedence/case/type-gating/unknown/metadata, включая `README.md`/`readme.md`, каталоги `README.md` и `docs.rs`, known-name symlink и executable `.rs`;
- полный Buffer для Night Ops icons/name/selection/marked/cut/symlink;
- Unicode/Nerd/ASCII/none и NO_COLOR, включая `none` + ASCII fallback и selected row в каждом режиме;
- 40×8, 80×24, 120×40, 160×40 и dual 71/72, long Unicode names и сохранение расширения; Unicode/ASCII/none запрещают private-use glyphs;
- config default/override/malformed и startup lifecycle;
- осознанные snapshots без автоматического обновления.
## Risks / Trade-offs
- [Nerd Font glyph выглядит квадратом] → Unicode default, явный opt-in и документированный prerequisite.
- [Цвета нарушают selection contrast] → state composition поверх semantic styles и full-Buffer tests; пользовательская визуальная проверка остаётся обязательной.
- [Точное имя скрывает link/executable тип] → отдельные non-color state markers.
- [Glob замедляет большой listing] → минимальный ordered список и exact-map common path; benchmark на большом synthetic listing.
- [Два appearance changes конфигурируют одни файлы] → общий config/Theme path и последовательное apply с обновлением design при расхождении.
## Migration Plan
1. Ввести resolver и unit tests без смены rendering.
2. Добавить semantic palette и config/CLI override.
3. Подключить icons/name styles к entry rows и width-aware truncation.
4. Обновить guideline/README/snapshots через design review.
5. Прогнать полный suite, независимый verify и пользовательский screenshot review.
6. Синхронизировать MODIFIED `terminal-ui` и архивировать change.
Откат восстанавливает текстовые типы; config `icons = "none"` дополнительно даёт совместимый plain list без удаления данных.

View file

@ -0,0 +1,32 @@
# Proposal
## Why
Сейчас тип элемента обозначается только текстом `DIR`/`FILE`/`LINK`, а имена имеют почти одинаковый цвет. Нужна более выразительная, но спокойная визуальная классификация с разными иконками для каталогов, проектных файлов и расширений, semantic colors и безопасной работой без Nerd Font.
## What Changes
- Добавить data-driven иконки для каталогов, специальных каталогов, точных имён (`Cargo.toml`, `README.md`, `.gitignore`), распространённых расширений (включая `.rs`), generic files, links, executables и special inodes.
- Разделить glyph, цвет иконки, стиль имени и состояние строки. По умолчанию Night Ops использует blue/cyan folders, rust/orange Rust icon, green executables, yellow images, magenta media, red archives и явные markers для links/errors.
- Определить детерминированный порядок правил и case policy: ordered glob overrides, directory names, exact file names, extensions, metadata fallback; unknown types получают generic glyph.
- Поддержать явные режимы `unicode` (без обязательного Nerd Font), `nerd`, `ascii` и `none` через persistent config с временным CLI override. Не пытаться выводить font capability только из `$TERM`.
- Сохранить selection/marked/cut/copy/inactive различия, контраст и текстовые типы при monochrome/icons-off; не кодировать критическое состояние только цветом.
- Включить icon width в существующий responsive budget и при truncation сохранять basename и, когда возможно, расширение.
- Задокументировать модель в `docs/tui-design-guidelines.md` и проверять её через новый `rcom-tui-design` skill, full-Buffer/snapshot/input tests и independent design review.
## Capabilities
### New Capabilities
Нет.
### Modified Capabilities
- `terminal-ui`: визуальная иерархия дополняется per-type icons, независимыми filename/icon styles, явными font fallback modes и accessibility/selection rules.
## Impact
- Новый чистый resolver классификации/иконок и semantic theme roles; `src/domain`, `src/ui/theme.rs`, `src/ui/render.rs` и text width/truncation helpers.
- CLI/config parsing для режима иконок; никаких filesystem content sniffing, remote shell или дополнительных сетевых запросов.
- Тесты resolver precedence, render buffers/snapshots, narrow/NO_COLOR/ASCII/icons-off и документация.
- Обязательный порядок: `add-file-type-icons-and-colors` создаёт общий config/semantic appearance path, затем `add-color-theme-presets` добавляет catalog и Theme Picker, затем `redesign-help-and-remove-hints` включает уже существующий picker в полный inventory. Broken-link detection вынесен в отдельный будущий change с typed Local/SFTP `LinkStatus`; текущий scope сохраняет generic symlink marker.

View file

@ -0,0 +1,42 @@
# Spec Delta
## MODIFIED Requirements
### Requirement: Визуальная иерархия
Система SHALL показывать заголовок расположения, источник local/SSH, список, выбор, активность панели и нижнюю строку статуса; активность MUST различаться не только цветом. Типы элементов SHALL иметь детерминированные иконки и semantic colors, а glyph, стиль иконки, стиль имени и состояние строки MUST задаваться независимо. Специальный шрифт MUST NOT быть обязательным.
#### Scenario: Две панели
- **WHEN** отображаются две панели
- **THEN** активная имеет отдельный маркер и акцентную рамку, а неактивная визуально приглушена без потери читаемости
#### Scenario: Выбранный элемент
- **WHEN** список содержит выбранный элемент
- **THEN** он выделен контрастным фоном и маркером, а типы элементов различимы иконками без избыточного `TYPE` либо текстовыми обозначениями в icons-off
#### Scenario: Терминал без расширенных цветов
- **WHEN** терминал не поддерживает полную палитру или установлен `NO_COLOR`
- **THEN** структура, фокус и выбор остаются различимы за счёт текста, рамок и фона
#### Scenario: Разные иконки для разных типов
- **WHEN** список содержит каталоги, generic files, известные точные имена, файлы с известными расширениями, links и executables
- **THEN** они получают различимые иконки соответствующих типов в списке и заголовке preview, включая отдельную Rust-иконку для `.rs`, а неизвестный тип получает generic fallback
#### Scenario: Детерминированный приоритет правил
- **WHEN** элемент одновременно соответствует нескольким правилам или отличается только регистром имени/расширения
- **THEN** результат определяется документированным порядком glob override, directory name, exact filename, extension и metadata fallback с явной case policy; обычные file/extension rules не применяются к каталогам
#### Scenario: Semantic цвета имени и иконки
- **WHEN** включена цветовая тема с поддержкой file-type classes
- **THEN** иконка и имя могут иметь разные согласованные цвета, а directories, executables, media, documents, archives и links используют устойчивые semantic классы без радуги несвязанных оттенков имени
#### Scenario: Selection и состояния операций
- **WHEN** строка является текущей, marked, copied, cut, symlink или находится в неактивной панели
- **THEN** состояние остаётся различимым не только по hue, а icon/name styling не скрывает selection и критические markers
#### Scenario: Режимы шрифта и отключение иконок
- **WHEN** пользователь выбрал persistent или временный режим `unicode`, `nerd`, `ascii` либо `none`
- **THEN** приложение использует соответствующий glyph set, CLI имеет приоритет над сохранённой настройкой, terminal ASCII fallback никогда не включает `none` обратно, при включённых иконках избыточная колонка `TYPE` удаляется, а `DIR`/`FILE`/`LINK`/`OTH` сохраняются в `none`, а отсутствие Nerd Font не приводит к обязательным private-use квадратам
#### Scenario: Иконки в узкой панели
- **WHEN** ширины недостаточно для полной строки с иконкой и metadata
- **THEN** вторичные metadata удаляются раньше basename, иконка не нарушает выравнивание, а truncation сохраняет имя и по возможности расширение

View file

@ -0,0 +1,31 @@
# Tasks
## 1. Детерминированная классификация
- [x] 1.1 Добавить typed `IconMode`, `ResolvedIcon` и чистый resolver без filesystem I/O; table-driven tests покрывают generic/special categories, `.rs`, known names, links/executables и unknown fallback.
- [x] 1.2 Реализовать порядок glob → directory name → exact filename → extension → metadata, полную case policy и запрет filename/extension maps для каталогов; property/table tests покрывают `README.md`/`readme.md`, каталог `docs.rs`, known-name symlink, executable `.rs`, детерминизм и first-match/duplicate semantics.
- [x] 1.3 Заполнить начальный catalog развития/документов/media/archives и generic glyphs, зафиксировать upstream attribution/license; resolver benchmark на большом synthetic listing подтверждает отсутствие glob-heavy common path.
## 2. Config и terminal modes
- [x] 2.1 Добавить общий typed appearance config с `icons = "unicode"`, explicit test path/`RCOM_CONFIG_HOME` и понятные ошибки; tests покрывают missing/default, все режимы и malformed input.
- [x] 2.2 Добавить `--icons unicode|nerd|ascii|none` с приоритетом над config и ASCII fallback для `TERM=dumb`/`RCOM_ASCII` без повторного включения `none`; CLI/startup tests доказывают ошибку до alternate screen, отсутствие сети/filesystem writes, удаление избыточного `TYPE` при icons и сохранение `DIR`/`FILE`/`LINK`/`OTH` в `none`.
- [x] 2.3 Обновить README и `docs/testing.md` фактическими режимами, Nerd Font prerequisite, config path и командами запуска; documented examples проверяются как CLI parse tests.
## 3. Semantic rendering
- [x] 3.1 Расширить `Theme` semantic file-type/icon roles и разделить glyph/icon/name style; создать canonical Night Ops fixture с каталогом, Cargo.toml, main.rs, executable, symlink и selected+marked row, указав glyph/icon/name/markers и Unicode/ASCII/none variants; full-Buffer tests используют тот же fixture.
- [x] 3.2 Подключить resolver к entry rows с composition selection/marked/cut/copy/symlink/inactive; tests доказывают non-color markers, читаемость selected row и отсутствие изменений AppState при render. Broken-link-specific styling не реализуется без будущего typed LinkStatus.
- [x] 3.3 Реализовать Unicode/Nerd/ASCII/none rendering и NO_COLOR/icons-off поведение; комбинированные tests покрывают каждый mode с NO_COLOR, `none` с ASCII terminal и selected row; snapshots обновляются осознанно, существующие UI regressions проходят.
- [x] 3.4 Включить icon width и filename-aware truncation в responsive budget; полный Buffer tests на 40×8, 80×24, 120×40, 160×40 и dual 71/72 проверяют basename/extension, overflow и breakpoints, а Unicode/ASCII/none запрещают Nerd private-use glyphs.
## 4. Приёмка
- [x] 4.1 Обновить `docs/spec-matrix.md`, guideline, README и acceptance по всем девяти scenarios; strict OpenSpec и named-test traceability должны пройти, `.snap.new` отсутствуют.
- [x] 4.2 Прогнать fmt, strict Clippy, полный tests/doc/PTY suite и зафиксировать числа; пользовательский visual review фиксирует representative rich/fallback frames без ложного универсального contrast claim.
- [x] 4.3 Получить независимый verify через `rcom-tui-design` skill, устранить CRITICAL/WARNING и повторить affected quality checks перед archive.
## Workflow follow-up
- После успешного verify синхронизировать MODIFIED `terminal-ui`, выполнить `openspec archive add-file-type-icons-and-colors` и проверить archived result.
- Затем применять `add-color-theme-presets`, расширяя созданный здесь config/semantic appearance path; Help redesign выполняется после Theme Picker, чтобы inventory включал существующие bindings.

View file

@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-06

View file

@ -0,0 +1,89 @@
# Design
## Context
См. `proposal.md`, ADDED `file-navigation` и `docs/tui-design-guidelines.md`. `move_selection`/`toggle_select` сейчас сразу вызывают `request_preview`, которое увеличивает generation и заменяет PreviewState на `loading=true`. Event loop уже имеет redraw tick с MissedTickBehavior::Skip, поэтому отдельный timer task или OS watcher не нужен.
## Goals / Non-Goals
**Goals:**
- Коалесцировать пользовательские preview reads без накопления задач.
- Немедленно инвалидировать старые responses и не показывать чужое содержимое.
- Разделить quiet debounce и фактическую медленную загрузку без внесения времени в чистый renderer.
**Non-Goals:**
- Новая задержка initial listing, ручного F3 или background refresh вне active selection debounce; существующий debounce при polling race сохраняется, а не создаётся заново.
- Изменение preview content, bounded чтения, key semantics или image protocols.
- Непрерывный async task на панель или busy loop.
## Decisions
### 1. Разделить schedule и execute preview
Selection path сначала создаёт typed `PreviewRequest` и увеличивает `preview_generation`, но возвращает новый `Effect::DebouncePreview(request)` вместо `LoadPreview`. PreviewState получает target нового выбора, `content=None`, `loading=false` и явный `debouncing=true`; старый response уже не проходит generation guard.
`Application` перехватывает DebouncePreview и сохраняет только один pending request на панель с `deadline = now + 40 ms` и `navigation_generation` на момент selection. Повторный selection заменяет request и deadline. `EffectRunner` не запускает чтение на этом этапе.
`Application::next_preview_deadline()` добавляет в `tokio::select!` `sleep_until` для ближайшего pending request. Новый input пересоздаёт/отменяет прежний sleep future, поэтому redraw tick остаётся отдельным и deadline действительно наступает в 40 ms, а не на следующем 50-ms tick. `MissedTickBehavior::Skip` остаётся защитой от накопления redraw ticks.
`dispatch_at`/`handle_key_at`/`expire_pending_at` используют один explicit clock. Tests проверяют 39 ms → нет LoadPreview, 40 ms → ровно один. Deadline не хранится в Clone/Eq доменной модели; он принадлежит session scheduler. Production использует `Instant::now`, tests не используют sleeps.
StartPreview принимается только при active `debouncing`, совпадающих preview generation/target и `selected_location == request.target`, равных SessionEpoch, совпадающем `navigation_generation` и успешном `session_matches_target`. Последний guard различает SSH hosts даже при одинаковых числовых epochs. Enter/Parent/GoHome/SSH connect изменяют navigation_generation и тем самым отбрасывают pending ещё до нового listing response; scheduler удаляет такой request без I/O. Same-location background polling и manual foreground listing не меняют navigation_generation, поэтому не инвалидируют selection pending.
Failed navigation/SSH connect завершает quiet state явно: старый pending удаляется по navigation_generation, а сохранённые location/selection получают новый immediate current preview request с новой preview generation. `debouncing` сбрасывается, scheduler не содержит orphan entry. Запрещается запуск именно старого pending, а не документированный replacement после failure.
### 2. Только пользовательский selection path
Debounce вызывается из `move_selection` и selection advance в `toggle_select`, включая все текущие first/last/page/half-page aliases. Initial `finish_listing`, `OpenPreview` и successful background listing вне active selection debounce используют существующий `request_preview_mode` и не получают новую задержку.
При отсутствии selected target DebouncePreview не создаётся, preview очищается. При navigation/endpoint change, закрытии overlay и новом listing stale pending request отбрасывается по identity. На editor boundary scheduler замораживается вместе с event loop; после resume срабатывает только current request.
`navigation_generation` — отдельный от response `listing_generation` счётчик. Он увеличивается при смене target/endpoint и SSH connect, но не при same-location background polling. Rebase pending при background не используется.
Active selection debounce означает одновременно `debouncing=true` и существующий matching pending request; orphan flag никогда не сохраняется. Same-target background `finish_listing` во время active debounce не вызывает immediate preview: существующие pending request/deadline и quiet frame сохраняются. Если background изменил selection либо debounce отсутствует, существующий immediate background path сохраняется. Это исключает race между 1s polling и удержанием клавиши. Если current preview уже запущен по pending, более поздний same-target background не запускает duplicate in-flight request.
`copy_for_second_pane` сбрасывает preview при `loading || debouncing` и увеличивает его preview generation. Клон не наследует quiet state без scheduler owner; исходная панель сохраняет свой единственный pending request.
### 3. Quiet rendering
`render_preview` показывает `LOADING PREVIEW` только при `loading && !background_refresh && !debouncing`. Во время debounce title вычисляется из текущего selected entry, а body остаётся пустым/нейтральным без Reading text. Старый content уже удалён, поэтому нет нарушения selection isolation.
Если request после deadline оказался медленным, обычный loading индикатор разрешён. Следующий selection немедленно создаёт новый generation и quiet debounce состояние.
### 4. Отмена и ограничения
На панель допускается один pending scheduler entry и один фактический preview worker. Новый LoadPreview использует существующую отмену superseded task. Старый async read может завершиться до deadline, но generation guard отбрасывает его. Быстрый repeat не создаёт новые blocking/read задачи до истечения последнего deadline.
При выходе pending entries просто удаляются без I/O. На terminal suspend никаких запусков между suspend/resume нет. `MissedTickBehavior::Skip` предотвращает накопление ticks; несколько просроченных deadlines обрабатываются по одному current request на панель.
### 5. Проверки
- Explicit clock: 39 ms нет `LoadPreview`, 40 ms ровно один; `sleep_until` тестируется отдельно от redraw tick.
- Все selection aliases проходят один путь; Repeat не создаёт очередь.
- Полный Buffer: нет `LOADING PREVIEW` на промежуточных строках, title текущий, старый текст отсутствует.
- Старый response инертен; wrong host при равных epochs, navigation start до deadline и geometry не запускаются.
- Same-target background во время debounce остаётся quiet; отдельно проверяются completion до deadline, background still running на deadline и changed selection до/после deadline. Navigation generation не меняется, current pending не отбрасывается и duplicate in-flight не создаётся.
- Dual clone до deadline сбрасывает `loading || debouncing`, не наследуя бесхозный scheduler state.
- Initial/F3/background вне debounce не задерживаются, а медленный current request сохраняет loading после debounce.
- PTY после завершения initial preview подтверждает byte-level burst, остановку на итоговом target и terminal restore. Отсутствие intermediate reads/loading-flash доказывается deterministic scheduler/full-Buffer tests; raw `LOADING PREVIEW` count не является таким доказательством. Один post-debounce loading frame разрешён.
- Независимый review через `rcom-tui-design` и визуальный acceptance пользователя.
## Risks / Trade-offs
- [До 40 ms preview не начинает читать] → это осознанная маленькая задержка ради устранения лишних reads; initial/F3 не затронуты.
- [Scheduler и reducer разойдутся] → request уже содержит generation/target, StartPreview повторно проверяет current identity.
- [Старый worker продолжает работу до следующего LoadPreview] → только один worker на панель, его результат инертен; actual cancellation происходит при запуске нового current worker.
- [Новый Effect будет ошибочно исполнен как read] → Application владеет DebouncePreview, runner имеет явный non-read branch, tests проверяют отсутствие I/O до deadline.
## Migration Plan
1. Добавить quiet PreviewState и failing render/scheduler tests.
2. Ввести DebouncePreview и pending deadlines в Application/redraw tick.
3. Перевести все selection movement paths и StartPreview guards.
4. Прогнать полный suite и PTY rapid navigation, обновить guideline/matrix/acceptance.
5. Получить independent verify и визуальный review.
6. Синхронизировать ADDED `file-navigation` и архивировать change.
Откат возвращает immediate selection preview без изменения файловых данных.

View file

@ -0,0 +1,32 @@
# Proposal
## Why
При быстром переключении каталогов каждый selection change немедленно очищает preview и запускает чтение, поэтому `LOADING PREVIEW`/`Reading…` мелькает на каждой строке и мешает навигации. Нужно коалесцировать запросы без показа старого содержимого для нового выбора и без нарушения stale-response guards.
## What Changes
- При пользовательском `j/k`, arrows и связанном selection movement откладывать preview read на короткий bounded debounce interval вместо запуска на каждую промежуточную строку.
- Во время debounce немедленно обновлять target/generation и заголовок, очищать несоответствующий старый preview и показывать спокойную пустую область без `LOADING PREVIEW`.
- После последнего selection change запускать ровно один current preview request; если чтение становится заметно медленным, индикатор загрузки разрешён после debounce.
- Initial listing, ручной F3 и background preview refresh вне active selection debounce сохраняют существующие immediate/foreground/background semantics; отмена и generation/target/SessionEpoch guards не ослабляются.
- Операции с выбором, включая multi-select advance и page/half-page movement, используют тот же debounce path; повторный ввод не создаёт неограниченные read/decode задачи.
- Добавить deterministic scheduler tests с injected/paused time, stale completion tests и PTY rapid-navigation regression без мелькания loading.
- Зафиксировать поведение в `docs/tui-design-guidelines.md`, spec matrix и acceptance.
## Capabilities
### New Capabilities
Нет.
### Modified Capabilities
- `file-navigation`: быстрая смена выбора SHALL коалесцировать preview reads и MUST NOT показывать повторяющийся loading-flash на каждой промежуточной строке или старый preview для нового выбора.
## Impact
- Selection-to-preview path в `src/app`, небольшой deadline scheduler в `src/session.rs` и существующий redraw tick в `src/tui.rs`.
- `src/ui/render.rs` получает отдельное quiet debounce состояние; runtime cancellation и preview guards сохраняются.
- Input/headless/PTY tests и документация. Новых dependencies, filesystem protocol или image behavior изменений нет.
- Apply после завершения текущих UI changes; `add-image-previews` использует тот же scheduler, чтобы rapid image selection также не создавала лишние workers.

View file

@ -0,0 +1,42 @@
# Spec Delta
## ADDED Requirements
### Requirement: Коалесцирование preview при навигации
Система SHALL откладывать preview чтение при быстром пользовательском selection movement на короткий bounded interval и запускать только current запрос. Промежуточные строки MUST NOT вызывать повторяющийся `LOADING PREVIEW`/reading-flash, а старый preview MUST NOT показываться для нового выбора.
#### Scenario: Быстрая навигация без мигания
- **WHEN** пользователь несколько раз подряд меняет выбор до истечения debounce
- **THEN** для каждой промежуточной строки не запускается preview read и не появляется `LOADING PREVIEW`; область остаётся спокойной, а заголовок соответствует текущему выбору
#### Scenario: Один запрос после остановки
- **WHEN** debounce истёк после последнего selection change
- **THEN** запускается ровно один preview request для текущего target/generation/endpoint, а не серия запросов для пройденных строк
#### Scenario: Stale preview и stale response
- **WHEN** выбор изменился до завершения предыдущего preview чтения
- **THEN** прежнее содержимое не показывается для нового выбора, а старый response отбрасывается по generation/target/SessionEpoch без изменения текущего кадра
#### Scenario: Сохранение других режимов
- **WHEN** выполняется initial listing, ручной F3 или background refresh того же элемента вне active selection debounce
- **THEN** используются существующие immediate/foreground/background semantics без добавления debounce задержки или повторного мигания
#### Scenario: Все формы selection movement
- **WHEN** используются `j/k`, arrows, first/last, page/half-page или multi-select advance
- **THEN** все они используют одинаковый debounce path, а число pending/read задач остаётся ограниченным при удержании клавиши
#### Scenario: Background listing во время debounce
- **WHEN** same-target background listing завершается до истечения active selection debounce
- **THEN** существующий pending request и quiet кадр сохраняются без преждевременного read/loading; если background изменил selection, используется immediate foreground current load
#### Scenario: Navigation во время debounce
- **WHEN** до deadline начался переход либо SSH connect
- **THEN** старый pending request отклоняется по navigation identity и полному host/session guard; при ошибке перехода/connect создаётся новый immediate current preview request для сохранённой selection с новой generation, а quiet state не остаётся без scheduler owner
#### Scenario: Включение dual во время debounce
- **WHEN** до deadline включается dual
- **THEN** клон получает preview reset при `loading || debouncing`, а исходная панель сохраняет свой pending/deadline и запускает ровно один current request
#### Scenario: Медленное чтение после debounce
- **WHEN** current preview request начался, но не завершается быстро
- **THEN** понятный индикатор загрузки разрешён после debounce и не скрывает ввод или другую панель; новый selection change снова переводит preview в quiet debounce состояние

View file

@ -0,0 +1,25 @@
# Tasks
## 1. Quiet preview state
- [x] 1.1 Добавить `debouncing` в PreviewState и отделить его от loading/background; full-Buffer tests показывают текущий title, пустую quiet область без `LOADING PREVIEW` и отсутствие старого текста при новом selection.
- [x] 1.2 Добавить failing regression для быстрого `j/k`: до deadline нет preview read/loading, после него один current request; существующий stale preview test продолжает отбрасывать старый response.
## 2. Deadline scheduler
- [x] 2.1 Добавить `Effect::DebouncePreview` и один pending request/deadline на панель в Application; единый explicit clock и deadline-aware `sleep_until` в select проверяют 39 ms без I/O и ровно один LoadPreview на 40 ms отдельно от 50-ms redraw tick.
- [x] 2.2 Добавить StartPreview с проверками debouncing, selected_location, preview generation/target, SessionEpoch, navigation_generation и session_matches_target; tests на равные epochs у разных hosts, Enter/Parent/SSH connect до deadline, MissedTickBehavior и editor resume не оставляют stale задач; failed Enter/Parent/SSH connect до и после deadline удаляют старый pending, сбрасывают debouncing и создают документированный immediate replacement для сохранённой selection.
- [x] 2.3 Перевести move_selection/toggle_select и все first/last/page/half-page/Repeat aliases на один path; input/scheduler tests доказывают ограниченное число pending/read задач без неограниченной очереди.
- [x] 2.4 Сохранить immediate initial/F3 и background вне debounce, quiet повторный selection и loading для медленного current request; named tests закрепляют отсутствие задержки на других путях.
- [x] 2.5 Сохранять same-target pending/quiet при background completion во время debounce, использовать immediate при changed selection и сбрасывать clone preview при `loading || debouncing`; tests покрывают background завершён/выполняется/изменил selection до и после deadline, отсутствие duplicate in-flight request и TogglePaneMode с сохранением source pending.
## 3. Приёмка навигации
- [x] 3.1 Разделить детерминированный headless запрет reads/loading и PTY: PTY подтверждает byte-level burst, остановку на итоговом target и terminal restore; raw loading count не является доказательством. Repeat/bounded workers проверяются input/scheduler tests. Обновить guideline/README/testing/spec matrix.
- [x] 3.2 Прогнать fmt, strict Clippy, полный tests/doc/PTY suite, зафиксировать числа и отсутствие `.snap.new`; пользовательский visual review подтверждает отсутствие мешающего мигания.
- [x] 3.3 Получить независимый verify через `rcom-tui-design` skill для ADDED requirement и всех девяти scenarios, устранить findings и повторить affected checks перед archive.
## Workflow follow-up
- После успешного verify синхронизировать ADDED `Коалесцирование preview при навигации` в main `file-navigation`, выполнить `openspec archive debounce-preview-navigation` и проверить archived result.
- `add-image-previews` должен использовать тот же scheduler для rapid image selection и не запускать workers на промежуточных строках.

View file

@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-05

View file

@ -0,0 +1,92 @@
# Design
## Context
См. `proposal.md`, delta `terminal-ui`, `docs/tui-design-guidelines.md` и `research_notes/Иконки и помощь rcom/help_ux.md`. Change применяется после icons и theme catalog/Theme Picker: это обязательный порядок для полного inventory, а не независимый apply. Текущий Help хранит только общий `overlay_scroll`, смешивает две независимые колонки и использует для page step размер активной панели. В inventory отсутствуют реальные Selection и часть context-specific команд. Task Details footer обещает `j/k Scroll`, но handler сначала меняет selected task.
## Goals / Non-Goals
**Goals:**
- Согласованные state, input и renderer с полным командным inventory.
- Одинаковые вычисления page geometry и scroll ranges на input и rendering.
- Читаемая широкая и минимальная 40×8 версии без цветовой зависимости.
- Discoverability помощи без постоянной нижней строки.
**Non-Goals:**
- Поиск/filter внутри help, context-sensitive-only help или menu→detail навигация.
- Workspace tabs; category tabs существуют только во время Help overlay.
- Общий input table rewrite ради visual redesign; coverage обеспечивается независимым inventory test.
- Изменение обычных workspace aliases вне Help/Task Details.
## Decisions
### 1. Help state и статический inventory
`HelpCategory` имеет фиксированный порядок Navigation, Selection, Files, Tasks, SSH, General. `AppState` хранит `HelpState { category, scroll }` либо эквивалентные отдельные поля. Открытие Help всегда начинает Navigation/0; смена категории делает scroll=0.
Статический inventory содержит category, stable action id, полный aliases text, нейтральное описание и context. Одно действие — одна логическая строка. Input matcher остаётся источником executable commands, а independently enumerated fixture проверяет каждый входной контекст: normal workspace, HostPicker, ThemePicker, Tasks, Task Details, Preview, Help, Destination/Confirmation/Collision, Entry Prompt/Confirmation, Undo/Editor и Quit confirmation. Collision `s/S/o/O`, quit `c/x`, Enter confirmation, ThemePicker `T` и printable editing описываются только в своём контексте. Case-sensitive `U`/`u`, `I` и `D`/`d` не сливаются. Список контекстов сам является частью coverage test; неизвестный новый handler без inventory должен провалить review.
### 2. Разделение horizontal/vertical navigation
`h`/Left/Shift-Tab и `l`/Right/Tab вызывают previous/next category с modulo wrap. Они не меняют scroll. `j/k` и arrows двигают на одну rendered line; page/half-page используют высоту help body. Vertical movement clamped.
Enter в Help не создаёт Command. Esc/`q`/`?`/F1 закрывают Help, F10 сохраняет quit. Category arrows/`h`/`l` и scroll принимают Press/Repeat; Tab/Shift-Tab, close и F10 — Press only; Release игнорируется. В Task Details `j/k`, Up/Down и paging направляются в scroll до task-selection branch, поэтому ни один вертикальный alias не меняет выбор за overlay; остальные task-list keys сохраняют исходное поведение.
### 3. Общий pure view model
`help_view_model(area, help_state, theme)` вычисляет:
- full tab strip либо compact `< N/6 Category >`;
- body rectangle и высоту;
- wrapped lines с description-column hanging indent;
- `total`, `max_scroll`, clamped offset и видимый диапазон;
- footer с переключением, прокруткой и закрытием.
Renderer использует модель без mutation. Input получает page/half-page из той же geometry, а не `active_page_size`. При input/resize сохранённый scroll нормализуется к `[0, max_scroll]`, чтобы повторный PageDown не оставлял скрытый большой offset; renderer дополнительно защищённо clamp.
Ниже 40×8 остаётся существующий terminal-too-small path.
### 4. Responsive rendering
Wide header показывает все шесть labels только если их measured widths помещаются; текущая категория получает brackets/marker и style. Иначе полный compact label с позицией, без инициалов и silent clipping.
Команды образуют один список с key column → description. Длинные aliases/descriptions переносятся с hanging indent, включая `l / Right / Enter`; permanent-delete warning не truncates. Последняя команда категории должна быть достижима при любом поддерживаемом viewport.
Overlay-local footers сохраняются. Они не являются удаляемой permanent workspace hint строкой.
### 5. Удаление hints и discoverability
`Layout.hints` и `render_hints` удаляются, а основная область получает освобождённую строку. Header на wide сохраняет режим и добавляет `? Help`; на narrow сначала удаляются subtitle/необязательные mode words, но `? Help` не исчезает. Status/errors не сокращаются ради старого hints inventory.
`?`/F1 остаются в General help и README. Первый запуск не показывает tutorial popup.
### 6. Проверки
- Per-category content/aliases и отсутствие внешних product names.
- Horizontal aliases/wrap/reset и vertical clamp с реальным body height.
- Все команды достижимы на 40×8 после wrapping/paging; повторный PageDown затем `k` действительно двигает вверх.
- Resize на first/middle/last offsets каждой категории, no panic и no render-order dependency.
- Full workspace isolation, Enter inert, F10 behavior и Task Details scroll.
- NO_COLOR/ASCII active category, snapshots и PTY close/reopen.
- Дизайнер и независимый tester используют `rcom-tui-design`; пользовательский visual review обязателен помимо automated PASS.
## Risks / Trade-offs
- [Не все команды видны одновременно] → позиция N/6, wrap categories, полная reachability tests и нейтральный header affordance.
- [Scroll/input расходятся после resize] → одна pure geometry модель и нормализация offset на обеих границах.
- [Inventory устареет относительно input] → independently enumerated bindings и stable action IDs вместо snapshot-only проверки.
- [Удаление hints ухудшит discoverability] → `? Help` виден всегда, General содержит обе entry aliases, README обновлён.
- [Исправление Task Details меняет старое скрытое selection] → это требуемый bugfix с named regression, другие task-list commands не меняются.
## Migration Plan
1. Ввести inventory/help state и failing coverage/interaction tests.
2. Реализовать pure view model, tabs и narrow rendering.
3. Переключить input/page geometry, исправить Task Details.
4. Удалить hints row и добавить responsive `? Help`.
5. Обновить snapshots/docs, выполнить полный suite, design review и независимый verify.
6. Синхронизировать MODIFIED `terminal-ui` и архивировать change.
Откат восстанавливает прежний overlay и layout, не затрагивая файлы или SSH.

View file

@ -0,0 +1,33 @@
# Proposal
## Why
Текущая помощь перегружена двумя независимыми колонками, смешанными действиями и названием `HELP · yazi + mc`; часть существующих команд отсутствует, а узкий viewport требует длинной прокрутки. Постоянная нижняя строка hints дополнительно отнимает место у содержимого. Нужна спокойная справка по задачам и явная, но компактная discoverability.
## What Changes
- Полностью удалить постоянную нижнюю строку key hints и отдать её высоту рабочей области; в существующем header на всех поддерживаемых размерах сохранить текстовый `? Help` affordance.
- Переделать help в шесть локальных category tabs: **Navigation, Selection, Files, Tasks, SSH, General**, с одним списком «клавиши → действие» и без упоминаний yazi/mc.
- Зафиксировать клавиши: `h`/Left/Shift-Tab — предыдущая категория, `l`/Right/Tab — следующая с wrap; `j/k`, arrows, page и half-page прокручивают только содержимое с clamp. Смена категории и новое открытие сбрасывают scroll.
- Показывать одно действие на логическую строку, все aliases с сохранением регистра и hanging wrap; Trash и permanent delete/`NO UNDO` должны оставаться явно различимыми. Enter в help ничего не выполняет.
- На узком терминале заменять переполненный tab strip на `< N/6 Category >`; полный label, позиция, switching и close controls остаются видимыми. Page size вычисляется по фактической высоте help body.
- Сохранить `?`/F1/Esc/`q` для закрытия help и F10 для quit, не изменяя панели/selection/clipboard; задачи и SSH имеют собственные context labels.
- Исправить раскрытое исследованием противоречие Task Details: `j/k`, Up/Down и paging в details прокручивают содержимое, а не незаметно выбирают задачу за overlay. Category/scroll aliases принимают Press/Repeat; Tab/Shift-Tab и close/quit — Press only, Release игнорируется.
- Добавить полную inventory команд, deterministic reachability/resize/NO_COLOR/ASCII tests и independent review через `rcom-tui-design`.
## Capabilities
### New Capabilities
Нет.
### Modified Capabilities
- `terminal-ui`: меняются встроенная справка и адаптивная раскладка: категорийная keyboard-only помощь, удаление permanent hints и responsive discoverability.
## Impact
- Небольшое явное help state и commands в `src/app`/`src/input`, help-specific page geometry в `src/tui`/`src/ui`.
- Static command inventory, новый single-column renderer в `src/ui/render.rs`, удаление hints из `src/ui/layout.rs` и добавление `? Help` в header.
- Обновление UI snapshots, accessibility/input/PTY tests, README, guideline и spec matrix.
- Новых dependencies и filesystem/SSH behavior изменений нет; workspace tabs в scope не входят. Change применяется после `add-file-type-icons-and-colors` и `add-color-theme-presets`, поскольку полный inventory включает уже существующий Theme Picker.

View file

@ -0,0 +1,65 @@
# Spec Delta
## MODIFIED Requirements
### Requirement: Адаптивная раскладка
Система SHALL перераспределять пространство без наложения текста и интерактивных областей при изменении размера терминала. Постоянная нижняя строка key hints MUST отсутствовать, а её высота SHALL использоваться рабочим содержимым. Текстовый вход в помощь MUST оставаться видимым в header на каждом поддерживаемом размере.
#### Scenario: Широкая однопанельная раскладка
- **WHEN** доступной ширины достаточно для списка и предпросмотра
- **THEN** активная панель показывает обе области одновременно
#### Scenario: Широкая двухпанельная раскладка
- **WHEN** ширины терминала достаточно для двух панелей
- **THEN** две равные панели используют всю основную ширину, а постоянное предпросмотр не отображается
#### Scenario: Двухпанельная раскладка средней ширины
- **WHEN** для полных метаданных в двух панелях недостаточно места
- **THEN** обе панели сохраняются с компактными колонками, а постоянное предпросмотр не появляется
#### Scenario: Очень узкий терминал
- **WHEN** две панели невозможно отобразить читаемо
- **THEN** показывается только активная панель с индикатором двухпанельного режима, а переключение панели остаётся доступным
#### Scenario: Слишком маленькая высота
- **WHEN** высота недостаточна для основного интерфейса
- **THEN** показывается компактное предупреждение о размере вместо повреждённой раскладки
#### Scenario: Освобождение места от постоянных подсказок
- **WHEN** отображается обычный workspace на любом поддерживаемом размере
- **THEN** отдельная нижняя строка hints отсутствует, а header содержит `? Help`; контекстные команды внутри overlays и состояний сохраняются
### Requirement: Встроенная справка
Система SHALL показывать по `?` и `F1` читаемую справку со всеми активными командами и aliases, сгруппированными в Navigation, Selection, Files, Tasks, SSH и General. Справка MUST быть keyboard-only, не содержать названий других файловых менеджеров и MUST NOT выполнять файловые действия при чтении.
#### Scenario: Справка поверх любой раскладки
- **WHEN** пользователь открывает справку
- **THEN** отображается читаемый слой с командами и способом закрытия, не меняя состояние панелей
#### Scenario: Справка по новым действиям
- **WHEN** пользователь читает раздел файловых действий
- **THEN** видны create/rename/trash/permanent delete/undo/editor клавиши и различие trash от необратимого удаления
#### Scenario: Переключение категорий
- **WHEN** пользователь нажимает `h`/Left/Shift-Tab либо `l`/Right/Tab
- **THEN** выбирается предыдущая либо следующая категория с wrap, выделенный label отмечен не только цветом, а scroll сбрасывается к началу
#### Scenario: Прокрутка категории
- **WHEN** пользователь использует `j/k`, Up/Down, PageUp/PageDown, Ctrl-b/Ctrl-f или Ctrl-u/Ctrl-d
- **THEN** содержимое прокручивается на строку, фактический viewport либо его половину без выхода за границы, а горизонтальные клавиши не прокручивают текст
#### Scenario: Полный и нейтральный список команд
- **WHEN** пользователь последовательно просматривает все шесть категорий
- **THEN** каждая активная команда и alias доступны с исходным регистром и явным контекстом: workspace, HostPicker, ThemePicker, Tasks/Task Details, Preview, Help, operation/collision/entry/quit confirmations и prompts; несвязанные действия не объединяются, названия yazi/mc отсутствуют, а Trash и permanent delete с `NO UNDO` различимы
#### Scenario: Узкая справка
- **WHEN** полный tab strip не помещается либо открыт размер 40×8
- **THEN** показывается компактный `< N/6 Category >`, описания переносятся с hanging indent без потери aliases, а диапазон, switching, scrolling и close controls остаются доступными
#### Scenario: Закрытие и read-only поведение
- **WHEN** пользователь нажимает Esc, `q`, `?` или F1
- **THEN** help закрывается с сохранением всего workspace; Enter ничего не выполняет, а F10 сохраняет существующее поведение quit
#### Scenario: Прокрутка Task Details
- **WHEN** открыты подробности задачи и пользователь нажимает `j/k`, Up/Down либо paging keys
- **THEN** прокручиваются именно подробности, а выбор задачи за overlay и остальной workspace не меняются; Press/Repeat обрабатываются по документированной input policy, а Release игнорируется

View file

@ -0,0 +1,32 @@
# Tasks
## 1. Полный inventory и состояние Help
- [x] 1.1 Ввести фиксированные шесть Help categories, startup Navigation/0 и статический inventory со stable action IDs, aliases, descriptions и contexts; unit tests покрывают порядок и отсутствие yazi/mc/product references.
- [x] 1.2 Независимо перечислить все действующие input contexts и bindings, включая workspace, HostPicker, ThemePicker, Tasks/Details, Preview, Help, operation/collision/entry/quit confirmations и prompts; tests сравнивают их с inventory, проверяют collision `s/S/o/O`, quit `c/x`, confirmation Enter, исходный регистр и отсутствие неучтённого контекста.
- [x] 1.3 Обновить `docs/spec-matrix.md` с named inventory tests и `docs/tui-design-guidelines.md`, если реализация inventory выявит уточнения; никаких executable actions из Help не добавляется.
## 2. Category navigation и прокрутка
- [x] 2.1 Добавить previous/next category commands для `h`/Left/Shift-Tab и `l`/Right/Tab с wrap и scroll reset; reducer/input tests сохраняют workspace и проверяют Press/Repeat для arrows/`h`/`l`, Press-only Tab/Shift-Tab/close/F10 и игнорирование Release.
- [x] 2.2 Реализовать общий pure help view model с body geometry, hanging wrap, max_scroll и нормализацией offset при input/resize; tests ловят raw-offset accumulation и зависимость от render order.
- [x] 2.3 Направить `j/k`, arrows, page и half-page на фактическую help body высоту с clamp; tests проверяют все aliases на wide и 40×8, а Enter остаётся inert.
- [x] 2.4 Исправить Task Details так, чтобы `j/k`, Up/Down и paging прокручивали details до task-selection branch; named regressions доказывают неизменный selected task для каждого вертикального alias, Press/Repeat scrolling и исходное закрытие/details navigation.
## 3. Новый визуальный слой и workspace
- [x] 3.1 Отрендерить `HELP`, wide category strip с non-color active marker и одну key→description колонку; snapshots/full-Buffer tests проверяют спокойную плотность, aliases wrapping и destructive warnings.
- [x] 3.2 Добавить compact `< N/6 Category >` при overflow и на 40×8, видимый range/switch/scroll/footer; reachability tests собирают все категории постранично без потери последней команды.
- [x] 3.3 Удалить постоянную hints row, отдать высоту workspace и добавить responsive `? Help` в header без сокращения errors; layout/geometry tests и существующие operation UI assertions обновляются по фактическому поведению.
- [x] 3.4 Проверить Esc/`q`/`?`/F1 close, F10 quit, NO_COLOR/ASCII и PTY close/reopen; осознанно обновить snapshots и сохранить terminal lifecycle.
## 4. Приёмка
- [x] 4.1 Обновить README, `docs/testing.md`, guideline, spec matrix и acceptance для всех MODIFIED scenarios; strict OpenSpec и named-test consistency должны пройти, `.snap.new` отсутствуют.
- [x] 4.2 Прогнать fmt, strict Clippy, полный tests/doc/PTY suite и зафиксировать числа; дизайнерский review предоставляет wide и 40×8 frames для пользовательского визуального verdict.
- [x] 4.3 Получить независимый verify через `rcom-tui-design` skill, устранить CRITICAL/WARNING и повторить affected quality checks перед archive.
## Workflow follow-up
- Не применять до завершения `add-file-type-icons-and-colors` и `add-color-theme-presets`: полный inventory должен включать существующий Theme Picker.
- После успешного verify синхронизировать оба MODIFIED requirements в main `terminal-ui`, выполнить `openspec archive redesign-help-and-remove-hints` и проверить archived result.

View file

@ -118,3 +118,42 @@
#### Scenario: Каталог недоступен
- **WHEN** переход завершился ошибкой прав доступа, сети или отсутствия каталога
- **THEN** прежнее открытое расположение сохраняется, а панель показывает понятную ошибку и позволяет повторить действие
### Requirement: Коалесцирование preview при навигации
Система SHALL откладывать preview чтение при быстром пользовательском selection movement на короткий bounded interval и запускать только current запрос. Промежуточные строки MUST NOT вызывать повторяющийся `LOADING PREVIEW`/reading-flash, а старый preview MUST NOT показываться для нового выбора.
#### Scenario: Быстрая навигация без мигания
- **WHEN** пользователь несколько раз подряд меняет выбор до истечения debounce
- **THEN** для каждой промежуточной строки не запускается preview read и не появляется `LOADING PREVIEW`; область остаётся спокойной, а заголовок соответствует текущему выбору
#### Scenario: Один запрос после остановки
- **WHEN** debounce истёк после последнего selection change
- **THEN** запускается ровно один preview request для текущего target/generation/endpoint, а не серия запросов для пройденных строк
#### Scenario: Stale preview и stale response
- **WHEN** выбор изменился до завершения предыдущего preview чтения
- **THEN** прежнее содержимое не показывается для нового выбора, а старый response отбрасывается по generation/target/SessionEpoch без изменения текущего кадра
#### Scenario: Сохранение других режимов
- **WHEN** выполняется initial listing, ручной F3 или background refresh того же элемента вне active selection debounce
- **THEN** используются существующие immediate/foreground/background semantics без добавления debounce задержки или повторного мигания
#### Scenario: Все формы selection movement
- **WHEN** используются `j/k`, arrows, first/last, page/half-page или multi-select advance
- **THEN** все они используют одинаковый debounce path, а число pending/read задач остаётся ограниченным при удержании клавиши
#### Scenario: Background listing во время debounce
- **WHEN** same-target background listing завершается до истечения active selection debounce
- **THEN** существующий pending request и quiet кадр сохраняются без преждевременного read/loading; если background изменил selection, используется immediate foreground current load
#### Scenario: Navigation во время debounce
- **WHEN** до deadline начался переход либо SSH connect
- **THEN** старый pending request отклоняется по navigation identity и полному host/session guard; при ошибке перехода/connect создаётся новый immediate current preview request для сохранённой selection с новой generation, а quiet state не остаётся без scheduler owner
#### Scenario: Включение dual во время debounce
- **WHEN** до deadline включается dual
- **THEN** клон получает preview reset при `loading || debouncing`, а исходная панель сохраняет свой pending/deadline и запускает ровно один current request
#### Scenario: Медленное чтение после debounce
- **WHEN** current preview request начался, но не завершается быстро
- **THEN** понятный индикатор загрузки разрешён после debounce и не скрывает ввод или другую панель; новый selection change снова переводит preview в quiet debounce состояние

View file

@ -42,7 +42,7 @@
- **THEN** вторичное состояние закрывается без изменения текущего каталога
### Requirement: Визуальная иерархия
Система SHALL показывать заголовок расположения, источник local/SSH, список, выбор, активность панели и нижнюю строку статуса; активность MUST различаться не только цветом.
Система SHALL показывать заголовок расположения, источник local/SSH, список, выбор, активность панели и нижнюю строку статуса; активность MUST различаться не только цветом. Типы элементов SHALL иметь детерминированные иконки и semantic colors, а glyph, стиль иконки, стиль имени и состояние строки MUST задаваться независимо. Специальный шрифт MUST NOT быть обязательным.
#### Scenario: Две панели
- **WHEN** отображаются две панели
@ -50,14 +50,38 @@
#### Scenario: Выбранный элемент
- **WHEN** список содержит выбранный элемент
- **THEN** он выделен контрастным фоном и маркером, а типы элементов различимы текстовыми обозначениями
- **THEN** он выделен контрастным фоном и маркером, а типы элементов различимы иконками без избыточного `TYPE` либо текстовыми обозначениями в icons-off
#### Scenario: Терминал без расширенных цветов
- **WHEN** терминал не поддерживает полную палитру или установлен `NO_COLOR`
- **THEN** структура, фокус и выбор остаются различимы за счёт текста, рамок и фона
#### Scenario: Разные иконки для разных типов
- **WHEN** список содержит каталоги, generic files, известные точные имена, файлы с известными расширениями, links и executables
- **THEN** они получают различимые иконки соответствующих типов в списке и заголовке preview, включая отдельную Rust-иконку для `.rs`, а неизвестный тип получает generic fallback
#### Scenario: Детерминированный приоритет правил
- **WHEN** элемент одновременно соответствует нескольким правилам или отличается только регистром имени/расширения
- **THEN** результат определяется документированным порядком glob override, directory name, exact filename, extension и metadata fallback с явной case policy; обычные file/extension rules не применяются к каталогам
#### Scenario: Semantic цвета имени и иконки
- **WHEN** включена цветовая тема с поддержкой file-type classes
- **THEN** иконка и имя могут иметь разные согласованные цвета, а directories, executables, media, documents, archives и links используют устойчивые semantic классы без радуги несвязанных оттенков имени
#### Scenario: Selection и состояния операций
- **WHEN** строка является текущей, marked, copied, cut, symlink или находится в неактивной панели
- **THEN** состояние остаётся различимым не только по hue, а icon/name styling не скрывает selection и критические markers
#### Scenario: Режимы шрифта и отключение иконок
- **WHEN** пользователь выбрал persistent или временный режим `unicode`, `nerd`, `ascii` либо `none`
- **THEN** приложение использует соответствующий glyph set, CLI имеет приоритет над сохранённой настройкой, terminal ASCII fallback никогда не включает `none` обратно, при включённых иконках избыточная колонка `TYPE` удаляется, а `DIR`/`FILE`/`LINK`/`OTH` сохраняются в `none`, а отсутствие Nerd Font не приводит к обязательным private-use квадратам
#### Scenario: Иконки в узкой панели
- **WHEN** ширины недостаточно для полной строки с иконкой и metadata
- **THEN** вторичные metadata удаляются раньше basename, иконка не нарушает выравнивание, а truncation сохраняет имя и по возможности расширение
### Requirement: Адаптивная раскладка
Система SHALL перераспределять пространство без наложения текста и интерактивных областей при изменении размера терминала.
Система SHALL перераспределять пространство без наложения текста и интерактивных областей при изменении размера терминала. Постоянная нижняя строка key hints MUST отсутствовать, а её высота SHALL использоваться рабочим содержимым. Текстовый вход в помощь MUST оставаться видимым в header на каждом поддерживаемом размере.
#### Scenario: Широкая однопанельная раскладка
- **WHEN** доступной ширины достаточно для списка и предпросмотра
@ -79,6 +103,9 @@
- **WHEN** высота недостаточна для основного интерфейса
- **THEN** показывается компактное предупреждение о размере вместо повреждённой раскладки
#### Scenario: Освобождение места от постоянных подсказок
- **WHEN** отображается обычный workspace на любом поддерживаемом размере
- **THEN** отдельная нижняя строка hints отсутствует, а header содержит `? Help`; контекстные команды внутри overlays и состояний сохраняются
### Requirement: Системные состояния
Система SHALL различать загрузку, пустой каталог, отсутствие предпросмотра, предупреждение и ошибку, не представляя их как пустой успешный результат. Фоновое обновление уже показанного каталога MUST сохранять его текущий кадр до завершения запроса и MUST NOT периодически подменять содержимое или строку статуса индикатором загрузки.
@ -103,7 +130,7 @@
- **THEN** индикатор загрузки сохраняется до применения результата независимо от режима background polling
### Requirement: Встроенная справка
Система SHALL показывать по `?` и `F1` справку с обеими схемами клавиш, сгруппированными по навигации, панелям, файловым действиям, редактору и подключениям.
Система SHALL показывать по `?` и `F1` читаемую справку со всеми активными командами и aliases, сгруппированными в Navigation, Selection, Files, Tasks, SSH и General. Справка MUST быть keyboard-only, не содержать названий других файловых менеджеров и MUST NOT выполнять файловые действия при чтении.
#### Scenario: Справка поверх любой раскладки
- **WHEN** пользователь открывает справку
@ -113,6 +140,29 @@
- **WHEN** пользователь читает раздел файловых действий
- **THEN** видны create/rename/trash/permanent delete/undo/editor клавиши и различие trash от необратимого удаления
#### Scenario: Переключение категорий
- **WHEN** пользователь нажимает `h`/Left/Shift-Tab либо `l`/Right/Tab
- **THEN** выбирается предыдущая либо следующая категория с wrap, выделенный label отмечен не только цветом, а scroll сбрасывается к началу
#### Scenario: Прокрутка категории
- **WHEN** пользователь использует `j/k`, Up/Down, PageUp/PageDown, Ctrl-b/Ctrl-f или Ctrl-u/Ctrl-d
- **THEN** содержимое прокручивается на строку, фактический viewport либо его половину без выхода за границы, а горизонтальные клавиши не прокручивают текст
#### Scenario: Полный и нейтральный список команд
- **WHEN** пользователь последовательно просматривает все шесть категорий
- **THEN** каждая активная команда и alias доступны с исходным регистром и явным контекстом: workspace, HostPicker, ThemePicker, Tasks/Task Details, Preview, Help, operation/collision/entry/quit confirmations и prompts; несвязанные действия не объединяются, названия yazi/mc отсутствуют, а Trash и permanent delete с `NO UNDO` различимы
#### Scenario: Узкая справка
- **WHEN** полный tab strip не помещается либо открыт размер 40×8
- **THEN** показывается компактный `< N/6 Category >`, описания переносятся с hanging indent без потери aliases, а диапазон, switching, scrolling и close controls остаются доступными
#### Scenario: Закрытие и read-only поведение
- **WHEN** пользователь нажимает Esc, `q`, `?` или F1
- **THEN** help закрывается с сохранением всего workspace; Enter ничего не выполняет, а F10 сохраняет существующее поведение quit
#### Scenario: Прокрутка Task Details
- **WHEN** открыты подробности задачи и пользователь нажимает `j/k`, Up/Down либо paging keys
- **THEN** прокручиваются именно подробности, а выбор задачи за overlay и остальной workspace не меняются; Press/Repeat обрабатываются по документированной input policy, а Release игнорируется
### Requirement: Безопасное владение терминалом
Система SHALL восстанавливать курсор, режим терминала и экран при штатном выходе, перед внешним редактором, после него и при обрабатываемой критической ошибке.
@ -123,3 +173,66 @@
#### Scenario: Возврат из внешнего редактора
- **WHEN** editor завершается успешно, с ошибкой или отменой
- **THEN** TUI заново инициализирует terminal state и показывает прежние панели, selection и актуальные задачи без повреждённого ввода/вывода
### Requirement: Цветовые темы
Система SHALL предоставлять 20 встроенных тем со стабильными IDs, именами и dark/light metadata: native Night Ops и 19 curated imports. Тема SHALL выбираться persistent настройкой, временным CLI override или Theme Picker с live preview и подтверждением без изменения layout, keyboard behavior или textual markers, а runtime MUST NOT обращаться к сети или исполнять theme code.
#### Scenario: Тема по умолчанию
- **WHEN** пользователь не задал настройку темы
- **THEN** используется существующая Night Ops: базовые background/panel/text/accents/file-type RGB не меняются, а muted/selection/selection_text имеют зафиксированную accessibility-коррекцию до общих contrast targets
#### Scenario: Просмотр catalog
- **WHEN** пользователь запускает `--list-themes`
- **THEN** без входа в TUI выводятся ровно 20 тем со стабильными IDs, display names и dark/light режимами: 11 dark и 9 light
#### Scenario: Persistent и временный выбор
- **WHEN** пользователь задал встроенный theme ID в общем config либо передал `--theme <id>`
- **THEN** сохранённая тема применяется при следующих запусках, а CLI override действует только на текущий запуск и имеет приоритет
#### Scenario: Live preview в Theme Picker
- **WHEN** пользователь открыл picker по `T` и меняет выбор через `j/k` или Up/Down
- **THEN** выбранная тема немедленно применяется ко всему интерфейсу для оценки, текущая при открытии тема сохраняется как rollback baseline, а config остаётся неизменным
#### Scenario: Порядок и границы Theme Picker
- **WHEN** пользователь листает темы через `j/k` или Up/Down, включая Press/Repeat и первую/последнюю запись
- **THEN** используется тот же display-name order, что в `--list-themes`, выбор clamped к catalog границам, а F10 через Press-only использует существующий quit path без записи config
#### Scenario: Responsive Theme Picker
- **WHEN** picker открыт на 40×8, 80×24, 120×40, в NO_COLOR или ASCII
- **THEN** выбранная строка имеет non-color marker и позицию `N/20`, остаётся в viewport при навигации, все 20 тем достижимы, а Enter/Esc controls и ошибка сохранения не перекрываются и не обрезают critical actions
#### Scenario: Отмена live preview
- **WHEN** пользователь нажимает Esc после любого числа preview
- **THEN** восстанавливается тема, которая была при открытии picker, picker закрывается, а config и его другие поля не изменяются
#### Scenario: Подтверждение темы
- **WHEN** пользователь нажимает Enter на выбранной теме
- **THEN** только theme ID атомарно сохраняется в config с сохранением остальных настроек, picker закрывается с новой темой; при ошибке записи показывается ошибка без automatic retry или скрытого постоянного выбора
#### Scenario: Неизвестная тема
- **WHEN** config или CLI содержит unknown ID
- **THEN** запуск сообщает понятную ошибку и доступные IDs до входа в alternate screen, без создания/перезаписи пользовательского config
#### Scenario: Semantic применение темы
- **WHEN** выбрана любая встроенная тема
- **THEN** panels, text, muted, active, secondary, errors, selection и file-type classes получают согласованные semantic colors, а геометрия, selection markers и keyboard commands не меняются
#### Scenario: Читаемый selection
- **WHEN** исходная или derived цветовая пара не удовлетворяет проектным contrast targets на panel/background либо effective selection surface
- **THEN** применяется задокументированный deterministic fallback для текста, filename, icons и markers; проверка использует итоговые fg/bg/modifiers после state composition, а accepted themes не могут её обойти
#### Scenario: Ограниченный терминал
- **WHEN** установлен `NO_COLOR`, выбран ASCII или icons-off режим
- **THEN** структура и состояния остаются различимыми независимо от выбранной темы, а decorative RGB/Nerd Font не становятся обязательными
#### Scenario: Проверка всех тем
- **WHEN** тема включается в release catalog
- **THEN** для неё проходят representative normal/muted/active/current/selected/marked/copied/cut/error/warning/help/dialog/tasks/preview/file-type fixtures, включая selected комбинации на focused/inactive surfaces, и пользовательский visual review; результаты не выдаются за универсальный контраст чужой terminal palette
#### Scenario: Provenance и лицензии
- **WHEN** тема импортируется из внешнего catalog
- **THEN** manifest содержит pinned source commit/file/hash, автора, upstream и license, репозиторий включает необходимые copyright/permission notices, а отсутствие явной разрешённой лицензии блокирует import
#### Scenario: Автономный runtime
- **WHEN** пользователь выбирает и применяет встроенную тему
- **THEN** используются только встроенные static данные без сети, kitty subprocess, shell или исполнения внешнего theme/config кода

View file

@ -0,0 +1,106 @@
# rcom превращает иконки, помощь и темы в систему
Главный вывод: rcom нужна не косметическая раскраска, а единая semantic-модель, в которой glyph, цвет иконки, стиль имени и состояние строки независимы, справка организована по задачам, а все темы проходят одинаковые проверки. **Для иконок рационально взять за образец архитектуру Yazi, а для сдержанных filename colors — semantic-палитру Ranger**, не копируя их конфигурацию и не делая Nerd Font обязательным. Перегруженную помощь предлагается заменить шестью keyboard-only вкладками — Navigation, Selection, Files, Tasks, SSH и General — с одним списком «клавиши → действие», полными aliases и отдельной политикой для узкого терминала. Постоянную нижнюю строку hints следует удалить, но оставить видимый `? Help` в header на всех поддерживаемых размерах. Будущий каталог составляет **ровно 20 тем: native Night Ops плюс 19 импортов из официального kitty-репозитория, 11 dark и 9 light**, включая Dracula и Catppuccin Mocha/Latte. Для сравнения, закреплённый снимок официальной коллекции kitty содержит **459 тем**, поэтому небольшой каталог rcom является осознанной кураторской выборкой, а не попыткой воспроизвести upstream целиком ([официальная документация kitty](https://sw.kovidgoyal.net/kitty/kittens/themes/), [pinned `themes.json`](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes.json)). Ниже факты о чужих программах и текущем rcom явно отделены от предлагаемого поведения; OpenSpec tasks остаются невыполненными, поэтому это план, а не утверждение о готовой реализации.
## Yazi задаёт архитектуру иконок, Ranger — сдержанную палитру
**Факты.** В стабильной документации **Yazi 26.9.1** выбор иконки и стиль имени разделены: `[icon]` задаёт текст glyph и необязательный собственный `fg`, а `[filetype].rules` независимо раскрашивает имя по URL, MIME и metadata. Приоритет иконок — `globs → dirs → files → exts → conds`; имена каталогов, файлов и расширений используют hash maps с O(1) lookup, тогда как globs выполняются первыми и стоят дороже. Из этого следует важное поведение: известное имя или расширение побеждает условия `link` и `exec`, поэтому symlink с именем `main.rs` сохраняет Rust-иконку, а не получает generic link glyph ([документация `[icon]`](https://yazi-rs.github.io/docs/configuration/theme/#icon), [реализация resolver](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/src/theme/icon.rs)). В shipped dark preset каталоги имеют синее имя, folder glyph — cyan `#03a9f4`, Rust glyph — `#dea584`; в light preset Rust использует `#6f5242`. Это примеры текущего preset, а не гарантия одинакового вида любой пользовательской конфигурации ([dark preset](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-dark.toml), [light preset](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-light.toml)).
Ranger, напротив, нативно раскрашивает преимущественно **semantic/inode-классы**, а не языки программирования. Его `default` scheme назначает каталогам bright blue и bold, executables — bright green и bold, изображениям — yellow, audio/video — magenta, архивам — red, valid links — cyan и broken links — magenta; отдельного правила для `.rs` нет. Классификация MIME-категорий преимущественно основана на имени и системной MIME-базе, а не на чтении содержимого через `file(1)` ([Ranger `default.py`](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/colorschemes/default.py#L23-L59), [классификация `fsobject.py`](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/container/fsobject.py#L219-L245)). Встроенного каталога per-file icons в Ranger нет: официальная wiki ссылается на сторонние `ranger_devicons` и `ranger-devicons2`, оба требуют Nerd Font; их fallback означает generic glyph для неизвестного типа, но не автоматический переход на plain text при отсутствии шрифта ([Ranger Plugins wiki](https://github.com/ranger/ranger/wiki/Plugins), [`ranger_devicons`](https://github.com/alexanderjeurissen/ranger_devicons/blob/1bcaff0366a9d345313dc5af14002cfdcddabb82/README.md), [`ranger-devicons2`](https://github.com/cdump/ranger-devicons2/blob/94bdcc19218681debb252475fd9d11cfd274d9b1/README.md)). Yazi также рекомендует, но не требует Nerd Font и позволяет полностью очистить icon rules; официального надёжного определения font capability нет ([installation](https://yazi-rs.github.io/docs/installation/), [FAQ об отключении иконок](https://yazi-rs.github.io/docs/faq/#dont-like-nerd-fonts)).
**Предложение для rcom.** Чистый resolver без filesystem I/O и content sniffing должен работать по фиксированному каскаду. Известная Rust-иконка может сохраняться у executable или symlink, но критическое состояние обязано оставаться отдельным маркером; unknown тип получает generic file/folder. Case-sensitive exact-правило допускается до ASCII-lowercase lookup, а duplicate и first-match semantics должны быть документированы, а не зависеть от порядка инициализации таблиц.
| Приоритет | Предлагаемое правило rcom | Практический смысл |
|---:|---|---|
| 1 | Небольшой ordered список glob overrides, first match | Явные исключения без glob-heavy common path |
| 2 | Exact directory name | Отдельные `.git`, `.github`, Downloads и другие значимые каталоги |
| 3 | Exact filename | `Cargo.toml`, `Cargo.lock`, `README*`, `.gitignore`, `Dockerfile`, `Makefile` до generic extension |
| 4 | Final extension с явной case policy | `.rs` и распространённые code/config/document/media/archive типы через быстрый map |
| 5 | Metadata: broken link → link → special inode → directory → executable → generic file | Предсказуемый fallback без потери `@`, `!`, `*` и текстового типа |
Стартовая Night Ops-палитра должна быть спокойной: **directories — blue/cyan, executables — green, valid links — cyan, broken links — red/magenta плюс `!`, images — yellow, audio/video — magenta, archives — red, documents — cyan или neutral, Rust — отдельный rust/orange glyph**. Богатые per-extension оттенки лучше оставить иконкам, а не превращать имена всех файлов в радугу. Цвет иконки не перекрашивает имя автоматически: например, orange Rust glyph может соседствовать с обычным `main.rs`, тогда как executable name остаётся green. Для режимов предлагаются `unicode` по умолчанию, opt-in `nerd`, `ascii` и `none`; persistent `icons = "unicode"` в общем `config.toml` сочетается с временным `--icons unicode|nerd|ascii|none`, а `$TERM` не выдаётся за доказательство наличия Nerd Font. Эти решения зафиксированы в [OpenSpec change `add-file-type-icons-and-colors`](../openspec/changes/add-file-type-icons-and-colors/), включая [design](../openspec/changes/add-file-type-icons-and-colors/design.md) и [delta spec](../openspec/changes/add-file-type-icons-and-colors/specs/terminal-ui/spec.md).
Доступность является частью resolver, а не последующей полировки. Current row получает контрастный background/reverse и стабильный маркер; marked, copied и cut имеют собственные обозначения; broken link не зависит от красного hue, а icons-off сохраняет текстовые `DIR`/`FILE`/`LINK` и state markers. На selected row произвольный RGB glyph либо заменяется проверенным selection color, либо сохраняется только после измеренной проверки контраста. `NO_COLOR`, ASCII и icons-off не должны стирать focus, selection или ошибки. В width budget сначала исчезают symlink target и вторичные metadata, затем сокращаются колонки; icon и basename сохраняются как можно дольше, middle truncation по возможности сохраняет расширение. Table-driven tests должны покрыть exact name против extension, case variants, known-name symlink, executable `.rs`, broken link, glob override и unknown fallback; full-Buffer tests дополнительно проверяют стили и ширину, а benchmark большого synthetic listing — отсутствие дорогого glob-пути для обычных файлов.
## Шесть вкладок заменяют 33 строки перегруженной помощи
**Факты о текущем rcom.** Help сейчас называется `HELP · yazi + mc`, на ширине от 70 колонок смешивает команды в двух независимо выровненных колонках, а ниже этого порога превращается в документ из **33 логических строк**. Selection и часть clipboard/context-specific команд отсутствуют, несвязанные действия объединены через `|`, а page size вычисляется по высоте активной панели, а не фактического help body ([renderer](/home/vrubel/services/rcom/src/ui/render.rs#L652-L794), [snapshot 40×8](/home/vrubel/services/rcom/tests/snapshots/ui_accessibility__snapshot_help_scrolled_40x8.snap#L5-L11), [event loop](/home/vrubel/services/rcom/src/tui.rs#L107-L119)). Действующая main spec ещё требует обе схемы клавиш и упоминает их происхождение, тогда как предлагаемый delta заменяет это требованием полного нейтрального inventory без названий других файловых менеджеров ([main `terminal-ui`](../openspec/specs/terminal-ui/spec.md), [help delta](../openspec/changes/redesign-help-and-remove-hints/specs/terminal-ui/spec.md)). Yazi действительно группирует quick-start по Navigation, Selection, File operations и Task manager, а ranger предоставляет руководство по `?`; однако источники **не доказывают**, что эти программы используют предлагаемые category tabs, их responsive layout или выбранные клавиши переключения ([Yazi quick start](https://yazi-rs.github.io/docs/quick-start/), [ranger manual](https://raw.githubusercontent.com/ranger/ranger/master/doc/ranger.pod)). Поэтому tabs — самостоятельное проектное решение rcom, а не заявленная имитация.
**Оценка вариантов.** Один непрерывный single-column документ проще реализовать и остаётся приемлемой lightweight-альтернативой, но полный inventory сделает его длиннее нынешних 33 строк и потребует section jumps. Search/filter добавляет text-entry mode и конфликты printable keys без необходимости для нескольких десятков действий; menu → detail создаёт лишний уровень навигации; context-sensitive-only help не может служить полной стабильной справкой. **Шесть вкладок над одним списком предпочтительны**: каждая категория образует небольшой рабочий набор, порядок чтения однозначен, а на 40 колонках strip естественно заменяется компактным переключателем. Плата за это — невозможность увидеть все команды одновременно, поэтому позиция `N/6`, wrap, reachability tests и полный inventory обязательны.
| Категория | Предлагаемое содержимое |
|---|---|
| **Navigation** | Cursor, parent/open, first/last, page/half-page, local home |
| **Selection** | Toggle, visual mode, select all, invert, clear; clipboard сюда не переносится |
| **Files** | Yank/cut/paste, copy/move в другую панель, create, rename, restorable trash, permanent delete/`NO UNDO`, undo, external editor |
| **Tasks** | Открытие/закрытие, выбор, details, cancel и прокрутка с явным context |
| **SSH** | Host picker, буквальный ввод filter, Backspace, выбор/connect и close |
| **General** | Активная панель и single/dual layout, hidden files, refresh, preview, error details, help, close/quit |
Отдельная седьмая вкладка Panes не нужна: её небольшой набор логично находится в General. Заголовок остаётся просто **`HELP`**. На широком экране показывается `[Navigation] Selection Files Tasks SSH General`, если измеренные display widths действительно помещаются; активная категория различима скобками или маркером без цвета. Ниже каждая логическая строка содержит ровно одно действие и две содержательные колонки — keys и description. Aliases сохраняют регистр (`U` против `u`, `I`, `D` против `d`), а длинные наборы вроде `l / Right / Enter` переносятся с hanging indent; permanent-delete warning нельзя обрезать.
| Ввод внутри Help | Предлагаемая модель взаимодействия |
|---|---|
| `h`, Left, Shift-Tab | Предыдущая категория с wrap и сбросом scroll |
| `l`, Right, Tab | Следующая категория с wrap и сбросом scroll |
| `j`, Down / `k`, Up | Одна rendered line вниз/вверх с clamp |
| PageDown, Ctrl-f / PageUp, Ctrl-b | Фактический help-body viewport вниз/вверх |
| Ctrl-d / Ctrl-u | Половина help-body viewport, минимум одна строка |
| `?`, F1, Esc, `q` | Закрыть Help с сохранением всего workspace |
| Enter | Ничего не выполняет: справка read-only |
| F10 | Сохранить существующий quit |
Горизонтальная ось никогда не прокручивает текст, вертикальная не переключает категории; категории wrap, документ clamp. Новое открытие начинается с Navigation/0, смена категории сбрасывает offset, а input и resize нормализуют scroll к `[0, max_scroll]`, чтобы накопленный PageDown не создавал видимость «застрявшего» `k`. Общая pure `help_view_model` должна вычислять wrapping, body height, page/half-page и footer одновременно для renderer и input. Если полный strip не помещается, выводится **`< N/6 Category >`** либо ASCII-вариант; при 40×8 планируются полный selected label, четыре body rows и видимый range/switch/scroll/close footer. Ниже 40×8 сохраняется terminal-too-small path.
Постоянная нижняя hints row удаляется, а её высота отдаётся содержимому; **видимый `? Help` остаётся в существующем header**, при нехватке ширины сначала исчезают subtitle и вторичные слова mode, но не help affordance. Overlay-local footers и подсказки в empty/error states сохраняются: это контекстная помощь, а не возвращение постоянной нижней строки. Отдельно требуется исправить обнаруженное противоречие Task Details: footer обещает `j/k Scroll`, но handler сначала меняет выбранную задачу; delta предписывает прокручивать именно details, не меняя selection за overlay ([footer](/home/vrubel/services/rcom/src/ui/actions.rs#L479-L511), [input order](/home/vrubel/services/rcom/src/input/mod.rs#L385-L439)). Полный план, inventory и named-test matrix находятся в [OpenSpec change `redesign-help-and-remove-hints`](../openspec/changes/redesign-help-and-remove-hints/), прежде всего в [design](../openspec/changes/redesign-help-and-remove-hints/design.md).
## Общий стандарт превращает красоту в проверяемый контракт
Повторно используемый стандарт уже оформлен в [`docs/tui-design-guidelines.md`](../docs/tui-design-guidelines.md), а рабочий процесс дизайнера и независимого тестировщика — в [`.agents/skills/rcom-tui-design/SKILL.md`](../.agents/skills/rcom-tui-design/SKILL.md). Guideline закрепляет приоритет содержимого над декорацией, keyboard-only управление, non-color state cues, стабильный кадр, запланированную деградацию на маленьком терминале и запрет внешних брендов внутри пользовательской помощи. Он также вводит общие semantic roles для panels, selection, file types и operation states, благодаря чему иконки, Help и темы перестают быть тремя несвязанными наборами hard-coded RGB.
Дизайнер сначала читает main/delta specs, изучает текущий UI и tests, формулирует пользовательскую задачу и проверяет normal, selected, focus, error, loading и empty states. Только затем он предлагает **один согласованный visual/interaction contract**: структуру, semantic colors/icons, клавиши и aliases, wrap/clamp, закрытие overlay, responsive degradation, `NO_COLOR`, ASCII и icons-off. Каждый наблюдаемый scenario связывается с будущим named test; если guideline и spec расходятся, расхождение фиксируется и разрешается через change, а не молчаливым выбором реализации.
Независимый тестировщик не подгоняет findings под замысел автора. Он сравнивает полный `Buffer`, включая стили, проверяет keyboard-only flow и все aliases, отсутствие потерянных команд и stale responses, а также размеры **40×8, 80×24, 120×40** и подходящий wide single/dual кадр. Selection, focus и errors проверяются без цвета и Nerd Font; overlap, flicker, нечитаемая плотность и обрезанные critical actions остаются findings даже при формально зелёных snapshots. Результаты разделяются на CRITICAL functional failures, WARNING spec/coverage gaps и SUGGESTION aesthetic improvements, каждый получает `file:line` и конкретную рекомендацию. Archive-ready нельзя присваивать при непроверенных scenarios, а субъективная красота требует пользовательского visual review после automated PASS.
После review политика archives синхронизирована: **red archives** в Night Ops и общей ANSI policy, с отдельным magenta для media/secondary и независимыми icon accents ([guideline](../docs/tui-design-guidelines.md), [theme design](../openspec/changes/add-color-theme-presets/design.md)).
## Двадцать тем отбираются из 459 с проверкой лицензий
**Факты об upstream.** Официальная документация `kitten themes` ссылается на **`kovidgoyal/kitty-themes`**, поддерживает live preview, поиск и light/dark filtering; старый `dexpota/kitty-themes` является историческим источником текущего репозитория, а не актуальной официальной ссылкой ([официальная документация](https://sw.kovidgoyal.net/kitty/kittens/themes/), [README коллекции](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/README.rst)). В commit **`a35d12290c3d6a74b1f94debc81281cb637f3568` от 2026-12-04** machine-readable `themes.json` содержит ровно 459 записей; 369 имеют `is_dark: true`, у 90 ключ отсутствует, а явного `is_dark: false` нет. Поэтому omitted-to-light допустим лишь как локальная нормализация curated allowlist с luminance и visual sanity check, а не как универсальная гарантия схемы ([pinned catalog](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes.json), [metadata generator](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/gen-metadata.py)). Kitty `.conf` предоставляет foreground/background, selection pair, ANSI `color0`–`color15` и необязательные cursor/tab/border/UI colors, но не определяет rcom-роли `panel`, `muted`, `active`, `secondary`, `error` и не содержит file-type semantics ([официальный `template.conf`](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/template.conf)).
**Предлагаемый точный каталог rcom — 20 записей, 11 dark и 9 light.** Night Ops остаётся native default и не получает чужой attribution; остальные 19 существуют в pinned collection и имеют explicit per-file MIT либо MIT/X11. IDs стабильны и не зависят от accents или upstream spelling.
| # | Stable ID и display name | Mode | Происхождение и лицензия |
|---:|---|---|---|
| 1 | `night-ops` — **Night Ops** | Dark | **rcom native** |
| 2 | `dracula` — **Dracula** | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Dracula.conf), MIT |
| 3 | `catppuccin-mocha` — **Catppuccin Mocha** | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Catppuccin-Mocha.conf), MIT |
| 4 | `catppuccin-latte` — **Catppuccin Latte** | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Catppuccin-Latte.conf), MIT |
| 5 | `gruvbox-dark` — **Gruvbox Dark** | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/gruvbox-dark.conf), MIT/X11 |
| 6 | `gruvbox-light` — **Gruvbox Light** | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/gruvbox-light.conf), MIT/X11 |
| 7 | `solarized-dark` — **Solarized Dark** | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Solarized_Dark.conf), MIT |
| 8 | `solarized-light` — **Solarized Light** | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Solarized_Light.conf), MIT |
| 9 | `tokyo-night` — **Tokyo Night** | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/tokyo_night_night.conf), MIT |
| 10 | `tokyo-night-day` — **Tokyo Night Day** | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/tokyo_night_day.conf), MIT |
| 11 | `one-half-dark` — **One Half Dark** | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/OneHalfDark.conf), MIT |
| 12 | `one-half-light` — **One Half Light** | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/OneHalfLight.conf), MIT |
| 13 | `rose-pine` — **Rosé Pine** | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/rose-pine.conf), MIT |
| 14 | `rose-pine-dawn` — **Rosé Pine Dawn** | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/rose-pine-dawn.conf), MIT |
| 15 | `everforest-dark-medium` — **Everforest Dark Medium** | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/everforest_dark_medium.conf), MIT |
| 16 | `everforest-light-medium` — **Everforest Light Medium** | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/everforest_light_medium.conf), MIT |
| 17 | `github-dark` — **GitHub Dark** | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/GitHub_Dark.conf), MIT |
| 18 | `github-light` — **GitHub Light** | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/GitHub_Light.conf), MIT |
| 19 | `flexoki-dark` — **Flexoki Dark** | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/flexoki_dark.conf), MIT |
| 20 | `flexoki-light` — **Flexoki Light** | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/flexoki_light.conf), MIT |
Импорт должен быть **development-only, pinned и fail-closed**. Importer читает `themes.json` и ровно 19 allowlisted `.conf` из зафиксированного commit, проверяет source SHA-256 и accepted per-file license, сохраняет author/upstream/source, разбирает только whitelist цветовых ключей и никогда не исполняет kitty config. `none` и `system` трактуются как отсутствие значения; source и derived colors хранятся раздельно. `background` и `text` берутся из обязательных source foreground/background; `panel` получает подходящий tab/inactive surface либо documented mix; `muted` проходит через inactive foreground, ANSI color8 и mix; `active` — через active border, URL и лучший blue color4/color12; `secondary` — через magenta color5/color13; `error` — через наиболее контрастный red color1/color9. ANSI 0–15 сохраняется для file-type classes, а normal/bright вариант выбирается по фактической surface contrast, а не по упрощённому правилу «dark всегда bright».
Selection pair из kitty является кандидатом, не готовой гарантией. Предлагаемые **проектные** пороги — 4.5:1 для selected text и 3:1 для selection boundary на background/panel; это не требования kitty и не универсальное WCAG-заявление о чужой terminal palette. При провале importer сохраняет hue, где возможно, корректирует lightness или active accent, выбирает foreground из `text`/`background` по измеренному контрасту и блокирует release при повторном провале. Static Rust data, manifest и notices генерируются заранее; runtime и обычный `cargo build` не обращаются к сети и не запускают kitty. Пользователь получает persistent `theme = "night-ops"`, временный `--theme <id>` и `--list-themes` без входа в TUI; unknown ID сообщает доступные значения до alternate screen и не перезаписывает config. В первый этап также входит Theme Picker по `T`: `j/k`/Up/Down показывают live preview всей темы без записи, Enter атомарно сохраняет только theme ID, а Esc восстанавливает baseline при открытии. Arbitrary user themes и OS auto dark/light сознательно не входят в первый этап.
**Лицензионная оговорка существенна.** Коллекция в целом распространяется под GPL-3.0, но отдельные theme files могут объявлять собственную лицензию; в pinned JSON только 270 из 459 записей имеют `license`, а 189 не имеют per-entry значения ([README license section](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/README.rst), [GPL-3.0 LICENSE](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/LICENSE), [catalog](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes.json)). Для каждого MIT-импорта требуется не только идентификатор в header, но и **точный upstream copyright плюс полный MIT permission notice**, поскольку MIT требует сохранять эти уведомления в копиях или substantial portions ([OSI MIT text](https://opensource.org/license/mit)). `THIRD_PARTY_NOTICES.md`, `LICENSES/` и machine-readable manifest должны содержать display/upstream names, author, exact file URL, pinned commit, upstream URL, source hash и license. Эти полные upstream notices в исследовании ещё не аудированы и остаются release blocker; Nord намеренно исключён из начального набора из-за отсутствия explicit per-file license, а популярность не смягчает gate. Это инженерная рекомендация, не юридическое заключение. Полный контракт каталога и importer workflow находятся в [OpenSpec change `add-color-theme-presets`](../openspec/changes/add-color-theme-presets/), включая [точный design](../openspec/changes/add-color-theme-presets/design.md) и [delta spec](../openspec/changes/add-color-theme-presets/specs/terminal-ui/spec.md).
## Conclusion
Общая semantic-модель меняет экономику дальнейшего развития: новый тип файла, раздел помощи или тема расширяют один проверяемый контракт вместо добавления локальных исключений. Обязательный порядок — сначала icons/config и semantic appearance path, затем темы и Theme Picker, после них Help redesign с полным актуальным inventory. Перед apply следует синхронизировать archive color policy и разрешить Task Details conflict на уровне spec и regression test, чтобы реализация не закрепила противоречивые обещания.
Главный критерий успеха здесь не количество glyph или знакомых названий, а сохранение иерархии при потере цвета, шрифта, ширины и контекста. Pinned provenance, полные license notices, deterministic precedence, semantic reachability и full-Buffer tests создают необходимую основу, но окончательную красоту и читаемость каждого representative кадра и каждой из 20 тем должен подтвердить пользовательский visual review. Исследование выполнено read-only: код, OpenSpec artifacts и тестовые snapshots не изменялись, test suite не запускался.

View file

@ -0,0 +1,291 @@
# Keyboard-only TUI help overlay for `rcom`
## Category organization and choice of overall pattern
### Takeaway
Use six keyboard-driven category tabs—**Navigation, Selection, Files, Tasks, SSH, General**—above one single-column command list. Tabs are preferable to another long document here because the existing narrow view already requires scrolling through 33 lines, while a complete inventory will be longer; a separate pane category is not worth a seventh tab.
### Cited Findings
- The current overlay mixes categories into two independently aligned columns at widths of 70 columns or more, calls itself `HELP · yazi + mc`, and combines unrelated commands with `|` on the same rows. Below that width it becomes one 33-line document. [Current renderer](/home/vrubel/services/rcom/src/ui/render.rs#L652-L794); [40x8 snapshot](/home/vrubel/services/rcom/tests/snapshots/ui_accessibility__snapshot_help_scrolled_40x8.snap#L5-L11)
- Selection and clipboard commands are real normal-mode commands (`Space`/Insert, `v`, Ctrl-a, `I`, `U`, `y`, `x`, `p`), but the current help has no Selection heading and omits several of these aliases/actions. Tasks, SSH, editor, undo, preview, panes, and general commands also have real, mode-specific input handlers. [Normal-mode mapper](/home/vrubel/services/rcom/src/input/mod.rs#L490-L563); [overlay handlers](/home/vrubel/services/rcom/src/input/mod.rs#L174-L260); [task handler](/home/vrubel/services/rcom/src/input/mod.rs#L385-L440)
- The current specification explicitly asks for both key schemes and groups covering navigation, panes, file actions, editor, and connections; it also requires a readable overlay that does not change pane state. [terminal-ui specification](/home/vrubel/services/rcom/openspec/specs/terminal-ui/spec.md#L105-L114)
- Yazi's own quick-start documentation organizes its large command reference into Navigation, Selection, File operations, and Task manager sections, among others. This supports the proposed task-based taxonomy, but does not by itself establish anything about the appearance of Yazi's help overlay. [Yazi quick start](https://yazi-rs.github.io/docs/quick-start/)
### Inferences
- **Recommended: category tabs plus one list.** This gives every category a small, predictable working set, avoids split-column reading order, and degrades cleanly to a compact section switcher at 40 columns. The cost is that not every command is visible at once; clear section position, switching keys, and completeness tests are therefore mandatory.
- **Acceptable lightweight alternative: one continuous, single-column, sectioned document.** It needs less state and fewer keys, and is preferable if minimizing implementation scope outweighs navigation speed. However, adding all currently omitted commands makes narrow-terminal browsing longer than the already-tested 33-line document. If chosen, add Home/End and section jumps rather than retaining the current dense rows.
- **Not recommended initially: searchable/filterable help.** Incremental filtering adds text-entry modes and printable-key conflicts for a command set of only a few dozen actions. It can be a later enhancement, not a prerequisite for this redesign.
- **Not recommended: a category-menu screen followed by a detail screen.** Enter/back navigation adds another mode without presenting more information than the compact tab switcher.
- **Not recommended as the sole help: context-sensitive help.** It is useful as a supplement inside tasks or SSH, but a complete, stable reference must remain available regardless of the active pane or current error.
Recommended contents:
| Tab | Scope |
| --- | --- |
| **Navigation** | Cursor movement, parent/open, first/last, full/half page, local home |
| **Selection** | Toggle, visual mode, select all, invert, clear; keep clipboard operations out of this tab |
| **Files** | Yank/cut/paste, copy/move to the other pane, create, rename, trash, permanent delete, undo, external editor |
| **Tasks** | Open/close tasks, select, details, cancel, task scrolling |
| **SSH** | Open host picker, filter/edit query, select/connect, close picker |
| **General** | Active pane and single/dual layout, hidden files, refresh, preview, error details, help, close overlay/leave visual mode, quit |
This keeps pane/layout commands in **General** rather than creating a sparsely populated seventh **Panes** tab. Use the title **`HELP`** only. On wide terminals, render a single tab strip such as `[Navigation] Selection Files Tasks SSH General`; below it, use one row per action with a key column and a description column. Those two columns are *key → meaning*, not two unrelated command columns.
## Tab switching, scrolling, narrow terminals, and boundary behavior
### Takeaway
Use horizontal keys exclusively for sections and vertical keys exclusively for scrolling: `h`/Left/Shift-Tab for previous section, `l`/Right/Tab for next; `j`/Down and `k`/Up for one line, with the existing page and half-page aliases. Wrap section navigation, clamp vertical scrolling, reset scroll on a section change, and replace the six-label strip with a full selected-section label at 40x8.
### Cited Findings
- Help currently accepts Esc/`q` to close, `?`/F1 to toggle, F10 to quit, and delegates `j`/`k`, arrows, PageUp/PageDown, Ctrl-b/Ctrl-f, and Ctrl-u/Ctrl-d to overlay scrolling. Tab, arrows Left/Right, `h`, and `l` are currently unused by the help handler, so section switching can be added without stealing an existing help command. [Help input handler](/home/vrubel/services/rcom/src/input/mod.rs#L174-L194); [shared scroll mapping](/home/vrubel/services/rcom/src/input/mod.rs#L462-L488)
- Scroll deltas are stored with saturating addition in `AppState.overlay_scroll`; rendering separately clamps the effective offset to `total - visible`. Every overlay change resets the raw offset to zero. [Reducer](/home/vrubel/services/rcom/src/app/mod.rs#L517-L548); [overlay reset](/home/vrubel/services/rcom/src/app/mod.rs#L598-L601); [render clamp](/home/vrubel/services/rcom/src/ui/render.rs#L897-L910)
- The runtime currently derives *all* overlay page steps from the active pane's visible entry rows, not from the help body. [Event loop](/home/vrubel/services/rcom/src/tui.rs#L107-L119); [dispatch by overlay](/home/vrubel/services/rcom/src/session.rs#L252-L275); [active-pane geometry](/home/vrubel/services/rcom/src/ui/layout.rs#L89-L102)
- The minimum supported workspace is 40x8. At exactly 40x8, the bordered help has a 38-column inner width and currently five body rows plus a one-row footer. The accessibility test deliberately walks all 33 logical lines at 40x8 and 40x10. [Layout constants](/home/vrubel/services/rcom/src/ui/layout.rs#L7-L11); [help geometry](/home/vrubel/services/rcom/src/ui/render.rs#L652-L673); [minimum-size reachability test](/home/vrubel/services/rcom/tests/ui_accessibility.rs#L56-L135)
### Inferences
#### Interaction contract
| Input | Help behavior |
| --- | --- |
| `h`, Left, Shift-Tab | Previous category; wrap last category after the first |
| `l`, Right, Tab | Next category; wrap first category after the last |
| `j`, Down | One rendered line down; clamp at bottom |
| `k`, Up | One rendered line up; clamp at top |
| PageDown, Ctrl-f | One actual help-body viewport down; clamp |
| PageUp, Ctrl-b | One actual help-body viewport up; clamp |
| Ctrl-d / Ctrl-u | Half a help-body viewport down/up; minimum one line; clamp |
| `?`, F1, Esc, `q` | Close help without changing the workspace |
| F10 | Preserve the existing application-quit behavior |
- **Different navigation axes must not share behavior.** Left/Right changes categories but never scrolls; Up/Down scrolls but never changes categories. Tab and Shift-Tab are additional horizontal aliases only while help is open; their normal workspace meaning remains unchanged.
- **Wrap categories, clamp content.** Wrapping six categories makes Shift-Tab from Navigation useful and avoids a dead-end tab strip. Vertical wrap would unexpectedly jump from the end of a reference to its beginning, so vertical movement should stop at the boundaries.
- **Switching a category resets its scroll to zero.** Reset on every section change and start at Navigation/offset zero on each fresh help opening. This is simpler and more predictable than six hidden offsets. Keep the state only for the lifetime of that help opening.
- **Do not execute commands from help.** Enter should remain unbound in help; the reference is read-only and cannot accidentally mutate files.
- Preserve Press/Repeat handling for scrolling and Press-only handling for destructive/global actions. Category switching may accept Press and Repeat for arrows/`h`/`l`, but Tab/Shift-Tab need only Press.
#### Responsive layout
- On a wide strip, show all category names only if their measured display widths fit. The selected category must include a non-color marker such as `[Navigation]` (and optionally bold/reverse video).
- When the complete strip does not fit, show one full label and position instead, for example **`< 1/6 Navigation >`** in ASCII mode or **`‹ 1/6 Navigation ›`** in Unicode mode. Do not reduce categories to unexplained initials and do not silently clip labels.
- At 40x8 this costs one inner row, leaving **four body rows** plus the footer. A suitable ASCII footer is `1-4/11 | h/l Tabs | j/k Scroll | Esc` (36 columns); wider layouts can additionally advertise arrows, Tab, paging, and `?`/`q`.
- Wrap a long description with a hanging indent aligned to the description column. Never truncate a key alias or the permanent-delete warning merely to preserve one physical row per command. Calculate scroll ranges *after* wrapping.
- Suggested narrow shape (body contents scroll):
```text
╭HELP──────────────────────────────────╮
│< 1/6 Navigation >│
│j / Down Next entry │
│k / Up Previous entry │
│h / Left Parent directory │
│l / Right /… Open directory │
│1-4/11 | h/l Tabs | j/k Scroll | Esc │
╰──────────────────────────────────────╯
```
The ellipsis above is illustrative only; the implementation should wrap that row so `Enter` is never lost.
- Replace active-pane page sizing with help-specific geometry computed from the current terminal rectangle: `page = body_height`, `half_page = max(body_height / 2, 1)`. The renderer and input path should use the same pure layout/view-model function.
- Normalize the stored scroll offset to `[0, max_scroll]` on input and resize, rather than only clamping during rendering. Otherwise repeated PageDown can leave a large raw offset and subsequent `k` presses can appear stuck at the bottom. Keep the renderer's defensive clamp as well.
- Below 40x8, retain the existing terminal-too-small behavior; supported-size help must never panic at empty or degenerate rectangles.
## Showing every alias without product names or dense collisions
### Takeaway
Describe aliases as equivalent keys for an action—`j / Down`, `A / F7`, `u / Ctrl-z`—without assigning them to another program. Use one action per row and explicit context labels for task/SSH/help behavior; do not squeeze unrelated actions onto a row with `|`.
### Cited Findings
- The authoritative normal-mode mapping shows that uppercase and lowercase keys are distinct (`U` clears selection while `u` undoes; `I` inverts selection while Ctrl-r refreshes), `gg` is a timed prefix, Insert aliases Space for selection, and both F-key and letter aliases coexist. [Input mapper and prefix handling](/home/vrubel/services/rcom/src/input/mod.rs#L81-L118); [normal bindings](/home/vrubel/services/rcom/src/input/mod.rs#L490-L563)
- Existing tests explicitly verify alias-to-command equivalence and the uppercase distinctions. [Alias tests](/home/vrubel/services/rcom/tests/input_commands.rs#L47-L175)
- The current renderer places selection and copy/move aliases in Navigation rows, concatenates preview and undo, and puts task details in an overloaded General row. This is a presentation problem, not a shortage of actual commands. [Current help data](/home/vrubel/services/rcom/src/ui/render.rs#L674-L718)
- The host picker captures printable characters before global aliases, including `j`, `q`, `r`, `s`, `~`, and `?`; therefore its help must not imply that those letters perform normal-mode commands while filtering. [Host picker input](/home/vrubel/services/rcom/src/input/mod.rs#L120-L172)
### Inferences
The following is the recommended **complete content inventory**, derived from the current mapper. Each cell lists all aliases for that row; labels are neutral descriptions, not keymap families.
**Navigation**
| Keys | Description |
| --- | --- |
| `j / Down` | Next entry |
| `k / Up` | Previous entry |
| `h / Left` | Parent directory |
| `l / Right / Enter` | Open directory |
| `gg / Home` | First entry |
| `G / End` | Last entry |
| `Ctrl-b / PgUp` | Page up |
| `Ctrl-f / PgDn` | Page down |
| `Ctrl-u` | Half page up |
| `Ctrl-d` | Half page down |
| `~` | Go to local home |
**Selection**
| Keys | Description |
| --- | --- |
| `Space / Insert` | Toggle selection and advance |
| `v` | Toggle visual selection |
| `Ctrl-a` | Select all visible entries |
| `I` | Invert visible selection |
| `U` | Clear selection |
**Files**
| Keys | Description |
| --- | --- |
| `y` | Yank/copy selection to clipboard |
| `x` | Cut selection to clipboard |
| `p` | Paste clipboard |
| `F5` | Copy selection to other pane |
| `F6` | Move selection to other pane |
| `a` | Create file |
| `A / F7` | Create directory |
| `r / F2` | Rename hovered entry |
| `d` | Trash selection (restorable) |
| `D / F8` | Permanently delete selection — **NO UNDO** |
| `u / Ctrl-z` | Review/undo latest undoable action |
| `e / F4` | Edit regular file |
**Tasks** (identify list versus details in descriptions or small subgroup labels)
| Keys | Description |
| --- | --- |
| `t` | Open tasks; close task list when already open |
| `j / Down` | Next task in task list |
| `k / Up` | Previous task in task list |
| `m / Enter` | Open task details |
| `c` | Cancel selected task |
| `Esc / m` | Back from task details |
| `PgUp / PgDn`, `Ctrl-b / Ctrl-f`, `Ctrl-u / Ctrl-d` | Scroll task content |
**SSH** (subheading “Host picker”)
| Keys | Description |
| --- | --- |
| `s` | Choose SSH host (workspace) |
| Printable text | Filter hosts; letters are entered literally |
| `Backspace` | Delete filter character |
| `Up / Down` | Previous/next host |
| `Enter` | Connect selected host |
| `Esc` | Close host picker |
**General**
| Keys | Description |
| --- | --- |
| `Tab / Shift-Tab` | Switch active pane (workspace) |
| `\` | Toggle single/dual pane |
| `.` | Show/hide hidden files |
| `Ctrl-r` | Refresh active listing |
| `F3` | Open preview; `F3 / Esc / q` closes preview |
| `m` | Show active-pane error details, when available |
| `? / F1` | Open/close this help |
| `Esc` | Close overlay; leave visual mode when no overlay is open |
| `q / F10` | Quit from workspace; within help, `q` closes help while F10 still quits |
Presentation rules:
- Preserve case literally and use consistent spellings: `Ctrl-r`, `Shift-Tab`, `PgUp`, `PgDn`, `Space`, `Enter`. Never collapse `D` into `d` or `U` into `u`.
- Keep the dangerous distinction in words on the Files page: **Trash (restorable)** versus **Permanently delete — NO UNDO**.
- A long alias set should wrap within the same action, not be split into misleading “primary” and “alternate” pages. At narrow widths, place the description on the next indented physical line if needed.
- Help's own controls need not be repeated as fake workspace commands. The footer and General row should clearly distinguish “close help” from “quit application.”
### Gaps
- There is a pre-existing task-details inconsistency: its footer says `j/k Scroll`, but the input handler handles `j`/`k` as task selection before shared scrolling is reached. The help redesign should not claim a resolved details behavior until that conflict is fixed or explicitly specified. [Task details footer](/home/vrubel/services/rcom/src/ui/actions.rs#L479-L511); [task input order](/home/vrubel/services/rcom/src/input/mod.rs#L385-L439)
## Discoverability after removing the permanent bottom hints
### Takeaway
Remove the dedicated bottom hints row, but retain a small **`? Help`** affordance in the existing header at every supported size. Keep contextual instructions inside empty/error states and overlays; do not replace the removed row with another permanent bottom row.
### Cited Findings
- The current permanent row is rendered only at heights of at least 10 and contains selection, clipboard, copy/move, tasks, help, and quit hints. Removing `layout.hints` releases one workspace row at those sizes. [Hint allocation](/home/vrubel/services/rcom/src/ui/layout.rs#L49-L76); [hint renderer](/home/vrubel/services/rcom/src/ui/render.rs#L642-L650)
- The header already contains the product name/tagline on the left and mode on the right. [Header renderer](/home/vrubel/services/rcom/src/ui/render.rs#L102-L125)
- The status row and empty-directory/listing-error states already provide state or contextual commands, while overlays generally retain their own local footer controls. [Status renderer](/home/vrubel/services/rcom/src/ui/render.rs#L587-L640); [empty/error messages](/home/vrubel/services/rcom/src/ui/render.rs#L240-L279); [task overlay footer](/home/vrubel/services/rcom/src/ui/actions.rs#L479-L513)
- At least one operation UI test finds `t Tasks` in the *rendered whole frame* rather than proving it is in the help body. Removing the hints row without adding Tasks to help would therefore reduce discoverability and break that test. [Operation UI assertion](/home/vrubel/services/rcom/tests/operation_ui.rs#L262-L275)
### Inferences
- Make the normal header right side responsive: wide layouts can show `DUAL PANE 1/2 · ? Help`; narrow layouts should first drop the `dual-pane file manager` subtitle and shorten mode text rather than dropping `? Help`. `? Help` is permanent, text-based, and requires no extra vertical space.
- Do not steal space from critical status/error messages to squeeze all old hints into the status line. If a right-aligned help label is more consistent with the existing visual hierarchy, it can instead live in the status row, but the implementation must compact the left status deterministically and preserve errors; the header is the cleaner default.
- Retain `?` and F1 as the normal-mode entry points. Include both aliases in the General help page, README/manual if one exists, and any empty/error message where a short `? Help` suffix fits naturally.
- Keep overlay-local footers: they are contextual instructions, not the permanent workspace hint row being removed. The help overlay itself must always show section switching, scrolling, and closing.
- Avoid first-run popups or timed tutorial messages as the primary discovery mechanism; they are not reliable on later launches and complicate deterministic state.
### Gaps
- No user research in the repository establishes whether users notice a header affordance more readily than a status affordance. The header recommendation follows from available space and the requirement to remove the bottom row; it should receive a simple 40x8 visual review.
## Accessibility, completeness, implementation feasibility, and deterministic tests
### Takeaway
Represent category and scroll as explicit state, render from a static section/action inventory, and make selected category and scroll position understandable in plain ASCII with no color. Extend the existing pure-renderer and input tests with full per-category reachability, boundary, resize, and alias-coverage tests rather than relying on snapshots alone.
### Cited Findings
- `AppState` currently stores only `overlay` and one shared `overlay_scroll`; `Overlay::Help` has no category state. Rendering takes `&AppState` and does not mutate it. [State fields](/home/vrubel/services/rcom/src/app/mod.rs#L235-L243); [overlay enum](/home/vrubel/services/rcom/src/app/mod.rs#L90-L108); [render signature and Help dispatch](/home/vrubel/services/rcom/src/ui/render.rs#L24-L100)
- Existing rendering utilities already provide bordered/cleared overlays, bounded rectangles, sanitization, Unicode-aware fitting/wrapping, ASCII fallbacks, effective scroll ranges, and textual scroll positions. [Help and utilities](/home/vrubel/services/rcom/src/ui/render.rs#L652-L805); [text imports](/home/vrubel/services/rcom/src/ui/render.rs#L1-L23)
- The specification requires activity/focus to differ by more than color and requires `NO_COLOR` interfaces to remain structurally legible. Existing lists use both markers and style. [Accessibility requirements](/home/vrubel/services/rcom/openspec/specs/terminal-ui/spec.md#L44-L57); [entry markers](/home/vrubel/services/rcom/src/ui/render.rs#L314-L353)
- Tests already use Ratatui `TestBackend`, compare application state before/after rendering, exercise keyboard reducers, collect all narrow frames, use Insta snapshots, and property-test multiple breakpoint sizes for panics. [Overlay tests](/home/vrubel/services/rcom/tests/ui_overlays.rs#L31-L72); [accessibility tests](/home/vrubel/services/rcom/tests/ui_accessibility.rs#L32-L57); [layout property test](/home/vrubel/services/rcom/tests/ui_layout.rs#L234-L266)
### Inferences
#### Feasible implementation shape
- Add a small `HelpCategory` enum in a fixed six-item order and either `AppState.help_category` or a `HelpState { category, scroll }`. Add commands such as `SelectHelpCategory(-1|1)`; reuse or refine `ScrollOverlay` for vertical deltas. `set_overlay(Help)` initializes category/offset, and category changes reset offset.
- Keep a static `HELP_SECTIONS` inventory containing category, stable action ID, aliases, description, and context. A pure `help_view_model(area, state)` should produce the tab mode, wrapped display lines, body height, total, effective offset, and footer. Both input geometry and rendering can then agree without renderer mutation.
- A future single binding table shared by input and help would eliminate drift, but a wholesale input refactor is not necessary for this visual redesign. If input remains a direct `match`, a test fixture must independently enumerate every normal binding and compare it with the help inventory.
- Removing the hints field/renderer is straightforward but changes page geometry: current tests expecting 34 rows at 120x40, 18 at 80x24, and 4 at 40x10 will each increase by one when the hints row disappears. Update those expectations only after confirming the new frame geometry. [Current page-size test](/home/vrubel/services/rcom/tests/ui_hardening.rs#L75-L117)
#### Minimum deterministic test matrix
1. **Content and naming:** For every category, every required action and alias from the inventory appears. Across all categories and supported sizes, the help output contains neither `yazi` nor `mc`; its title is `HELP`. Trash and permanent delete remain textually distinct.
2. **Horizontal model:** Left/`h`/Shift-Tab and Right/`l`/Tab produce the same previous/next transitions; Navigation-left wraps to General and General-right wraps to Navigation. Each transition resets scroll and leaves panes, selection, clipboard, mode, and locations unchanged.
3. **Vertical model:** Test every existing scroll alias. Page and half-page steps use the *help body's* height at 40x8 and a wide size. Top/bottom clamp, and one `k` after many PageDown presses visibly leaves the bottom (catching raw-offset accumulation).
4. **Narrow completeness:** At exactly 40x8, assert one compact full category label and four body rows. For each category, repeatedly page to the bottom, join frames, and assert every action and every alias is reachable, including wrapped lines and `Enter` in `l / Right / Enter`.
5. **Resize:** Shrink and grow while on every category and at first/middle/last offsets. Assert clamped ranges, no missing final command, no panic, and no dependence on render order.
6. **Non-color/ASCII:** Render `Theme::no_color()` and `Theme::ascii()`. The active category remains identifiable by brackets/marker and `N/6`; scroll range remains textual; no Nerd Font private-use glyph is required.
7. **Close/isolation:** Esc, `q`, `?`, and F1 close help; F10 retains quit behavior. Existing tests that file/planner/selection keys do not leak through help must remain. Closing help preserves the entire prior workspace.
8. **Discovery/layout:** At all supported normal sizes the workspace contains `? Help` and no old bottom-hints string or allocated hints row. Header text does not overlap. Update snapshots for wide help, 40x8 initial/scrolled help, and all affected main layouts.
9. **Property tests:** Extend the existing width/height/overlay matrix with category and large-scroll values. Assert bounded output and no panic; use semantic reachability tests, not snapshots alone, to prove no command loss.
### Gaps
- This was a read-only investigation: no code was changed and no test suite was run. Exact wide breakpoints and wrapping snapshots should be derived with the implementation's Unicode-width utilities rather than guessed by character count.
## Verifiable patterns from other keyboard TUIs
### Takeaway
Borrow only two verified ideas: task-based documentation categories and a consistently available help command with list navigation. The cited Yazi and ranger sources do **not** verify a category-tab help overlay, so the proposed tabs are an `rcom` design choice rather than a claimed imitation.
### Cited Findings
- Yazi 26.9.1 documents F1/`~` as help entry points and groups its quick-start command reference by tasks including Navigation, Selection, File operations, and Task manager. These keys are Yazi's own bindings and should not replace `rcom`'s `?`/F1. [Yazi quick start](https://yazi-rs.github.io/docs/quick-start/)
- Yazi's keymap documentation defines a help layer with close, escape (clear filter or hide help), and arrow operations; arrow operations support top/bottom and separately named previous/next wraparound variants. Its shipped help keymap lists `j`/`k`, Up/Down, Ctrl-p/Ctrl-n, Esc/Ctrl-[, Ctrl-c, and Enter to close and run selected actions. [Yazi help-layer documentation](https://yazi-rs.github.io/docs/configuration/keymap/#help); [Yazi shipped keymap](https://raw.githubusercontent.com/sxyazi/yazi/shipped/yazi-config/preset/keymap-default.toml)
- Ranger's source manual says `?` opens its manual and describes access to lists of key bindings, commands, or settings. It separately documents settings for scroll wrapping and collapsing long key-hint submaps. [Ranger manual source](https://raw.githubusercontent.com/ranger/ranger/master/doc/ranger.pod)
- Neither cited source provides enough evidence to claim particular tab visuals, category-switching keys, narrow-terminal behavior, or pagination behavior in Yazi's or ranger's help UI. The Yazi documentation verifies commands and operations, not the rendered layout. [Yazi keymap documentation](https://yazi-rs.github.io/docs/configuration/keymap/); [Ranger manual source](https://raw.githubusercontent.com/ranger/ranger/master/doc/ranger.pod)
### Inferences
- Adopt Yazi's useful **information architecture** (Navigation/Selection/Files/Tasks), not its product name, entry keys, or Enter-to-run behavior. Read-only help is safer and sufficient for `rcom`.
- Yazi's distinction between ordinary clamped movement and explicitly named wraparound movement supports making boundary policy deliberate. For `rcom`, use wrap only for the six categories and clamp the document, as specified above.
- Yazi's documented filter-aware help shows that filtering is a plausible later enhancement, but `rcom` need not reproduce it now. If filtering is ever added, Esc should first clear a nonempty filter and only then close help, with that state covered by tests.
- Ranger demonstrates a manual accessible through one well-known key rather than dependence on a permanent row of every command. This supports retaining a visible `? Help` entry point while moving exhaustive aliases into the overlay.
- Do not cite either program in the redesigned UI. Neutral alias labels fully communicate `rcom`'s behavior without attributing key families.
### Gaps
- Web search was unavailable during this investigation; external claims above were checked directly against current official Yazi documentation/shipped configuration and ranger's source manual. No visual behavior beyond those primary sources is asserted.

View file

@ -0,0 +1,307 @@
# Image previews for rcom: research notes
Research date: **2026-12-06**. This is a read-only research note for the proposed OpenSpec change `add-image-previews`.
## Executive recommendation
Use **`ratatui-image` 12.0.0 for terminal protocols and `image` 0.25.10 for bounded decoding**. Both are actively published, their licenses are compatible with rcom, and their current versions match rcom's Ratatui 0.30.2 / Rust 1.88 baseline. Do not port Yazi's adapter wholesale and do not write three wire protocols in rcom.
A realistic first implementation should:
- render the **actual decoded pixels** of the selected PNG/JPEG/GIF/BMP/WebP file in both the normal preview pane and the F3 preview overlay; metadata may accompany the image but is not an acceptable successful result by itself;
- treat animated input as one static image, with no animation timer;
- preserve aspect ratio, downscale to the inner preview rectangle, and never crop by default;
- work for local and SSH selections by reading bounded bytes through the existing filesystem port, then decoding locally;
- use Kitty, iTerm2, or Sixel when `ratatui-image` detects them, with **Unicode halfblocks as the normal no-graphics-protocol fallback**, so an unsupported terminal still sees the image rather than only metadata;
- offer an explicit images-disabled/no-capability text fallback, independent of `IconMode::None`;
- bound input bytes, source dimensions, decoded allocation, concurrency, and cache size; decode/resize/encode off the UI thread;
- retain rcom's generation/target/session checks and add geometry and terminal-lifecycle identity to prepared rendering state;
- leave SVG, AVIF/HEIF/JXL, PDF/video thumbnails, animation, Überzug++, external Chafa/ImageMagick processes, and a disk thumbnail cache out of the first change.
The native protocols should be described as **best-effort terminal integrations**, not as correctness proved by headless tests. Halfblocks provide the deterministic, universal baseline. Kitty/iTerm2/Sixel still need a small manual terminal matrix.
## 1. What Yazi currently does
The official image-preview documentation is at <https://yazi-rs.github.io/docs/image-preview/>. The source observations below use Yazi `main` commit [`555c65beccf0f81f922c3607d9beff9ecca279a2`](https://github.com/sxyazi/yazi/tree/555c65beccf0f81f922c3607d9beff9ecca279a2), dated 2026-12-06; the documentation identifies version 26.9.1.
### 1.1 Image recognition and preview pipeline
Yazi does not decide that a file is an image solely in its widget:
1. Its local MIME fetcher invokes `file -bL --mime-type` and parses the result. The preview rules route `image/*` to the built-in `image` plugin; AVIF/HEIF/JXL go through ImageMagick and SVG through a separate converter. Sources: [mime-local.lua](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-plugin/preset/plugins/mime-local.lua#L59-L99), [default preview rules](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-config/preset/yazi-default.toml#L121-L124).
2. The image plugin waits for the configured `image_delay` (30 ms by default), then calls `ya.image_show(url, job.area)`. Its preload path can create a cached, resized encoded image. Source: [image.lua](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-plugin/preset/plugins/image.lua#L1-L24), [defaults](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-config/preset/yazi-default.toml#L20-L28).
3. `Image::decode_from` guesses the format from content, applies `image::Limits`, reads EXIF orientation, and performs decoding in `tokio::task::spawn_blocking`. Resizing/orientation and driver encoding also run in blocking tasks. Source: [image.rs](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-adapter/src/image.rs#L14-L118).
4. The target pixel size is the smaller of the preview area (columns/rows multiplied by terminal cell pixel size) and configured `max_width`/`max_height` (600×900 by default). If cell metrics are unavailable, Yazi uses those configured pixel bounds. Source: [image.rs sizing](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-adapter/src/image.rs#L43-L84).
Yazi's default decoder limits are 512 MiB and 10,000×10,000 pixels on each axis. They are useful precedents, not necessarily good defaults for a responsive preview in rcom. Source: [yazi-default.toml](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-config/preset/yazi-default.toml#L95-L103).
### 1.2 Terminal detection and driver choice
Yazi combines environment hints with actual terminal reports:
- Brand hints come from `TERM`, `TERM_PROGRAM`, and variables such as `KITTY_WINDOW_ID`, `KONSOLE_VERSION`, `ITERM_SESSION_ID`, `WEZTERM_EXECUTABLE`, `GHOSTTY_RESOURCES_DIR`, `WT_Session`, and others. Source: [brand.rs](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-emulator/src/brand.rs#L34-L100).
- The probe sends XTVERSION, a Kitty query, a Kitty shared-memory query, DA1, and `CSI 16 t`, with tmux passthrough when needed. DA1 attribute 4 records Sixel support; `CSI 16 t` records cell pixel dimensions. The initial probe has bounded waits/timeouts rather than waiting forever. Source: [probe.rs](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-emulator/src/probe.rs#L28-L118), [emulator.rs report handling](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-emulator/src/emulator.rs#L77-L99).
- Kitty and Ghostty select Kitty graphics with Unicode placeholders; Konsole selects Yazi's older Kitty placement approach; iTerm2, WezTerm, VSCode, Tabby and others select the iTerm2 inline protocol; Foot, Windows Terminal and Black Box select Sixel. Unknown terminals use probe results. Source: [drivers.rs](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-adapter/src/drivers/drivers.rs#L21-L101).
- If no terminal protocol is selected, Yazi tries Überzug++ on X11/supported Wayland compositors and finally external Chafa. The official table and tmux/Zellij caveats are at <https://yazi-rs.github.io/docs/image-preview/>.
The source's driver lists are priority hints, not a guarantee that every rendering error will retry every later protocol. `Drivers::matches` ultimately returns one driver. rcom should likewise avoid silently cycling protocols after partial output, which can leave worse artifacts than a clean halfblock fallback.
### 1.3 What each Yazi driver emits
- **Current Kitty (`Kgp`)**: downscales, transmits RGB/RGBA through shared memory when available or 3,072-byte raw chunks encoded as base64, and creates a virtual placement with `U=1`. It writes U+10EEEE placeholder cells plus row/column diacritics. Erasing writes spaces and issues a quiet Kitty delete. Source: [kgp.rs](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-adapter/src/drivers/kgp.rs#L315-L430).
- **Old Kitty (`KgpOld`)**: transmits the image and creates explicit per-cell placements. Yazi avoids it under tmux because of protocol limitations. Source: [kgp_old.rs](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-adapter/src/drivers/kgp_old.rs#L17-L132).
- **iTerm2 (`Iip`)**: re-encodes the resized image as PNG when alpha is present or JPEG otherwise, base64-encodes it, and emits OSC 1337 with `inline=1`, explicit pixel dimensions and `doNotMoveCursor=1`. Source: [iip.rs](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-adapter/src/drivers/iip.rs#L15-L70).
- **Sixel**: downscales, quantizes to at most 256 colors (reserving a slot for transparency), and emits a DCS Sixel payload. Source: [sixel.rs](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-adapter/src/drivers/sixel.rs#L21-L133).
- **Chafa**: runs `chafa` with animation and passthrough disabled and converts its symbol output to text. Source: [chafa.rs](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-adapter/src/drivers/chafa.rs#L15-L84).
### 1.4 Cancellation, stale output, resize and resume
Yazi gives each preview a cancellation scope. Starting a new preview cancels the old scope; the async runner selects cancellation versus completion. Its preview signature includes file identity, MIME type **and preview `Rect`**, so a layout change is a new preview identity. Sources: [preview_mut.rs](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-core/src/tab/preview_mut.rs#L33-L78), [preview_sig.rs](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-core/src/tab/preview_sig.rs#L1-L18).
The adapter tracks the shown `Rect`, erases it on image reset, and has a collision hook so other clearing operations can erase overlapping graphics. Source: [adapter.rs](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-adapter/src/adapter.rs#L33-L74).
On resume after a subprocess/suspend, Yazi resets the preview, recreates the terminal, triggers resize/reflow and performs a full render. Source: [resume.rs](https://github.com/sxyazi/yazi/blob/555c65beccf0f81f922c3607d9beff9ecca279a2/yazi-actor/src/app/resume.rs#L17-L29). This is directly relevant to rcom: resetting only Ratatui's buffers is not sufficient for a Kitty protocol object that believes it has already transmitted its image.
## 2. Crates: APIs, fit and licenses
Versions below are current as of 2026-12-06. “Maintained” here means recent upstream publication/source activity, not a future support guarantee.
| Crate | Current role and useful API | License / compatibility | Recommendation |
|---|---|---|---|
| [`ratatui-image`](https://docs.rs/ratatui-image/12.0.0/ratatui_image/) 12.0.0, published 2026-12-04 | `Picker::from_query_stdio`, `Picker::halfblocks`, `Picker::new_protocol`, `Image`, `StatefulImage`, `ThreadProtocol`; Kitty, iTerm2, Sixel and halfblocks | **MIT**; Rust 1.86; Ratatui `^0.30.1`; rcom already has Ratatui 0.30.2. [manifest](https://docs.rs/crate/ratatui-image/12.0.0/source/Cargo.toml.orig) | **Use it.** It solves Ratatui buffer integration as well as wire encoding. |
| [`image`](https://docs.rs/image/0.25.10/image/) 0.25.10 | `ImageReader::with_guessed_format`, `guess_format`, `Limits`, `DynamicImage`, orientation and resizing | **MIT OR Apache-2.0**; Rust 1.88 exactly matches rcom. [manifest](https://docs.rs/crate/image/0.25.10/source/Cargo.toml.orig) | **Use it explicitly** with selected format features and custom limits. |
| [`icy_sixel`](https://docs.rs/icy_sixel/0.7.0/icy_sixel/) 0.7.0 | Pure-Rust Sixel encoder/decoder; `SixelImage::from_rgba(...).encode()` or lower-level `sixel_encode` | **MIT OR Apache-2.0**. [manifest](https://docs.rs/crate/icy_sixel/0.7.0/source/Cargo.toml.orig) | Suitable for a custom Sixel backend, but redundant when using `ratatui-image` (which already uses `icy_sixel` 0.5.x). |
| [`yazi-adapter`](https://docs.rs/yazi-adapter/26.5.6/yazi_adapter/) 26.5.6 | Yazi's path-based global `ADAPTOR.image_show(path, Rect)` and decoding helpers | **MIT**, but published crate requires Rust **1.95** and many Yazi-internal crates/global configuration/TTY state. [manifest](https://docs.rs/crate/yazi-adapter/26.5.6/source/Cargo.toml) | **Research reference only.** It is incompatible with rcom's Rust 1.88 and poorly isolated for local+SFTP byte previews. |
### 2.1 `ratatui-image` API choice
The crate's own guide distinguishes two paths: <https://docs.rs/ratatui-image/12.0.0/ratatui_image/#widget-choice>.
- `Picker::new_protocol(dynamic_image, Size, Resize::Fit(...))` does resize/encoding once and returns a fixed `Protocol`; `Image::new(&protocol)` is cheap to render. This is the simplest fit for rcom's current immutable `&AppState` rendering, provided prepared protocol state lives in a UI/runtime cache rather than inside the pure reducer.
- `StatefulImage` adapts at render time. Its documentation explicitly warns that resize/encoding can block the UI and recommends `ThreadProtocol`: <https://docs.rs/ratatui-image/12.0.0/ratatui_image/struct.StatefulImage.html>.
- `ThreadProtocol` has request IDs and rejects superseded resize responses through `update_resized_protocol`: <https://docs.rs/ratatui-image/12.0.0/ratatui_image/thread/struct.ThreadProtocol.html>. It is useful, but does not replace rcom's file generation/target/session identity.
For a first change, fixed `Protocol` + `Image` is easier to reason about. Prepare it asynchronously for `(preview generation, image identity, inner Size, font size, protocol, terminal epoch)`. If the area changes, retain the decoded source and prepare a replacement off-thread; do not render an oversized old Sixel/iTerm2 protocol into a smaller area. `Protocol::needs_placeholder` can drive the temporary placeholder. If dynamic resizing later needs to be continuous, move to `ThreadProtocol` with an actually off-thread `resize_encode` worker.
`Resize::Fit(Some(FilterType::Triangle))` is a good quality/scope default. In the current implementation `Fit` downscales but does not upscale; `Scale` is the variant that also enlarges. Source: [lib.rs](https://github.com/ratatui/ratatui-image/blob/d4857310e3dc7ae010028cea9ef2e6b3c84d6057/src/lib.rs#L368-L540).
### 2.2 Detection behavior in `ratatui-image`
`Picker::from_query_stdio()` must run **before any Crossterm/Ratatui event reader**. It writes queries to stdout and consumes replies from stdin; an active `EventStream` would compete for those bytes. API warning: <https://docs.rs/ratatui-image/12.0.0/ratatui_image/picker/struct.Picker.html#method.from_query_stdio>.
The current implementation:
- sends a one-pixel Kitty `a=q` query, DA1 for Sixel, `CSI 16 t` for cell size, and finally the widely supported `CSI 5 n` status query as a completion marker;
- defaults to a 2,000 ms timeout and has `QueryStdioOptions::timeout_ms`;
- prefers actual I/O capability replies to stale environment hints for Kitty/Sixel; iTerm2 is selected from terminal environment hints because its old custom probe is commented out;
- uses halfblocks if no usable protocol/font metrics are found, and has an explicit `Picker::halfblocks()` constructor for tests;
- has special handling for WezTerm/Konsole and tmux passthrough.
Sources: [cap_parser.rs query/parser](https://github.com/ratatui/ratatui-image/blob/d4857310e3dc7ae010028cea9ef2e6b3c84d6057/src/picker/cap_parser.rs#L34-L254), [picker.rs selection](https://github.com/ratatui/ratatui-image/blob/d4857310e3dc7ae010028cea9ef2e6b3c84d6057/src/picker.rs#L101-L186), [environment/tmux hints](https://github.com/ratatui/ratatui-image/blob/d4857310e3dc7ae010028cea9ef2e6b3c84d6057/src/picker.rs#L370-L420).
Two rcom-specific cautions:
1. Call detection after terminal initialization but **before `run_event_loop` constructs `EventStream`**. On editor resume, rcom's current event stream remains alive; do not casually issue another stdio probe there. Invalidate/reprepare the image instead. Refreshing font metrics on resume requires a coordinated pause/recreation of input reading and can be a later enhancement.
2. Current `detect_tmux_and_outer_protocol_from_env` executes `tmux set -p allow-passthrough on`. That is a user-visible setting change. rcom should decide this policy explicitly; a conservative first version can select halfblocks under tmux rather than mutate tmux configuration. Yazi's documentation instead asks tmux users to configure `allow-passthrough` themselves: <https://yazi-rs.github.io/docs/image-preview/#tmux-users>.
### 2.3 Avoid unintended native dependencies
`ratatui-image` defaults include `chafa-dyn`, which dynamically links to libchafa. Its primitive halfblock encoder does not need that library. For rcom, start with the equivalent of:
```toml
ratatui-image = { version = "12.0.0", default-features = false, features = ["crossterm"] }
image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "gif", "bmp", "webp"] }
```
The `tokio` feature is only needed if rcom chooses `ThreadProtocol` with Tokio channels. Feature documentation: <https://docs.rs/ratatui-image/12.0.0/ratatui_image/#features>.
## 3. Protocol tradeoffs
Authoritative protocol references:
- Kitty graphics, including queries and placements: <https://sw.kovidgoyal.net/kitty/graphics-protocol/>.
- Kitty Unicode placeholders: <https://sw.kovidgoyal.net/kitty/graphics-protocol/#unicode-placeholders>.
- Kitty deletion and storage quotas: <https://sw.kovidgoyal.net/kitty/graphics-protocol/#deleting-images> and <https://sw.kovidgoyal.net/kitty/graphics-protocol/#image-persistence-and-storage-quotas>.
- iTerm2 inline images: <https://iterm2.com/documentation-images.html>.
- iTerm2 feature reporting (`FILE`, and also `Sx` for Sixel): <https://iterm2.com/feature-reporting/>.
- DEC Sixel format and scrolling behavior: <https://www.vt100.net/docs/vt3xx-gp/chapter14.html>.
### Kitty
**Advantages**
- RGB/RGBA quality and efficient reuse: transmit once, then represent placements in Ratatui cells using Unicode placeholders.
- Placeholder cells move and disappear with ordinary text, which fits Ratatui's immediate-mode diffing much better than manually positioned permanent placements.
- Direct base64 chunks work over terminal transports; shared memory can reduce local transfer overhead. `ratatui-image` can also probe optional zlib compression, but its own documentation recommends leaving it off unless bandwidth dominates.
**Costs/risks**
- The graphics protocol has many partial implementations. Supporting a basic Kitty query does not by itself prove Unicode placeholder support. Kitty now has a feature query for `U=1`, but the current crate primarily uses a basic probe plus terminal-specific exclusions.
- Terminal-side image IDs and storage are stateful. Dropping a Rust value is not the same as sending Kitty's delete command. Current `ratatui-image` transmits once per protocol object but exposes no general high-level image-hide/free lifecycle comparable to Yazi's adapter. Random IDs for successive files can consume terminal quota until eviction. Do not claim explicit terminal-memory cleanup in the first spec unless rcom adds a small deletion extension or upstream support.
- Suspend/resume or terminal re-creation must invalidate the protocol's “already transmitted” state and recreate it; otherwise Kitty can remain blank after resume.
**First-scope verdict:** include through `ratatui-image`; manually test Kitty and Ghostty. Do not implement Yazi's old per-cell Kitty driver for Konsole in rcom.
### iTerm2 / OSC 1337
**Advantages**
- Conceptually simple: inline base64 file data with width/height and aspect-ratio controls. It covers iTerm2 and is also the most reliable choice for WezTerm in `ratatui-image`'s compatibility matrix.
- No application-managed image ID/placement table is required.
**Costs/risks**
- Base64 adds overhead, and `ratatui-image` currently re-encodes to PNG and delivers the full payload on each render. Avoid doing that encoding in `Frame::render`.
- Detection in the current crate is environment-based, not a robust active query. iTerm2's newer feature-reporting protocol has a `FILE` capability, but adopting it is extra parser/event work.
- Clearing behavior varies by emulator. iTerm2 3.5 has multipart sequences, but rcom should not add a second custom transport initially.
Sources for the crate behavior: [iterm2.rs](https://github.com/ratatui/ratatui-image/blob/d4857310e3dc7ae010028cea9ef2e6b3c84d6057/src/protocol/iterm2.rs#L1-L125), [compatibility matrix](https://github.com/ratatui/ratatui-image/blob/d4857310e3dc7ae010028cea9ef2e6b3c84d6057/README.md#compatibility-matrix).
**First-scope verdict:** include through the crate and manually test iTerm2 or WezTerm. Keep selection/redraw encoding bounded and off-thread.
### Sixel
**Advantages**
- Established DEC bitmap format supported by Foot, xterm builds, Windows Terminal and others.
- DA1 attribute 4 gives a relatively standard capability signal; there is no Kitty-like application image-ID database.
**Costs/risks**
- Palette quantization and encoding cost CPU; full data is sent on each render in `ratatui-image`. Transparency is limited and often needs compositing over the terminal background.
- The preview area must be protected from ordinary text overdraw. Sixel near the terminal's last line can scroll; this is a known `ratatui-image` issue: <https://github.com/ratatui/ratatui-image/issues/57>.
- Multiplexer support is uneven: Yazi documents tmux build/passthrough requirements and serious current Zellij Sixel problems. Other terminals report support but clear graphics incorrectly.
**First-scope verdict:** include only because the crate already supplies it; treat it as best-effort and manually test Foot/xterm plus the last-line/resize cases. If this expands QA too much, disabling Sixel and using halfblocks is a legitimate configuration fallback, not a metadata-only success.
### Unicode halfblocks (the essential fallback)
`ratatui-image` uses `▀`/`▄` and foreground/background RGB colors to represent two vertical pixels per cell. This is still an actual image preview, works without a graphics protocol, and is fully inspectable in Ratatui's `TestBackend`. It costs resolution and produces many colored cells, and requires Unicode plus usable color output. Its primitive encoder is at [halfblocks/primitive.rs](https://github.com/ratatui/ratatui-image/blob/d4857310e3dc7ae010028cea9ef2e6b3c84d6057/src/protocol/halfblocks/primitive.rs#L1-L124).
For `TERM=dumb`, ASCII-only/no-color output, non-TTY/headless operation, or an explicit image-disable setting, use a clear text image-unavailable/metadata placeholder instead. **`IconMode::None` is not that setting**: turning off file icons must not turn off the selected image.
## 4. Safe bounded decoding and asynchronous design
### 4.1 Input and allocation limits
rcom currently uses `MAX_PREVIEW_BYTES = 64 KiB` and `ReadFileSystem::read_prefix`, whose implementations read at most `limit + 1` bytes and set `truncated`. That port is reusable for local and SSH images, but 64 KiB is not a viable full-image cap.
Recommended pipeline:
1. Read a small prefix and use content magic (`image::guess_format` or `ImageReader::with_guessed_format`) as a hint; extension/MIME may be an additional hint, but the decoder must validate content. `guess_format` explicitly does not validate the whole file: <https://docs.rs/image/0.25.10/image/fn.guess_format.html>.
2. For a supported image, obtain at most `MAX_IMAGE_BYTES` with the same lookahead mechanism. If `truncated`, return “image too large for preview” plus metadata; never decode a truncated prefix as if it were complete. Metadata size can pre-reject obviously large files but is not a substitute for the read cap.
3. In a blocking worker, construct `ImageReader<Cursor<Vec<u8>>>`, guess from content, and call `reader.limits(custom_limits)` **before** decoding. API: <https://docs.rs/image/0.25.10/image/struct.ImageReader.html>.
4. Set strict `max_image_width` and `max_image_height`, non-strict `max_alloc`, and an independent checked `width × height` pixel limit. Check arithmetic with `checked_mul`; include the subsequent RGBA conversion, resized copy and base64/protocol buffer in the memory budget, not just decoder allocations.
5. Downscale to the available cell rectangle before terminal encoding. Reject zero-sized images/areas cleanly. Keep only the current decoded image per pane initially; at most a tiny byte-bounded LRU later.
`image::Limits` semantics matter: width and height are strict; `max_alloc` is non-strict and some decoders may ignore it. The default `max_alloc` is 512 MiB and default dimensions are unlimited. Source: <https://docs.rs/image/0.25.10/image/struct.Limits.html>. Therefore rcom must set all three and must not advertise `max_alloc` as a hard process-memory sandbox.
Possible conservative starting values to tune in implementation tests (these are rcom recommendations, not Yazi facts): 16 MiB encoded input, 8192 pixels per axis, 32 million total pixels, 256 MiB decoder `max_alloc`, and one active decoded image per pane. Record the full transient memory estimate in the design before finalizing them.
If hard CPU/time/memory isolation from malicious files is a requirement, an in-process Rust decoder cannot provide it reliably; that needs a separately constrained helper process. That is beyond the first scope.
### 4.2 Cancellation and stale results
rcom already aborts the previous async preview task per pane and rejects results when preview generation, target, session epoch or endpoint no longer match (`src/runtime.rs`, `src/app/mod.rs::finish_preview`). Keep this as the outer correctness boundary.
Add the following image-specific rules:
- A short selection delay/coalescing window (Yazi uses 30 ms) avoids starting full reads for every item during rapid navigation.
- Decode, resize and protocol encoding run off the UI task. Use a small global semaphore or dedicated worker and coalesce queued work per pane; do not let rapid navigation accumulate an unbounded `spawn_blocking` queue.
- Check a cancellation token before read, before decode, after decode, before resize/encode and before sending the result. This avoids new work but cannot interrupt a codec already running.
- Every prepared result carries `(pane, preview generation, target, session epoch, image identity, target Size, font size, protocol, terminal epoch)`. The reducer/runtime accepts only the current identity. Yazi's inclusion of preview `Rect` in its signature is the relevant precedent.
- A timeout on an async wrapper is not CPU cancellation. Tokio explicitly states that aborting a running `spawn_blocking` task has no effect and recommends a semaphore for CPU-bound work: <https://docs.rs/tokio/1.54.1/tokio/task/fn.spawn_blocking.html>.
- Worker output is only data placed into current state. Workers must never write escape sequences directly to stdout; only the draw path for the currently accepted protocol may do so. This eliminates late stale terminal writes by construction.
### 4.3 Resize, overlays, hide and suspend/resume
- Key prepared state by the **inner** preview area, not the outer bordered `Rect`. Recompute when the pane/overlay layout changes; debounce resize storms.
- While a replacement is being resized, either show the old image only if it still fits safely or show a placeholder. Never allow an old oversized image to spill over adjacent panes.
- Switching to text/directory/no selection, loading a different image, opening a covering overlay, or disabling images must remove the prepared widget from the draw path and clear its cells. Kitty placeholders then disappear as text; Sixel/iTerm2 need the crate's clearing behavior. Test actual terminals for residue.
- rcom's `TerminalGuard::resume` currently creates a fresh `Terminal`. Increment a terminal epoch and invalidate prepared protocols at that boundary so Kitty retransmits and every backend gets a full redraw. Yazi resets/recreates/reflows on resume for the same reason.
- On normal exit/suspend, leave the alternate screen through the existing guard. Do not add raw terminal writes after the guard is restored.
## 5. Headless and mock testing without image assets or network
### 5.1 Deterministic automated tests
Use tiny **programmatically generated** images (`RgbaImage`/`DynamicImage`, or encode a 2×2/4×2 image to an in-memory `Cursor<Vec<u8>>`). No fixture downloads, external image files, Chafa, ImageMagick or real terminal are needed.
1. **Decode/classification tests**
- PNG/JPEG magic selects the image path; text and arbitrary binary retain existing behavior.
- Corrupt/truncated image data produces a specific image-unavailable result, not a panic.
- Exact byte cap succeeds; cap+1 returns the too-large fallback; mock local and SFTP filesystems prove no unbounded read.
- Pure dimension/budget functions reject excess width, height, total pixels and arithmetic overflow. Test these separately with generated dimensions/property tests rather than allocating giant images.
- Static GIF/WebP behavior is fixed by the spec; no animation tasks are spawned.
2. **Geometry tests**
- Wide, tall and tiny generated images preserve aspect ratio and fit within `Size`.
- Zero-width/zero-height and one-cell areas show a placeholder without panic.
- Growing/shrinking the area invalidates the old protocol; stale resize completions are rejected.
3. **Actual-pixel rendering with Ratatui `TestBackend`**
- Construct `Picker::halfblocks()` explicitly; never call stdio detection in unit tests.
- Render both the normal preview and F3 overlay. Assert expected `▀`/`▄` cells and known RGB foreground/background values, not merely the presence of “Name/Size” metadata.
- Assert borders and neighboring pane text remain intact and the image does not exceed its allocated cells.
- `TestBackend` API: <https://docs.rs/ratatui/0.30.2/ratatui/backend/struct.TestBackend.html>. `ratatui-image`'s own quick start demonstrates exactly this picker/backend combination: <https://docs.rs/ratatui-image/12.0.0/ratatui_image/#quick-start>.
4. **Protocol-shape tests, not fake visual claims**
- Force each `ProtocolType` on a test picker and inspect Ratatui cells. Kitty should produce placeholder cells; Sixel/iTerm2 put their escape payload in the first cell and mark the remaining area skipped.
- Assert structural properties only. Do not snapshot random Kitty IDs, entire base64 blobs or codec-version-dependent Sixel output.
- These tests prove buffer integration, not that a real emulator displays pixels.
5. **Capability parser tests**
- Feed synthetic Kitty OK, DA1 with/without attribute 4, `CSI 16 t`, final status, malformed and garbage responses into a pure parser.
- Test no response/timeout with a short injected duration or a mock PTY; do not sleep for the production two-second default.
- Prefer a pure function over an environment map. If tests mutate process environment, serialize them; avoid environment races.
- Upstream parser examples are at [cap_parser.rs tests](https://github.com/ratatui/ratatui-image/blob/d4857310e3dc7ae010028cea9ef2e6b3c84d6057/src/picker/cap_parser.rs#L387-L440).
6. **Async/lifecycle tests with controllable mocks**
- Block image A with a `Notify`/oneshot, complete B first, then release A; only B may become visible. Repeat for target, generation and SSH-session mismatch.
- Complete an old-area encode after a new-area encode; the old protocol must be discarded.
- Prove cancellation before a queued blocking job prevents it from starting, and that late completion after cancellation emits nothing visible.
- Use atomic active/max-active counters in a fake codec/worker to prove the concurrency bound.
- A mock terminal/image presenter records hide, invalidate, redraw and resume calls. Switching image→text/directory/no-selection and opening/closing overlays must not leave the old presenter active.
7. **Icons-off and no-image fallback tests**
- With `IconMode::None`, the preview title has no icon but the generated image's halfblock pixels are still present.
- With images explicitly disabled, ASCII/no-color/`TERM=dumb`, or an injected no-presenter capability, the UI shows a sanitized image-unavailable/metadata result and emits no graphics payload.
- Corrupt, unsupported and over-limit images follow the same non-panicking fallback while other preview kinds remain unchanged.
### 5.2 Manual tests that automation cannot replace
Before claiming native-protocol support, run a tiny local smoke matrix:
- Kitty or Ghostty: image quality, rapid selection, overlay hide/show, resize, editor suspend/resume, exit;
- iTerm2 or WezTerm: correct size, no stale image, reasonable redraw bandwidth;
- Foot or Sixel-enabled xterm: transparency/background, bottom-edge behavior, clearing and resize;
- unsupported terminal such as standard Alacritty: halfblocks rather than metadata;
- tmux with the explicitly chosen passthrough policy; local and SSH-selected files;
- rapid `j/k`, very large/corrupt files and terminal resize during decoding.
`ratatui-image` maintains a separate real-terminal screenshot suite and publishes its compatibility matrix at <https://github.com/ratatui/ratatui-image#compatibility-matrix>. That is useful supporting evidence, but rcom still needs its own lifecycle checks.
## 6. Suggested OpenSpec boundaries and scenarios
### Required first-change behavior
- Given a selected supported image and a usable preview area, when loading completes, the preview displays decoded image pixels fitted to the pane; a metadata-only result is not considered success.
- The same image content path is used by the normal preview and full preview overlay.
- Local and SSH reads have explicit encoded-byte, dimension, pixel and allocation limits; excess produces a safe fallback.
- Image work does not execute synchronously in Ratatui rendering, and superseded reads/decodes/resizes cannot replace current state or write terminal output.
- Terminal protocol detection happens once before the event reader, is bounded, and falls back to actual halfblock pixels; no native support is guessed solely from rcom's icon mode.
- Resize and terminal resume invalidate incompatible prepared state and trigger safe repreparation/full redraw.
- Automated tests demonstrate pixels with a generated in-memory image and `TestBackend`, including icons-off and explicit no-image fallback.
### Explicitly deferred
- animation and video;
- SVG/PDF and formats requiring external converters;
- Überzug++ X11/Wayland windows and external Chafa;
- custom Kitty-old/multipart-iTerm2/Sixel implementations;
- persistent disk thumbnail cache, preloading neighboring images, and hard sandboxing of codecs;
- claiming that headless tests verify real terminal rendering.
## Bottom line
Yazi's important lessons are not its escape sequences alone; they are the surrounding design: content-based image routing, bounded blocking decode, cell-aware sizing, cancellation scopes, area-aware preview identity, explicit image erasure/collision handling, and terminal reset on resume. For rcom, `ratatui-image` supplies the protocol/buffer layer while rcom should reuse its existing bounded filesystem and latest-generation preview architecture. Halfblocks make “show the selected image” achievable everywhere in a testable first release, while Kitty/iTerm2/Sixel improve quality when the terminal genuinely supports them.

View file

@ -0,0 +1,177 @@
# Official kitty theme ecosystem (2026) for rcom
Research snapshot: 2026-12-05. Facts are under **Cited Findings**; proposed rcom behavior is under **Inferences**. The collection snapshot used for exact counts and links is commit [`a35d12290c3d6a74b1f94debc81281cb637f3568`](https://github.com/kovidgoyal/kitty-themes/commit/a35d12290c3d6a74b1f94debc81281cb637f3568) (2026-12-04).
## Which repository/docs are officially linked by kitty and how many themes are available?
### Takeaway
Kitty's current official documentation links **`kovidgoyal/kitty-themes`**, not the older `dexpota/kitty-themes`, as the collection used by `kitten themes`. The official prose still says “over three hundred”; the machine-readable catalog contained **459 themes** at the pinned 2026-12-04 snapshot.
### Cited Findings
- The official [Changing kitty colors](https://sw.kovidgoyal.net/kitty/kittens/themes/) page says that `kitten themes` provides live previews, name search, light/dark filtering, and a collection of “over three hundred” pre-built themes, and links to [kovidgoyal/kitty-themes](https://github.com/kovidgoyal/kitty-themes). Its contribution instructions point to that same repository and its `template.conf`.
- The current collection README says it was **initially imported from** [dexpota/kitty-themes](https://github.com/dexpota/kitty-themes); that older repository is therefore upstream history, not the collection currently linked by kitty's documentation. — [Current README](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/README.rst)
- Counting the top-level objects in the checked-in [`themes.json`](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes.json) gives **459** entries. Every entry has a `file` under `themes/` and a `name`. This is an exact snapshot count, not a claim that the moving catalog will remain at 459.
- The repository's [`gen-metadata.py`](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/gen-metadata.py) enumerates `themes/*.conf`, invokes `kitten __parse_theme_metadata__`, adds the file path, normalizes license spellings, sorts by name, and writes `themes.json`.
### Inferences
- Use `kovidgoyal/kitty-themes` as the import source and cite the official kitten documentation for provenance. Pin the exact commit in rcom's generated manifest; do not fetch an unpinned `master` during every build or at runtime.
- Describe the size in user-facing planning as “about 460 upstream themes (459 in the pinned snapshot), of which rcom deliberately curates 19 imports plus Night Ops.” This avoids repeating the documentation's now-imprecise “over 300.”
### Gaps
- The catalog is a moving branch. A later import must recount `themes.json` and record a new commit rather than assuming 459 remains current.
## What fields exist in kitty theme files and which can map to rcom roles?
### Takeaway
A kitty theme is a plain `.conf` file of kitty settings with optional `##` metadata. The useful portable core is `foreground`, `background`, the selection pair, UI/tab/cursor colors, and ANSI `color0`–`color15`; these can seed rcom roles, but panel, muted, and accent roles need deterministic fallbacks and contrast checks rather than blind copying.
### Cited Findings
- The official [`template.conf`](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/template.conf) defines an optional metadata block with `name`, `author`, `license`, `upstream`, and a multi-line `blurb` (which must be last). Without `name`, the name is derived from the filename.
- The same template lists these setting groups: basic `foreground`, `background`, `selection_foreground`, `selection_background`; cursor colors; `url_color`; active/inactive/bell border colors; Wayland/macOS titlebar colors; active/inactive tab and tab-bar colors; three mark foreground/background pairs; and ANSI `color0`/`color8` through `color7`/`color15`. It also permits `color16` through `color255`. Values are not universally literal hex colors: examples include `none`, `system`, `black`, and the symbolic value `background`.
- The official documentation states that a theme is simply a `.conf` containing kitty settings; selecting it copies the file to `current-theme.conf` and includes it in `kitty.conf`. The template also warns that non-color settings may be present but will not work through `kitty @ set-colors`. — [Themes kitten documentation](https://sw.kovidgoyal.net/kitty/kittens/themes/); [template.conf](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/template.conf)
- Real files vary in which optional UI settings they provide. For example, [Catppuccin Mocha](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Catppuccin-Mocha.conf) supplies tab-bar, border, titlebar, and mark colors, while [One Half Light](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/OneHalfLight.conf) supplies the basic colors, selection, cursor, URL, and ANSI palette but no tab colors.
### Inferences
Recommended role extraction, in priority order:
| rcom role | Recommended source/fallback | Reason for caution |
|---|---|---|
| `background` | `background` | Require it; reject a candidate if absent or unsupported. |
| `panel` | Non-`none` `tab_bar_background`; otherwise a suitable `inactive_tab_background`; otherwise derive by mixing a small amount of `foreground` into `background` | A terminal theme need not define a separate surface. An inactive tab can also be too bright or identical to the main background. |
| `text` | `foreground` | Require readable contrast against both `background` and derived `panel`. |
| `muted` | Contrast-tested `inactive_tab_foreground`, then `color8`, then a deterministic foreground/background mix | `color8` is bright black/ANSI gray, not a guaranteed accessible muted-text role. |
| `active` | Contrast-tested `active_border_color`, then `url_color`, then the better of `color4`/`color12` | Do **not** blindly use `active_tab_background`: in several themes it equals the ordinary background or is a light fill intended to sit behind dark text. |
| `secondary` | `color5`, with `color13` as the brighter/darker alternative selected by contrast | ANSI magenta/purple gives a second accent without colliding with red errors. |
| `error` | The better-contrasting red of `color1`/`color9`, while retaining a clearly red hue | Terminal bright red may be preferable on one surface but not another. |
| `selection` | `selection_background` + `selection_foreground`, subject to the validation in the final section | Explicit support exists, but its terminal appearance need not be suitable for every TUI selection state. |
| Optional `success` / `warning` / `info` | `color2`/`color10`, `color3`/`color11`, and `color6`/`color14`, respectively | These are useful semantic extensions from ANSI green/yellow/cyan, not kitty-defined rcom roles. |
Importer recommendations:
- Parse only a whitelist of color settings. Resolve the small set of symbolic values actually needed (for example, `cursor_text_color background`), and treat `none`/`system` as absence for rcom. Do not execute or generally evaluate kitty configuration.
- Keep the original 16 ANSI colors in the generated record even when the eight headline rcom roles are derived. They are needed for coherent status and file-type colors.
- Store the source value and the final derived value separately so later changes to the derivation algorithm are auditable.
- Generate static Rust data at development/build preparation time, with no network dependency in the TUI. Render a review swatch containing all roles before accepting each import.
### Gaps
- Kitty does not define rcom's `panel`, `muted`, `active`, `secondary`, or `error` semantics. The table is an rcom mapping proposal, not an official kitty conversion specification.
- Optional fields vary considerably, so there is no single source-key mapping that works without fallbacks.
## Are dark/light classifications and machine-readable metadata available?
### Takeaway
Yes: [`themes.json`](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes.json) is directly machine-readable. In the pinned snapshot, **369** entries have `is_dark: true` and **90** omit `is_dark`; there is no explicit `is_dark: false`, so light classification should be normalized locally and sanity-checked from the background color.
### Cited Findings
- Across the 459 JSON objects, field presence is: `file` 459, `name` 459, `is_dark` 369, `num_settings` 457, `blurb` 245, `author` 275, `license` 270, and `upstream` 193. All 369 present `is_dark` values are `true`; the other 90 omit the key. — [themes.json, pinned snapshot](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes.json)
- Example dark records include [Catppuccin-Mocha](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Catppuccin-Mocha.conf), represented in JSON with `is_dark: true`; [Catppuccin-Latte](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Catppuccin-Latte.conf) has no `is_dark` key. Both have `name`, `file`, `author`, `license`, `upstream`, `blurb`, and `num_settings` in the JSON catalog. — [themes.json](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes.json)
- The official kitten UI explicitly supports choosing between light and dark themes, and kitty can save separate `dark-theme.auto.conf`, `light-theme.auto.conf`, and `no-preference-theme.auto.conf` files for OS color-scheme switching. — [Official kitten documentation](https://sw.kovidgoyal.net/kitty/kittens/themes/)
- The generator normalizes spellings including `MIT/X11` and `MIT license` to `MIT`, several GPL spellings to SPDX-like names, and `CC0 1.0` to `CC0-1.0`. — [gen-metadata.py](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/gen-metadata.py)
### Inferences
- Generate rcom's own required `mode: "dark" | "light"` field. Start with `dark` only when `is_dark == true`; normalize omitted `is_dark` to `light` for this curated set, then verify that background relative luminance and a rendered preview agree. Preserve the original nullable metadata so this normalization remains visible.
- Consume `name`, `file`, `author`, `license`, `upstream`, and `blurb` for the manifest and notices. `num_settings` is useful for diagnostics, not for theme quality or completeness.
- Pair dark/light variants only in rcom's presentation layer. Do not assume filename naming alone establishes a pair; use the curated allowlist.
### Gaps
- The template does not list `is_dark` as an author-supplied metadata field, and `themes.json` has no explicit light boolean. The exact inference procedure inside kitty's metadata parser was not established in this research; therefore absence of `is_dark` should be treated as the collection's light/non-dark convention, not as a self-describing schema guarantee.
- Metadata alone does not guarantee accessible contrast or visual quality.
## What attribution/license files must accompany imported theme data?
### Takeaway
The collection as a whole is GPL-3.0, but individual theme files can declare their own licenses. The 19 imports proposed below all declare **MIT** or **MIT/X11** (normalized to MIT in the catalog), allowing rcom to avoid ambiguous unlicensed entries; their exact upstream copyright and MIT permission notices still need to be collected and shipped.
### Cited Findings
- The current repository README states verbatim in substance: “The overall license of this repository is the GPLv3, however, individual theme files can have their own licenses, as specified in the theme file itself.” — [README license section](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/README.rst)
- The repository root contains the full [GNU General Public License version 3](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/LICENSE).
- Only 270 of the 459 catalog entries have a `license` value. The distribution in the pinned JSON is MIT 229, GPL-3.0 30, LGPL-3.0 2, CC-BY-SA-4.0 2, GPL-3.0-or-later 1, Apache-2.0 2, CC0-1.0 2, GPL-2.0 1, and UPL-1.0 1; 189 have no per-entry license value. — [themes.json](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes.json)
- For example, [Dracula](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Dracula.conf) declares `## license: MIT`, author Keegan Carruthers-Smith, and a Dracula upstream URL. [Gruvbox Dark](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/gruvbox-dark.conf) declares `MIT/X11`, which the generator normalizes to `MIT`. [Nord](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Nord.conf), by contrast, has author/upstream metadata but no per-file license declaration.
- The MIT license requires that its copyright notice and permission notice be included in all copies or substantial portions of the software. — [OSI MIT license text](https://opensource.org/license/mit)
### Inferences
For the proposed MIT-only import set, ship:
1. **`THIRD_PARTY_NOTICES.md`** with one record per import: rcom display name, upstream theme name, author, exact kitty collection file URL, pinned collection commit, upstream URL, and license identifier.
2. **The exact upstream copyright notice and full MIT permission text** for each imported theme, either in per-theme files under `LICENSES/` or in a clearly separated notices file. Resolve and pin the upstream repository/commit at import time rather than treating the words `## license: MIT` as the entire required notice.
3. **A machine-readable manifest** containing the same provenance and the source-file hash. Keep native Night Ops explicitly marked `origin: rcom-native`; do not add kitty attribution to it.
4. **The collection's GPL-3.0 LICENSE and corresponding compliance** if any repository-level GPL-covered material or a theme without an overriding license is copied. Do not assume such entries are MIT or public domain. Keeping the curated imports restricted to clear per-file MIT themes avoids needing to make that broader licensing decision here.
Recommended import gate: reject any candidate without an explicit accepted per-file license and an obtainable copyright/license notice. This is why Nord is not in the proposed initial 20 despite being recognizable.
### Gaps
- Kitty theme files commonly provide a license identifier and author but not the complete upstream copyright/license text. Those upstream notices were not individually audited in this read-only research and must be collected before distribution.
- This is engineering guidance, not a legal opinion on whether a particular collection of color values is copyrightable or on combined-work obligations. A release review should confirm the chosen notices and distribution model.
## Which exactly 20 recognizable themes should rcom ship?
### Takeaway
Proposed initial set: **20 total = 1 native Night Ops + 19 kitty imports; 11 dark and 9 light**. It uses recognizable families with several dark/light pairs and restricts every kitty import to a per-file MIT/MIT-X11 declaration.
### Cited Findings
- Every imported name below links to an existing theme file in the pinned official collection. The file headers provide the stated MIT or MIT/X11 licensing and authorship; the corresponding [themes.json](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes.json) supplies machine-readable dark classification and normalizes MIT/X11 to MIT.
- Catppuccin has separate official collection files for [Mocha](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Catppuccin-Mocha.conf) and [Latte](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Catppuccin-Latte.conf), so the requested pair need not be synthesized by rcom.
### Inferences
This is the proposed curated set, not an upstream ranking:
| # | rcom display name | Mode | Origin and license |
|---:|---|---|---|
| 1 | **Night Ops** | Dark | **rcom native**, not imported from kitty |
| 2 | Dracula | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Dracula.conf), MIT |
| 3 | Catppuccin Mocha | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Catppuccin-Mocha.conf), MIT |
| 4 | Catppuccin Latte | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Catppuccin-Latte.conf), MIT |
| 5 | Gruvbox Dark | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/gruvbox-dark.conf), MIT/X11 |
| 6 | Gruvbox Light | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/gruvbox-light.conf), MIT/X11 |
| 7 | Solarized Dark | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Solarized_Dark.conf), MIT |
| 8 | Solarized Light | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/Solarized_Light.conf), MIT |
| 9 | Tokyo Night | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/tokyo_night_night.conf), MIT |
| 10 | Tokyo Night Day | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/tokyo_night_day.conf), MIT |
| 11 | One Half Dark | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/OneHalfDark.conf), MIT |
| 12 | One Half Light | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/OneHalfLight.conf), MIT |
| 13 | Rosé Pine | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/rose-pine.conf), MIT |
| 14 | Rosé Pine Dawn | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/rose-pine-dawn.conf), MIT |
| 15 | Everforest Dark Medium | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/everforest_dark_medium.conf), MIT |
| 16 | Everforest Light Medium | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/everforest_light_medium.conf), MIT |
| 17 | GitHub Dark | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/GitHub_Dark.conf), MIT |
| 18 | GitHub Light | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/GitHub_Light.conf), MIT |
| 19 | Flexoki Dark | Dark | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/flexoki_dark.conf), MIT |
| 20 | Flexoki Light | Light | [kitty import](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/flexoki_light.conf), MIT |
Use stable rcom IDs independent of display spelling, for example `night-ops`, `dracula`, `catppuccin-mocha`, and `rose-pine-dawn`. Store `origin: native` only for Night Ops and `origin: kitty` plus full provenance for the other 19.
### Gaps
- “Recognizable” and visual suitability are curation judgments. The set still needs rendered rcom previews, contrast checks, and product approval; inclusion here is not a claim that terminal colors translate perfectly.
- If maintainers insist on Nord, its missing per-file license declaration needs a separate license review rather than silently treating it as MIT.
## How should selection foreground/background and file-type colors be handled, and what is a practical import workflow?
### Takeaway
Use kitty's explicit selection pair as a candidate, not an unquestioned final value; derive a contrast-safe fallback when necessary. Kitty supplies terminal colors, not file-type semantics, so rcom should define a small stable ANSI-to-file-type mapping and validate it on both dark and light surfaces.
### Cited Findings
- Kitty's template explicitly supports `selection_foreground` and `selection_background` alongside the 16 basic ANSI colors, but contains no directory, executable, symlink, archive, or other file-type color settings. — [template.conf](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/template.conf)
- The selected sources show why fallback logic matters: [Gruvbox Dark](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/gruvbox-dark.conf) uses orange `#d65d0e` selection with light foreground; [GitHub Dark](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/GitHub_Dark.conf) uses blue selection with the main background as selection foreground; [Everforest Dark Medium](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/everforest_dark_medium.conf) uses a muted gray-green pair. These are intentional terminal aesthetics, not uniform rcom contrast guarantees.
- The proposed sources also demonstrate inconsistent optional UI roles: [One Half Light](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/OneHalfLight.conf) has no tab colors, while [GitHub Light](https://github.com/kovidgoyal/kitty-themes/blob/a35d12290c3d6a74b1f94debc81281cb637f3568/themes/GitHub_Light.conf) supplies a distinct tab-bar background.
### Inferences
**Selection algorithm:**
1. Read both selection values when present. Resolve symbolic references and reject unsupported values.
2. Test selected text against selection background, and test selection background against both main background and panel. A useful rcom acceptance target is 4.5:1 for ordinary selected text and 3:1 for the visual boundary/state indicator; these are recommended project targets, not kitty requirements.
3. If the pair fails, retain its hue where practical but adjust lightness or mix the active accent into the background; choose `text` or `background` as selected foreground based on measured contrast. Ensure selected rows remain distinguishable without relying only on a subtle luminance change.
4. Keep keyboard focus/active-row emphasis distinct from selection where rcom has both states. Do not overload `active_tab_background` as selection merely because it exists.
**File-type palette proposal:**
- Regular file: `text`; directory: blue `color4`/`color12`; executable: green `color2`/`color10`; symlink: cyan `color6`/`color14`; archive/compressed: magenta `color5`/`color13`; special/device/socket: yellow `color3`/`color11`; broken link/error: the validated `error` red.
- Choose normal versus bright ANSI variant by contrast against the actual row surface, not by a universal “dark themes use bright colors” rule. Preserve enough lightness/chroma separation that directory and symlink remain distinguishable.
- Treat this mapping as rcom policy. It is not present in kitty's file format and should be documented and previewed independently.
**Practical curation/import workflow:**
1. Pin the collection commit and allowlist exactly the 19 imported files above; parse `themes.json` plus each selected `.conf`.
2. Require accepted license metadata and retrieve/pin the exact upstream license notice before generating the theme. Fail closed on missing provenance.
3. Parse only supported color keys, preserve ANSI 0–15 and original selection values, normalize dark/light mode, and generate the rcom semantic roles with the priorities above.
4. Emit a manifest with `id`, display name, mode, native/imported origin, source commit/file/hash, author, upstream, license, and derivation version. Generate static Rust palette data and notices from the same manifest to prevent attribution drift.
5. Run automated contrast tests plus a visual fixture for normal text, muted text, panel, active row, selection, error/success/warning, and every file type in both focused and unfocused states. Manually approve each generated theme; do not bulk-import all 459.
6. Keep Night Ops as the hand-authored native reference palette. Imported themes should conform to the same semantic contract, not redefine rcom's roles based on whichever optional kitty keys happen to be present.
### Gaps
- No actual contrast measurements or rcom screenshot review were performed in this read-only research. Those remain release-blocking curation checks.
- Kitty has no official file-type mapping to reuse; rcom must own and test that policy.

View file

@ -0,0 +1,127 @@
# Ranger file-type icons and filename colors (current as of 2026-12-05)
## Native file-type color classification and colorscheme mechanics
### Takeaway
Ranger natively colors **semantic/file-inode categories**, not individual programming languages. Its shipped `default` scheme gives directories bright blue, executables bright green, images yellow, other media magenta, containers red, and links cyan/magenta, but it has no built-in `.rs`/Rust-specific filename or icon rule.
### Cited Findings
- **Version/history boundary:** the newest version tag found in the official repository is **v1.9.4**, whose version-bump commit is dated 2024-11-04; the current development branch was also checked at commit `4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8` (2026-11-26). Findings below describe that current `master` source unless explicitly called a released v1.9.4 feature; do not silently treat every post-v1.9.4 change as released. — [v1.9.4 version-bump commit](https://github.com/ranger/ranger/commit/324ae4b164049141250e9387b0760fe96a3eef18); [current source commit](https://github.com/ranger/ranger/commit/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8)
- A colorscheme is a Python `ColorScheme` subclass implementing `use(context)`, which returns `(foreground, background, attribute)`. `ColorScheme.get(*keys)` turns the supplied string keys into a `Context`, calls `use`, validates the three integers, and caches the result. Users select a scheme with `set colorscheme NAME`. — [`ranger/gui/colorscheme.py`, lines 4–24 and 46–65](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/gui/colorscheme.py#L4-L65)
- Custom schemes are loaded from `~/.config/ranger/colorschemes/` before Ranger's bundled schemes. The current default config lists `default`, `jungle`, `snow`, and `solarized`; the official wiki also points to external schemes and warns that schemes are executable code with system access. — [`ranger/gui/colorscheme.py`, lines 85–145](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/gui/colorscheme.py#L85-L145); [`ranger/config/rc.conf`, lines 159–161](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/config/rc.conf#L159-L161); [official Colorschemes wiki](https://github.com/ranger/ranger/wiki/Colorschemes)
- For each browser row, Ranger combines generic MIME-category keys with state/inode keys. The latter include `selected`, `marked`, `directory`/`file`, user-executable, FIFO, socket, device, cut/copied, and good/bad symlink. This is the information normally delivered to the colorscheme, rather than the literal filename or extension. — [`ranger/gui/widgets/browsercolumn.py`, lines 438–443 and 517–553](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/gui/widgets/browsercolumn.py#L438-L553)
- MIME-category classification is primarily **name-based**: `set_mimetype()` calls `mimetypes.guess_type(basename)`, then sets `video`, `image`, `audio`, their union `media`, `document`, and `container`. Documents additionally match a hard-coded extension/basename list; containers match a hard-coded extension list. This coloring path is not content sniffing with `file(1)`, even though a separate `filetype` property exists for file information. — [`ranger/container/fsobject.py`, lines 31–40, 121–127, 155–158, and 219–245](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/container/fsobject.py#L31-L245)
- Exact `default` browser colors, in override order:
- directories: **bright blue + bold**;
- executables: **bright green + bold**, except media, containers, FIFOs, and sockets;
- images: **yellow**; audio/video/other media: **magenta**;
- containers/archives: **red**;
- sockets: **bright magenta + bold**;
- FIFOs: **yellow**; devices: **bright yellow + bold**;
- valid links: **cyan**; broken links: **magenta**, overriding earlier foreground choices.
— [`ranger/colorschemes/default.py`, lines 23–59](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/colorschemes/default.py#L23-L59)
- Although `document` is a native context key, the current `default.py` never tests `context.document`; documents therefore have no distinct default document color merely because they are documents. Likewise, there is no Rust-specific branch. A `.rs` file receives only whatever generic category/state styling applies, such as executable styling if its mode has the user-execute bit. — [classification in `fsobject.py`](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/container/fsobject.py#L219-L245); [complete browser styling in `default.py`](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/colorschemes/default.py#L23-L94)
- The default scheme uses curses' named colors plus a `BRIGHT` offset. `BRIGHT` is 8 only when terminfo reports at least 16 colors, otherwise 0; the default scheme also substitutes dim white for bright black in cut/copied rows on such terminals. Actual named-color appearance depends on the terminal palette. — [`ranger/gui/color.py`, lines 61–89](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/gui/color.py#L61-L89); [`default.py`, lines 70–78](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/colorschemes/default.py#L70-L78)
- `jungle` inherits the default scheme but changes ordinary directory foreground from blue to green; `snow` is deliberately monochrome and relies on bold/bright/reverse attributes. This confirms that the palette is scheme policy, not a fixed guarantee of blue folders in every Ranger scheme. — [`ranger/colorschemes/jungle.py`](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/colorschemes/jungle.py); [`ranger/colorschemes/snow.py`](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/colorschemes/snow.py)
### Inferences
- For rcom, “Ranger-like colors” should mean the concrete **`default` scheme mapping above**, not “all Ranger themes” and not per-language filename colors.
- Blue directories and a distinct Rust icon are compatible with Ranger's default palette **only as two separate mechanisms**: blue directory text is native; a Rust glyph comes from an icon plugin/custom code. A distinct Rust **filename** color is not an rc.conf-only native feature.
- A useful rcom baseline is: directory blue/bold, executable green, valid link cyan, broken link magenta or red, image yellow, audio/video magenta, archive red. Adding document cyan is a reasonable design choice, but must not be attributed to Ranger's `default` scheme.
- Keep file classification and presentation separate. In particular, use stat metadata for links/executables/special inodes and a deterministic exact-name/extension table for language icons. If MIME detection is added, document whether it is name-based or content-based; Ranger's normal color classification is the former.
### Gaps
- The exact color seen for named curses colors cannot be specified independently of the user's terminal palette; no universal contrast ratio can be claimed for Ranger's blue/green/etc.
- MIME recognition for a particular extension can vary with the Python/system MIME database. The source proves the generic algorithm, but not one immutable `.rs` MIME result on every host.
## Icon support: built-in, plugin, optional dependency, matching rules
### Takeaway
Ranger does not ship a built-in per-file icon catalog. Its official plugin wiki points users to third-party `ranger_devicons` and `ranger-devicons2`; both require a Nerd Font for their bundled glyph sets, and neither automatically falls back to plain text when the terminal font lacks those glyphs.
### Cited Findings
- The official user guide describes built-in linemodes for filename, permissions, file information, times, sizes, and metadata titles—not an icon linemode. The official Plugins wiki separately lists **`ranger_devicons`** (“file icon glyphs for ranger”) and **`ranger-devicons2`** (“icons and types (like `ls -F`)”). These are community repositories listed by Ranger, not Ranger-core modules or an official compatibility guarantee. — [Official User Guide, built-in linemodes](https://github.com/ranger/ranger/wiki/Official-User-Guide#more-tips); [official Plugins wiki](https://github.com/ranger/ranger/wiki/Plugins)
- Ranger's wiki instructs users to put plugins in `~/.config/ranger/plugins/` and warns that plugins have full computer access. Thus icon support is an optional Python plugin/configuration choice, not a zero-configuration core dependency. — [official Plugins wiki](https://github.com/ranger/ranger/wiki/Plugins)
- `ranger_devicons` registers a `devicons` linemode whose `filetitle()` returns `icon + separator + relative_path`. Installation is a Git clone into Ranger's plugin directory plus `default_linemode devicons`; the separator defaults to one space and is configurable through `RANGER_DEVICONS_SEPARATOR`. — [plugin README](https://github.com/alexanderjeurissen/ranger_devicons/blob/1bcaff0366a9d345313dc5af14002cfdcddabb82/README.md); [`__init__.py`](https://github.com/alexanderjeurissen/ranger_devicons/blob/1bcaff0366a9d345313dc5af14002cfdcddabb82/__init__.py)
- Its prerequisites explicitly require installing a patched **Nerd Font** and selecting it as the terminal font. The mapping source warns that unsupported glyphs appear as “weird squares.” There is no font-capability detection or plain-text fallback in this code. — [README prerequisites](https://github.com/alexanderjeurissen/ranger_devicons/blob/1bcaff0366a9d345313dc5af14002cfdcddabb82/README.md#prerequisites); [`devicons.py` mapping comment](https://github.com/alexanderjeurissen/ranger_devicons/blob/1bcaff0366a9d345313dc5af14002cfdcddabb82/devicons.py#L28-L31)
- `ranger_devicons` matching is deterministic and small: directories use exact directory-name/XDG/locale mappings, then generic folder ``; non-directories use a case-sensitive exact basename mapping, then Ranger's lowercased final extension, then generic file ``. Its table explicitly maps **`rs` and `rlib` to Rust glyph ``**, and includes common media, document, archive, and programming-language extensions. — [`devicons.py`, directory/file/extension mappings and `devicon()`](https://github.com/alexanderjeurissen/ranger_devicons/blob/1bcaff0366a9d345313dc5af14002cfdcddabb82/devicons.py#L31-L420)
- “Fallback” in `ranger_devicons` therefore means **unknown match → generic Nerd Font folder/file glyph**, not **missing font → no icon**. Disabling the linemode is the practical plain-text route. — [`devicon()` implementation](https://github.com/alexanderjeurissen/ranger_devicons/blob/1bcaff0366a9d345313dc5af14002cfdcddabb82/devicons.py#L411-L420)
- `ranger-devicons2` also requires a Nerd Font, registers `default_linemode devicons2`, and sources its generated rules from `nvim-web-devicons`. Its order is lowercase exact basename, filename patterns, lowercased extension, then generic folder/file. It additionally appends `ls -F`-like state symbols: broken link `!`, directory link `~`, other link `@`, socket `=`, FIFO `|`, executable `*`, and device markers. — [plugin README](https://github.com/cdump/ranger-devicons2/blob/94bdcc19218681debb252475fd9d11cfd274d9b1/README.md); [`__init__.py`](https://github.com/cdump/ranger-devicons2/blob/94bdcc19218681debb252475fd9d11cfd274d9b1/__init__.py)
- Neither examined plugin gives an icon its own independent color: the linemode returns one combined text string, and the browser applies the colorscheme to that filename text using the row's generic context. A Rust icon can therefore be distinct in **shape**, while its foreground still follows the ordinary file/executable/link/etc. row color. — [`ranger_devicons/__init__.py`](https://github.com/alexanderjeurissen/ranger_devicons/blob/1bcaff0366a9d345313dc5af14002cfdcddabb82/__init__.py#L10-L19); [`ranger-devicons2/__init__.py`](https://github.com/cdump/ranger-devicons2/blob/94bdcc19218681debb252475fd9d11cfd274d9b1/__init__.py#L57-L67); [Ranger browser text rendering](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/gui/widgets/browsercolumn.py#L365-L477)
### Inferences
- For rcom, implement icons natively as data-driven rules rather than reproducing Ranger's external-plugin requirement. A practical priority is **exact filename → compound/special extension → final extension → inode/condition fallback**, with an explicit case policy. If glob rules are offered, define their priority and cost rather than allowing accidental ordering.
- Ship at least a Nerd Font preset and a no-Nerd-Font fallback (`unicode`/`ascii`/`none`). Unknown file types should get generic file/folder icons; missing Nerd Font support should select the fallback preset, not display private-use squares. Terminal `TERM` alone cannot prove glyph coverage, so expose an explicit override and document the font prerequisite.
- Keep **icon glyph, icon color, filename style, and state marker** as separate fields. This enables the requested example: blue folder icon/name; Rust glyph `` in a Rust accent color; ordinary or document-colored `main.rs` filename; executable/link markers still visible.
- Do not describe `ranger_devicons` as an “official Ranger plugin.” Accurate wording: “a third-party plugin linked from Ranger's official wiki.” The same applies to `ranger-devicons2`.
### Gaps
- Wiki inclusion is not a support/stability endorsement, and there is no official Ranger-to-plugin compatibility matrix in the consulted documentation.
- Glyph width and rendering vary by Nerd Font version and terminal. The source establishes the font requirement but cannot guarantee alignment everywhere; the plugin's configurable separator is evidence that icon spacing may need adjustment.
## Selection/focus and accessibility behavior
### Takeaway
Ranger's current row is primarily shown with reverse video, which preserves a non-color cue; marked files, inactive panes, tags, and copy/cut state then modify or override category colors. Its only explicit screen-reader-related setting found is `show_cursor`, so rcom should treat Ranger as a useful interaction baseline, not a complete accessibility specification.
### Cited Findings
- Ranger terminology distinguishes the **currently highlighted file** from **marked files**: commands normally operate on all marked files, or on the current file when none are marked. Space marks the current file, `v` toggles the selection, and `V` starts visual range selection. — [Official User Guide, Selection](https://github.com/ranger/ranger/wiki/Official-User-Guide#selection)
- In `default`, a `selected` browser row gets `reverse`; in the main column it also gets bold. A marked main-column row gets bold yellow. Copy/cut rows that are not current become bold bright black, or dim white without bright-color support. Tags have a real marker character, not only a color. — [`default.py`, lines 23–27 and 60–86](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/colorschemes/default.py#L23-L86)
- In multipane mode an inactive pane's foreground is overwritten with cyan at the end of browser coloring, so ordinary category foreground distinctions are intentionally flattened there. In the monochrome `snow` scheme, the selected row still uses reverse video. — [`default.py`, lines 93–94](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/colorschemes/default.py#L93-L94); [`snow.py`](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/colorschemes/snow.py)
- The default `rc.conf` says “Turning this on makes sense for screen readers” immediately before `set show_cursor false`; the man page describes the option as “Always show the terminal cursor?” Thus cursor visibility is an available accessibility aid, disabled by default. — [`rc.conf`, lines 250–251](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/config/rc.conf#L250-L251); [`doc/ranger.pod`, `show_cursor`](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/doc/ranger.pod#L1274-L1277)
- `ranger-devicons2` demonstrates redundant textual state markers for links, executables, FIFOs, sockets, and devices, while core default colors alone communicate valid/broken links and several special inode classes. — [`ranger-devicons2/__init__.py`, `get_symbol()`](https://github.com/cdump/ranger-devicons2/blob/94bdcc19218681debb252475fd9d11cfd274d9b1/__init__.py#L28-L54); [Ranger default browser colors](https://github.com/ranger/ranger/blob/4bd20bb023bcbaddb03a5bf6680817fc8a68d9e8/ranger/colorschemes/default.py#L39-L59)
### Inferences
- rcom should make the focused row obvious through **background/reverse plus a stable marker or indicator bar**, not hue alone. Keep marked/multi-selected state visually distinct from focus, with its own symbol; do not rely only on Ranger's yellow.
- Preserve critical state under selection: either retain the icon's type color while styling the filename/background, or add explicit link/executable/broken-link markers. Test that reverse video does not erase these distinctions.
- Prefer dimming or reducing emphasis in inactive panes over Ranger default's blanket cyan recolor if per-type colors are a core rcom goal. Always retain the active-pane indicator.
- Provide `no-color`/monochrome and no-icon modes, visible focus/markers in both, sufficient contrast in the shipped dark/light themes, and an option to keep the terminal cursor visible for screen-reader users. These are rcom recommendations, not claims that Ranger already provides a complete accessibility suite.
### Gaps
- No formal Ranger accessibility/contrast audit or comprehensive screen-reader behavior specification was found in the official guide/source consulted.
- Reverse-video rendering and contrast remain terminal/theme dependent; source inspection alone cannot establish WCAG contrast for user-configured terminal palettes.
## Useful comparison/contrast with Yazi and recommendations for rcom
### Takeaway
Yazi 26.9.1 already offers the integrated, declarative model closest to the requested result: built-in nvim-web-devicons, independent icon foreground colors, ordered name/extension/condition matching, and filetype style rules by MIME/name/state. Ranger contributes a simple semantic baseline and strong reverse-video focus convention; Yazi is the better model for rich per-type icons, while rcom should add explicit no-Nerd-Font and accessibility fallbacks.
### Cited Findings
- **Yazi version boundary:** the official documentation consulted is labeled **26.9.1**. Its `[icon]` section says Yazi has built-in support for `nvim-web-devicons`; users can prepend/append or replace rules. Every rule has `text` and optional `fg`, so icon color is independent of the filename's filetype style. — [Yazi 26.9.1 `theme.toml`, `[icon]`](https://yazi-rs.github.io/docs/configuration/theme/#icon)
- Yazi icon priority is **globs → directory names → exact file names → extensions → conditions**. Conditions include directory, hidden, link, orphan, dummy, block/character device, FIFO, socket, executable, and sticky; boolean combinators are supported. Directory/file/extension maps have O(1) lookup, while globs are slower and run first. — [Yazi 26.9.1 icon matching](https://yazi-rs.github.io/docs/configuration/theme/#icon)
- Yazi `[filetype].rules` separately styles matching file list items by `mime`, `url`, and optional `is` state. Rules accept full styles (fg/bg/bold/dim/italic/underline/reverse/etc.); `url = "*/"` is the directory fallback, and `is` covers executable, link, orphan, and special inodes. Colors can be named ANSI-like values or hex RGB. — [Yazi 26.9.1 style types and `[filetype]`](https://yazi-rs.github.io/docs/configuration/theme/#types); [filetype rules](https://yazi-rs.github.io/docs/configuration/theme/#filetype)
- Yazi's current default dark preset closely mirrors Ranger's broad filename palette—image yellow, audio/video magenta, archives red, executables green, directory fallback blue—and additionally colors selected document MIME types cyan. Its icon preset has per-extension colors, including **`rs` glyph `` with `#dea584`**, generic/hovered blue folder glyphs with `#03a9f4`, and conditions for links/special files/executables. — [`yazi-config/preset/theme-dark.toml`, current `main`](https://github.com/sxyazi/yazi/blob/main/yazi-config/preset/theme-dark.toml)
- Nerd Fonts are **recommended, optional** dependencies in Yazi's installation docs, not mandatory runtime dependencies. Because icon text is configurable, users can replace glyphs; this contrasts with the examined Ranger plugins' explicit patched-font requirement and absence of an automatic plain-text mode. — [Yazi 26.9.1 installation prerequisites](https://yazi-rs.github.io/docs/installation/); [Yazi icon rule configuration](https://yazi-rs.github.io/docs/configuration/theme/#icon)
- Yazi's preset uses reverse for current/parent indicators and selected UI elements, plus distinct marker styles for copied/cut/marked/selected states. This is broadly consistent with the accessibility recommendation to retain non-hue cues, though it is not itself an accessibility guarantee. — [Yazi default dark preset](https://github.com/sxyazi/yazi/blob/main/yazi-config/preset/theme-dark.toml); [Yazi theme indicator/marker settings](https://yazi-rs.github.io/docs/configuration/theme/#indicator)
### Inferences
- **Recommended rcom architecture:**
1. A `FileClass` derived from metadata/name (directory, regular, executable, link/broken-link, image, audio/video, document, archive, special inode).
2. An ordered icon resolver with exact names (for `Cargo.toml`, `README.md`, `.gitignore`, etc.), extensions (`.rs` → ``), and generic/special-file conditions.
3. Independent `icon_style` and `filename_style`, then composable UI state (hover/focus, marked, cut/copied, inactive pane).
4. Named themes with ANSI fallback plus optional RGB, rather than hard-coding terminal-dependent curses values throughout rendering.
- **Recommended default visual language:** folders blue (optionally bold), Rust icon `` in a restrained orange/rust accent, images yellow, audio/video magenta, archives red, executables green, valid links cyan, broken links red/magenta with `!`, and documents cyan or muted foreground. Only the first broad categories are Ranger-default facts; per-Rust coloring and document cyan follow Yazi or are new rcom design choices.
- Prefer built-in defaults with user overrides in a declarative config, like Yazi, over requiring a Python plugin. Include a small set of exact-name rules before extension rules so project-significant files look intentional rather than merely sharing a generic `.toml`/`.md` icon.
- Offer Nerd Font, plain Unicode/ASCII, and off presets. Use ordinary file/folder fallbacks for unknown types and keep filenames readable if glyphs are unavailable. Avoid emoji as the only fallback unless width is tested, because terminal emoji presentation can be double-width or vary by platform.
- Do not let icon color alone communicate broken links, focus, or multi-selection. Combine icon/text color with `!`, `@`, `*`, a focus indicator, and a marked marker. Keep a monochrome theme and visible-cursor option.
- **Attribution-safe summary for planning:** “Ranger has native category-based colorschemes and third-party Nerd Font icon plugins. Yazi has built-in configurable per-file icons and icon colors. rcom plans integrated per-type icons/colors with blue folders, a distinct Rust icon, explicit fallbacks, and non-color focus/state indicators.”
### Gaps
- The Yazi preset link is to current `main`, whereas the behavioral documentation is versioned 26.9.1; treat exact preset glyphs/hex values as a current-source example, not a promise that every Yazi 26.9.1 installation has an identical customized user theme.
- No performance benchmark was collected for icon resolution. Yazi documents O(1) maps and slower globs, but rcom still needs its own large-directory measurements and cache invalidation tests.

View file

@ -0,0 +1,105 @@
# Yazi file icons and filename coloring (research current to 2026-12-05)
## How are icon rules matched and prioritized (directory, symlink, extension, exact filename, glob)?
### Takeaway
Yazi separates **icon selection** from **filename styling**. Icons use one strict cascade—URL globs, directory names, exact filenames, extensions, then metadata conditions—whereas filename styles use an independent first-match list of URL/MIME/metadata rules. This yields good fast defaults but has important precedence consequences: a known filename/extension wins over `link`/`exec`, and a glob can override every other icon category.
### Cited Findings
- The current stable documentation is labeled **Yazi 26.9.1**. The official configuration guide identifies the release defaults under the repository's `shipped` tag; this research checked that tag at commit `8dd895c695a5950330c2623eb43debf323b60654` as well as the stable documentation. — [Configuration overview](https://yazi-rs.github.io/docs/configuration/overview/); [shipped preset](https://github.com/sxyazi/yazi/tree/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset)
- Documented icon priority is: **`globs` → `dirs` → `files` → `exts` → `conds`**. `dirs`, `files`, and `exts` are hash maps with O(1) lookup; globs always run first and are slower, so the documentation advises not to use them excessively. — [theme.toml: `[icon]`](https://yazi-rs.github.io/docs/configuration/theme/#icon)
- The implementation confirms short-circuit matching: first matching glob returns immediately; for a directory only `dirs` is tried before conditions; for a non-directory `files`, then `exts`, then conditions are tried. Source path: `yazi-config/src/theme/icon.rs`, `Icon::matches`. — [Yazi source: icon.rs](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/src/theme/icon.rs)
- Rule shape is `{ name = "...", text = "...", fg = "..." }` for `dirs`/`files`/`exts`, `{ url = "...", ... }` for `globs`, and `{ if = "...", ... }` for `conds`. Icon rules expose icon **text and foreground color**, not the filename's style. — [theme.toml: icon rule properties](https://yazi-rs.github.io/docs/configuration/theme/#icon)
- Exact name/extension lookup first tries the original spelling and then an ASCII-lowercase key. Thus case-sensitive entries can coexist, while a lowercase rule also serves as an ASCII-case-insensitive fallback; this is a source-level detail beyond the brief public docs. Source path: `yazi-config/src/theme/icon_names.rs`, `IconNames::matches`. — [Yazi source: icon_names.rs](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/src/theme/icon_names.rs)
- Within glob and condition lists, the **first** matching rule wins. Prepending puts user rules before defaults and appending puts them after defaults. For name/extension hash maps, merge order is append → defaults → prepend, so a prepended duplicate wins and an appended duplicate does not replace an existing default key. Source paths: `icon_globs.rs`, `icon_conds.rs`, and `icon.rs`. — [icon_globs.rs](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/src/theme/icon_globs.rs); [icon_conds.rs](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/src/theme/icon_conds.rs); [icon.rs merge logic](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/src/theme/icon.rs)
- URL glob matching is case-insensitive by default; prefix `\s` for case-sensitive matching. A trailing `/` denotes directories: `*` is all files and `*/` all directories. Patterns containing `/` use literal path-separator matching; simple filename globs can match a basename at any depth. Source path: `yazi-config/src/pattern.rs`; the special wildcards are also documented for filetype rules. — [Yazi source: pattern.rs](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/src/pattern.rs); [theme.toml: `[filetype]`](https://yazi-rs.github.io/docs/configuration/theme/#filetype)
- Documented condition factors are `dir`, `hidden`, `link`, `orphan`, `dummy`, `block`, `char`, `fifo`, `sock`, `exec`, and `sticky`; expressions support `|`, `&`, `!`, and parentheses. The shipped source additionally implements `hovered`, used by the default open-folder rule. — [theme.toml: conditions](https://yazi-rs.github.io/docs/configuration/theme/#icon); [Yazi source: icon_cond.rs](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/src/theme/icon_cond.rs); [default conditions in theme-dark.toml](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-dark.toml)
- Shipped condition order puts special files before generic fallbacks: `orphan`, `link`, block/char/FIFO/socket/sticky/dummy, then `dir & hovered`, `dir`, `exec`, and finally `!dir`. Defaults therefore show an open folder glyph for a generic hovered directory, a closed folder otherwise, a terminal glyph for an otherwise-unmatched executable, and a generic file glyph last. — [theme-dark.toml: `[icon].conds`](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-dark.toml)
- Because name/extension categories precede conditions, a symlink named like a known file or carrying a known extension gets that file icon rather than the generic link icon; likewise an executable `.rs` file retains the Rust icon. A specially named directory also keeps its special icon when hovered rather than reaching `dir & hovered`. These outcomes follow directly from the implemented cascade. — [Yazi source: icon.rs](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/src/theme/icon.rs); [default icon conditions](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-dark.toml)
- Users can replace complete lists (`globs = []`, `dirs = [...]`, etc.) or augment them with `prepend_*` and `append_*`. User configuration overrides preset configuration rather than requiring the whole preset to be copied. — [Configuration mixing](https://yazi-rs.github.io/docs/configuration/overview/#mixing); [theme.toml: icon examples](https://yazi-rs.github.io/docs/configuration/theme/#icon)
### Inferences
- **Adopt for rcom:** keep the same conceptual split: a small deterministic icon resolver plus a separate filename-style resolver. It permits blue directory names with cyan folder glyphs, orange Rust glyphs without forcing all Rust filenames orange, and green executable names independently of their specific icon.
- **Adopt the fast-path design:** exact filename and extension hash maps should handle the common case; reserve path globs and compound metadata expressions for overrides. Make ordering and duplicate-key behavior explicit in rcom's own documentation.
- **Consider improving on Yazi:** if rcom wants symlinks or executables always visually identifiable, add a deliberate overlay/badge layer (or a policy switch) instead of letting exact-name/extension matches silently erase all link/executable icon semantics.
### Gaps
- The public icon-condition documentation does not list `hovered`, although the stable source and shipped defaults use it. Treat it as implemented but under-documented rather than as a fully specified public contract.
## How are file names colored, including selection/focus interactions?
### Takeaway
Filename colors come from `[filetype].rules`, using first-match URL/MIME/metadata predicates and full text styles. Cursor/hover is applied afterward by patching the row style; multi-selection is a separate left-edge marker, not the same state as hover. Yazi's default cyan-looking row is not a fixed cyan selection background: current and parent hover default to reverse video.
### Cited Findings
- `[filetype].rules` supports matching by `url` and/or `mime`, plus `is` metadata restriction. Every rule accepts complete `Style` properties: foreground/background, bold, dim, italic, underline, blink, rapid blink, reversed, hidden, and crossed-out. `is` must accompany a `url` or `mime` selector. — [theme.toml: Style](https://yazi-rs.github.io/docs/configuration/theme/#typesstyle); [theme.toml: `[filetype]`](https://yazi-rs.github.io/docs/configuration/theme/#filetype)
- Source evaluation is a linear `.iter().find(...)`: the first matching filetype rule supplies the style; later matches do not merge. Source paths: `yazi-config/src/theme/filetype.rs` and `filetype_rule.rs`. — [filetype.rs](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/src/theme/filetype.rs); [filetype_rule.rs](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/src/theme/filetype_rule.rs)
- Shipped filename colors are ordered as images yellow → audio/video magenta → listed archive MIME types red → PDF/DOC/RTF cyan → absent/stale VFS gray → orphan symlink red **background** → executable green → dummy file/directory red background → directory blue fallback. Ordinary files without another match retain the terminal's default foreground. The same semantic rules ship in dark and light presets. — [theme-dark.toml: `[filetype]`](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-dark.toml); [theme-light.toml: `[filetype]`](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-light.toml)
- There is no ordinary `link` filename-color rule in the shipped defaults; only `orphan` gets a special filename background. A symlink target is rendered separately as ` -> target` and defaults to italic, controlled by `[mgr].symlink_target`; `[mgr].show_symlink` controls whether that target is shown. — [theme-dark.toml](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-dark.toml); [yazi.toml: `show_symlink`](https://yazi-rs.github.io/docs/configuration/yazi/#mgrshow_symlink); [theme.toml: `symlink_target`](https://yazi-rs.github.io/docs/configuration/theme/#mgrsymlink_target)
- The default renderer starts with `file:style()`, then for a hovered row patches `[indicator].current`, `.preview`, or `.parent` depending on pane. Shipped defaults are `current = { reversed = true }`, `parent = { reversed = true }`, and `preview = { underline = true }`. Source path: `yazi-plugin/preset/components/entity.lua`, `Entity:style`. — [entity.lua](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-plugin/preset/components/entity.lua); [theme-dark.toml: `[indicator]`](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-dark.toml)
- On non-hovered rows, the icon is a separately styled span using its own `fg`. On hovered rows the renderer emits icon text without that individual icon style, so it participates in the row's patched filetype/indicator style. This avoids retaining an arbitrary icon foreground under reverse video but means the hovered icon loses its independent color. — [entity.lua: `Entity:icon` and `Entity:redraw`](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-plugin/preset/components/entity.lua)
- Search/find matches inside the filename get `[mgr].find_keyword` styling (default yellow, bold, italic, underline); the hovered match-position counter uses `find_position` (default magenta, bold, italic). These are span-level additions to the row's base style. — [theme.toml: manager styles](https://yazi-rs.github.io/docs/configuration/theme/#mgr); [entity.lua: `highlights` and `found`](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-plugin/preset/components/entity.lua)
- Visual/pre-selected (`marker_marked`), selected (`marker_selected`), copied, and cut states are represented by a one-cell left bar using `marker_symbol = "│"`; their defaults are respectively light cyan, light yellow, light green, and light red in both foreground and background. Marker priority is marked → selected → copied → cut. They do not themselves replace the filetype filename style. — [theme-dark.toml: markers](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-dark.toml); [marker.lua](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-plugin/preset/components/marker.lua)
- Consequently, a supplied screenshot's **blue folders** match Yazi's default filename rule; default dark folder glyphs are cyan `#03a9f4`, dark Rust `rs` glyphs are `#dea584`, and dark `lock` glyphs are `#bbbbbb`. A cyan **full selected/cursor row** would require a custom indicator/flavor; it is not the shipped cursor behavior. The light preset deliberately changes Rust to `#6f5242` and lock to `#5e5e5e`. — [dark icon defaults](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-dark.toml); [light icon defaults](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-light.toml); [default indicators](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-dark.toml)
- Narrow-list behavior reserves space for the right-aligned line mode, truncates the left entity to the remaining width, and uses a custom `….ext` ellipsis when truncation reaches the filename, preserving the extension for non-directories. Source paths: `components/current.lua`, `parent.lua`, and `entity.lua:ellipsis`. — [current.lua](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-plugin/preset/components/current.lua); [parent.lua](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-plugin/preset/components/parent.lua); [entity.lua](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-plugin/preset/components/entity.lua)
### Inferences
- **For the desired rcom look:** a close starting palette is directory filename blue + directory glyph cyan; generic file/lock glyph gray; Rust glyph muted orange; selected/cursor filename cyan or a cyan background with a carefully chosen contrasting foreground. This is a design recommendation, not Yazi's exact default selected-row behavior.
- Keep **hover**, **multi-select**, **cut/copy**, and **find highlight** as orthogonal states with an explicit composition order. Use a non-color marker in addition to row color so state remains understandable in monochrome or low-color terminals.
- For rcom, decide explicitly whether a focused row preserves icon colors. Yazi drops per-icon styling on hover for visual coherence; preserving it can look richer but risks poor contrast against a selection background.
- Preserve extensions during middle truncation, as Yazi does, and allow optional metadata/symlink-target columns to disappear before sacrificing the entire filename.
### Gaps
- The sources define style composition and shipped colors but do not promise WCAG contrast ratios or a color-blindness certification. Actual contrast depends on the terminal palette and flavor.
## Which built-in icon/theme defaults, configuration APIs, and terminal constraints are documented?
### Takeaway
Yazi ships a generated nvim-web-devicons-derived catalog with dark/light presets, named terminal colors or hex RGB, and a mergeable `theme.toml`/flavor system. Nerd Fonts are recommended and enabled by default, not required; missing font glyphs produce placeholders, and users can disable all icons. Base-16 filename defaults inherit the terminal palette and therefore cannot guarantee legibility everywhere.
### Cited Findings
- The built-in catalog originates from **nvim-web-devicons** and is periodically regenerated from upstream using `scripts/icons/generate.lua`; icon contributions are directed upstream. The docs describe this as built-in nvim-web-devicons support. — [CONTRIBUTING.md: Improving Icons](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/CONTRIBUTING.md); [theme.toml: `[icon]`](https://yazi-rs.github.io/docs/configuration/theme/#icon)
- The preset contains named-directory icons (for example `.config`, `.git`, `.github`, Desktop, Documents, Downloads), a large exact-filename list (for example `.gitignore`, Dockerfile, LICENSE, Makefile, README.md), a large extension list, and generic metadata fallbacks. Default generic file icons are white in the dark preset and black in the light preset; directory and executable glyphs are cyan and green in both. — [theme-dark.toml: `[icon]`](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-dark.toml); [theme-light.toml: `[icon]`](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-light.toml)
- `Color` accepts hex RGB such as `#484D66` or 17 named values: `reset`, black/white, normal and light red/green/yellow/blue/magenta/cyan, gray, and dark gray. Named filename colors let the terminal theme determine the actual RGB; built-in icons predominantly use explicit hex colors. — [theme.toml: Color](https://yazi-rs.github.io/docs/configuration/theme/#typescolor); [preset theme](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-dark.toml)
- User configuration lives at `~/.config/yazi/theme.toml` on Unix-like systems or `%AppData%\yazi\config\theme.toml` on Windows; `YAZI_CONFIG_HOME` can relocate the configuration directory. Presets are already built into releases. — [Configuration overview](https://yazi-rs.github.io/docs/configuration/overview/)
- A **flavor** is a packaged theme in `flavors/<kebab-name>.yazi/flavor.toml`; `[flavor].dark` and `.light` select flavors for terminal dark/light mode. Yazi merges user `theme.toml` over `flavor.toml`, so user settings win, and unspecified fields fall back to presets. Flavors can also carry a matching `tmtheme.xml` for code preview. — [Flavors overview](https://yazi-rs.github.io/docs/flavors/overview/)
- The docs recommend validating theme/flavor fields against `https://yazi-rs.github.io/schemas/theme.json` (for example with Taplo) because outdated fields are a common reason themes stop working. — [Flavors: troubleshooting](https://yazi-rs.github.io/docs/flavors/overview/#why-is-my-flavortheme-not-working)
- `file(1)` is the required file-type/MIME detector and Nerd Fonts are an optional recommended dependency. On Windows, the official recommended route is Git for Windows' `file.exe` configured through `YAZI_FILE_ONE`; the official `mime-ext.yazi` plugin is an extension-database alternative when `file` is unavailable. — [Installation prerequisites](https://yazi-rs.github.io/docs/installation/); [Installation: Windows](https://yazi-rs.github.io/docs/installation/#windows)
- Without terminal Nerd Font support, private-use icon codepoints appear as squares or question marks. The documented remedies are Symbols Nerd Font as a fallback font where supported, or a patched Nerd Font as the terminal's single font, followed by terminal restart. — [FAQ: icons not displayed properly](https://yazi-rs.github.io/docs/faq/#icons-incorrect-display)
- Nerd Font icons are enabled by default. The documented no-Nerd-Font/no-icons fallback is to clear `globs`, `dirs`, `files`, `exts`, and `conds` in `[icon]`; the FAQ also shows removing status separators. This is configuration-based, not an automatic font-capability detection mechanism. — [FAQ: I don't like Nerd Fonts](https://yazi-rs.github.io/docs/faq/#dont-like-nerd-fonts)
- The default filetype palette uses terminal base16 colors specifically to track the user's terminal theme, but the FAQ acknowledges poor terminal palettes and differing light/dark needs; it recommends a flavor matching the terminal theme. — [FAQ: text color not distinct](https://yazi-rs.github.io/docs/faq/#why-is-my-text-color-not-distinct)
- Kitty has a documented icon sizing anomaly when file-list items inherit the terminal foreground: icons can shrink and enlarge while scrolling. Applying a file-list foreground via a flavor is the documented workaround; the default theme cannot choose one universal foreground because it does not know whether the terminal background is light or dark. — [FAQ: kitty icon sizing](https://yazi-rs.github.io/docs/faq/#why-do-my-icons-shrink-in-kitty-and-enlarge-when-scrolling)
- `dim` is explicitly not supported by all terminals. `[app].overall` supports only `bg`, and setting terminal background requires OSC 11 support. These are additional reasons not to make subtle attributes or terminal background control the sole visual cue. — [theme.toml: Style](https://yazi-rs.github.io/docs/configuration/theme/#typesstyle); [theme.toml: app overall](https://yazi-rs.github.io/docs/configuration/theme/#appoverall)
### Inferences
- **Reuse the catalog concept, not necessarily Yazi's TOML verbatim:** rcom can derive a maintained icon map from nvim-web-devicons, but should record upstream version/license and provide a regeneration script rather than manually maintaining hundreds of drifting entries.
- Ship dark and light semantic palettes. For screenshot-like aesthetics, use named ANSI colors for broad filename classes when terminal integration matters, and explicit RGB icon colors only with tested light/dark variants.
- Provide three explicit modes: rich Nerd Font, plain Unicode/ASCII, and icons off. Since the official docs describe manual font setup rather than reliable detection, rcom should not pretend it can infer glyph coverage from `$TERM`; remember a user setting and make fallback easy.
- A schema-validated, layered config model (defaults → theme pack → user overrides) is worth adopting. Prepend/append list operations are useful, but rcom should document first-match and override semantics more prominently than Yazi does.
### Gaps
- Official material does not document a universal automatic Nerd Font detection/fallback algorithm or guaranteed glyph widths across terminals. It also does not specify a built-in icon-count guarantee; the generated catalog changes with upstream updates.
## What mistakes should rcom avoid for accessibility and narrow terminals, and what behavior is worth adopting?
### Takeaway
The strongest adoptable behaviors are deterministic precedence, separate icon/name styling, orthogonal state indicators, light/dark palettes, configurable icon fallback, and extension-preserving truncation. The main risks are color-only state, unpredictable palette contrast, private-use glyphs without an alternative, expensive glob-heavy resolution, and over-budget rows that hide filenames.
### Cited Findings
- Yazi itself acknowledges that default colors may be indistinct on poor terminal palettes and that light/dark modes need different colors; its mitigation is terminal-matched flavors rather than a claim that one palette works universally. — [FAQ: text color](https://yazi-rs.github.io/docs/faq/#why-is-my-text-color-not-distinct)
- Yazi supplies a non-color one-cell marker for selected/copied/cut/visual states, separately from reverse-video hover; find matches additionally use bold/italic/underline rather than color alone. — [marker.lua](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-plugin/preset/components/marker.lua); [default manager styles](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-dark.toml)
- Broken links and dummy metadata are especially conspicuous in the default theme through red **background**, not merely a subtle foreground shift; orphan and dummy also have dedicated fallback icons. — [default filetype rules and icon conditions](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-config/preset/theme-dark.toml)
- Yazi measures component widths, subtracts right-aligned metadata from available row width, truncates with ellipsis, and preserves a non-directory extension when possible. — [current.lua layout](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-plugin/preset/components/current.lua); [entity.lua ellipsis](https://github.com/sxyazi/yazi/blob/8dd895c695a5950330c2623eb43debf323b60654/yazi-plugin/preset/components/entity.lua)
- Glob rules have a documented performance cost, whereas exact names/extensions use O(1) maps. — [theme.toml: icon performance](https://yazi-rs.github.io/docs/configuration/theme/#icon)
- Missing Nerd Font support yields placeholder glyphs, and Yazi provides a complete icon-off configuration. — [FAQ: incorrect icons](https://yazi-rs.github.io/docs/faq/#icons-incorrect-display); [FAQ: disable Nerd Fonts](https://yazi-rs.github.io/docs/faq/#dont-like-nerd-fonts)
### Inferences
- **Accessibility recommendation:** never encode directory/symlink/executable/error/selection solely by hue. Pair filename color with shape or text (folder/link/executable glyph, `-> target`, permission/exec column, selection bar), and ensure an icons-off mode still exposes critical state textually.
- **Contrast recommendation:** test every icon/name color on both dark and light backgrounds and on focused rows. Avoid dim as a required cue. For a cyan selected row, compute a deliberate contrasting foreground instead of simply reversing arbitrary icon RGB values; allow a high-contrast theme.
- **Color semantics recommendation:** use a restrained semantic palette—blue directories, neutral generic files/locks, orange Rust, green executables, red errors/broken links—and avoid giving every extension a different filename color. Keep the richer per-extension hues primarily on icons so filenames remain scannable.
- **Narrow-terminal recommendation:** define an explicit width budget and degradation sequence: truncate optional symlink target/right metadata first; hide or shorten secondary columns next; preserve icon + as much basename as possible; use middle ellipsis that retains extension; finally allow icons off. Do not let a Nerd Font glyph's terminal width break alignment—measure rendered cells with the TUI library and test ambiguous/wide glyphs.
- **Resolver recommendation:** cache exact-name/extension lookups per entry and keep globs ordered and bounded. Test precedence cases explicitly: exact filename vs extension, special directory vs hovered-open directory, known-name symlink vs link fallback, executable known extension vs exec fallback, broken link, glob override, and case variants.
- **Configuration recommendation:** expose separate `icon` and `filename_style` rule sets, with reset/replace and ordered prepend/append operations. Document that icon foreground does not automatically recolor the filename unless rcom intentionally adds such an option.
### Gaps
- No official Yazi source found here prescribes a minimum terminal width, exact accessibility contrast threshold, or an algorithm for choosing black/white foreground over arbitrary selection backgrounds. Those remain rcom design and testing responsibilities rather than documented Yazi behavior.

1003
src/app/help.rs Normal file

File diff suppressed because it is too large Load diff

View file

@ -8,6 +8,7 @@ use std::collections::{BTreeMap, BTreeSet};
use std::ffi::OsString;
pub mod actions;
pub mod help;
pub mod operations;
pub mod preview;
@ -18,6 +19,9 @@ pub use actions::{
PrepareUndoResult, PreparedEditor, PreparedEntryAction, RunEditorRequest, UndoConsequence,
UndoInverseKind, UndoRecord, UndoSession, UndoSummary,
};
pub use help::{
HELP_INVENTORY, HelpCategory, HelpContext, HelpEntry, HelpState, HelpViewport, help_entries,
};
pub use operations::{
CollisionChoice, CollisionResolution, DestinationFingerprint, ExecuteOperationRequest,
ItemDiagnostic, OperationCollision, OperationSession, PaneSnapshot, PlanOperationOutput,
@ -32,7 +36,8 @@ use crate::domain::{
use crate::fs::FsError;
pub use crate::operations::OperationKind;
use crate::operations::{OperationEvent, OperationId, PlanId, TaskId, TaskManager};
use crate::preview::Preview;
use crate::preview::{EncodedImage, Preview};
use crate::ui::{Theme, ThemeId};
pub type Generation = u64;
pub type SessionEpoch = u64;
@ -94,6 +99,7 @@ pub enum Overlay {
Help,
HostPicker,
Preview,
ThemePicker,
Message,
DestinationPrompt,
ConfirmOperation,
@ -107,15 +113,54 @@ pub enum Overlay {
Quit,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ThemePickerState {
pub selected: ThemeId,
pub baseline: Theme,
pub scroll: usize,
pub error: Option<String>,
}
impl ThemePickerState {
fn new(theme: Theme) -> Self {
let selected = theme.id;
let index = ThemeId::ALL
.iter()
.position(|id| *id == selected)
.unwrap_or(0);
Self {
selected,
baseline: theme,
scroll: index.saturating_sub(2),
error: None,
}
}
pub fn selected_index(&self) -> usize {
ThemeId::ALL
.iter()
.position(|id| *id == self.selected)
.unwrap_or(0)
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct PreviewState {
/// Location for which the current preview request or result was produced.
pub target: Option<Location>,
pub content: Option<Preview>,
pub loading: bool,
/// Selection coalescing clears stale content without showing a loading flash.
pub debouncing: bool,
/// Tracks a pending/running selection request across a failed navigation attempt.
pub selection_recovery: bool,
/// Background rereads retain completed content/error until a current response arrives.
pub background_refresh: bool,
pub error: Option<FsError>,
/// Encoded bytes are accepted reducer metadata; prepared terminal protocols stay outside state.
pub encoded_image: Option<EncodedImage>,
/// Generation of accepted encoded bytes, distinct from an in-flight background request.
pub image_generation: Generation,
}
#[derive(Clone, Debug, Eq, PartialEq)]
@ -155,6 +200,8 @@ pub struct PaneState {
pub background_refresh: bool,
pub error: Option<FsError>,
pub listing_generation: Generation,
/// Changes on target/endpoint navigation, but not same-location background polling.
pub navigation_generation: Generation,
pub preview_generation: Generation,
/// `None` for local panes and for remote panes which do not have a session yet.
pub session_epoch: Option<SessionEpoch>,
@ -183,6 +230,7 @@ impl PaneState {
background_refresh: false,
error: None,
listing_generation: 0,
navigation_generation: 0,
preview_generation: 0,
session_epoch: None,
session_host: match &location.source {
@ -219,7 +267,7 @@ impl PaneState {
// A preview response is addressed to the source pane only. Do not leave the clone waiting
// for a request which the runner never started for it.
if copy.preview.loading {
if copy.preview.loading || copy.preview.debouncing {
copy.preview = PreviewState::default();
copy.preview_generation = next_generation(copy.preview_generation);
}
@ -237,8 +285,15 @@ pub struct AppState {
pub panes: [PaneState; 2],
pub mode: PaneMode,
pub active: PaneId,
pub theme: Theme,
/// Invalidates terminal-owned prepared graphics after editor suspend/resume.
pub terminal_epoch: u64,
pub images_enabled: bool,
pub theme_picker: Option<ThemePickerState>,
pub overlay: Overlay,
/// Logical first line of a scrollable overlay. Rendering clamps it to the current viewport.
/// Category and normalized rendered-line offset for the current Help opening.
pub help: HelpState,
/// Logical first line of non-Help scrollable overlays. Rendering clamps it to the viewport.
pub overlay_scroll: usize,
pub should_quit: bool,
pub clipboard: Option<Clipboard>,
@ -281,7 +336,12 @@ impl AppState {
],
mode: PaneMode::Single,
active: PaneId::Left,
theme: Theme::default(),
terminal_epoch: 0,
images_enabled: true,
theme_picker: None,
overlay: Overlay::None,
help: HelpState::default(),
overlay_scroll: 0,
should_quit: false,
clipboard: None,
@ -514,6 +574,79 @@ impl AppState {
.into_iter()
.collect()
}
Command::OpenThemePicker => {
if self.overlay == Overlay::None {
self.theme_picker = Some(ThemePickerState::new(self.theme));
self.set_overlay(Overlay::ThemePicker);
}
Vec::new()
}
Command::MoveThemeSelection { delta, page_size } => {
if self.overlay == Overlay::ThemePicker
&& let Some(picker) = &mut self.theme_picker
{
let current = picker.selected_index() as isize;
let last = ThemeId::ALL.len() as isize - 1;
let next = (current + delta).clamp(0, last) as usize;
picker.selected = ThemeId::ALL[next];
picker.error = None;
let visible = page_size.max(1).min(ThemeId::ALL.len());
if next < picker.scroll {
picker.scroll = next;
} else if next >= picker.scroll + visible {
picker.scroll = next + 1 - visible;
}
picker.scroll = picker.scroll.min(ThemeId::ALL.len() - visible);
self.theme = picker.baseline.with_id(picker.selected);
}
Vec::new()
}
Command::SaveTheme => {
if self.overlay == Overlay::ThemePicker
&& let Some(picker) = &self.theme_picker
{
return vec![Effect::SaveTheme(picker.selected)];
}
Vec::new()
}
Command::ThemeSaveFinished { id, result } => {
if self.overlay == Overlay::ThemePicker
&& let Some(picker) = &mut self.theme_picker
&& picker.selected == id
{
match result {
Ok(_) => {
self.theme_picker = None;
self.set_overlay(Overlay::None);
}
Err(error) => {
self.theme = picker.baseline;
picker.error = Some(error);
}
}
}
Vec::new()
}
Command::SelectHelpCategory(delta) => {
if self.overlay == Overlay::Help {
self.help.category = self.help.category.moved(delta);
self.help.scroll = 0;
}
Vec::new()
}
Command::ScrollHelp { delta, max_scroll } => {
if self.overlay == Overlay::Help {
let current = self.help.scroll.min(max_scroll);
self.help.scroll = current.saturating_add_signed(delta).min(max_scroll);
}
Vec::new()
}
Command::NormalizeHelpScroll(max_scroll) => {
if self.overlay == Overlay::Help {
self.help.scroll = self.help.scroll.min(max_scroll);
}
Vec::new()
}
Command::ToggleHelp => {
let overlay = if self.overlay == Overlay::Help {
Overlay::None
@ -541,7 +674,7 @@ impl AppState {
Command::ScrollOverlay(delta) => {
if matches!(
self.overlay,
Overlay::Help | Overlay::Message | Overlay::Tasks | Overlay::TaskDetails
Overlay::Message | Overlay::Tasks | Overlay::TaskDetails
) {
self.overlay_scroll = self.overlay_scroll.saturating_add_signed(delta);
}
@ -572,6 +705,13 @@ impl AppState {
Vec::new()
}
Overlay::Quit => self.decide_quit(QuitDecision::Stay),
Overlay::ThemePicker => {
if let Some(picker) = self.theme_picker.take() {
self.theme = picker.baseline;
}
self.set_overlay(Overlay::None);
Vec::new()
}
_ => {
// Closing Tasks never cancels its operations.
self.set_overlay(Overlay::None);
@ -584,6 +724,14 @@ impl AppState {
}
Command::ListingFinished(result) => self.finish_listing(result),
Command::PreviewFinished(result) => self.finish_preview(result),
Command::ImagePrepared(result) => self.finish_image_preparation(result),
Command::StartPreview {
request,
navigation_generation,
} => self
.start_preview(request, navigation_generation)
.into_iter()
.collect(),
Command::SynchronizeSshEpoch {
host,
session_epoch,
@ -596,6 +744,9 @@ impl AppState {
}
fn set_overlay(&mut self, overlay: Overlay) {
if overlay == Overlay::Help || self.overlay == Overlay::Help {
self.help = HelpState::default();
}
self.overlay = overlay;
self.overlay_scroll = 0;
}
@ -652,7 +803,7 @@ impl AppState {
};
if moved {
self.select_visual_path(active);
self.request_preview(active)
self.debounce_preview(active)
} else {
None
}
@ -672,7 +823,7 @@ impl AppState {
};
if moved {
self.select_visual_path(active);
self.request_preview(active)
self.debounce_preview(active)
} else {
None
}
@ -824,6 +975,9 @@ impl AppState {
if target.source == pane.location.source {
cancel_cross_endpoint_pending(pane);
}
if !background_refresh && target != pane.location {
pane.navigation_generation = next_generation(pane.navigation_generation);
}
pane.listing_generation = next_generation(pane.listing_generation);
pane.pending_target = Some(target.clone());
pane.pending_selection = preferred_selection;
@ -844,7 +998,11 @@ impl AppState {
}
fn request_preview(&mut self, pane_id: PaneId) -> Option<Effect> {
self.request_preview_mode(pane_id, false)
self.request_preview_kind(pane_id, false, false)
}
fn debounce_preview(&mut self, pane_id: PaneId) -> Option<Effect> {
self.request_preview_kind(pane_id, false, true)
}
fn request_preview_mode(
@ -852,6 +1010,16 @@ impl AppState {
pane_id: PaneId,
background_refresh: bool,
) -> Option<Effect> {
self.request_preview_kind(pane_id, background_refresh, false)
}
fn request_preview_kind(
&mut self,
pane_id: PaneId,
background_refresh: bool,
debounce: bool,
) -> Option<Effect> {
let images_enabled = self.images_enabled;
let pane = self.pane_mut(pane_id);
pane.preview_generation = next_generation(pane.preview_generation);
let generation = pane.preview_generation;
@ -872,28 +1040,63 @@ impl AppState {
if retain_completed_preview {
pane.preview.target = Some(target.clone());
pane.preview.loading = true;
pane.preview.debouncing = false;
pane.preview.selection_recovery = false;
pane.preview.background_refresh = true;
} else {
pane.preview = PreviewState {
target: Some(target.clone()),
content: None,
loading: true,
loading: !debounce,
debouncing: debounce,
selection_recovery: debounce,
background_refresh: false,
error: None,
encoded_image: None,
image_generation: generation,
};
}
Some(Effect::LoadPreview(PreviewRequest {
let request = PreviewRequest {
pane: pane_id,
generation,
target,
session_epoch,
}))
images_enabled,
};
Some(if debounce {
Effect::DebouncePreview(request)
} else {
Effect::LoadPreview(request)
})
}
fn start_preview(
&mut self,
request: PreviewRequest,
navigation_generation: Generation,
) -> Option<Effect> {
let pane = self.pane_mut(request.pane);
if !pane.preview.debouncing
|| pane.preview_generation != request.generation
|| pane.preview.target.as_ref() != Some(&request.target)
|| pane.selected_location().as_ref() != Some(&request.target)
|| pane.navigation_generation != navigation_generation
|| pane.session_epoch != request.session_epoch
|| !session_matches_target(pane, &request.target)
{
return None;
}
pane.preview.loading = true;
pane.preview.debouncing = false;
pane.preview.background_refresh = false;
Some(Effect::LoadPreview(request))
}
fn request_ssh_connect(&mut self, pane_id: PaneId, host: HostAlias) -> Option<Effect> {
self.set_overlay(Overlay::None);
let pane = self.pane_mut(pane_id);
cancel_cross_endpoint_pending(pane);
pane.navigation_generation = next_generation(pane.navigation_generation);
pane.listing_generation = next_generation(pane.listing_generation);
let generation = pane.listing_generation;
let expected_session_epoch = pane.session_epoch;
@ -1005,12 +1208,31 @@ impl AppState {
// A new successful listing also selects an entry, so persistent and overlay preview
// can share the same generation-isolated request path.
self.request_preview_mode(pane_id, was_background)
.into_iter()
.collect()
let preserve_selection_debounce = {
let pane = self.pane(pane_id);
was_background
&& (pane.preview.debouncing
|| (pane.preview.loading
&& !pane.preview.background_refresh
&& pane.preview.content.is_none()
&& pane.preview.error.is_none()))
&& pane.preview.target == pane.selected_location()
};
if preserve_selection_debounce {
Vec::new()
} else {
self.request_preview_mode(pane_id, was_background)
.into_iter()
.collect()
}
}
Err(error) => {
let recover_debounced_preview = {
let pane = self.pane(pane_id);
pane.preview.selection_recovery
};
let pane = self.pane_mut(pane_id);
pane.preview.debouncing = false;
if let Some(pending_home) = pane.pending_home.take() {
let same_host = match (&pane.location.source, &target.source) {
(SourceId::Ssh(confirmed), SourceId::Ssh(attempted)) => {
@ -1039,7 +1261,11 @@ impl AppState {
pane.pending_connect = None;
pane.loading = false;
pane.error = Some(error);
Vec::new()
if recover_debounced_preview {
self.request_preview(pane_id).into_iter().collect()
} else {
Vec::new()
}
}
}
}
@ -1051,6 +1277,7 @@ impl AppState {
target,
session_epoch,
result,
encoded_image,
} = result;
let pane = self.pane_mut(pane_id);
if pane.preview_generation != generation
@ -1062,20 +1289,59 @@ impl AppState {
}
pane.preview.loading = false;
pane.preview.debouncing = false;
pane.preview.selection_recovery = false;
pane.preview.background_refresh = false;
match result {
Ok(preview) => {
pane.preview.content = Some(preview);
pane.preview.encoded_image = encoded_image;
pane.preview.image_generation = generation;
pane.preview.error = None;
}
Err(error) => {
pane.preview.content = None;
pane.preview.encoded_image = None;
pane.preview.image_generation = generation;
pane.preview.error = Some(error);
}
}
Vec::new()
}
fn finish_image_preparation(&mut self, result: ImagePreparationResult) -> Vec<Effect> {
if result.result.is_ok() {
return Vec::new();
}
let identity = result.identity;
let pane = self.pane_mut(identity.pane);
if pane.preview_generation != identity.generation
|| pane.preview.target.as_ref() != Some(&identity.target)
|| pane.selected_location().as_ref() != Some(&identity.target)
|| pane.session_epoch != identity.session_epoch
|| !session_matches_target(pane, &identity.target)
{
return Vec::new();
}
if pane
.preview
.content
.as_ref()
.is_some_and(|preview| preview.kind == crate::preview::PreviewKind::Image)
{
pane.preview.content = Some(crate::preview::Preview {
kind: crate::preview::PreviewKind::Metadata,
lines: vec![
"Image preview is unavailable.".to_owned(),
format!("Reason: {}", result.result.unwrap_err()),
],
truncated: false,
});
pane.preview.encoded_image = None;
}
Vec::new()
}
fn synchronize_ssh_epoch(&mut self, host: HostAlias, session_epoch: SessionEpoch) {
for pane in &mut self.panes {
let confirmed_host = match &pane.location.source {
@ -1171,6 +1437,10 @@ impl AppState {
let connection = match result {
Ok(connection) => connection,
Err(error) => {
let recover_debounced_preview = {
let preview = &self.pane(pane_id).preview;
preview.selection_recovery
};
let confirmed_host = match &self.pane(pane_id).location.source {
SourceId::Ssh(confirmed) => Some(confirmed.clone()),
SourceId::Local => None,
@ -1182,15 +1452,23 @@ impl AppState {
pane.pending_home = None;
pane.loading = false;
pane.preview.loading = false;
pane.preview.debouncing = false;
if confirmed_host.as_ref() != Some(&host) {
restore_confirmed_session(pane);
}
pane.error = Some(error);
if recover_debounced_preview {
return self.request_preview(pane_id).into_iter().collect();
}
return Vec::new();
}
};
if connection.location.source != SourceId::Ssh(host.clone()) {
let recover_preview = {
let preview = &self.pane(pane_id).preview;
preview.selection_recovery
};
let confirmed_host = match &self.pane(pane_id).location.source {
SourceId::Ssh(confirmed) => Some(confirmed.clone()),
SourceId::Local => None,
@ -1201,12 +1479,16 @@ impl AppState {
pane.pending_home = None;
pane.loading = false;
pane.preview.loading = false;
pane.preview.debouncing = false;
if confirmed_host.as_ref() != Some(&host) {
restore_confirmed_session(pane);
}
pane.error = Some(FsError::Other(
"SSH connector returned a location for a different host".into(),
));
if recover_preview {
return self.request_preview(pane_id).into_iter().collect();
}
return Vec::new();
}
@ -1227,6 +1509,7 @@ impl AppState {
if superseded {
// A newer synchronization of the attempted host has superseded this result. Do not
// leave the pane stuck in a completed connection's loading state.
let recover_preview = pane.preview.selection_recovery;
let confirmed_host = match &pane.location.source {
SourceId::Ssh(confirmed) => Some(confirmed.clone()),
SourceId::Local => None,
@ -1237,9 +1520,13 @@ impl AppState {
pane.pending_home = None;
pane.loading = false;
pane.preview.loading = false;
pane.preview.debouncing = false;
if confirmed_host.as_ref() != Some(&host) {
restore_confirmed_session(pane);
}
if recover_preview {
return self.request_preview(pane_id).into_iter().collect();
}
return Vec::new();
}
}
@ -1350,6 +1637,7 @@ pub struct PreviewRequest {
pub generation: Generation,
pub target: Location,
pub session_epoch: Option<SessionEpoch>,
pub images_enabled: bool,
}
impl PreviewRequest {
@ -1360,6 +1648,7 @@ impl PreviewRequest {
target: self.target,
session_epoch: self.session_epoch,
result,
encoded_image: None,
}
}
}
@ -1371,6 +1660,13 @@ pub struct PreviewResult {
pub target: Location,
pub session_epoch: Option<SessionEpoch>,
pub result: Result<Preview, FsError>,
pub encoded_image: Option<EncodedImage>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ImagePreparationResult {
pub identity: crate::image_preview::PreparedImageIdentity,
pub result: Result<(), String>,
}
/// Successful SSH connect/canonicalize output. The reducer subsequently requests its listing.
@ -1415,7 +1711,11 @@ pub struct ConnectSshResult {
pub enum Effect {
LoadListing(ListingRequest),
LoadPreview(PreviewRequest),
/// Session-owned coalescing; EffectRunner must not perform I/O for this variant.
DebouncePreview(PreviewRequest),
ConnectSsh(ConnectSshRequest),
/// Persist only the selected theme; the session owns config I/O and fingerprint checks.
SaveTheme(ThemeId),
/// Read-only preflight; no task is started and no write effect is emitted.
PlanOperation(PlanOperationRequest),
/// Explicitly confirmed execution of the manager's currently active copy/move operation.
@ -1537,6 +1837,22 @@ pub enum Command {
RefreshPane(PaneId),
GoHome(Location),
ToggleHelp,
SelectHelpCategory(isize),
ScrollHelp {
delta: isize,
max_scroll: usize,
},
NormalizeHelpScroll(usize),
OpenThemePicker,
MoveThemeSelection {
delta: isize,
page_size: usize,
},
SaveTheme,
ThemeSaveFinished {
id: ThemeId,
result: Result<Vec<u8>, String>,
},
OpenHostPicker,
OpenPreview,
OpenMessage,
@ -1545,6 +1861,11 @@ pub enum Command {
ConnectSsh(HostAlias),
ListingFinished(ListingResult),
PreviewFinished(PreviewResult),
ImagePrepared(ImagePreparationResult),
StartPreview {
request: PreviewRequest,
navigation_generation: Generation,
},
SynchronizeSshEpoch {
host: HostAlias,
session_epoch: SessionEpoch,

View file

@ -757,7 +757,14 @@ impl AppState {
Some(effect)
}
pub(crate) fn restore_theme_baseline(&mut self) {
if let Some(picker) = self.theme_picker.take() {
self.theme = picker.baseline;
}
}
pub(crate) fn request_quit(&mut self) {
self.restore_theme_baseline();
if self.has_unfinished_tasks() {
self.set_overlay(Overlay::Quit);
} else {
@ -772,6 +779,7 @@ impl AppState {
match decision {
QuitDecision::Stay => {
self.quit_after_tasks = false;
self.restore_theme_baseline();
self.set_overlay(Overlay::None);
Vec::new()
}

View file

@ -1,48 +1,105 @@
//! Execution of preview effects through the read-only filesystem port.
//!
//! Task cancellation belongs to the asynchronous runner. This helper only performs the bounded
//! reads and attaches the request identity to its result; the reducer rejects superseded results.
//! Task cancellation belongs to the asynchronous runner. This helper only performs bounded
//! reads and attaches request identity; decoding/preparing recognized images is delegated to the
//! serialized application image worker after the reducer accepts the result.
use std::sync::Arc;
use super::{PreviewRequest, PreviewResult};
use crate::domain::{Entry, EntryKind, Location};
use crate::fs::{FsError, ReadFileSystem};
use crate::image_preview::{MAX_IMAGE_BYTES, supported_format};
use crate::preview::{
DIRECTORY_PREVIEW_LIMIT, EntryPreview, MAX_PREVIEW_BYTES, PreviewKind, binary_placeholder,
directory_preview, metadata_placeholder, preview_bytes,
DIRECTORY_PREVIEW_LIMIT, EncodedImage, EntryPreview, MAX_PREVIEW_BYTES, Preview, PreviewKind,
binary_placeholder, directory_preview, metadata_placeholder, preview_bytes,
};
/// Executes one preview request without retaining more than [`MAX_PREVIEW_BYTES`] of file data.
///
/// Metadata is loaded for every entry kind. Directories are listed non-recursively, regular files
/// use the bounded preview core, and unsupported kinds produce a metadata-only placeholder. All
/// filesystem failures remain typed in the returned [`PreviewResult`].
/// Executes one preview request without retaining more than the applicable bounded input limit.
pub async fn execute_preview(request: PreviewRequest, fs: &dyn ReadFileSystem) -> PreviewResult {
let result = build_preview(fs, &request.target).await;
request.into_result(result)
match build_preview(fs, &request.target, request.images_enabled).await {
Ok(output) => {
let mut result = request.into_result(Ok(output.preview));
result.encoded_image = output.image;
result
}
Err(error) => request.into_result(Err(error)),
}
}
struct PreviewOutput {
preview: Preview,
image: Option<EncodedImage>,
}
impl From<Preview> for PreviewOutput {
fn from(preview: Preview) -> Self {
Self {
preview,
image: None,
}
}
}
async fn build_preview(
fs: &dyn ReadFileSystem,
target: &Location,
) -> Result<crate::preview::Preview, FsError> {
images_enabled: bool,
) -> Result<PreviewOutput, FsError> {
let entry = fs.metadata(target).await?;
match entry.kind {
EntryKind::Directory => {
let entries = fs.list_prefix(target, DIRECTORY_PREVIEW_LIMIT + 1).await?;
Ok(directory_preview(entries.into_iter().map(|entry| {
EntryPreview::new(entry.name, entry.kind.is_directory())
})))
Ok(directory_preview(
entries
.into_iter()
.map(|entry| EntryPreview::new(entry.name, entry.kind.is_directory())),
)
.into())
}
EntryKind::File => {
let prefix = fs.read_prefix(target, MAX_PREVIEW_BYTES).await?;
if let Some(format) = supported_format(&prefix.data) {
if !images_enabled {
return Ok(binary_placeholder([
"Image preview is disabled or unavailable in this terminal.",
&format!("Type: {format:?}"),
])
.into());
}
let encoded = fs.read_prefix(target, MAX_IMAGE_BYTES).await?;
if encoded.truncated {
return Ok(metadata_placeholder([
"Image exceeds the 16 MiB preview limit; pixels are not decoded.",
&format!("Type: {format:?}"),
])
.into());
}
let preview = metadata_placeholder([
format!("Image format: {format:?}"),
"Preparing static pixel preview…".to_owned(),
]);
return Ok(PreviewOutput {
preview: Preview {
kind: PreviewKind::Image,
..preview
},
image: Some(EncodedImage {
bytes: Arc::new(encoded.data),
format,
}),
});
}
let preview = preview_bytes(&prefix.data, prefix.truncated);
if preview.kind == PreviewKind::Binary {
Ok(binary_placeholder(metadata_lines(&entry)))
Ok(binary_placeholder(metadata_lines(&entry)).into())
} else {
Ok(preview)
Ok(preview.into())
}
}
EntryKind::Symlink | EntryKind::Other => Ok(metadata_placeholder(metadata_lines(&entry))),
EntryKind::Symlink | EntryKind::Other => {
Ok(metadata_placeholder(metadata_lines(&entry)).into())
}
}
}

30
src/cli.rs Normal file
View file

@ -0,0 +1,30 @@
//! Command-line arguments kept separate from terminal initialization for testability.
use std::path::PathBuf;
use clap::Parser;
use crate::ui::{IconMode, ThemeId};
#[derive(Debug, Parser)]
#[command(
name = "rcom",
version,
about = "Dual-pane local and SSH terminal file manager"
)]
pub struct Cli {
/// Existing local directory to open in the initial pane.
pub path: Option<PathBuf>,
/// Override the icon family for this process without changing the saved config.
#[arg(long, value_enum)]
pub icons: Option<IconMode>,
/// Override the built-in color theme for this process without changing the saved config.
#[arg(long, value_enum)]
pub theme: Option<ThemeId>,
/// Print the offline built-in theme catalog and exit before terminal initialization.
#[arg(long)]
pub list_themes: bool,
/// Disable image decoding and terminal graphics probes for this process.
#[arg(long)]
pub no_images: bool,
}

200
src/config.rs Normal file
View file

@ -0,0 +1,200 @@
//! Typed user configuration with deterministic paths and no implicit writes.
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use directories::ProjectDirs;
use serde::Deserialize;
use thiserror::Error;
use crate::ui::{IconMode, ThemeId};
/// Shared application settings. Unknown fields are ignored for forward compatibility.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize)]
pub struct Config {
#[serde(default)]
pub icons: IconMode,
#[serde(default)]
pub theme: ThemeId,
#[serde(default = "default_images")]
pub images: bool,
}
const fn default_images() -> bool {
true
}
impl Default for Config {
fn default() -> Self {
Self {
icons: IconMode::default(),
theme: ThemeId::default(),
images: default_images(),
}
}
}
impl Config {
/// A CLI value overrides only the current process and never mutates this config.
pub fn selected_icon_mode(&self, cli_override: Option<IconMode>) -> IconMode {
cli_override.unwrap_or(self.icons)
}
pub fn selected_theme(&self, cli_override: Option<ThemeId>) -> ThemeId {
cli_override.unwrap_or(self.theme)
}
pub fn images_enabled(&self, no_images: bool) -> bool {
self.images && !no_images
}
}
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("Cannot read config {path}: {source}")]
Read {
path: PathBuf,
#[source]
source: io::Error,
},
#[error("Cannot parse config {path}: {source}")]
Parse {
path: PathBuf,
#[source]
source: toml::de::Error,
},
}
pub fn load_from_path(path: &Path) -> Result<Config, ConfigError> {
match std::fs::read_to_string(path) {
Ok(contents) => toml::from_str(&contents).map_err(|source| ConfigError::Parse {
path: path.to_path_buf(),
source,
}),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Config::default()),
Err(source) => Err(ConfigError::Read {
path: path.to_path_buf(),
source,
}),
}
}
/// Session-scoped config writer with an exact-content external-change fingerprint.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ConfigFaultPoint {
CreateDirectory,
Write,
Sync,
Rename,
}
#[derive(Clone, Debug)]
pub struct ThemeConfigStore {
path: PathBuf,
fingerprint: Option<Vec<u8>>,
fault: Option<ConfigFaultPoint>,
}
impl ThemeConfigStore {
pub fn new(path: PathBuf) -> Self {
Self {
path,
fingerprint: None,
fault: None,
}
}
#[doc(hidden)]
pub fn inject_fault_for_test(&mut self, fault: ConfigFaultPoint) {
self.fault = Some(fault);
}
fn check_fault(&self, stage: ConfigFaultPoint) -> Result<(), String> {
if self.fault == Some(stage) {
Err(format!("injected config {stage:?} failure"))
} else {
Ok(())
}
}
pub fn capture(&mut self) -> Result<(), String> {
self.fingerprint = read_optional(&self.path)?;
Ok(())
}
/// Saves only `theme`, retaining every other TOML field and refusing external changes.
pub fn save(&mut self, id: ThemeId) -> Result<Vec<u8>, String> {
let current = read_optional(&self.path)?;
if current != self.fingerprint {
return Err("Config changed outside rcom; reopen Theme Picker and retry".into());
}
let source = current
.as_deref()
.map(|bytes| {
std::str::from_utf8(bytes)
.map(str::to_owned)
.map_err(|error| format!("Config is not UTF-8: {error}"))
})
.unwrap_or_else(|| Ok(String::new()))?;
let mut document = if source.trim().is_empty() {
toml::Value::Table(toml::map::Map::new())
} else {
toml::from_str::<toml::Value>(&source)
.map_err(|error| format!("Cannot parse config for theme save: {error}"))?
};
let table = document
.as_table_mut()
.ok_or_else(|| "Config root must be a TOML table".to_owned())?;
table.insert("theme".into(), toml::Value::String(id.as_str().to_owned()));
let output = toml::to_string_pretty(&document)
.map_err(|error| format!("Cannot serialize config: {error}"))?;
let parent = self.path.parent().unwrap_or_else(|| Path::new("."));
self.check_fault(ConfigFaultPoint::CreateDirectory)?;
std::fs::create_dir_all(parent).map_err(|error| {
format!(
"Cannot create config directory {}: {error}",
parent.display()
)
})?;
let mut temporary = tempfile::NamedTempFile::new_in(parent)
.map_err(|error| format!("Cannot create temporary config: {error}"))?;
self.check_fault(ConfigFaultPoint::Write)?;
temporary
.write_all(output.as_bytes())
.map_err(|error| format!("Cannot write temporary config: {error}"))?;
self.check_fault(ConfigFaultPoint::Sync)?;
temporary
.as_file()
.sync_all()
.map_err(|error| format!("Cannot sync temporary config: {error}"))?;
self.check_fault(ConfigFaultPoint::Rename)?;
temporary
.persist(&self.path)
.map_err(|error| format!("Cannot replace {}: {}", self.path.display(), error.error))?;
self.fingerprint = Some(output.as_bytes().to_vec());
Ok(output.into_bytes())
}
}
fn read_optional(path: &Path) -> Result<Option<Vec<u8>>, String> {
match std::fs::read(path) {
Ok(contents) => Ok(Some(contents)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(format!("Cannot read config {}: {error}", path.display())),
}
}
pub fn config_path() -> PathBuf {
if let Some(root) = std::env::var_os("RCOM_CONFIG_HOME") {
return config_path_at(Path::new(&root));
}
ProjectDirs::from("", "", "rcom").map_or_else(
|| PathBuf::from("config.toml"),
|directories| config_path_at(directories.config_dir()),
)
}
/// Constructs the filename below an explicitly selected config root.
pub fn config_path_at(root: &Path) -> PathBuf {
root.join("config.toml")
}

373
src/image_preview.rs Normal file
View file

@ -0,0 +1,373 @@
//! Bounded, static image decoding shared by Local and SSH preview preparation.
//!
//! No function in this module writes to a terminal. Encoding and resize work is intended for the
//! single blocking worker; the renderer receives only a fixed `ratatui_image::Protocol`.
use std::io::{Cursor, IsTerminal};
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::app::{Generation, PaneId, SessionEpoch};
use crate::domain::Location;
use image::{DynamicImage, ImageReader, Limits};
use ratatui::layout::Size;
use ratatui_image::{
FontSize, Resize,
picker::{Picker, ProtocolType, cap_parser::QueryStdioOptions},
protocol::Protocol,
};
use thiserror::Error;
pub const MAX_IMAGE_BYTES: usize = 16 * 1024 * 1024;
pub const MAX_IMAGE_AXIS: u32 = 8192;
pub const MAX_IMAGE_PIXELS: u64 = 32_000_000;
pub const MAX_IMAGE_ALLOC: u64 = 256 * 1024 * 1024;
pub const HALFBLOCK_FONT_SIZE: FontSize = FontSize {
width: 10,
height: 20,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SupportedImageFormat {
Png,
Jpeg,
Gif,
Bmp,
WebP,
}
#[derive(Debug, Error)]
pub enum ImagePreviewError {
#[error("image exceeds the 16 MiB encoded input limit")]
EncodedTooLarge,
#[error("unsupported image format")]
UnsupportedFormat,
#[error("image dimensions exceed the safe preview limits")]
DimensionsTooLarge,
#[error("image preview area is empty")]
EmptyArea,
#[error("cannot read image: {0}")]
Read(#[from] std::io::Error),
#[error("cannot decode image: {0}")]
Decode(#[from] image::ImageError),
#[error("cannot prepare image: {0}")]
Prepare(String),
}
/// Uses decoded content magic, never the filename extension, as the first format gate.
pub fn supported_format(bytes: &[u8]) -> Option<SupportedImageFormat> {
match image::guess_format(bytes).ok()? {
image::ImageFormat::Png => Some(SupportedImageFormat::Png),
image::ImageFormat::Jpeg => Some(SupportedImageFormat::Jpeg),
image::ImageFormat::Gif => Some(SupportedImageFormat::Gif),
image::ImageFormat::Bmp => Some(SupportedImageFormat::Bmp),
image::ImageFormat::WebP => Some(SupportedImageFormat::WebP),
_ => None,
}
}
pub fn checked_dimensions(width: u32, height: u32) -> Result<(), ImagePreviewError> {
let pixels = u64::from(width).checked_mul(u64::from(height));
if width == 0
|| height == 0
|| width > MAX_IMAGE_AXIS
|| height > MAX_IMAGE_AXIS
|| pixels.is_none_or(|pixels| pixels > MAX_IMAGE_PIXELS)
{
return Err(ImagePreviewError::DimensionsTooLarge);
}
Ok(())
}
/// Decodes only complete bounded input. Animated formats intentionally produce one static image.
pub fn decode_static(bytes: Vec<u8>, truncated: bool) -> Result<DynamicImage, ImagePreviewError> {
if truncated || bytes.len() > MAX_IMAGE_BYTES {
return Err(ImagePreviewError::EncodedTooLarge);
}
supported_format(&bytes).ok_or(ImagePreviewError::UnsupportedFormat)?;
// Query dimensions before pixel allocation, then let the decoder enforce the same limits again.
let dimensions = ImageReader::new(Cursor::new(&bytes))
.with_guessed_format()?
.into_dimensions()?;
checked_dimensions(dimensions.0, dimensions.1)?;
let mut reader = ImageReader::new(Cursor::new(&bytes)).with_guessed_format()?;
let mut limits = Limits::default();
limits.max_image_width = Some(MAX_IMAGE_AXIS);
limits.max_image_height = Some(MAX_IMAGE_AXIS);
limits.max_alloc = Some(MAX_IMAGE_ALLOC);
reader.limits(limits);
let image = reader.decode()?;
checked_dimensions(image.width(), image.height())?;
Ok(image)
}
/// Universal side-effect-free path used under tmux and on unsupported terminals.
/// Unlike `Picker::halfblocks`, this never probes the environment or mutates tmux configuration.
pub fn prepare_halfblocks(
image: DynamicImage,
available: Size,
) -> Result<Protocol, ImagePreviewError> {
if available.width == 0 || available.height == 0 {
return Err(ImagePreviewError::EmptyArea);
}
checked_dimensions(image.width(), image.height())?;
let resize = Resize::Fit(Some(image::imageops::FilterType::Triangle));
let size = resize.size_for(&image, HALFBLOCK_FONT_SIZE, available);
if size.width == 0 || size.height == 0 {
return Err(ImagePreviewError::EmptyArea);
}
let resized = resize.resize(&image, HALFBLOCK_FONT_SIZE, size, None);
Ok(Protocol::Halfblocks(
ratatui_image::protocol::halfblocks::Halfblocks::new(resized, size)
.map_err(|error| ImagePreviewError::Prepare(error.to_string()))?,
))
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FontMetrics {
pub width: u16,
pub height: u16,
}
impl From<FontSize> for FontMetrics {
fn from(size: FontSize) -> Self {
Self {
width: size.width,
height: size.height,
}
}
}
#[derive(Clone, Debug)]
pub enum ImageProtocolFactory {
Picker(Picker),
/// Direct constructor deliberately avoids every upstream Picker constructor under tmux.
Halfblocks,
}
impl ImageProtocolFactory {
pub fn protocol_type(&self) -> ProtocolType {
match self {
Self::Picker(picker) => picker.protocol_type(),
Self::Halfblocks => ProtocolType::Halfblocks,
}
}
pub fn font_metrics(&self) -> FontMetrics {
match self {
Self::Picker(picker) => picker.font_size().into(),
Self::Halfblocks => FontMetrics {
width: HALFBLOCK_FONT_SIZE.width,
height: HALFBLOCK_FONT_SIZE.height,
},
}
}
pub fn prepare(
&self,
image: DynamicImage,
available: Size,
) -> Result<Protocol, ImagePreviewError> {
checked_dimensions(image.width(), image.height())?;
if available.width == 0 || available.height == 0 {
return Err(ImagePreviewError::EmptyArea);
}
match self {
Self::Picker(picker) => picker
.new_protocol(
image,
available,
Resize::Fit(Some(image::imageops::FilterType::Triangle)),
)
.map_err(|error| ImagePreviewError::Prepare(error.to_string())),
Self::Halfblocks => prepare_halfblocks(image, available),
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct ImageDetectionGates {
pub images: bool,
pub colors: bool,
pub ascii: bool,
pub dumb: bool,
pub tty: bool,
pub tmux: bool,
}
impl ImageDetectionGates {
pub fn from_environment(images: bool, colors: bool, ascii: bool) -> Self {
let dumb = std::env::var("TERM").is_ok_and(|term| term.eq_ignore_ascii_case("dumb"));
let tmux = std::env::var_os("TMUX").is_some_and(|value| !value.is_empty())
|| std::env::var("TERM").is_ok_and(|term| term.starts_with("tmux"))
|| std::env::var("TERM_PROGRAM")
.is_ok_and(|program| program.eq_ignore_ascii_case("tmux"));
Self {
images,
colors,
ascii,
dumb,
tty: std::io::stdin().is_terminal() && std::io::stdout().is_terminal(),
tmux,
}
}
fn accepts_pixels(self) -> bool {
self.images && self.colors && !self.ascii && !self.dumb && self.tty
}
}
#[derive(Clone, Copy)]
pub struct ImageRenderContext<'a> {
pub cache: &'a ImagePreviewCache,
pub factory: &'a ImageProtocolFactory,
}
impl ImageRenderContext<'_> {
pub fn identity(
&self,
pane: PaneId,
generation: Generation,
target: Location,
session_epoch: Option<SessionEpoch>,
area: Size,
terminal_epoch: u64,
) -> PreparedImageIdentity {
PreparedImageIdentity {
pane,
generation,
target,
session_epoch,
area,
font: self.factory.font_metrics(),
protocol: self.factory.protocol_type(),
terminal_epoch,
}
}
}
#[derive(Debug, Default)]
pub struct ImageWorkerMetrics {
active: AtomicUsize,
max_active: AtomicUsize,
}
impl ImageWorkerMetrics {
pub fn snapshot(&self) -> (usize, usize) {
(
self.active.load(Ordering::SeqCst),
self.max_active.load(Ordering::SeqCst),
)
}
pub(crate) fn enter(&self) -> ActiveImageWorker<'_> {
let active = self.active.fetch_add(1, Ordering::SeqCst) + 1;
self.max_active.fetch_max(active, Ordering::SeqCst);
ActiveImageWorker(self)
}
}
pub(crate) struct ActiveImageWorker<'a>(&'a ImageWorkerMetrics);
impl Drop for ActiveImageWorker<'_> {
fn drop(&mut self) {
self.0.active.fetch_sub(1, Ordering::SeqCst);
}
}
#[derive(Clone, Debug, Default)]
pub enum ImageEngine {
#[default]
Disabled,
Enabled(ImageProtocolFactory),
}
impl ImageEngine {
pub fn detect(gates: ImageDetectionGates) -> Self {
Self::detect_with(gates, || {
Picker::from_query_stdio_with_options(QueryStdioOptions {
timeout_ms: 100,
..QueryStdioOptions::default()
})
})
}
/// Injectable query makes disabled/tmux no-probe behavior deterministic in tests.
pub fn detect_with<E>(
gates: ImageDetectionGates,
query: impl FnOnce() -> Result<Picker, E>,
) -> Self {
if !gates.accepts_pixels() {
return Self::Disabled;
}
if gates.tmux {
return Self::Enabled(ImageProtocolFactory::Halfblocks);
}
match query() {
Ok(picker) => Self::Enabled(ImageProtocolFactory::Picker(picker)),
Err(_) => Self::Enabled(ImageProtocolFactory::Halfblocks),
}
}
pub fn factory(&self) -> Option<&ImageProtocolFactory> {
match self {
Self::Disabled => None,
Self::Enabled(factory) => Some(factory),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PreparedImageIdentity {
pub pane: PaneId,
pub generation: Generation,
pub target: Location,
pub session_epoch: Option<SessionEpoch>,
pub area: Size,
pub font: FontMetrics,
pub protocol: ProtocolType,
pub terminal_epoch: u64,
}
#[derive(Clone)]
pub struct PreparedImage {
pub identity: PreparedImageIdentity,
pub protocol: Protocol,
}
/// At most one prepared image per pane; no protocol is stored in Clone/Eq application state.
#[derive(Default)]
pub struct ImagePreviewCache {
entries: [Option<PreparedImage>; 2],
}
impl ImagePreviewCache {
pub fn insert(&mut self, image: PreparedImage) {
let pane = image.identity.pane;
self.entries[pane.index()] = Some(image);
}
pub fn current(&self, identity: &PreparedImageIdentity) -> Option<&Protocol> {
self.entries[identity.pane.index()]
.as_ref()
.filter(|image| &image.identity == identity)
.map(|image| &image.protocol)
}
pub fn remove_pane(&mut self, pane: PaneId) {
self.entries[pane.index()] = None;
}
pub fn clear(&mut self) {
self.entries = [None, None];
}
pub fn len(&self) -> usize {
self.entries.iter().filter(|entry| entry.is_some()).count()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}

View file

@ -9,7 +9,7 @@ use std::time::{Duration, Instant};
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use directories::UserDirs;
use crate::app::{CollisionChoice, Command, QuitDecision};
use crate::app::{CollisionChoice, Command, HelpViewport, QuitDecision};
use crate::domain::Location;
use crate::ssh::HostPickerState;
@ -171,25 +171,84 @@ impl InputState {
}
}
pub fn handle_help_key(&mut self, key: KeyEvent, page_size: usize) -> InputOutcome {
pub fn handle_theme_picker_key(&mut self, key: KeyEvent, page_size: usize) -> InputOutcome {
if key.kind == KeyEventKind::Release {
return InputOutcome::Ignored;
}
self.pending = None;
if is_press(key, KeyCode::F(10)) {
return InputOutcome::Command(Command::Quit);
}
if is_press(key, KeyCode::Esc) {
return InputOutcome::Command(Command::CloseOverlay);
}
if is_press(key, KeyCode::Enter) {
return InputOutcome::Command(Command::SaveTheme);
}
if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) {
let delta = match key.code {
KeyCode::Down => Some(1),
KeyCode::Up => Some(-1),
KeyCode::Char('j') if is_plain(key) => Some(1),
KeyCode::Char('k') if is_plain(key) => Some(-1),
_ => None,
};
if let Some(delta) = delta {
return InputOutcome::Command(Command::MoveThemeSelection { delta, page_size });
}
}
InputOutcome::Ignored
}
pub fn handle_help_key(&mut self, key: KeyEvent, viewport: HelpViewport) -> InputOutcome {
if key.kind == KeyEventKind::Release {
return InputOutcome::Ignored;
}
self.pending = None;
if is_press(key, KeyCode::F(10)) {
InputOutcome::Command(Command::Quit)
} else if is_press(key, KeyCode::Esc)
return InputOutcome::Command(Command::Quit);
}
if is_press(key, KeyCode::Esc)
|| (key.kind == KeyEventKind::Press && is_plain_char(key, 'q'))
{
InputOutcome::Command(Command::CloseOverlay)
} else if (key.kind == KeyEventKind::Press && is_plain_char(key, '?'))
return InputOutcome::Command(Command::CloseOverlay);
}
if (key.kind == KeyEventKind::Press && is_plain_char(key, '?'))
|| is_press(key, KeyCode::F(1))
{
InputOutcome::Command(Command::ToggleHelp)
} else {
scroll_overlay_command(key, page_size)
.map_or(InputOutcome::Ignored, InputOutcome::Command)
return InputOutcome::Command(Command::ToggleHelp);
}
if key.kind == KeyEventKind::Press {
match key.code {
KeyCode::Tab => {
return InputOutcome::Command(Command::SelectHelpCategory(1));
}
KeyCode::BackTab => {
return InputOutcome::Command(Command::SelectHelpCategory(-1));
}
_ => {}
}
}
if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) {
let category_delta = match key.code {
KeyCode::Char('h') | KeyCode::Left if is_plain(key) => Some(-1),
KeyCode::Char('l') | KeyCode::Right if is_plain(key) => Some(1),
_ => None,
};
if let Some(delta) = category_delta {
return InputOutcome::Command(Command::SelectHelpCategory(delta));
}
}
match scroll_overlay_command(key, viewport.page_size) {
Some(Command::ScrollOverlay(delta)) => InputOutcome::Command(Command::ScrollHelp {
delta,
max_scroll: viewport.max_scroll,
}),
Some(_) => unreachable!("overlay scrolling only produces ScrollOverlay"),
None => InputOutcome::Ignored,
}
}
@ -424,6 +483,11 @@ impl InputState {
}
pub fn handle_task_details_key(&mut self, key: KeyEvent, page_size: usize) -> InputOutcome {
// Vertical aliases belong to the details viewport, never to the obscured task selection.
if let Some(command) = scroll_overlay_command(key, page_size) {
self.pending = None;
return InputOutcome::Command(command);
}
if key.kind == KeyEventKind::Press
&& matches!(key.code, KeyCode::Char('m'))
&& is_plain(key)
@ -530,6 +594,7 @@ fn map_command(key: KeyEvent, page_size: usize) -> Option<Command> {
'.' => Some(Command::ToggleHidden),
's' => Some(Command::OpenHostPicker),
't' => Some(Command::OpenTasks),
'T' => Some(Command::OpenThemePicker),
'm' => Some(Command::OpenMessage),
'?' => Some(Command::ToggleHelp),
'q' => Some(Command::Quit),

View file

@ -2,8 +2,11 @@
pub mod actions;
pub mod app;
pub mod cli;
pub mod config;
pub mod domain;
pub mod fs;
pub mod image_preview;
pub mod input;
pub mod operations;
pub mod preview;

View file

@ -1,42 +1,64 @@
use std::path::PathBuf;
use std::sync::Arc;
use clap::Parser;
use directories::UserDirs;
use rcom::cli::Cli;
use rcom::config::{config_path, load_from_path};
use rcom::fs::{BackendRegistry, LocalFs};
use rcom::image_preview::{ImageDetectionGates, ImageEngine, ImageRenderContext};
use rcom::session::{Application, initial_location};
use rcom::ssh::{ConnectionManager, DiscoveryResult, OpenSshConnector, discover};
use rcom::tui::run_event_loop;
use rcom::ui::terminal::TerminalGuard;
use rcom::ui::{Theme, render};
#[derive(Debug, Parser)]
#[command(
name = "rcom",
version,
about = "Dual-pane local and SSH terminal file manager"
)]
struct Cli {
/// Existing local directory to open in the initial pane.
path: Option<PathBuf>,
}
use rcom::ui::{Theme, ThemeId, render_with_context};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
if cli.list_themes {
for id in ThemeId::ALL {
println!(
"{}\t{}\t{}",
id.as_str(),
id.display_name(),
id.mode().as_str()
);
}
return Ok(());
}
let config = load_from_path(&config_path())?;
let images = config.images_enabled(cli.no_images);
let theme = Theme::from_env_with_appearance(
config.selected_icon_mode(cli.icons),
config.selected_theme(cli.theme),
);
let initial = initial_location(cli.path).await?;
let discovery = ssh_discovery();
let registry = BackendRegistry::new(Arc::new(LocalFs::new()));
let connections = ConnectionManager::new(Arc::new(OpenSshConnector::default()), registry);
let (mut application, mut results) = Application::new(initial, connections, discovery);
application.configure_theme(theme, config_path());
let mut terminal = TerminalGuard::enter()?;
let theme = Theme::from_env();
application.configure_images(ImageEngine::detect(ImageDetectionGates::from_environment(
images,
theme.colors_enabled(),
theme.is_ascii(),
)));
let image_cache = application.image_cache();
let image_factory = application.image_factory();
run_event_loop(
&mut application,
&mut results,
&mut terminal,
|frame, state, picker| render(frame, state, picker, &theme),
|frame, state, picker| {
let cache = image_cache.lock().unwrap();
let context = image_factory.as_ref().map(|factory| ImageRenderContext {
cache: &cache,
factory,
});
render_with_context(frame, state, picker, &state.theme, context);
},
)
.await
}

View file

@ -6,6 +6,7 @@
use std::ffi::OsString;
use std::io;
use std::sync::Arc;
use tokio::io::{AsyncRead, AsyncReadExt};
@ -23,6 +24,14 @@ pub enum PreviewKind {
Binary,
Metadata,
Directory,
Image,
}
/// Complete bounded encoded image accepted by the current preview response.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EncodedImage {
pub bytes: Arc<Vec<u8>>,
pub format: crate::image_preview::SupportedImageFormat,
}
/// Safe, UI-ready preview lines.

View file

@ -78,11 +78,21 @@ impl EffectRunner {
)
}
pub(crate) fn command_sender(&self) -> mpsc::Sender<Command> {
self.sender.clone()
}
pub fn execute(&mut self, effect: Effect) {
match effect {
Effect::LoadListing(request) => self.spawn_listing(request),
Effect::LoadPreview(request) => self.spawn_preview(request),
Effect::DebouncePreview(_) => {
// Application owns the deadline; the runner never performs early preview I/O.
}
Effect::ConnectSsh(request) => self.spawn_connect(request),
Effect::SaveTheme(_) => {
// Application intercepts config I/O so no runner response can bypass the picker.
}
Effect::PlanOperation(request) => self.spawn_operation_plan(request),
Effect::ExecuteOperation(request) => self.spawn_operation(request),
Effect::CancelOperation(operation) => self.cancel_operation(operation),

View file

@ -1,22 +1,32 @@
//! UI-independent application controller connecting input, reducer, and asynchronous effects.
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use crossterm::event::KeyEvent;
use directories::UserDirs;
use tokio::sync::mpsc;
use ratatui::layout::Rect;
use tokio::sync::{Semaphore, mpsc};
use tokio_util::sync::CancellationToken;
use crate::actions::{DirectEditor, EditorCommand, EditorOutcome, EditorWorkspace, ExternalEditor};
use crate::app::{
AppState, Command, EditorChangeResult, EditorProcessResult, Effect, Overlay, PaneId, PaneMode,
RunEditorRequest,
AppState, Command, EditorChangeResult, EditorProcessResult, Effect, HelpViewport,
ImagePreparationResult, Overlay, PaneId, PaneMode, PreviewRequest, RunEditorRequest,
};
use crate::config::{ConfigFaultPoint, ThemeConfigStore};
use crate::domain::{EntryKind, Location};
use crate::fs::{FsError, LocalFs, ReadFileSystem};
use crate::image_preview::{
ImageEngine, ImagePreviewCache, ImageProtocolFactory, ImageWorkerMetrics, PreparedImage,
PreparedImageIdentity, decode_static,
};
use crate::input::{InputOutcome, InputState, PendingKey};
use crate::runtime::EffectRunner;
use crate::ssh::{ConnectionManager, DiscoveryResult, HostPickerState};
use crate::ui::layout::preview_image_area;
use crate::ui::{Theme, ThemeId};
pub async fn initial_location(argument: Option<PathBuf>) -> Result<Location, FsError> {
let path = match argument {
@ -34,6 +44,15 @@ pub async fn initial_location(argument: Option<PathBuf>) -> Result<Location, FsE
Ok(location)
}
pub const PREVIEW_DEBOUNCE: Duration = Duration::from_millis(40);
#[derive(Clone, Debug)]
struct PendingPreview {
request: PreviewRequest,
navigation_generation: u64,
deadline: Instant,
}
pub struct Application {
state: AppState,
input: InputState,
@ -43,6 +62,16 @@ pub struct Application {
editor_command: Option<EditorCommand>,
pending_editor: Option<PendingEditor>,
finished_editor: Option<FinishedEditor>,
theme_config: Option<ThemeConfigStore>,
pending_previews: [Option<PendingPreview>; 2],
image_engine: ImageEngine,
image_cache: Arc<Mutex<ImagePreviewCache>>,
pending_images: Arc<Mutex<Vec<PreparedImage>>>,
image_gate: Arc<Semaphore>,
image_metrics: Arc<ImageWorkerMetrics>,
image_cancellation: [CancellationToken; 2],
image_requested: [Option<PreparedImageIdentity>; 2],
terminal_area: Rect,
}
struct PendingEditor {
@ -116,6 +145,16 @@ impl Application {
editor_command,
pending_editor: None,
finished_editor: None,
theme_config: None,
pending_previews: [None, None],
image_engine: ImageEngine::Disabled,
image_cache: Arc::new(Mutex::new(ImagePreviewCache::default())),
pending_images: Arc::new(Mutex::new(Vec::new())),
image_gate: Arc::new(Semaphore::new(1)),
image_metrics: Arc::new(ImageWorkerMetrics::default()),
image_cancellation: [CancellationToken::new(), CancellationToken::new()],
image_requested: [None, None],
terminal_area: Rect::default(),
},
results,
)
@ -135,6 +174,48 @@ impl Application {
&self.host_picker
}
/// Installs startup appearance and the only config path allowed to persist Theme Picker saves.
pub fn configure_theme(&mut self, theme: Theme, config_path: PathBuf) {
self.state.theme = theme;
self.theme_config = Some(ThemeConfigStore::new(config_path));
}
pub fn configure_images(&mut self, engine: ImageEngine) {
self.state.images_enabled = engine.factory().is_some();
self.image_engine = engine;
self.reconcile_images();
}
pub fn image_cache(&self) -> Arc<Mutex<ImagePreviewCache>> {
self.image_cache.clone()
}
pub fn image_factory(&self) -> Option<ImageProtocolFactory> {
self.image_engine.factory().cloned()
}
#[doc(hidden)]
pub fn image_worker_metrics(&self) -> (usize, usize) {
self.image_metrics.snapshot()
}
#[doc(hidden)]
pub fn set_image_worker_permits_for_test(&mut self, permits: usize) {
self.image_gate = Arc::new(Semaphore::new(permits));
}
#[doc(hidden)]
pub fn release_image_worker_permit_for_test(&self) {
self.image_gate.add_permits(1);
}
#[doc(hidden)]
pub fn inject_theme_config_fault_for_test(&mut self, fault: ConfigFaultPoint) {
if let Some(config) = &mut self.theme_config {
config.inject_fault_for_test(fault);
}
}
pub fn pending_key(&self) -> Option<PendingKey> {
self.input.pending_key()
}
@ -144,21 +225,71 @@ impl Application {
}
pub fn dispatch(&mut self, command: Command) {
for effect in self.state.reduce(command) {
self.execute(effect);
}
self.dispatch_at(command, Instant::now());
}
fn execute(&mut self, effect: Effect) {
#[doc(hidden)]
pub fn dispatch_at(&mut self, command: Command, now: Instant) {
if let Command::ImagePrepared(result) = &command
&& !self.accept_prepared_image(result)
{
self.reconcile_images();
return;
}
let capture_error = if command == Command::OpenThemePicker {
self.theme_config.as_mut().map(ThemeConfigStore::capture)
} else {
None
};
for effect in self.state.reduce(command) {
self.execute_at(effect, now);
}
if let Some(Err(error)) = capture_error
&& let Some(picker) = &self.state.theme_picker
{
self.dispatch_at(
Command::ThemeSaveFinished {
id: picker.selected,
result: Err(error),
},
now,
);
}
self.reconcile_images();
}
fn execute_at(&mut self, effect: Effect, now: Instant) {
match effect {
Effect::PrepareEditor(request) => self
.runner
.prepare_editor_with_command(request, self.editor_command.clone()),
Effect::RunEditor(request) => self.prepare_editor_process(request),
Effect::SaveTheme(id) => self.save_theme(id),
Effect::DebouncePreview(request) => {
let pane = request.pane;
let navigation_generation = self.state.pane(pane).navigation_generation;
self.pending_previews[pane.index()] = Some(PendingPreview {
request,
navigation_generation,
deadline: now + PREVIEW_DEBOUNCE,
});
}
Effect::LoadPreview(request) => {
self.pending_previews[request.pane.index()] = None;
self.runner.execute(Effect::LoadPreview(request));
}
effect => self.runner.execute(effect),
}
}
fn save_theme(&mut self, id: ThemeId) {
let result = self.theme_config.as_mut().map_or_else(
|| Err("Theme config path is not configured".to_owned()),
|config| config.save(id),
);
self.dispatch(Command::ThemeSaveFinished { id, result });
}
fn prepare_editor_process(&mut self, request: RunEditorRequest) {
let workspace = request
.prepared
@ -250,12 +381,43 @@ impl Application {
}
pub fn handle_key(&mut self, key: KeyEvent, page_size: usize) {
self.handle_key_with_help_viewport_at(key, page_size, None, Instant::now());
}
#[doc(hidden)]
pub fn handle_key_at(&mut self, key: KeyEvent, page_size: usize, now: Instant) {
self.handle_key_with_help_viewport_at(key, page_size, None, now);
}
pub fn handle_key_with_help_viewport(
&mut self,
key: KeyEvent,
page_size: usize,
help_viewport: Option<HelpViewport>,
) {
self.handle_key_with_help_viewport_at(key, page_size, help_viewport, Instant::now());
}
fn handle_key_with_help_viewport_at(
&mut self,
key: KeyEvent,
page_size: usize,
help_viewport: Option<HelpViewport>,
now: Instant,
) {
let outcome = match self.state.overlay {
Overlay::None => self.input.handle_key(key, page_size),
Overlay::None => self.input.handle_key_at(key, page_size, now),
Overlay::HostPicker => self
.input
.handle_host_picker_key(key, &mut self.host_picker),
Overlay::Help => self.input.handle_help_key(key, page_size),
Overlay::ThemePicker => self.input.handle_theme_picker_key(key, page_size),
Overlay::Help => self.input.handle_help_key(
key,
help_viewport.unwrap_or(HelpViewport {
page_size,
max_scroll: usize::MAX,
}),
),
Overlay::Preview => self.input.handle_preview_key(key),
Overlay::Message => self.input.handle_message_key(key, page_size),
Overlay::DestinationPrompt => self.input.handle_destination_key(key),
@ -271,12 +433,226 @@ impl Application {
Overlay::Quit => self.input.handle_quit_key(key),
};
if let InputOutcome::Command(command) = outcome {
self.dispatch(command);
self.dispatch_at(command, now);
}
}
pub fn expire_pending(&mut self) {
self.input.expire_pending_at(std::time::Instant::now());
self.expire_pending_at(Instant::now());
}
#[doc(hidden)]
pub fn expire_pending_at(&mut self, now: Instant) {
self.input.expire_pending_at(now);
for pane in [PaneId::Left, PaneId::Right] {
let expired = self.pending_previews[pane.index()]
.as_ref()
.is_some_and(|pending| pending.deadline <= now);
if expired {
let pending = self.pending_previews[pane.index()].take().unwrap();
self.dispatch_at(
Command::StartPreview {
request: pending.request,
navigation_generation: pending.navigation_generation,
},
now,
);
}
}
}
pub fn next_preview_deadline(&self) -> Option<Instant> {
self.pending_previews
.iter()
.filter_map(|pending| pending.as_ref().map(|pending| pending.deadline))
.min()
}
#[doc(hidden)]
pub fn pending_preview_count(&self) -> usize {
self.pending_previews
.iter()
.filter(|entry| entry.is_some())
.count()
}
#[doc(hidden)]
pub fn terminal_area(&self) -> Rect {
self.terminal_area
}
pub fn update_terminal_area(&mut self, area: Rect) {
if self.terminal_area != area {
self.terminal_area = area;
self.reconcile_images();
}
}
#[doc(hidden)]
pub fn resume_images(&mut self) {
self.state.terminal_epoch = self.state.terminal_epoch.saturating_add(1);
for cancellation in &self.image_cancellation {
cancellation.cancel();
}
self.image_requested = [None, None];
self.pending_images.lock().unwrap().clear();
self.image_cache.lock().unwrap().clear();
self.reconcile_images();
}
#[doc(hidden)]
pub fn current_image_identity(&self, pane_id: PaneId) -> Option<PreparedImageIdentity> {
if self.state.should_quit {
return None;
}
let factory = self.image_engine.factory()?;
let pane = self.state.pane(pane_id);
let image = pane.preview.encoded_image.as_ref()?;
let target = pane.preview.target.clone()?;
if pane.selected_location().as_ref() != Some(&target) {
return None;
}
let area = preview_image_area(
self.terminal_area,
self.state.mode,
self.state.active,
self.state.overlay,
)?;
Some(PreparedImageIdentity {
pane: pane_id,
generation: pane.preview.image_generation,
target,
session_epoch: pane.session_epoch,
area,
font: factory.font_metrics(),
protocol: factory.protocol_type(),
terminal_epoch: self.state.terminal_epoch,
})
.filter(|identity| {
identity.area.width > 0 && identity.area.height > 0 && !image.bytes.is_empty()
})
}
fn reconcile_images(&mut self) {
for pane in [PaneId::Left, PaneId::Right] {
let identity = self.current_image_identity(pane);
if identity.is_none() {
self.image_cancellation[pane.index()].cancel();
self.image_requested[pane.index()] = None;
self.image_cache.lock().unwrap().remove_pane(pane);
continue;
}
let identity = identity.unwrap();
if self.image_requested[pane.index()].as_ref() == Some(&identity) {
continue;
}
self.image_cancellation[pane.index()].cancel();
let cancellation = CancellationToken::new();
self.image_cancellation[pane.index()] = cancellation.clone();
self.image_requested[pane.index()] = Some(identity.clone());
self.spawn_image_preparation(identity, cancellation);
}
}
fn spawn_image_preparation(
&self,
identity: PreparedImageIdentity,
cancellation: CancellationToken,
) {
let Some(encoded) = self.state.pane(identity.pane).preview.encoded_image.clone() else {
return;
};
let Some(factory) = self.image_engine.factory().cloned() else {
return;
};
let gate = self.image_gate.clone();
let pending = self.pending_images.clone();
let metrics = self.image_metrics.clone();
let sender = self.runner.command_sender();
tokio::spawn(async move {
let permit = tokio::select! {
biased;
_ = cancellation.cancelled() => return,
permit = gate.acquire_owned() => permit.expect("image semaphore is never closed"),
};
// Cancellation and permit may become ready together; never start blocking work then.
if cancellation.is_cancelled() {
return;
}
let blocking_cancellation = cancellation.clone();
let prepared = tokio::task::spawn_blocking(move || {
let _active = metrics.enter();
if blocking_cancellation.is_cancelled() {
return Err("cancelled before image decode".to_owned());
}
let image = decode_static(encoded.bytes.as_ref().clone(), false)
.map_err(|error| error.to_string())?;
if blocking_cancellation.is_cancelled() {
return Err("cancelled after image decode".to_owned());
}
let protocol = factory
.prepare(image, identity.area)
.map_err(|error| error.to_string())?;
if blocking_cancellation.is_cancelled() {
return Err("cancelled before image publication".to_owned());
}
Ok(protocol)
})
.await
.map_err(|error| format!("image worker failed: {error}"));
drop(permit);
if cancellation.is_cancelled() {
return;
}
let result = match prepared {
Ok(Ok(protocol)) => {
pending
.lock()
.unwrap()
.retain(|image| image.identity.pane != identity.pane);
pending.lock().unwrap().push(PreparedImage {
identity: identity.clone(),
protocol,
});
Ok(())
}
Ok(Err(error)) => Err(error),
Err(error) => Err(error),
};
let _ = sender
.send(Command::ImagePrepared(ImagePreparationResult {
identity,
result,
}))
.await;
});
}
/// Returns false for any stale result, including errors, before the reducer can observe it.
fn accept_prepared_image(&mut self, result: &ImagePreparationResult) -> bool {
let identity = &result.identity;
let current = self.current_image_identity(identity.pane).as_ref() == Some(identity);
let requested = self.image_requested[identity.pane.index()].as_ref() == Some(identity);
if !current || !requested {
self.pending_images
.lock()
.unwrap()
.retain(|image| &image.identity != identity);
return false;
}
if result.result.is_err() {
return true;
}
let prepared = {
let mut pending = self.pending_images.lock().unwrap();
let position = pending
.iter()
.position(|image| &image.identity == identity)
.unwrap_or_else(|| panic!("accepted image must have one prepared result"));
pending.remove(position)
};
self.image_cache.lock().unwrap().insert(prepared);
true
}
/// Requests one read-only listing per visible, non-loading pane. The reducer retains the active

View file

@ -16,9 +16,10 @@ use ratatui::Frame;
use ratatui::layout::Rect;
use tokio::sync::mpsc;
use crate::app::{AppState, Command};
use crate::app::{AppState, Command, Overlay};
use crate::session::Application;
use crate::ssh::HostPickerState;
use crate::ui::help::help_view_model;
use crate::ui::layout::active_page_size;
use crate::ui::terminal::{RcomTerminal, TerminalGuard};
@ -70,6 +71,14 @@ impl EventLoopTerminal for RcomTerminal {
}
}
async fn wait_for_preview_deadline(deadline: Option<std::time::Instant>) {
if let Some(deadline) = deadline {
tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)).await;
} else {
std::future::pending::<()>().await;
}
}
pub async fn run_event_loop<T: EventLoopTerminal>(
application: &mut Application,
results: &mut mpsc::Receiver<Command>,
@ -90,10 +99,18 @@ pub async fn run_event_loop<T: EventLoopTerminal>(
terminal
.resume()
.context("failed to restore rcom interface after editor")?;
application.resume_images();
application.finish_editor().await;
continue;
}
let terminal_size = terminal.terminal().size()?;
application.update_terminal_area(Rect::new(
0,
0,
terminal_size.width,
terminal_size.height,
));
terminal
.terminal()
.draw(|frame| {
@ -104,20 +121,30 @@ pub async fn run_event_loop<T: EventLoopTerminal>(
return Ok(());
}
let preview_deadline = application.next_preview_deadline();
let preview_wakeup = wait_for_preview_deadline(preview_deadline);
tokio::select! {
event = events.next() => {
match event {
Some(Ok(Event::Key(key))) => {
let size = terminal.terminal().size()?;
let state = application.state();
let page_size = active_page_size(
Rect::new(0, 0, size.width, size.height),
state.mode,
state.active,
);
application.handle_key(key, page_size);
let area = Rect::new(0, 0, size.width, size.height);
let page_size = active_page_size(area, state.mode, state.active);
let help_viewport = (state.overlay == Overlay::Help)
.then(|| help_view_model(area, &state.help).viewport());
application.handle_key_with_help_viewport(key, page_size, help_viewport);
}
Some(Ok(Event::Resize(width, height))) => {
let state = application.state();
if state.overlay == Overlay::Help {
let model = help_view_model(
Rect::new(0, 0, width, height),
&state.help,
);
application.dispatch(Command::NormalizeHelpScroll(model.max_scroll));
}
}
Some(Ok(Event::Resize(_, _))) => {}
Some(Ok(_)) => {}
Some(Err(error)) => return Err(error).context("terminal event stream failed"),
None => return Err(anyhow::anyhow!("terminal event stream closed")),
@ -131,9 +158,31 @@ pub async fn run_event_loop<T: EventLoopTerminal>(
_ = redraw.tick() => {
application.expire_pending();
}
_ = preview_wakeup => {
application.expire_pending();
}
_ = live_refresh.tick() => {
application.refresh_visible();
}
}
}
}
#[cfg(test)]
mod tests {
use std::time::{Duration, Instant};
#[tokio::test(start_paused = true)]
async fn preview_deadline_wakes_at_40ms_independently_of_redraw_ticks() {
let start = Instant::now();
let task = tokio::spawn(super::wait_for_preview_deadline(Some(
start + Duration::from_millis(40),
)));
tokio::task::yield_now().await;
tokio::time::advance(Duration::from_millis(39)).await;
tokio::task::yield_now().await;
assert!(!task.is_finished());
tokio::time::advance(Duration::from_millis(1)).await;
task.await.unwrap();
}
}

270
src/ui/help.rs Normal file
View file

@ -0,0 +1,270 @@
//! Pure, shared Help geometry and wrapped content for rendering and keyboard input.
use ratatui::layout::Rect;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
use crate::app::{HelpCategory, HelpState, HelpViewport, help_entries};
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum HelpTabs {
Full,
Compact {
position: usize,
label: &'static str,
},
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HelpViewModel {
pub overlay: Rect,
pub inner: Rect,
pub tabs_area: Option<Rect>,
pub tabs: HelpTabs,
pub body: Rect,
pub footer: Option<Rect>,
pub footer_text: String,
pub lines: Vec<String>,
pub offset: usize,
pub total: usize,
pub max_scroll: usize,
}
impl HelpViewModel {
pub const fn viewport(&self) -> HelpViewport {
HelpViewport {
page_size: self.body.height as usize,
max_scroll: self.max_scroll,
}
}
pub fn compact_label(&self) -> Option<String> {
match self.tabs {
HelpTabs::Full => None,
HelpTabs::Compact { position, label } => Some(format!("< {position}/6 {label} >")),
}
}
}
/// Computes the complete Help frame without reading or mutating application state.
///
/// In particular, input and rendering share `body.height` and `max_scroll`; wrapping is performed
/// before either value is calculated. The renderer still clamps the supplied offset defensively.
pub fn help_view_model(area: Rect, state: &HelpState) -> HelpViewModel {
let overlay = centered(area, 100, 32);
let inner = Rect::new(
overlay.x.saturating_add(1),
overlay.y.saturating_add(1),
overlay.width.saturating_sub(2),
overlay.height.saturating_sub(2),
);
let tabs_area = (inner.height > 0).then(|| Rect::new(inner.x, inner.y, inner.width, 1));
let footer_height = u16::from(inner.height >= 2);
let gap_height = u16::from(inner.height >= 10);
let tabs_height = u16::from(tabs_area.is_some());
let body = Rect::new(
inner.x,
inner.y.saturating_add(tabs_height + gap_height),
inner.width,
inner
.height
.saturating_sub(tabs_height + gap_height + footer_height),
);
let footer = (footer_height > 0).then(|| {
Rect::new(
inner.x,
inner.y.saturating_add(inner.height.saturating_sub(1)),
inner.width,
1,
)
});
let full_tabs_width = HelpCategory::ALL
.iter()
.map(|category| UnicodeWidthStr::width(category.label()))
.sum::<usize>()
+ 2
+ 2 * (HelpCategory::ALL.len() - 1);
let tabs = if full_tabs_width <= usize::from(inner.width) {
HelpTabs::Full
} else {
HelpTabs::Compact {
position: state.category.index() + 1,
label: state.category.label(),
}
};
let entries = help_entries(state.category).collect::<Vec<_>>();
let longest_alias = entries
.iter()
.map(|entry| UnicodeWidthStr::width(entry.aliases))
.max()
.unwrap_or(0);
let key_width = longest_alias.min(if body.width >= 70 { 30 } else { 18 });
let indent = key_width.saturating_add(2);
let mut lines = Vec::new();
for entry in entries {
let mut source = entry.aliases.to_owned();
source.extend(std::iter::repeat_n(
' ',
key_width.saturating_sub(UnicodeWidthStr::width(entry.aliases)),
));
source.push_str(" ");
source.push_str(entry.context.label());
source.push_str(": ");
source.push_str(entry.description);
lines.extend(wrap_hanging(&source, usize::from(body.width), indent));
}
let total = lines.len();
let visible = usize::from(body.height);
let max_scroll = total.saturating_sub(visible);
let offset = state.scroll.min(max_scroll);
let range = scroll_position(offset, visible, total);
let full_footer =
format!("{range} | h/l/Tab Category | j/k/PgUp/PgDn Scroll | Esc/q/?/F1 Close");
let footer_text = if UnicodeWidthStr::width(full_footer.as_str()) <= usize::from(inner.width) {
full_footer
} else {
format!("{range} h/l j/k/Pg Esc/q/?/F1")
};
HelpViewModel {
overlay,
inner,
tabs_area,
tabs,
body,
footer,
footer_text,
lines,
offset,
total,
max_scroll,
}
}
/// Hard-wraps without losing aliases and indents continuation lines to the description column.
fn wrap_hanging(input: &str, width: usize, indent: usize) -> Vec<String> {
if width == 0 {
return vec![String::new()];
}
let indent = indent.min(width.saturating_sub(1));
let continuation_width = width.saturating_sub(indent).max(1);
let indentation = " ".repeat(indent);
let mut lines = Vec::new();
let mut line = String::new();
let mut used = 0;
for character in input.chars() {
let character_width = UnicodeWidthChar::width(character).unwrap_or(0);
let limit = if lines.is_empty() {
width
} else {
continuation_width
};
if used > 0 && used + character_width > limit {
let content_start = if lines.is_empty() {
0
} else {
indentation.len()
};
let break_at = line
.char_indices()
.filter(|(index, character)| {
*index >= content_start
&& character.is_whitespace()
&& line[*index..].chars().any(|rest| !rest.is_whitespace())
})
.map(|(index, _)| index)
.next_back();
let remainder = break_at.map(|index| {
let remainder = line.split_off(index).trim_start().to_owned();
let trimmed = line.trim_end().len();
line.truncate(trimmed);
remainder
});
lines.push(std::mem::take(&mut line));
line.push_str(&indentation);
if let Some(remainder) = remainder {
used = UnicodeWidthStr::width(remainder.as_str());
line.push_str(&remainder);
} else {
used = 0;
}
}
line.push(character);
used += character_width;
}
if !line.is_empty() || lines.is_empty() {
lines.push(line);
}
lines
}
fn scroll_position(offset: usize, visible: usize, total: usize) -> String {
if total == 0 {
return "0/0".to_owned();
}
if visible == 0 {
return format!("0-0/{total}");
}
let start = offset.saturating_add(1).min(total);
let end = offset.saturating_add(visible).min(total);
format!("{start}-{end}/{total}")
}
fn centered(area: Rect, max_width: u16, max_height: u16) -> Rect {
let horizontal_margin = if area.width > max_width.saturating_add(4) {
2
} else {
0
};
let vertical_margin = if area.height > max_height.saturating_add(2) {
1
} else {
0
};
let width = max_width.min(area.width.saturating_sub(horizontal_margin * 2));
let height = max_height.min(area.height.saturating_sub(vertical_margin * 2));
Rect::new(
area.x + area.width.saturating_sub(width) / 2,
area.y + area.height.saturating_sub(height) / 2,
width,
height,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn minimum_help_has_compact_tabs_four_body_rows_and_complete_controls() {
let model = help_view_model(Rect::new(0, 0, 40, 8), &HelpState::default());
assert_eq!(model.body.height, 4);
assert_eq!(model.compact_label().as_deref(), Some("< 1/6 Navigation >"));
assert!(model.footer_text.contains("h/l"));
assert!(model.footer_text.contains("j/k/Pg"));
assert!(model.footer_text.contains("Esc/q/?/F1"));
assert!(UnicodeWidthStr::width(model.footer_text.as_str()) <= 38);
}
#[test]
fn hanging_wrap_retains_every_non_padding_character() {
let wrapped = wrap_hanging("keys Context: a description that wraps", 20, 6);
assert!(wrapped.len() > 1);
assert!(
wrapped
.iter()
.skip(1)
.all(|line| line.starts_with(" "))
);
let compact = wrapped.concat().replace(' ', "");
assert_eq!(compact, "keysContext:adescriptionthatwraps");
assert!(
wrapped
.iter()
.all(|line| UnicodeWidthStr::width(line.as_str()) <= 20)
);
}
}

362
src/ui/icons.rs Normal file
View file

@ -0,0 +1,362 @@
//! Deterministic file-type icons without filesystem I/O or font-capability guesses.
use std::collections::HashMap;
use std::sync::OnceLock;
use clap::ValueEnum;
use glob::{MatchOptions, Pattern};
use serde::{Deserialize, Serialize};
use crate::domain::{Entry, EntryKind};
/// Glyph family selected explicitly by the user. Unicode is the no-special-font default.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize, ValueEnum)]
#[serde(rename_all = "lowercase")]
#[value(rename_all = "lower")]
pub enum IconMode {
#[default]
Unicode,
Nerd,
Ascii,
None,
}
/// Broad semantic filename class, independent of the icon's more specific identity.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FileClass {
Directory,
Regular,
Executable,
Symlink,
Image,
Media,
Document,
Archive,
Special,
}
/// Static icon data. The glyph variants never depend on terminal environment detection.
pub struct IconRule {
pub id: &'static str,
nerd: &'static str,
unicode: &'static str,
ascii: &'static str,
}
/// Resolved icon and its independent semantic filename class.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ResolvedIcon {
pub id: &'static str,
pub glyph: &'static str,
pub class: FileClass,
}
/// Immutable rule resolver; no listing or metadata calls are performed.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct IconResolver {
mode: IconMode,
}
impl IconResolver {
pub const fn new(mode: IconMode) -> Self {
Self { mode }
}
pub const fn mode(self) -> IconMode {
self.mode
}
pub fn resolve(self, entry: &Entry) -> ResolvedIcon {
let rule = resolve_rule(entry);
ResolvedIcon {
id: rule.id,
glyph: match self.mode {
IconMode::Unicode => rule.unicode,
IconMode::Nerd => rule.nerd,
IconMode::Ascii => rule.ascii,
IconMode::None => "",
},
class: file_class(entry),
}
}
}
macro_rules! icon {
($name:ident, $id:literal, $nerd:literal, $unicode:literal, $ascii:literal) => {
static $name: IconRule = IconRule {
id: $id,
nerd: $nerd,
unicode: $unicode,
ascii: $ascii,
};
};
}
icon!(DIRECTORY, "directory", "\u{f07b}", "📁", "D");
icon!(DIRECTORY_GIT, "directory-git", "\u{f02a2}", "🌿", "G");
icon!(DIRECTORY_CODE, "directory-code", "\u{f121}", "💻", "D");
icon!(DIRECTORY_DOCS, "directory-docs", "\u{f02d}", "📚", "D");
icon!(DIRECTORY_TESTS, "directory-tests", "\u{f0c3}", "🧪", "T");
icon!(DIRECTORY_BUILD, "directory-build", "\u{f1b2}", "📦", "B");
icon!(DIRECTORY_CONFIG, "directory-config", "\u{f013}", "⚙", "C");
icon!(FILE, "file", "\u{f016}", "📄", "f");
icon!(RUST, "rust", "\u{e7a8}", "🦀", "R");
icon!(CARGO, "cargo", "\u{f1b2}", "📦", "C");
icon!(LOCK, "lock", "\u{f023}", "🔒", "L");
icon!(README, "readme", "\u{f02d}", "📖", "i");
icon!(GITIGNORE, "gitignore", "\u{f1d3}", "🚫", "G");
icon!(DOCKER, "docker", "\u{f308}", "🐳", "D");
icon!(MAKEFILE, "makefile", "\u{f0ad}", "🛠", "M");
icon!(CONFIG, "config", "\u{f013}", "⚙", "c");
icon!(CODE, "code", "\u{f121}", "λ", "x");
icon!(MARKDOWN, "markdown", "\u{f48a}", "📝", "m");
icon!(JSON, "json", "\u{f1c9}", "🧾", "j");
icon!(YAML, "yaml", "\u{f1c9}", "🧾", "y");
icon!(SHELL, "shell", "\u{f120}", "🐚", "s");
icon!(HTML, "html", "\u{f13b}", "🌐", "h");
icon!(CSS, "css", "\u{f13c}", "🎨", "c");
icon!(DATABASE, "database", "\u{f1c0}", "🗄", "d");
icon!(DOCUMENT, "document", "\u{f0f6}", "📄", "d");
icon!(IMAGE, "image", "\u{f03e}", "🖼", "i");
icon!(MEDIA, "media", "\u{f03d}", "🎬", "m");
icon!(ARCHIVE, "archive", "\u{f1c6}", "🗜", "z");
icon!(EXECUTABLE, "executable", "\u{f120}", "🚀", "*");
icon!(SYMLINK, "symlink", "\u{f0c1}", "🔗", "~");
icon!(SPECIAL, "special", "\u{f071}", "⚠", "!");
type Rule = &'static IconRule;
type RuleEntry = (&'static str, Rule);
const DIRECTORIES: &[RuleEntry] = &[
(".git", &DIRECTORY_GIT),
(".github", &DIRECTORY_GIT),
("src", &DIRECTORY_CODE),
("tests", &DIRECTORY_TESTS),
("docs", &DIRECTORY_DOCS),
("target", &DIRECTORY_BUILD),
("node_modules", &DIRECTORY_BUILD),
(".config", &DIRECTORY_CONFIG),
(".settings", &DIRECTORY_CONFIG),
(".vscode", &DIRECTORY_CONFIG),
(".idea", &DIRECTORY_CONFIG),
("Desktop", &DIRECTORY),
("Documents", &DIRECTORY_DOCS),
("Downloads", &DIRECTORY),
];
const FILES: &[RuleEntry] = &[
("Cargo.toml", &CARGO),
("Cargo.lock", &LOCK),
("rustfmt.toml", &RUST),
(".gitignore", &GITIGNORE),
("Dockerfile", &DOCKER),
("Makefile", &MAKEFILE),
("LICENSE", &DOCUMENT),
];
const EXTENSIONS: &[RuleEntry] = &[
("rs", &RUST),
("rlib", &RUST),
("toml", &CONFIG),
("lock", &LOCK),
("md", &MARKDOWN),
("markdown", &MARKDOWN),
("json", &JSON),
("jsonc", &JSON),
("yaml", &YAML),
("yml", &YAML),
("sh", &SHELL),
("bash", &SHELL),
("zsh", &SHELL),
("fish", &SHELL),
("py", &CODE),
("js", &CODE),
("mjs", &CODE),
("cjs", &CODE),
("ts", &CODE),
("mts", &CODE),
("cts", &CODE),
("jsx", &CODE),
("tsx", &CODE),
("html", &HTML),
("css", &CSS),
("c", &CODE),
("h", &CODE),
("cpp", &CODE),
("cc", &CODE),
("hpp", &CODE),
("go", &CODE),
("java", &CODE),
("rb", &CODE),
("php", &CODE),
("sql", &DATABASE),
("sqlite", &DATABASE),
("db", &DATABASE),
("txt", &DOCUMENT),
("pdf", &DOCUMENT),
("doc", &DOCUMENT),
("docx", &DOCUMENT),
("odt", &DOCUMENT),
("rtf", &DOCUMENT),
("png", &IMAGE),
("jpg", &IMAGE),
("jpeg", &IMAGE),
("gif", &IMAGE),
("webp", &IMAGE),
("svg", &IMAGE),
("bmp", &IMAGE),
("ico", &IMAGE),
("mp3", &MEDIA),
("wav", &MEDIA),
("flac", &MEDIA),
("ogg", &MEDIA),
("mp4", &MEDIA),
("mkv", &MEDIA),
("webm", &MEDIA),
("mov", &MEDIA),
("avi", &MEDIA),
("zip", &ARCHIVE),
("tar", &ARCHIVE),
("gz", &ARCHIVE),
("tgz", &ARCHIVE),
("bz2", &ARCHIVE),
("xz", &ARCHIVE),
("zst", &ARCHIVE),
("rar", &ARCHIVE),
("7z", &ARCHIVE),
];
const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "ico"];
const MEDIA_EXTENSIONS: &[&str] = &[
"mp3", "wav", "flac", "ogg", "mp4", "mkv", "webm", "mov", "avi",
];
const DOCUMENT_EXTENSIONS: &[&str] = &["txt", "pdf", "doc", "docx", "odt", "rtf", "md", "markdown"];
const ARCHIVE_EXTENSIONS: &[&str] = &["zip", "tar", "gz", "tgz", "bz2", "xz", "zst", "rar", "7z"];
fn map(
entries: &'static [RuleEntry],
lock: &'static OnceLock<HashMap<&'static str, Rule>>,
) -> &'static HashMap<&'static str, Rule> {
lock.get_or_init(|| entries.iter().copied().collect())
}
fn directory_map() -> &'static HashMap<&'static str, Rule> {
static MAP: OnceLock<HashMap<&'static str, Rule>> = OnceLock::new();
map(DIRECTORIES, &MAP)
}
fn file_map() -> &'static HashMap<&'static str, Rule> {
static MAP: OnceLock<HashMap<&'static str, Rule>> = OnceLock::new();
map(FILES, &MAP)
}
fn extension_map() -> &'static HashMap<&'static str, Rule> {
static MAP: OnceLock<HashMap<&'static str, Rule>> = OnceLock::new();
map(EXTENSIONS, &MAP)
}
fn glob_rules() -> &'static [(Pattern, Rule)] {
static RULES: OnceLock<Vec<(Pattern, Rule)>> = OnceLock::new();
RULES.get_or_init(|| {
vec![(
Pattern::new("README*").expect("valid built-in glob"),
&README,
)]
})
}
fn resolve_rule(entry: &Entry) -> Rule {
if let Some(name) = entry.name.to_str() {
for (pattern, rule) in glob_rules() {
if pattern.matches_with(
name,
MatchOptions {
case_sensitive: false,
..MatchOptions::default()
},
) {
return rule;
}
}
if entry.kind.is_directory() {
return directory_map().get(name).copied().unwrap_or(&DIRECTORY);
}
if let Some(rule) = file_map().get(name) {
return rule;
}
if let Some(extension) = PathExtension::new(name).into_option() {
if let Some(rule) = extension_map().get(extension) {
return rule;
}
if let Some(rule) = extension_map().get(extension.to_ascii_lowercase().as_str()) {
return rule;
}
}
} else if entry.kind.is_directory() {
return &DIRECTORY;
}
match entry.kind {
EntryKind::Directory => &DIRECTORY,
EntryKind::Symlink => &SYMLINK,
EntryKind::Other => &SPECIAL,
EntryKind::File if is_executable(entry) => &EXECUTABLE,
EntryKind::File => &FILE,
}
}
struct PathExtension<'a>(&'a str);
impl<'a> PathExtension<'a> {
fn new(name: &'a str) -> Self {
name.rsplit_once('.')
.filter(|(stem, extension)| !stem.is_empty() && !extension.is_empty())
.map_or(Self(""), |(_, extension)| Self(extension))
}
fn into_option(self) -> Option<&'a str> {
(!self.0.is_empty()).then_some(self.0)
}
}
fn is_executable(entry: &Entry) -> bool {
entry.permissions.is_some_and(|mode| mode & 0o111 != 0)
}
fn file_class(entry: &Entry) -> FileClass {
match entry.kind {
EntryKind::Directory => return FileClass::Directory,
EntryKind::Symlink => return FileClass::Symlink,
EntryKind::Other => return FileClass::Special,
EntryKind::File if is_executable(entry) => return FileClass::Executable,
EntryKind::File => {}
}
let extension = entry
.name
.to_str()
.and_then(|name| name.rsplit_once('.').map(|(_, extension)| extension))
.map(str::to_ascii_lowercase);
match extension.as_deref() {
Some(extension) if IMAGE_EXTENSIONS.contains(&extension) => FileClass::Image,
Some(extension) if MEDIA_EXTENSIONS.contains(&extension) => FileClass::Media,
Some(extension) if DOCUMENT_EXTENSIONS.contains(&extension) => FileClass::Document,
Some(extension) if ARCHIVE_EXTENSIONS.contains(&extension) => FileClass::Archive,
_ => FileClass::Regular,
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
#[test]
fn built_in_exact_catalogs_have_no_duplicate_keys() {
for entries in [DIRECTORIES, FILES, EXTENSIONS] {
let mut keys = HashSet::new();
for (key, _) in entries {
assert!(keys.insert(*key), "duplicate catalog key: {key}");
}
}
}
}

View file

@ -29,7 +29,6 @@ pub struct FrameLayout {
pub header: Option<Rect>,
pub workspace: Rect,
pub status: Option<Rect>,
pub hints: Option<Rect>,
pub columns: Vec<ColumnLayout>,
}
@ -41,17 +40,13 @@ pub fn frame_layout(area: Rect, mode: PaneMode, active: PaneId) -> FrameLayout {
header: None,
workspace: area,
status: None,
hints: None,
columns: Vec::new(),
};
}
let hints_height = u16::from(area.height >= 10);
let status_height = 1;
let header_height = 1;
let workspace_height = area
.height
.saturating_sub(header_height + status_height + hints_height);
let workspace_height = area.height.saturating_sub(header_height + status_height);
let header = Some(Rect::new(area.x, area.y, area.width, header_height));
let workspace = Rect::new(
area.x,
@ -65,23 +60,12 @@ pub fn frame_layout(area: Rect, mode: PaneMode, active: PaneId) -> FrameLayout {
area.width,
status_height,
));
let hints = (hints_height > 0).then(|| {
Rect::new(
area.x,
area.y
.saturating_add(area.height.saturating_sub(hints_height)),
area.width,
hints_height,
)
});
let columns = columns(workspace, mode, active);
FrameLayout {
too_small: false,
header,
workspace,
status,
hints,
columns,
}
}
@ -168,6 +152,49 @@ fn scale(width: u16, percentage: u32) -> u16 {
((u32::from(width) * percentage) / 100) as u16
}
pub fn centered(area: Rect, max_width: u16, max_height: u16) -> Rect {
let horizontal_margin = if area.width > max_width.saturating_add(4) {
2
} else {
0
};
let vertical_margin = if area.height > max_height.saturating_add(2) {
1
} else {
0
};
let width = max_width.min(area.width.saturating_sub(horizontal_margin * 2));
let height = max_height.min(area.height.saturating_sub(vertical_margin * 2));
Rect::new(
area.x + area.width.saturating_sub(width) / 2,
area.y + area.height.saturating_sub(height) / 2,
width,
height,
)
}
/// Current inner pixel area for persistent preview or F3. Other overlays suppress graphics.
pub fn preview_image_area(
area: Rect,
mode: PaneMode,
active: PaneId,
overlay: crate::app::Overlay,
) -> Option<ratatui::layout::Size> {
let preview = match overlay {
crate::app::Overlay::None => frame_layout(area, mode, active)
.columns
.into_iter()
.find(|column| column.role == ColumnRole::Preview)
.map(|column| column.area),
crate::app::Overlay::Preview => Some(centered(area, 120, 34)),
_ => None,
}?;
Some(ratatui::layout::Size {
width: preview.width.saturating_sub(2),
height: preview.height.saturating_sub(2),
})
}
fn column(role: ColumnRole, area: Rect, offset: u16, width: u16) -> ColumnLayout {
ColumnLayout {
role,

View file

@ -1,6 +1,8 @@
//! Ratatui rendering and terminal lifecycle.
mod actions;
pub mod help;
pub mod icons;
pub mod layout;
mod operations;
pub mod render;
@ -8,5 +10,9 @@ pub mod terminal;
pub mod text;
pub mod theme;
pub use render::render;
pub use theme::{Palette, Theme};
pub use icons::{FileClass, IconMode, IconResolver, ResolvedIcon};
pub use render::{render, render_with_context};
pub use theme::{
FileTypePalette, Palette, Theme, ThemeDefinition, ThemeId, ThemeMode, ThemeOrigin, ThemeSeed,
contrast_ratio,
};

View file

@ -5,21 +5,23 @@ use std::time::SystemTime;
use chrono::{DateTime, Utc};
use ratatui::Frame;
use ratatui::layout::{Alignment, Rect};
use ratatui::layout::{Alignment, Rect, Size};
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, Paragraph};
use unicode_width::UnicodeWidthStr;
use crate::app::{AppState, Overlay, PaneId, PaneMode, PaneState};
use crate::app::{AppState, Clipboard, Overlay, PaneId, PaneMode, PaneState};
use crate::domain::{Entry, EntryKind, Location, SourceId};
use crate::operations::WorkKind;
use crate::image_preview::ImageRenderContext;
use crate::operations::{OperationKind, WorkKind};
use crate::preview::{Preview, TRUNCATION_MARKER};
use crate::ssh::HostPickerState;
use super::Theme;
use super::layout::{ColumnRole, frame_layout, pane_rows_area};
use super::text::{fit, sanitize, truncate_middle, wrap};
use super::help::{HelpTabs, help_view_model};
use super::layout::{ColumnRole, centered, frame_layout, pane_rows_area};
use super::text::{fit, sanitize, truncate_filename, truncate_middle, wrap};
use super::{IconMode, ResolvedIcon, Theme, ThemeId};
/// Draws a complete frame without mutating application or picker state.
pub fn render(
@ -27,6 +29,17 @@ pub fn render(
app: &AppState,
host_picker: Option<&HostPickerState>,
theme: &Theme,
) {
render_with_context(frame, app, host_picker, theme, None);
}
/// Production rendering with optional fixed prepared images; no resize/encode occurs in Frame.
pub fn render_with_context(
frame: &mut Frame,
app: &AppState,
host_picker: Option<&HostPickerState>,
theme: &Theme,
image_context: Option<ImageRenderContext<'_>>,
) {
let area = frame.area();
if area.is_empty() {
@ -50,28 +63,44 @@ pub fn render(
frame,
column.area,
app.pane(id),
app.clipboard.as_ref(),
id,
id == app.active,
app.mode,
theme,
),
ColumnRole::Preview => {
render_preview(frame, column.area, app.active_pane(), theme, false);
render_preview(
frame,
column.area,
app.active_pane(),
app.active,
theme,
false,
image_context,
app.terminal_epoch,
);
}
}
}
if let Some(status) = layout.status {
render_status(frame, status, app, theme);
}
if let Some(hints) = layout.hints {
render_hints(frame, hints, theme);
}
match app.overlay {
Overlay::None => {}
Overlay::Help => render_help(frame, area, app.overlay_scroll, theme),
Overlay::Help => render_help(frame, area, app, theme),
Overlay::HostPicker => render_host_picker(frame, area, host_picker, theme),
Overlay::Preview => render_preview_overlay(frame, area, app.active_pane(), theme),
Overlay::Preview => render_preview_overlay(
frame,
area,
app.active_pane(),
app.active,
theme,
image_context,
app.terminal_epoch,
),
Overlay::ThemePicker => render_theme_picker(frame, area, app, theme),
Overlay::Message => render_message_overlay(frame, area, app, theme),
Overlay::EntryPrompt | Overlay::ConfirmEntryAction | Overlay::Undo | Overlay::Edit => {
super::actions::render_action_overlay(frame, area, app, theme)
@ -100,24 +129,42 @@ pub fn render(
}
fn render_header(frame: &mut Frame, area: Rect, app: &AppState, theme: &Theme) {
const BRAND: &str = " RCOM ";
const SUBTITLE: &str = "dual-pane file manager";
const HELP: &str = "? Help";
let mode = match app.mode {
PaneMode::Single => "SINGLE",
PaneMode::Dual if app.active == PaneId::Left => "DUAL PANE 1/2",
PaneMode::Dual => "DUAL PANE 2/2",
};
let left = Line::from(vec![
Span::styled(
" RCOM ",
Style::new()
.fg(theme.color(theme.palette.active))
.bg(theme.color(theme.palette.background))
.add_modifier(ratatui::style::Modifier::BOLD),
),
Span::styled("dual-pane file manager", theme.base()),
]);
frame.render_widget(Paragraph::new(left).style(theme.base()), area);
let width = usize::from(area.width);
let brand_width = UnicodeWidthStr::width(BRAND);
let mode_width = UnicodeWidthStr::width(mode);
let help_width = UnicodeWidthStr::width(HELP);
let show_mode = brand_width + mode_width + 2 + help_width <= width;
let reserved_right = if show_mode { mode_width + 2 } else { 0 } + help_width;
let show_subtitle =
brand_width + UnicodeWidthStr::width(SUBTITLE) + 2 + reserved_right <= width;
let mut left = vec![Span::styled(
BRAND,
Style::new()
.fg(theme.color(theme.palette.active))
.bg(theme.color(theme.palette.background))
.add_modifier(ratatui::style::Modifier::BOLD),
)];
if show_subtitle {
left.push(Span::styled(SUBTITLE, theme.base()));
}
frame.render_widget(Paragraph::new(Line::from(left)).style(theme.base()), area);
let mut right = Vec::new();
if show_mode {
right.push(Span::styled(format!("{mode} "), theme.base()));
}
right.push(Span::styled(HELP, theme.active()));
frame.render_widget(
Paragraph::new(mode)
Paragraph::new(Line::from(right))
.alignment(Alignment::Right)
.style(theme.base()),
area,
@ -154,6 +201,7 @@ fn render_pane(
frame: &mut Frame,
area: Rect,
pane: &PaneState,
clipboard: Option<&Clipboard>,
id: PaneId,
active: bool,
mode: PaneMode,
@ -278,7 +326,7 @@ fn render_pane(
theme,
);
} else {
render_entries(frame, area, inner, pane, active, theme);
render_entries(frame, area, inner, pane, clipboard, active, theme);
}
}
@ -287,12 +335,23 @@ fn render_entries(
pane_area: Rect,
inner: Rect,
pane: &PaneState,
clipboard: Option<&Clipboard>,
active: bool,
theme: &Theme,
) {
let rows_area = pane_rows_area(pane_area);
if rows_area.y > inner.y {
let header = entry_row(" ", "TYPE", "NAME", "SIZE", "MODIFIED", inner.width, theme);
let header = entry_row(
" ",
"TYPE",
None,
"NAME",
"SIZE",
"MODIFIED",
inner.width,
theme,
false,
);
frame.render_widget(
Paragraph::new(header).style(theme.secondary()),
Rect::new(inner.x, inner.y, inner.width, 1),
@ -315,6 +374,10 @@ fn render_entries(
let entry = &pane.entries[index];
let is_selected = selected == Some(index);
let id = pane.location.entry_id(&entry.name);
let marked = pane.selection_set.contains(&id);
let clipboard_kind = clipboard
.filter(|clipboard| clipboard.sources.contains(&id))
.map(|clipboard| clipboard.kind);
let marker = format!(
"{}{}",
if is_selected {
@ -322,36 +385,46 @@ fn render_entries(
} else {
" "
},
if pane.selection_set.contains(&id) {
"*"
} else {
" "
match (marked, clipboard_kind) {
(true, Some(OperationKind::Copy)) if theme.is_ascii() => "C",
(true, Some(OperationKind::Move)) if theme.is_ascii() => "X",
(true, Some(OperationKind::Copy)) => "±",
(true, Some(OperationKind::Move)) => "∓",
(true, None) => "*",
(false, Some(OperationKind::Copy)) => "+",
(false, Some(OperationKind::Move)) => "-",
(false, None) => " ",
}
);
let name = entry_display_name(entry);
let line = entry_row(
&marker,
entry_kind(entry.kind),
Some(theme.icon_resolver().resolve(entry)),
&name,
&format_size(entry.size, theme),
&format_modified(entry.modified),
rows_area.width,
theme,
is_selected,
);
let style = if is_selected {
theme.selection()
} else {
normal_style
};
frame.render_widget(
Paragraph::new(line).style(style),
Rect::new(
rows_area.x,
rows_area.y.saturating_add(row as u16),
rows_area.width,
1,
),
let row_area = Rect::new(
rows_area.x,
rows_area.y.saturating_add(row as u16),
rows_area.width,
1,
);
frame.render_widget(Paragraph::new(line).style(style), row_area);
// Raw spans used as spacing do not necessarily touch their cells in the Buffer. Apply the
// effective selected style afterwards so selection has no Reset-colored gaps around icons.
if is_selected {
frame.buffer_mut().set_style(row_area, style);
}
}
}
@ -359,33 +432,78 @@ fn render_entries(
fn entry_row(
marker: &str,
kind: &str,
icon: Option<ResolvedIcon>,
name: &str,
size: &str,
modified: &str,
width: u16,
theme: &Theme,
) -> String {
selected: bool,
) -> Line<'static> {
let width = usize::from(width);
let marker_width = UnicodeWidthStr::width(marker);
let show_size = width >= 30;
let show_modified = width >= 46;
let size_width = if show_size { 9 } else { 0 };
let modified_width = if show_modified { 17 } else { 0 };
let name_width = width.saturating_sub(7 + size_width + modified_width);
let show_text_kind = theme.icon_resolver().mode() == IconMode::None;
let text_kind_width = if show_text_kind { 5 } else { 1 };
let glyph_width = icon
.as_ref()
.map_or(0, |icon| UnicodeWidthStr::width(icon.glyph));
let icon_width = if glyph_width == 0 { 0 } else { glyph_width + 1 };
let name_width = width
.saturating_sub(marker_width + text_kind_width + icon_width + size_width + modified_width);
let name = if name.ends_with('/') {
truncate_middle(name, name_width, theme.is_ascii())
} else {
truncate_filename(name, name_width, theme.is_ascii())
};
let mut output = String::new();
output.push_str(&fit(marker, 2, theme.is_ascii()));
output.push_str(&fit(kind, 4, theme.is_ascii()));
output.push(' ');
output.push_str(&fit(name, name_width, theme.is_ascii()));
let mut spans = vec![Span::raw(fit(marker, marker_width, theme.is_ascii()))];
if show_text_kind {
spans.push(Span::raw(fit(kind, 4, theme.is_ascii())));
}
spans.push(Span::raw(" "));
if let Some(icon) = icon.filter(|_| glyph_width > 0) {
let style = if selected {
Style::new()
} else {
theme.icon_style(&icon)
};
spans.push(Span::styled(
fit(icon.glyph, glyph_width, theme.is_ascii()),
style,
));
spans.push(Span::raw(" "));
}
let name_style = match (selected, icon) {
(false, Some(icon)) => theme.filename_style(icon.class),
_ => Style::new(),
};
spans.push(Span::styled(
fit(&name, name_width, theme.is_ascii()),
name_style,
));
if show_size {
output.push(' ');
output.push_str(&format!("{size:>8}"));
spans.push(Span::raw(format!(" {size:>8}")));
}
if show_modified {
output.push(' ');
output.push_str(modified);
spans.push(Span::raw(format!(" {modified}")));
}
fit(&output, width, theme.is_ascii())
let used: usize = spans
.iter()
.map(|span| UnicodeWidthStr::width(span.content.as_ref()))
.sum();
if used < width {
spans.push(Span::raw(" ".repeat(width - used)));
}
if selected {
for span in &mut spans {
span.style = theme.selection();
}
}
Line::from(spans)
}
fn render_parent(frame: &mut Frame, area: Rect, pane: &PaneState, theme: &Theme) {
@ -447,17 +565,36 @@ fn render_parent(frame: &mut Frame, area: Rect, pane: &PaneState, theme: &Theme)
);
}
fn render_preview(frame: &mut Frame, area: Rect, pane: &PaneState, theme: &Theme, overlay: bool) {
let selected = pane.selected_entry().map(entry_display_name);
let title = match selected {
Some(name) => format!("PREVIEW{}{}", theme.separator(), name),
None => "PREVIEW".to_owned(),
#[allow(clippy::too_many_arguments)]
fn render_preview(
frame: &mut Frame,
area: Rect,
pane: &PaneState,
pane_id: PaneId,
theme: &Theme,
overlay: bool,
image_context: Option<ImageRenderContext<'_>>,
terminal_epoch: u64,
) {
let title_width = usize::from(area.width.saturating_sub(2));
let title = if let Some(entry) = pane.selected_entry() {
let icon = theme.icon_resolver().resolve(entry);
let prefix = format!("PREVIEW{}", theme.separator());
let mut spans = vec![Span::raw(prefix.clone())];
let mut used = UnicodeWidthStr::width(prefix.as_str());
if !icon.glyph.is_empty() {
let width = UnicodeWidthStr::width(icon.glyph);
spans.push(Span::styled(icon.glyph, theme.icon_style(&icon)));
spans.push(Span::raw(" "));
used += width + 1;
}
let name = entry_display_name(entry);
let name = truncate_middle(&name, title_width.saturating_sub(used), theme.is_ascii());
spans.push(Span::styled(name, theme.filename_style(icon.class)));
Line::from(spans)
} else {
Line::from("PREVIEW")
};
let title = truncate_middle(
&title,
usize::from(area.width.saturating_sub(2)),
theme.is_ascii(),
);
let block = Block::new()
.borders(Borders::ALL)
.border_type(theme.border_type())
@ -477,7 +614,9 @@ fn render_preview(frame: &mut Frame, area: Rect, pane: &PaneState, theme: &Theme
return;
}
if pane.selected_entry().is_none() {
if pane.preview.debouncing {
frame.render_widget(Paragraph::new("").style(theme.panel()), inner);
} else if pane.selected_entry().is_none() {
render_message(
frame,
inner,
@ -509,7 +648,11 @@ fn render_preview(frame: &mut Frame, area: Rect, pane: &PaneState, theme: &Theme
theme,
);
} else if let Some(preview) = &pane.preview.content {
render_preview_content(frame, inner, preview, theme);
let rendered_image = preview.kind == crate::preview::PreviewKind::Image
&& render_prepared_image(frame, inner, pane, pane_id, terminal_epoch, image_context);
if !rendered_image {
render_preview_content(frame, inner, preview, theme);
}
} else {
render_message(
frame,
@ -522,6 +665,38 @@ fn render_preview(frame: &mut Frame, area: Rect, pane: &PaneState, theme: &Theme
}
}
fn render_prepared_image(
frame: &mut Frame,
area: Rect,
pane: &PaneState,
pane_id: PaneId,
terminal_epoch: u64,
context: Option<ImageRenderContext<'_>>,
) -> bool {
let Some(context) = context else {
return false;
};
let Some(target) = pane.preview.target.clone() else {
return false;
};
let identity = context.identity(
pane_id,
pane.preview.image_generation,
target,
pane.session_epoch,
Size::new(area.width, area.height),
terminal_epoch,
);
let Some(protocol) = context.cache.current(&identity) else {
return false;
};
if protocol.needs_placeholder(area).is_some() {
return false;
}
frame.render_widget(ratatui_image::Image::new(protocol), area);
true
}
fn render_preview_content(frame: &mut Frame, area: Rect, preview: &Preview, theme: &Theme) {
let footer_height = u16::from(preview.truncated);
let body = Rect::new(
@ -639,23 +814,16 @@ fn render_status(frame: &mut Frame, area: Rect, app: &AppState, theme: &Theme) {
frame.render_widget(Paragraph::new(message).style(style), area);
}
fn render_hints(frame: &mut Frame, area: Rect, theme: &Theme) {
let hints = "Space Select · y/x/p Yank/Cut/Paste · F5/F6 Copy/Move · t Tasks · ? Help · q Quit";
let hints = fit(
&hints.replace('·', if theme.is_ascii() { "|" } else { "·" }),
usize::from(area.width),
theme.is_ascii(),
);
frame.render_widget(Paragraph::new(hints).style(theme.base()), area);
}
fn render_help(frame: &mut Frame, area: Rect, scroll: usize, theme: &Theme) {
let overlay = centered(area, 100, 32);
fn render_theme_picker(frame: &mut Frame, area: Rect, app: &AppState, theme: &Theme) {
let Some(picker) = &app.theme_picker else {
return;
};
let overlay = centered(area, 64, 24);
let block = Block::new()
.borders(Borders::ALL)
.border_type(theme.border_type())
.border_style(theme.active())
.title(format!("HELP{}yazi + mc", theme.separator()))
.title("THEMES")
.style(theme.panel());
let inner = block.inner(overlay);
frame.render_widget(Clear, overlay);
@ -663,146 +831,152 @@ fn render_help(frame: &mut Frame, area: Rect, scroll: usize, theme: &Theme) {
if inner.is_empty() {
return;
}
let footer_height = u16::from(inner.height >= 3);
let body = Rect::new(
inner.x,
inner.y,
inner.width,
inner.height.saturating_sub(footer_height),
);
let navigation = help_lines(
theme,
&[
("NAVIGATION", ""),
("", "j / Down Next entry"),
("", "k / Up Previous entry"),
("", "h / Left Parent directory"),
("", "l / Right / Enter Open directory"),
("", "gg / Home First entry"),
("", "G / End Last entry"),
("", "Ctrl-b / Ctrl-f Page up / down | Space Select"),
("", "PgUp / PgDn Page up / down (mc) | y/x/p"),
("", "Ctrl-u / Ctrl-d Half page up / down"),
("", "~ Local home | F5/F6 Copy/Move"),
],
);
let workspace = help_lines(
theme,
&[
("PANES", ""),
("", "Tab / Shift-Tab Switch active pane"),
("", "\\ Toggle single / dual"),
("", ". Toggle hidden files"),
("", "Ctrl-r Refresh listing"),
("", "F3 Preview overlay | u / Ctrl-z Undo latest"),
("FILE ACTIONS / EDITOR", ""),
("", "a / A / F7 New file / directory"),
("", "r / F2 Rename hovered entry"),
("", "d Trash (restorable)"),
("", "D / F8 Delete = NO UNDO"),
("", "e / F4 Edit regular file"),
("SSH", ""),
("", "s Choose SSH host"),
("", "Type Filter hosts"),
("", "Enter Connect host"),
("GENERAL", ""),
(
"",
"m Error details | Tasks: c Cancel / m Details",
),
("", "? / F1 Toggle this help"),
("", "Esc Close overlay"),
("", "q / F10 Quit"),
],
);
let visible = usize::from(body.height);
let total = if body.width >= 70 {
navigation.len().max(workspace.len())
} else {
navigation.len() + 1 + workspace.len()
};
let offset = effective_scroll(scroll, visible, total);
if body.width >= 70 {
let left_width = body.width / 2;
frame.render_widget(
Paragraph::new(
navigation
.into_iter()
.skip(offset)
.collect::<Vec<Line<'static>>>(),
let footer_height = u16::from(inner.height >= 2);
let error_height = u16::from(picker.error.is_some() && inner.height >= 4);
let list_height = inner
.height
.saturating_sub(footer_height)
.saturating_sub(error_height);
let visible = usize::from(list_height).max(1);
let selected = picker.selected_index();
let mut offset = effective_scroll(picker.scroll, visible, ThemeId::ALL.len());
if selected < offset {
offset = selected;
} else if selected >= offset + visible {
offset = selected + 1 - visible;
}
offset = offset.min(ThemeId::ALL.len().saturating_sub(visible));
let lines = ThemeId::ALL
.iter()
.enumerate()
.skip(offset)
.take(visible)
.map(|(index, id)| {
let marker = if index == selected { ">" } else { " " };
let row = format!(
"{marker} {} {} {}/20",
id.display_name(),
id.mode().as_str(),
index + 1
);
Line::from(fit(&row, usize::from(inner.width), theme.is_ascii())).style(
if index == selected {
theme.selection()
} else {
theme.text()
},
)
.style(theme.panel()),
Rect::new(body.x, body.y, left_width, body.height),
);
})
.collect::<Vec<_>>();
frame.render_widget(
Paragraph::new(lines).style(theme.panel()),
Rect::new(inner.x, inner.y, inner.width, list_height),
);
if error_height > 0 {
let error = picker.error.as_deref().unwrap_or("Theme save failed");
frame.render_widget(
Paragraph::new(
workspace
.into_iter()
.skip(offset)
.collect::<Vec<Line<'static>>>(),
)
.style(theme.panel()),
Rect::new(
body.x.saturating_add(left_width),
body.y,
body.width.saturating_sub(left_width),
body.height,
),
);
} else {
let mut combined = navigation;
combined.push(Line::from(""));
combined.extend(workspace);
frame.render_widget(
Paragraph::new(
combined
.into_iter()
.skip(offset)
.collect::<Vec<Line<'static>>>(),
)
.style(theme.panel()),
body,
Paragraph::new(fit(
&format!("ERROR: {}", sanitize(error)),
usize::from(inner.width),
theme.is_ascii(),
))
.style(theme.error()),
Rect::new(inner.x, inner.y + list_height, inner.width, error_height),
);
}
if footer_height > 0 {
let navigation = if inner.width >= 55 {
"j/k PgUp/PgDn Ctrl-u/d"
} else {
"j/k PgUp/Dn"
};
let footer = format!(
"{}{}{navigation}{}Esc/?/q Close",
scroll_position(offset, visible, total),
theme.separator(),
theme.separator()
);
frame.render_widget(
Paragraph::new(fit(&footer, usize::from(inner.width), theme.is_ascii()))
.alignment(Alignment::Right)
.style(theme.secondary()),
Rect::new(
inner.x,
inner.y.saturating_add(inner.height.saturating_sub(1)),
inner.width,
1,
),
Paragraph::new(fit(
"Enter Save | Esc Cancel",
usize::from(inner.width),
theme.is_ascii(),
))
.alignment(Alignment::Center)
.style(theme.secondary()),
Rect::new(inner.x, inner.y + inner.height - 1, inner.width, 1),
);
}
}
fn help_lines(theme: &Theme, rows: &[(&str, &str)]) -> Vec<Line<'static>> {
rows.iter()
.map(|(heading, command)| {
if command.is_empty() {
Line::from((*heading).to_owned()).style(theme.active())
} else {
Line::from((*command).to_owned())
fn render_help(frame: &mut Frame, area: Rect, app: &AppState, theme: &Theme) {
let model = help_view_model(area, &app.help);
let block = Block::new()
.borders(Borders::ALL)
.border_type(theme.border_type())
.border_style(theme.active())
.title("HELP")
.style(theme.panel());
frame.render_widget(Clear, model.overlay);
frame.render_widget(block, model.overlay);
if model.inner.is_empty() {
return;
}
if let Some(tabs_area) = model.tabs_area {
match model.tabs {
HelpTabs::Full => {
let mut spans = Vec::new();
for (index, category) in crate::app::HelpCategory::ALL.iter().enumerate() {
if index > 0 {
spans.push(Span::raw(" "));
}
let active = *category == app.help.category;
let label = if active {
format!("[{}]", category.label())
} else {
category.label().to_owned()
};
spans.push(Span::styled(
label,
if active {
theme.active()
} else {
theme.muted()
},
));
}
frame.render_widget(
Paragraph::new(Line::from(spans)).style(theme.panel()),
tabs_area,
);
}
})
.collect()
HelpTabs::Compact { .. } => {
let label = model.compact_label().unwrap_or_default();
frame.render_widget(
Paragraph::new(label)
.alignment(Alignment::Center)
.style(theme.active()),
tabs_area,
);
}
}
}
frame.render_widget(
Paragraph::new(
model
.lines
.iter()
.skip(model.offset)
.map(|line| Line::from(line.clone()).style(theme.text()))
.collect::<Vec<_>>(),
)
.style(theme.panel()),
model.body,
);
if let Some(footer) = model.footer {
frame.render_widget(
Paragraph::new(fit(
&model.footer_text,
usize::from(footer.width),
theme.is_ascii(),
))
.alignment(Alignment::Right)
.style(theme.secondary()),
footer,
);
}
}
fn render_message_overlay(frame: &mut Frame, area: Rect, app: &AppState, theme: &Theme) {
@ -1059,9 +1233,26 @@ fn render_hosts(frame: &mut Frame, area: Rect, picker: &HostPickerState, theme:
}
}
fn render_preview_overlay(frame: &mut Frame, area: Rect, pane: &PaneState, theme: &Theme) {
fn render_preview_overlay(
frame: &mut Frame,
area: Rect,
pane: &PaneState,
pane_id: PaneId,
theme: &Theme,
image_context: Option<ImageRenderContext<'_>>,
terminal_epoch: u64,
) {
let overlay = centered(area, 120, 34);
render_preview(frame, overlay, pane, theme, true);
render_preview(
frame,
overlay,
pane,
pane_id,
theme,
true,
image_context,
terminal_epoch,
);
if overlay.height >= 3 {
let hints = "F3 / Esc / q Close";
let area = Rect::new(
@ -1079,27 +1270,6 @@ fn render_preview_overlay(frame: &mut Frame, area: Rect, pane: &PaneState, theme
}
}
fn centered(area: Rect, max_width: u16, max_height: u16) -> Rect {
let horizontal_margin = if area.width > max_width.saturating_add(4) {
2
} else {
0
};
let vertical_margin = if area.height > max_height.saturating_add(2) {
1
} else {
0
};
let width = max_width.min(area.width.saturating_sub(horizontal_margin * 2));
let height = max_height.min(area.height.saturating_sub(vertical_margin * 2));
Rect::new(
area.x + area.width.saturating_sub(width) / 2,
area.y + area.height.saturating_sub(height) / 2,
width,
height,
)
}
fn truncate_source_badge(source: &str, width: usize, ascii: bool) -> String {
if UnicodeWidthStr::width(source) <= width {
return source.to_owned();
@ -1131,6 +1301,13 @@ fn entry_display_name(entry: &Entry) -> String {
let suffix = match entry.kind {
EntryKind::Directory => "/",
EntryKind::Symlink => "@",
EntryKind::File
if entry
.permissions
.is_some_and(|permissions| permissions & 0o111 != 0) =>
{
"*"
}
EntryKind::File | EntryKind::Other => "",
};
format!("{}{suffix}", sanitize(&entry.name.to_string_lossy()))

View file

@ -75,6 +75,31 @@ pub fn truncate_middle(input: &str, width: usize, ascii: bool) -> String {
output
}
/// Truncates a filename while retaining its final extension when the budget permits it.
pub fn truncate_filename(input: &str, width: usize, ascii: bool) -> String {
if UnicodeWidthStr::width(input) <= width {
return input.to_owned();
}
let extension = input
.rsplit_once('.')
.filter(|(stem, extension)| !stem.is_empty() && !extension.is_empty())
.map(|(stem, _extension)| &input[stem.len()..]);
let Some(extension) = extension else {
return truncate_middle(input, width, ascii);
};
let marker = if ascii { "..." } else { "…" };
let extension_width = UnicodeWidthStr::width(extension);
let marker_width = UnicodeWidthStr::width(marker);
if width <= extension_width + marker_width {
return truncate_middle(input, width, ascii);
}
let prefix_width = width - extension_width - marker_width;
let mut output = take_prefix(input, prefix_width);
output.push_str(marker);
output.push_str(extension);
output
}
/// Pads on the right using display columns rather than bytes or scalar values.
pub(crate) fn pad_right(input: &str, width: usize) -> String {
let mut output = input.to_owned();
@ -133,7 +158,7 @@ mod tests {
use pretty_assertions::assert_eq;
use unicode_width::UnicodeWidthStr;
use super::{sanitize, truncate_middle, wrap};
use super::{sanitize, truncate_filename, truncate_middle, wrap};
#[test]
fn controls_and_bidi_marks_cannot_escape_a_row() {
@ -156,6 +181,16 @@ mod tests {
assert_eq!(wrap("abc", 0), vec![String::new()]);
}
#[test]
fn filename_truncation_preserves_extension_and_display_width() {
for ascii in [false, true] {
let result = truncate_filename("a-very-long-source-file.rs", 15, ascii);
assert_eq!(UnicodeWidthStr::width(result.as_str()), 15);
assert!(result.ends_with(".rs"), "{result}");
}
assert_eq!(truncate_filename("short.rs", 12, false), "short.rs");
}
#[test]
fn middle_truncation_respects_wide_unicode_and_ascii_fallback() {
for ascii in [false, true] {

View file

@ -1,10 +1,234 @@
//! Night Ops palette and terminal capability fallbacks.
//! Built-in semantic themes and terminal capability fallbacks.
use std::env;
use std::{env, fmt, str::FromStr};
use clap::ValueEnum;
use ratatui::style::{Color, Modifier, Style};
use serde::{Deserialize, Serialize};
/// The RGB accents of the Night Ops visual system.
use super::{FileClass, IconMode, IconResolver, ResolvedIcon};
/// Stable persisted identifiers. `ALL` uses the same display-name order as the picker and CLI.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq, Serialize, ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum ThemeId {
CatppuccinLatte,
CatppuccinMocha,
Dracula,
EverforestDarkMedium,
EverforestLightMedium,
FlexokiDark,
FlexokiLight,
GithubDark,
GithubLight,
GruvboxDark,
GruvboxLight,
#[default]
NightOps,
OneHalfDark,
OneHalfLight,
RosePine,
RosePineDawn,
SolarizedDark,
SolarizedLight,
TokyoNight,
TokyoNightDay,
}
impl ThemeId {
pub const ALL: [Self; 20] = [
Self::CatppuccinLatte,
Self::CatppuccinMocha,
Self::Dracula,
Self::EverforestDarkMedium,
Self::EverforestLightMedium,
Self::FlexokiDark,
Self::FlexokiLight,
Self::GithubDark,
Self::GithubLight,
Self::GruvboxDark,
Self::GruvboxLight,
Self::NightOps,
Self::OneHalfDark,
Self::OneHalfLight,
Self::RosePine,
Self::RosePineDawn,
Self::SolarizedDark,
Self::SolarizedLight,
Self::TokyoNight,
Self::TokyoNightDay,
];
pub fn as_str(self) -> &'static str {
match self {
Self::CatppuccinLatte => "catppuccin-latte",
Self::CatppuccinMocha => "catppuccin-mocha",
Self::Dracula => "dracula",
Self::EverforestDarkMedium => "everforest-dark-medium",
Self::EverforestLightMedium => "everforest-light-medium",
Self::FlexokiDark => "flexoki-dark",
Self::FlexokiLight => "flexoki-light",
Self::GithubDark => "github-dark",
Self::GithubLight => "github-light",
Self::GruvboxDark => "gruvbox-dark",
Self::GruvboxLight => "gruvbox-light",
Self::NightOps => "night-ops",
Self::OneHalfDark => "one-half-dark",
Self::OneHalfLight => "one-half-light",
Self::RosePine => "rose-pine",
Self::RosePineDawn => "rose-pine-dawn",
Self::SolarizedDark => "solarized-dark",
Self::SolarizedLight => "solarized-light",
Self::TokyoNight => "tokyo-night",
Self::TokyoNightDay => "tokyo-night-day",
}
}
pub fn definition(self) -> &'static ThemeDefinition {
if self == Self::NightOps {
&NIGHT_OPS_DEFINITION
} else {
IMPORTED_THEMES
.iter()
.find(|definition| definition.id == self.as_str())
.expect("every ThemeId has a generated definition")
}
}
pub fn display_name(self) -> &'static str {
match self {
Self::CatppuccinLatte => "Catppuccin Latte",
Self::CatppuccinMocha => "Catppuccin Mocha",
Self::Dracula => "Dracula",
Self::EverforestDarkMedium => "Everforest Dark Medium",
Self::EverforestLightMedium => "Everforest Light Medium",
Self::FlexokiDark => "Flexoki Dark",
Self::FlexokiLight => "Flexoki Light",
Self::GithubDark => "GitHub Dark",
Self::GithubLight => "GitHub Light",
Self::GruvboxDark => "Gruvbox Dark",
Self::GruvboxLight => "Gruvbox Light",
Self::NightOps => "Night Ops",
Self::OneHalfDark => "One Half Dark",
Self::OneHalfLight => "One Half Light",
Self::RosePine => "Rosé Pine",
Self::RosePineDawn => "Rosé Pine Dawn",
Self::SolarizedDark => "Solarized Dark",
Self::SolarizedLight => "Solarized Light",
Self::TokyoNight => "Tokyo Night",
Self::TokyoNightDay => "Tokyo Night Day",
}
}
pub fn mode(self) -> ThemeMode {
match self {
Self::CatppuccinLatte
| Self::EverforestLightMedium
| Self::FlexokiLight
| Self::GithubLight
| Self::GruvboxLight
| Self::OneHalfLight
| Self::RosePineDawn
| Self::SolarizedLight
| Self::TokyoNightDay => ThemeMode::Light,
_ => ThemeMode::Dark,
}
}
pub fn available_ids() -> String {
Self::ALL
.iter()
.map(|id| id.as_str())
.collect::<Vec<_>>()
.join(", ")
}
}
impl fmt::Display for ThemeId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl FromStr for ThemeId {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Self::ALL
.iter()
.copied()
.find(|id| id.as_str() == value)
.ok_or_else(|| {
format!(
"unknown theme {value:?}; available themes: {}",
Self::available_ids()
)
})
}
}
impl<'de> Deserialize<'de> for ThemeId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
value.parse().map_err(serde::de::Error::custom)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ThemeMode {
Dark,
Light,
}
impl ThemeMode {
pub fn as_str(self) -> &'static str {
match self {
Self::Dark => "dark",
Self::Light => "light",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ThemeOrigin {
Native,
Kitty,
}
/// Semantic file classes and independently configurable icon accents.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FileTypePalette {
pub directory: Color,
pub regular: Color,
pub executable: Color,
pub symlink: Color,
pub image: Color,
pub media: Color,
pub document: Color,
pub archive: Color,
pub special: Color,
pub rust_icon: Color,
}
impl FileTypePalette {
pub const NIGHT_OPS: Self = Self {
directory: Color::Rgb(0x82, 0xaa, 0xff),
regular: Color::Rgb(0xd8, 0xe0, 0xf0),
executable: Color::Rgb(0x9e, 0xce, 0x6a),
symlink: Color::Rgb(0x65, 0xd6, 0xe8),
image: Color::Rgb(0xe0, 0xaf, 0x68),
media: Color::Rgb(0xbb, 0x9a, 0xf7),
document: Color::Rgb(0x7d, 0xcf, 0xff),
archive: Color::Rgb(0xff, 0x7a, 0x90),
special: Color::Rgb(0xe0, 0xaf, 0x68),
rust_icon: Color::Rgb(0xde, 0xa5, 0x84),
};
}
/// Semantic colors shared by lists, overlays, dialogs and previews.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Palette {
pub background: Color,
@ -15,6 +239,8 @@ pub struct Palette {
pub secondary: Color,
pub error: Color,
pub selection: Color,
pub selection_text: Color,
pub file_types: FileTypePalette,
}
impl Palette {
@ -22,20 +248,57 @@ impl Palette {
background: Color::Rgb(0x0b, 0x10, 0x20),
panel: Color::Rgb(0x11, 0x18, 0x2b),
text: Color::Rgb(0xd8, 0xe0, 0xf0),
muted: Color::Rgb(0x71, 0x80, 0x9b),
muted: Color::Rgb(0x78, 0x86, 0xa0),
active: Color::Rgb(0x65, 0xd6, 0xe8),
secondary: Color::Rgb(0xa8, 0x9b, 0xff),
error: Color::Rgb(0xff, 0x7a, 0x90),
selection: Color::Rgb(0x20, 0x30, 0x4a),
selection: Color::Rgb(0x62, 0x6e, 0x80),
selection_text: Color::Rgb(0xff, 0xff, 0xff),
file_types: FileTypePalette::NIGHT_OPS,
};
}
/// Source values retained separately from RCOM's derived semantic roles.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ThemeSeed {
pub background: Color,
pub text: Color,
pub panel: Option<Color>,
pub muted: Option<Color>,
pub active: Option<Color>,
pub selection_background: Option<Color>,
pub selection_text: Option<Color>,
pub ansi: [Color; 16],
}
pub struct ThemeDefinition {
pub id: &'static str,
pub display_name: &'static str,
pub mode: ThemeMode,
pub origin: ThemeOrigin,
pub native_palette: Option<Palette>,
pub seed: Option<ThemeSeed>,
}
const NIGHT_OPS_DEFINITION: ThemeDefinition = ThemeDefinition {
id: "night-ops",
display_name: "Night Ops",
mode: ThemeMode::Dark,
origin: ThemeOrigin::Native,
native_palette: Some(Palette::NIGHT_OPS),
seed: None,
};
const IMPORTED_THEMES: &[ThemeDefinition] = include!("themes_data.rs");
/// Rendering capabilities. Textual focus/selection markers are used in every theme.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Theme {
pub id: ThemeId,
pub palette: Palette,
colors: bool,
ascii: bool,
icons: IconResolver,
}
impl Default for Theme {
@ -45,50 +308,88 @@ impl Default for Theme {
}
impl Theme {
pub const fn night_ops() -> Self {
pub fn night_ops() -> Self {
Self {
id: ThemeId::NightOps,
palette: Palette::NIGHT_OPS,
colors: true,
ascii: false,
icons: IconResolver::new(IconMode::Unicode),
}
}
/// Builds a theme from the conventional terminal environment.
///
/// `NO_COLOR` and `TERM=dumb` disable RGB output. A dumb terminal also uses ASCII borders,
/// markers and truncation. `RCOM_ASCII` is an explicit opt-in for limited Unicode terminals.
pub fn from_env() -> Self {
Self::from_env_with_icons(IconMode::Unicode)
}
pub fn from_env_with_icons(mode: IconMode) -> Self {
Self::from_env_with_appearance(mode, ThemeId::NightOps)
}
/// Applies persistent/CLI appearance first, then terminal capability fallbacks.
pub fn from_env_with_appearance(mode: IconMode, id: ThemeId) -> Self {
let dumb = env::var("TERM").is_ok_and(|term| term.eq_ignore_ascii_case("dumb"));
let no_color = env::var_os("NO_COLOR").is_some() || dumb;
let ascii = dumb || env::var_os("RCOM_ASCII").is_some();
Self::with_capabilities(!no_color, ascii)
Self::with_capabilities_for(id, !no_color, ascii).with_icon_mode(mode)
}
pub const fn no_color() -> Self {
pub fn with_id(mut self, id: ThemeId) -> Self {
self.id = id;
self.palette = palette_for(id);
self
}
pub fn with_icon_mode(mut self, mode: IconMode) -> Self {
let effective = if self.ascii && !matches!(mode, IconMode::None) {
IconMode::Ascii
} else {
mode
};
self.icons = IconResolver::new(effective);
self
}
pub(crate) fn icon_resolver(self) -> IconResolver {
self.icons
}
pub fn no_color() -> Self {
Self::with_capabilities(false, false)
}
pub const fn ascii() -> Self {
pub fn ascii() -> Self {
Self::with_capabilities(false, true)
}
pub const fn with_capabilities(colors: bool, ascii: bool) -> Self {
pub fn with_capabilities(colors: bool, ascii: bool) -> Self {
Self::with_capabilities_for(ThemeId::NightOps, colors, ascii)
}
pub fn with_capabilities_for(id: ThemeId, colors: bool, ascii: bool) -> Self {
Self {
palette: Palette::NIGHT_OPS,
id,
palette: palette_for(id),
colors,
ascii,
icons: IconResolver::new(if ascii {
IconMode::Ascii
} else {
IconMode::Unicode
}),
}
}
pub const fn colors_enabled(self) -> bool {
pub fn colors_enabled(self) -> bool {
self.colors
}
pub const fn is_ascii(self) -> bool {
pub fn is_ascii(self) -> bool {
self.ascii
}
pub(crate) const fn border_type(self) -> ratatui::widgets::BorderType {
pub(crate) fn border_type(self) -> ratatui::widgets::BorderType {
if self.ascii {
ratatui::widgets::BorderType::Plain
} else {
@ -96,27 +397,27 @@ impl Theme {
}
}
pub(crate) const fn active_marker(self) -> &'static str {
pub(crate) fn active_marker(self) -> &'static str {
if self.ascii { ">" } else { "▸" }
}
pub(crate) const fn selected_marker(self) -> &'static str {
pub(crate) fn selected_marker(self) -> &'static str {
if self.ascii { ">" } else { "▸" }
}
pub(crate) const fn warning_marker(self) -> &'static str {
pub(crate) fn warning_marker(self) -> &'static str {
if self.ascii { "!" } else { "⚠" }
}
pub(crate) const fn loading_marker(self) -> &'static str {
pub(crate) fn loading_marker(self) -> &'static str {
if self.ascii { "*" } else { "◌" }
}
pub(crate) const fn unknown(self) -> &'static str {
pub(crate) fn unknown(self) -> &'static str {
if self.ascii { "-" } else { "—" }
}
pub(crate) const fn separator(self) -> &'static str {
pub(crate) fn separator(self) -> &'static str {
if self.ascii { " | " } else { " · " }
}
@ -166,13 +467,270 @@ impl Theme {
.add_modifier(Modifier::BOLD)
}
pub(crate) fn filename_style(self, class: FileClass) -> Style {
let palette = self.palette.file_types;
let color = match class {
FileClass::Directory => palette.directory,
FileClass::Regular => palette.regular,
FileClass::Executable => palette.executable,
FileClass::Symlink => palette.symlink,
FileClass::Image => palette.image,
FileClass::Media => palette.media,
FileClass::Document => palette.document,
FileClass::Archive => palette.archive,
FileClass::Special => palette.special,
};
Style::new().fg(self.color(color))
}
pub(crate) fn icon_style(self, icon: &ResolvedIcon) -> Style {
let color = if icon.id == "rust" {
self.palette.file_types.rust_icon
} else {
match icon.class {
FileClass::Directory => self.palette.file_types.directory,
FileClass::Regular => self.palette.file_types.regular,
FileClass::Executable => self.palette.file_types.executable,
FileClass::Symlink => self.palette.file_types.symlink,
FileClass::Image => self.palette.file_types.image,
FileClass::Media => self.palette.file_types.media,
FileClass::Document => self.palette.file_types.document,
FileClass::Archive => self.palette.file_types.archive,
FileClass::Special => self.palette.file_types.special,
}
};
Style::new().fg(self.color(color))
}
pub(crate) fn selection(self) -> Style {
let mut style = Style::new()
.fg(self.color(self.palette.text))
.add_modifier(Modifier::REVERSED | Modifier::BOLD);
.fg(self.color(self.palette.selection_text))
.add_modifier(Modifier::BOLD);
if self.colors {
style = style.bg(self.palette.selection);
} else {
style = style.add_modifier(Modifier::REVERSED);
}
style
}
}
fn palette_for(id: ThemeId) -> Palette {
let definition = id.definition();
match definition.native_palette {
Some(palette) => palette,
None => derive_palette(definition.seed.expect("import missing seed")),
}
}
fn derive_palette(seed: ThemeSeed) -> Palette {
let background = seed.background;
let panel = ensure_contrast(
match seed.panel {
Some(color) => color,
None => mix(background, seed.text, 0.06),
},
background,
1.15,
);
let text = ensure_on_surfaces(seed.text, &[background, panel], 4.5);
let muted_source = match seed.muted {
Some(color) => color,
None => seed.ansi[8],
};
let muted = ensure_on_surfaces(muted_source, &[panel, background], 4.5);
let active_source = match seed.active {
Some(color) => color,
None => best_contrast(seed.ansi[4], seed.ansi[12], panel),
};
let active = ensure_on_surfaces(active_source, &[panel, background], 4.5);
let secondary = ensure_on_surfaces(
best_contrast(seed.ansi[5], seed.ansi[13], panel),
&[panel, background],
4.5,
);
let error = ensure_on_surfaces(
best_contrast(seed.ansi[1], seed.ansi[9], panel),
&[panel, background],
4.5,
);
let selection = ensure_on_surfaces(
match seed.selection_background {
Some(color) => color,
None => mix(panel, active, 0.28),
},
&[panel, background],
3.0,
);
let selection_text = ensure_contrast(
match seed.selection_text {
Some(color) => color,
None => text,
},
selection,
4.5,
);
let regular = ensure_on_surfaces(text, &[panel, background], 4.5);
let directory = ensure_on_surfaces(
best_contrast(seed.ansi[4], seed.ansi[12], panel),
&[panel, background],
4.5,
);
let executable = ensure_on_surfaces(
best_contrast(seed.ansi[2], seed.ansi[10], panel),
&[panel, background],
4.5,
);
let symlink = ensure_on_surfaces(
best_contrast(seed.ansi[6], seed.ansi[14], panel),
&[panel, background],
4.5,
);
let image = ensure_on_surfaces(
best_contrast(seed.ansi[3], seed.ansi[11], panel),
&[panel, background],
4.5,
);
let media = ensure_on_surfaces(
best_contrast(seed.ansi[5], seed.ansi[13], panel),
&[panel, background],
4.5,
);
let document = ensure_on_surfaces(
best_contrast(symlink, text, panel),
&[panel, background],
4.5,
);
let archive = ensure_on_surfaces(error, &[panel, background], 4.5);
let special = image;
Palette {
background,
panel,
text,
muted,
active,
secondary,
error,
selection,
selection_text,
file_types: FileTypePalette {
directory,
regular,
executable,
symlink,
image,
media,
document,
archive,
special,
rust_icon: archive,
},
}
}
fn rgb(color: Color) -> (u8, u8, u8) {
match color {
Color::Rgb(red, green, blue) => (red, green, blue),
_ => (0, 0, 0),
}
}
fn mix(left: Color, right: Color, amount: f64) -> Color {
let (lr, lg, lb) = rgb(left);
let (rr, rg, rb) = rgb(right);
Color::Rgb(
(lr as f64 + (rr as f64 - lr as f64) * amount) as u8,
(lg as f64 + (rg as f64 - lg as f64) * amount) as u8,
(lb as f64 + (rb as f64 - lb as f64) * amount) as u8,
)
}
fn linear_channel(value: u8) -> f64 {
let value = value as f64 / 255.0;
if value <= 0.04045 {
value / 12.92
} else {
((value + 0.055) / 1.055).powf(2.4)
}
}
fn luminance(color: Color) -> f64 {
let (red, green, blue) = rgb(color);
0.2126 * linear_channel(red) + 0.7152 * linear_channel(green) + 0.0722 * linear_channel(blue)
}
/// WCAG relative-luminance ratio for the explicit RGB colors used by rich themes.
pub fn contrast_ratio(left: Color, right: Color) -> f64 {
let left = luminance(left);
let right = luminance(right);
let (light, dark) = if left > right {
(left, right)
} else {
(right, left)
};
(light + 0.05) / (dark + 0.05)
}
fn best_contrast(left: Color, right: Color, surface: Color) -> Color {
if contrast_ratio(left, surface) >= contrast_ratio(right, surface) {
left
} else {
right
}
}
fn ensure_contrast(color: Color, surface: Color, target: f64) -> Color {
if contrast_ratio(color, surface) >= target {
return color;
}
let white = Color::Rgb(255, 255, 255);
let black = Color::Rgb(0, 0, 0);
let light = best_contrast(white, black, surface);
let mut step = 1;
while step <= 20 {
let adjusted = mix(color, light, step as f64 / 20.0);
if contrast_ratio(adjusted, surface) >= target {
return adjusted;
}
step += 1;
}
light
}
fn ensure_on_surfaces(color: Color, surfaces: &[Color], target: f64) -> Color {
let white = Color::Rgb(255, 255, 255);
let black = Color::Rgb(0, 0, 0);
let mut best = color;
let mut best_score = 0.0;
let mut direction = 0;
while direction < 2 {
let endpoint = if direction == 0 { white } else { black };
let mut step = 0;
while step <= 20 {
let candidate = mix(color, endpoint, step as f64 / 20.0);
let mut index = 0;
let mut score = 21.0;
let mut passes = true;
while index < surfaces.len() {
let ratio = contrast_ratio(candidate, surfaces[index]);
if ratio < score {
score = ratio;
}
if ratio < target {
passes = false;
}
index += 1;
}
if passes {
return candidate;
}
if score > best_score {
best = candidate;
best_score = score;
}
step += 1;
}
direction += 1;
}
best
}

630
src/ui/themes_data.rs Normal file
View file

@ -0,0 +1,630 @@
// Generated by tools/import_themes.py; do not edit manually.
&[
ThemeDefinition {
id: "dracula",
display_name: "Dracula",
mode: ThemeMode::Dark,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0x28, 0x2a, 0x36),
text: Color::Rgb(0xf8, 0xf8, 0xf2),
panel: Some(Color::Rgb(0x62, 0x72, 0xa4)),
muted: Some(Color::Rgb(0x28, 0x2a, 0x36)),
active: Some(Color::Rgb(0x8b, 0xe9, 0xfd)),
selection_background: Some(Color::Rgb(0x44, 0x47, 0x5a)),
selection_text: Some(Color::Rgb(0xff, 0xff, 0xff)),
ansi: [Color::Rgb(0x21, 0x22, 0x2c),
Color::Rgb(0xff, 0x55, 0x55),
Color::Rgb(0x50, 0xfa, 0x7b),
Color::Rgb(0xf1, 0xfa, 0x8c),
Color::Rgb(0xbd, 0x93, 0xf9),
Color::Rgb(0xff, 0x79, 0xc6),
Color::Rgb(0x8b, 0xe9, 0xfd),
Color::Rgb(0xf8, 0xf8, 0xf2),
Color::Rgb(0x62, 0x72, 0xa4),
Color::Rgb(0xff, 0x6e, 0x6e),
Color::Rgb(0x69, 0xff, 0x94),
Color::Rgb(0xff, 0xff, 0xa5),
Color::Rgb(0xd6, 0xac, 0xff),
Color::Rgb(0xff, 0x92, 0xdf),
Color::Rgb(0xa4, 0xff, 0xff),
Color::Rgb(0xff, 0xff, 0xff)],
}),
},
ThemeDefinition {
id: "catppuccin-mocha",
display_name: "Catppuccin Mocha",
mode: ThemeMode::Dark,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0x1e, 0x1e, 0x2e),
text: Color::Rgb(0xcd, 0xd6, 0xf4),
panel: Some(Color::Rgb(0x11, 0x11, 0x1b)),
muted: Some(Color::Rgb(0xcd, 0xd6, 0xf4)),
active: Some(Color::Rgb(0xb4, 0xbe, 0xfe)),
selection_background: Some(Color::Rgb(0xf5, 0xe0, 0xdc)),
selection_text: Some(Color::Rgb(0x1e, 0x1e, 0x2e)),
ansi: [Color::Rgb(0x45, 0x47, 0x5a),
Color::Rgb(0xf3, 0x8b, 0xa8),
Color::Rgb(0xa6, 0xe3, 0xa1),
Color::Rgb(0xf9, 0xe2, 0xaf),
Color::Rgb(0x89, 0xb4, 0xfa),
Color::Rgb(0xf5, 0xc2, 0xe7),
Color::Rgb(0x94, 0xe2, 0xd5),
Color::Rgb(0xba, 0xc2, 0xde),
Color::Rgb(0x58, 0x5b, 0x70),
Color::Rgb(0xf3, 0x8b, 0xa8),
Color::Rgb(0xa6, 0xe3, 0xa1),
Color::Rgb(0xf9, 0xe2, 0xaf),
Color::Rgb(0x89, 0xb4, 0xfa),
Color::Rgb(0xf5, 0xc2, 0xe7),
Color::Rgb(0x94, 0xe2, 0xd5),
Color::Rgb(0xa6, 0xad, 0xc8)],
}),
},
ThemeDefinition {
id: "catppuccin-latte",
display_name: "Catppuccin Latte",
mode: ThemeMode::Light,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0xef, 0xf1, 0xf5),
text: Color::Rgb(0x4c, 0x4f, 0x69),
panel: Some(Color::Rgb(0xbc, 0xc0, 0xcc)),
muted: Some(Color::Rgb(0x4c, 0x4f, 0x69)),
active: Some(Color::Rgb(0x72, 0x87, 0xfd)),
selection_background: Some(Color::Rgb(0xdc, 0x8a, 0x78)),
selection_text: Some(Color::Rgb(0xef, 0xf1, 0xf5)),
ansi: [Color::Rgb(0x5c, 0x5f, 0x77),
Color::Rgb(0xd2, 0x0f, 0x39),
Color::Rgb(0x40, 0xa0, 0x2b),
Color::Rgb(0xdf, 0x8e, 0x1d),
Color::Rgb(0x1e, 0x66, 0xf5),
Color::Rgb(0xea, 0x76, 0xcb),
Color::Rgb(0x17, 0x92, 0x99),
Color::Rgb(0xac, 0xb0, 0xbe),
Color::Rgb(0x6c, 0x6f, 0x85),
Color::Rgb(0xd2, 0x0f, 0x39),
Color::Rgb(0x40, 0xa0, 0x2b),
Color::Rgb(0xdf, 0x8e, 0x1d),
Color::Rgb(0x1e, 0x66, 0xf5),
Color::Rgb(0xea, 0x76, 0xcb),
Color::Rgb(0x17, 0x92, 0x99),
Color::Rgb(0xbc, 0xc0, 0xcc)],
}),
},
ThemeDefinition {
id: "gruvbox-dark",
display_name: "Gruvbox Dark",
mode: ThemeMode::Dark,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0x28, 0x28, 0x28),
text: Color::Rgb(0xeb, 0xdb, 0xb2),
panel: Some(Color::Rgb(0x20, 0x20, 0x20)),
muted: Some(Color::Rgb(0xeb, 0xdb, 0xb2)),
active: Some(Color::Rgb(0x45, 0x85, 0x88)),
selection_background: Some(Color::Rgb(0xd6, 0x5d, 0x0e)),
selection_text: Some(Color::Rgb(0xeb, 0xdb, 0xb2)),
ansi: [Color::Rgb(0x3c, 0x38, 0x36),
Color::Rgb(0xcc, 0x24, 0x1d),
Color::Rgb(0x98, 0x97, 0x1a),
Color::Rgb(0xd7, 0x99, 0x21),
Color::Rgb(0x45, 0x85, 0x88),
Color::Rgb(0xb1, 0x62, 0x86),
Color::Rgb(0x68, 0x9d, 0x6a),
Color::Rgb(0xa8, 0x99, 0x84),
Color::Rgb(0x92, 0x83, 0x74),
Color::Rgb(0xfb, 0x49, 0x34),
Color::Rgb(0xb8, 0xbb, 0x26),
Color::Rgb(0xfa, 0xbd, 0x2f),
Color::Rgb(0x83, 0xa5, 0x98),
Color::Rgb(0xd3, 0x86, 0x9b),
Color::Rgb(0x8e, 0xc0, 0x7c),
Color::Rgb(0xfb, 0xf1, 0xc7)],
}),
},
ThemeDefinition {
id: "gruvbox-light",
display_name: "Gruvbox Light",
mode: ThemeMode::Light,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0xfb, 0xf1, 0xc7),
text: Color::Rgb(0x3c, 0x38, 0x36),
panel: None,
muted: None,
active: Some(Color::Rgb(0x45, 0x85, 0x88)),
selection_background: Some(Color::Rgb(0xd6, 0x5d, 0x0e)),
selection_text: Some(Color::Rgb(0x3c, 0x38, 0x36)),
ansi: [Color::Rgb(0xeb, 0xdb, 0xb2),
Color::Rgb(0xcc, 0x24, 0x1d),
Color::Rgb(0x98, 0x97, 0x1a),
Color::Rgb(0xd7, 0x99, 0x21),
Color::Rgb(0x45, 0x85, 0x88),
Color::Rgb(0xb1, 0x62, 0x86),
Color::Rgb(0x68, 0x9d, 0x6a),
Color::Rgb(0x7c, 0x6f, 0x64),
Color::Rgb(0x92, 0x83, 0x74),
Color::Rgb(0x9d, 0x00, 0x06),
Color::Rgb(0x79, 0x74, 0x0e),
Color::Rgb(0xb5, 0x76, 0x14),
Color::Rgb(0x07, 0x66, 0x78),
Color::Rgb(0x8f, 0x3f, 0x71),
Color::Rgb(0x42, 0x7b, 0x58),
Color::Rgb(0x28, 0x28, 0x28)],
}),
},
ThemeDefinition {
id: "solarized-dark",
display_name: "Solarized Dark",
mode: ThemeMode::Dark,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0x00, 0x2b, 0x36),
text: Color::Rgb(0x83, 0x94, 0x96),
panel: Some(Color::Rgb(0x00, 0x22, 0x2b)),
muted: Some(Color::Rgb(0x83, 0x94, 0x96)),
active: None,
selection_background: Some(Color::Rgb(0x07, 0x36, 0x42)),
selection_text: Some(Color::Rgb(0x93, 0xa1, 0xa1)),
ansi: [Color::Rgb(0x00, 0x27, 0x31),
Color::Rgb(0xd0, 0x1b, 0x24),
Color::Rgb(0x72, 0x89, 0x05),
Color::Rgb(0xa5, 0x77, 0x05),
Color::Rgb(0x20, 0x75, 0xc7),
Color::Rgb(0xc6, 0x1b, 0x6e),
Color::Rgb(0x25, 0x91, 0x85),
Color::Rgb(0xe9, 0xe2, 0xcb),
Color::Rgb(0x00, 0x1e, 0x26),
Color::Rgb(0xbd, 0x36, 0x12),
Color::Rgb(0x46, 0x5a, 0x61),
Color::Rgb(0x52, 0x67, 0x6f),
Color::Rgb(0x70, 0x81, 0x83),
Color::Rgb(0x58, 0x56, 0xb9),
Color::Rgb(0x81, 0x90, 0x8f),
Color::Rgb(0xfc, 0xf4, 0xdc)],
}),
},
ThemeDefinition {
id: "solarized-light",
display_name: "Solarized Light",
mode: ThemeMode::Light,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0xfd, 0xf6, 0xe3),
text: Color::Rgb(0x65, 0x7b, 0x83),
panel: Some(Color::Rgb(0x93, 0xa1, 0xa1)),
muted: Some(Color::Rgb(0xfd, 0xf6, 0xe3)),
active: Some(Color::Rgb(0xcb, 0x4b, 0x16)),
selection_background: Some(Color::Rgb(0xee, 0xe8, 0xd5)),
selection_text: Some(Color::Rgb(0x58, 0x6e, 0x75)),
ansi: [Color::Rgb(0x07, 0x36, 0x42),
Color::Rgb(0xdc, 0x32, 0x2f),
Color::Rgb(0x85, 0x99, 0x00),
Color::Rgb(0xb5, 0x89, 0x00),
Color::Rgb(0x26, 0x8b, 0xd2),
Color::Rgb(0xd3, 0x36, 0x82),
Color::Rgb(0x2a, 0xa1, 0x98),
Color::Rgb(0xee, 0xe8, 0xd5),
Color::Rgb(0x93, 0xa1, 0xa1),
Color::Rgb(0xcb, 0x4b, 0x16),
Color::Rgb(0x58, 0x6e, 0x75),
Color::Rgb(0x65, 0x7b, 0x83),
Color::Rgb(0x83, 0x94, 0x96),
Color::Rgb(0x6c, 0x71, 0xc4),
Color::Rgb(0x93, 0xa1, 0xa1),
Color::Rgb(0xfd, 0xf6, 0xe3)],
}),
},
ThemeDefinition {
id: "tokyo-night",
display_name: "Tokyo Night",
mode: ThemeMode::Dark,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0x1a, 0x1b, 0x26),
text: Color::Rgb(0xc0, 0xca, 0xf5),
panel: Some(Color::Rgb(0x29, 0x2e, 0x42)),
muted: Some(Color::Rgb(0x54, 0x5c, 0x7e)),
active: Some(Color::Rgb(0x7a, 0xa2, 0xf7)),
selection_background: Some(Color::Rgb(0x28, 0x34, 0x57)),
selection_text: Some(Color::Rgb(0xc0, 0xca, 0xf5)),
ansi: [Color::Rgb(0x15, 0x16, 0x1e),
Color::Rgb(0xf7, 0x76, 0x8e),
Color::Rgb(0x9e, 0xce, 0x6a),
Color::Rgb(0xe0, 0xaf, 0x68),
Color::Rgb(0x7a, 0xa2, 0xf7),
Color::Rgb(0xbb, 0x9a, 0xf7),
Color::Rgb(0x7d, 0xcf, 0xff),
Color::Rgb(0xa9, 0xb1, 0xd6),
Color::Rgb(0x41, 0x48, 0x68),
Color::Rgb(0xff, 0x89, 0x9d),
Color::Rgb(0x9f, 0xe0, 0x44),
Color::Rgb(0xfa, 0xba, 0x4a),
Color::Rgb(0x8d, 0xb0, 0xff),
Color::Rgb(0xc7, 0xa9, 0xff),
Color::Rgb(0xa4, 0xda, 0xff),
Color::Rgb(0xc0, 0xca, 0xf5)],
}),
},
ThemeDefinition {
id: "tokyo-night-day",
display_name: "Tokyo Night Day",
mode: ThemeMode::Light,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0xe1, 0xe2, 0xe7),
text: Color::Rgb(0x37, 0x60, 0xbf),
panel: Some(Color::Rgb(0xc4, 0xc8, 0xda)),
muted: Some(Color::Rgb(0x89, 0x90, 0xb3)),
active: Some(Color::Rgb(0x2e, 0x7d, 0xe9)),
selection_background: Some(Color::Rgb(0xb7, 0xc1, 0xe3)),
selection_text: Some(Color::Rgb(0x37, 0x60, 0xbf)),
ansi: [Color::Rgb(0xb4, 0xb5, 0xb9),
Color::Rgb(0xf5, 0x2a, 0x65),
Color::Rgb(0x58, 0x75, 0x39),
Color::Rgb(0x8c, 0x6c, 0x3e),
Color::Rgb(0x2e, 0x7d, 0xe9),
Color::Rgb(0x98, 0x54, 0xf1),
Color::Rgb(0x00, 0x71, 0x97),
Color::Rgb(0x61, 0x72, 0xb0),
Color::Rgb(0xa1, 0xa6, 0xc5),
Color::Rgb(0xff, 0x47, 0x74),
Color::Rgb(0x5c, 0x85, 0x24),
Color::Rgb(0xa2, 0x76, 0x29),
Color::Rgb(0x35, 0x8a, 0xff),
Color::Rgb(0xa4, 0x63, 0xff),
Color::Rgb(0x00, 0x7e, 0xa8),
Color::Rgb(0x37, 0x60, 0xbf)],
}),
},
ThemeDefinition {
id: "one-half-dark",
display_name: "One Half Dark",
mode: ThemeMode::Dark,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0x28, 0x2c, 0x34),
text: Color::Rgb(0xdc, 0xdf, 0xe4),
panel: Some(Color::Rgb(0x20, 0x23, 0x2a)),
muted: Some(Color::Rgb(0xdc, 0xdf, 0xe4)),
active: Some(Color::Rgb(0x00, 0x87, 0xbd)),
selection_background: Some(Color::Rgb(0xff, 0xfa, 0xcd)),
selection_text: Some(Color::Rgb(0x00, 0x00, 0x00)),
ansi: [Color::Rgb(0x28, 0x2c, 0x34),
Color::Rgb(0xe0, 0x6c, 0x75),
Color::Rgb(0x98, 0xc3, 0x79),
Color::Rgb(0xe5, 0xc0, 0x7b),
Color::Rgb(0x61, 0xaf, 0xef),
Color::Rgb(0xc6, 0x78, 0xdd),
Color::Rgb(0x56, 0xb6, 0xc2),
Color::Rgb(0xdc, 0xdf, 0xe4),
Color::Rgb(0x5d, 0x67, 0x7a),
Color::Rgb(0xe0, 0x6c, 0x75),
Color::Rgb(0x98, 0xc3, 0x79),
Color::Rgb(0xe5, 0xc0, 0x7b),
Color::Rgb(0x61, 0xaf, 0xef),
Color::Rgb(0xc6, 0x78, 0xdd),
Color::Rgb(0x56, 0xb6, 0xc2),
Color::Rgb(0xdc, 0xdf, 0xe4)],
}),
},
ThemeDefinition {
id: "one-half-light",
display_name: "One Half Light",
mode: ThemeMode::Light,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0xfa, 0xfa, 0xfa),
text: Color::Rgb(0x38, 0x3a, 0x42),
panel: None,
muted: None,
active: Some(Color::Rgb(0xf0, 0xf0, 0xf0)),
selection_background: Some(Color::Rgb(0xbf, 0xce, 0xff)),
selection_text: Some(Color::Rgb(0x38, 0x3a, 0x42)),
ansi: [Color::Rgb(0x38, 0x3a, 0x42),
Color::Rgb(0xe4, 0x56, 0x49),
Color::Rgb(0x40, 0xa1, 0x4f),
Color::Rgb(0xc1, 0x84, 0x01),
Color::Rgb(0x01, 0x84, 0xbc),
Color::Rgb(0xa6, 0x26, 0xa4),
Color::Rgb(0x09, 0x97, 0xb3),
Color::Rgb(0xfa, 0xfa, 0xfa),
Color::Rgb(0x38, 0x3a, 0x42),
Color::Rgb(0xe4, 0x56, 0x49),
Color::Rgb(0x40, 0xa1, 0x4f),
Color::Rgb(0xc1, 0x84, 0x01),
Color::Rgb(0x01, 0x84, 0xbc),
Color::Rgb(0xa6, 0x26, 0xa4),
Color::Rgb(0x09, 0x97, 0xb3),
Color::Rgb(0xfa, 0xfa, 0xfa)],
}),
},
ThemeDefinition {
id: "rose-pine",
display_name: "Rosé Pine",
mode: ThemeMode::Dark,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0x19, 0x17, 0x24),
text: Color::Rgb(0xe0, 0xde, 0xf4),
panel: Some(Color::Rgb(0x19, 0x17, 0x24)),
muted: Some(Color::Rgb(0x6e, 0x6a, 0x86)),
active: Some(Color::Rgb(0xc4, 0xa7, 0xe7)),
selection_background: Some(Color::Rgb(0x40, 0x3d, 0x52)),
selection_text: Some(Color::Rgb(0xe0, 0xde, 0xf4)),
ansi: [Color::Rgb(0x26, 0x23, 0x3a),
Color::Rgb(0xeb, 0x6f, 0x92),
Color::Rgb(0x31, 0x74, 0x8f),
Color::Rgb(0xf6, 0xc1, 0x77),
Color::Rgb(0x9c, 0xcf, 0xd8),
Color::Rgb(0xc4, 0xa7, 0xe7),
Color::Rgb(0xeb, 0xbc, 0xba),
Color::Rgb(0xe0, 0xde, 0xf4),
Color::Rgb(0x6e, 0x6a, 0x86),
Color::Rgb(0xeb, 0x6f, 0x92),
Color::Rgb(0x31, 0x74, 0x8f),
Color::Rgb(0xf6, 0xc1, 0x77),
Color::Rgb(0x9c, 0xcf, 0xd8),
Color::Rgb(0xc4, 0xa7, 0xe7),
Color::Rgb(0xeb, 0xbc, 0xba),
Color::Rgb(0xe0, 0xde, 0xf4)],
}),
},
ThemeDefinition {
id: "rose-pine-dawn",
display_name: "Rosé Pine Dawn",
mode: ThemeMode::Light,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0xfa, 0xf4, 0xed),
text: Color::Rgb(0x57, 0x52, 0x79),
panel: Some(Color::Rgb(0xfa, 0xf4, 0xed)),
muted: Some(Color::Rgb(0x98, 0x93, 0xa5)),
active: Some(Color::Rgb(0x90, 0x7a, 0xa9)),
selection_background: Some(Color::Rgb(0xdf, 0xda, 0xd9)),
selection_text: Some(Color::Rgb(0x57, 0x52, 0x79)),
ansi: [Color::Rgb(0xf2, 0xe9, 0xe1),
Color::Rgb(0xb4, 0x63, 0x7a),
Color::Rgb(0x28, 0x69, 0x83),
Color::Rgb(0xea, 0x9d, 0x34),
Color::Rgb(0x56, 0x94, 0x9f),
Color::Rgb(0x90, 0x7a, 0xa9),
Color::Rgb(0xd7, 0x82, 0x7e),
Color::Rgb(0x57, 0x52, 0x79),
Color::Rgb(0x98, 0x93, 0xa5),
Color::Rgb(0xb4, 0x63, 0x7a),
Color::Rgb(0x28, 0x69, 0x83),
Color::Rgb(0xea, 0x9d, 0x34),
Color::Rgb(0x56, 0x94, 0x9f),
Color::Rgb(0x90, 0x7a, 0xa9),
Color::Rgb(0xd7, 0x82, 0x7e),
Color::Rgb(0x57, 0x52, 0x79)],
}),
},
ThemeDefinition {
id: "everforest-dark-medium",
display_name: "Everforest Dark Medium",
mode: ThemeMode::Dark,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0x2d, 0x35, 0x3b),
text: Color::Rgb(0xd3, 0xc6, 0xaa),
panel: Some(Color::Rgb(0x34, 0x3f, 0x44)),
muted: Some(Color::Rgb(0x9d, 0xa9, 0xa0)),
active: Some(Color::Rgb(0xa7, 0xc0, 0x80)),
selection_background: Some(Color::Rgb(0x50, 0x5a, 0x60)),
selection_text: Some(Color::Rgb(0x9d, 0xa9, 0xa0)),
ansi: [Color::Rgb(0x34, 0x3f, 0x44),
Color::Rgb(0xe6, 0x7e, 0x80),
Color::Rgb(0xa7, 0xc0, 0x80),
Color::Rgb(0xdb, 0xbc, 0x7f),
Color::Rgb(0x7f, 0xbb, 0xb3),
Color::Rgb(0xd6, 0x99, 0xb6),
Color::Rgb(0x83, 0xc0, 0x92),
Color::Rgb(0x85, 0x92, 0x89),
Color::Rgb(0x86, 0x8d, 0x80),
Color::Rgb(0xe6, 0x7e, 0x80),
Color::Rgb(0xa7, 0xc0, 0x80),
Color::Rgb(0xdb, 0xbc, 0x7f),
Color::Rgb(0x7f, 0xbb, 0xb3),
Color::Rgb(0xd6, 0x99, 0xb6),
Color::Rgb(0x83, 0xc0, 0x92),
Color::Rgb(0x9d, 0xa9, 0xa0)],
}),
},
ThemeDefinition {
id: "everforest-light-medium",
display_name: "Everforest Light Medium",
mode: ThemeMode::Light,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0xfd, 0xf6, 0xe3),
text: Color::Rgb(0x5c, 0x6a, 0x72),
panel: Some(Color::Rgb(0xfd, 0xf6, 0xe3)),
muted: Some(Color::Rgb(0x93, 0x9f, 0x91)),
active: Some(Color::Rgb(0x8d, 0xa1, 0x01)),
selection_background: Some(Color::Rgb(0xea, 0xed, 0xc8)),
selection_text: Some(Color::Rgb(0x82, 0x91, 0x81)),
ansi: [Color::Rgb(0x70, 0x80, 0x89),
Color::Rgb(0xf8, 0x55, 0x52),
Color::Rgb(0x8d, 0xa1, 0x01),
Color::Rgb(0xdf, 0xa0, 0x00),
Color::Rgb(0x3a, 0x94, 0xc5),
Color::Rgb(0xdf, 0x69, 0xba),
Color::Rgb(0x35, 0xa7, 0x7c),
Color::Rgb(0x93, 0x9f, 0x91),
Color::Rgb(0x82, 0x91, 0x81),
Color::Rgb(0xe6, 0x68, 0x68),
Color::Rgb(0x93, 0xb2, 0x59),
Color::Rgb(0xdf, 0xa0, 0x00),
Color::Rgb(0x3a, 0x94, 0xc5),
Color::Rgb(0xdf, 0x69, 0xba),
Color::Rgb(0x35, 0xa7, 0x7c),
Color::Rgb(0xa6, 0xb0, 0xa0)],
}),
},
ThemeDefinition {
id: "github-dark",
display_name: "GitHub Dark",
mode: ThemeMode::Dark,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0x0d, 0x11, 0x17),
text: Color::Rgb(0xc9, 0xd1, 0xd9),
panel: Some(Color::Rgb(0x01, 0x04, 0x09)),
muted: Some(Color::Rgb(0x8b, 0x94, 0x9e)),
active: None,
selection_background: Some(Color::Rgb(0x58, 0xa6, 0xff)),
selection_text: Some(Color::Rgb(0x0d, 0x11, 0x17)),
ansi: [Color::Rgb(0x48, 0x4f, 0x58),
Color::Rgb(0xff, 0x7b, 0x72),
Color::Rgb(0x3f, 0xb9, 0x50),
Color::Rgb(0xd2, 0x99, 0x22),
Color::Rgb(0x58, 0xa6, 0xff),
Color::Rgb(0xbc, 0x8c, 0xff),
Color::Rgb(0x39, 0xc5, 0xcf),
Color::Rgb(0xb1, 0xba, 0xc4),
Color::Rgb(0x6e, 0x76, 0x81),
Color::Rgb(0xff, 0xa1, 0x98),
Color::Rgb(0x56, 0xd3, 0x64),
Color::Rgb(0xe3, 0xb3, 0x41),
Color::Rgb(0x79, 0xc0, 0xff),
Color::Rgb(0xd2, 0xa8, 0xff),
Color::Rgb(0x56, 0xd4, 0xdd),
Color::Rgb(0xff, 0xff, 0xff)],
}),
},
ThemeDefinition {
id: "github-light",
display_name: "GitHub Light",
mode: ThemeMode::Light,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0xff, 0xff, 0xff),
text: Color::Rgb(0x24, 0x29, 0x2f),
panel: Some(Color::Rgb(0xf6, 0xf8, 0xfa)),
muted: Some(Color::Rgb(0x57, 0x60, 0x6a)),
active: None,
selection_background: Some(Color::Rgb(0x09, 0x69, 0xda)),
selection_text: Some(Color::Rgb(0xff, 0xff, 0xff)),
ansi: [Color::Rgb(0x24, 0x29, 0x2f),
Color::Rgb(0xcf, 0x22, 0x2e),
Color::Rgb(0x11, 0x63, 0x29),
Color::Rgb(0x4d, 0x2d, 0x00),
Color::Rgb(0x09, 0x69, 0xda),
Color::Rgb(0x82, 0x50, 0xdf),
Color::Rgb(0x1b, 0x7c, 0x83),
Color::Rgb(0x6e, 0x77, 0x81),
Color::Rgb(0x57, 0x60, 0x6a),
Color::Rgb(0xa4, 0x0e, 0x26),
Color::Rgb(0x1a, 0x7f, 0x37),
Color::Rgb(0x63, 0x3c, 0x01),
Color::Rgb(0x21, 0x8b, 0xff),
Color::Rgb(0xa4, 0x75, 0xf9),
Color::Rgb(0x31, 0x92, 0xaa),
Color::Rgb(0x8c, 0x95, 0x9f)],
}),
},
ThemeDefinition {
id: "flexoki-dark",
display_name: "Flexoki Dark",
mode: ThemeMode::Dark,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0x10, 0x0f, 0x0f),
text: Color::Rgb(0xff, 0xfc, 0xf0),
panel: Some(Color::Rgb(0x28, 0x27, 0x26)),
muted: Some(Color::Rgb(0x87, 0x85, 0x80)),
active: Some(Color::Rgb(0xaf, 0x30, 0x29)),
selection_background: Some(Color::Rgb(0x40, 0x3e, 0x3c)),
selection_text: Some(Color::Rgb(0xff, 0xfc, 0xf0)),
ansi: [Color::Rgb(0x10, 0x0f, 0x0f),
Color::Rgb(0xaf, 0x30, 0x29),
Color::Rgb(0x66, 0x80, 0x0b),
Color::Rgb(0xad, 0x83, 0x01),
Color::Rgb(0x20, 0x5e, 0xa6),
Color::Rgb(0xa0, 0x2f, 0x6f),
Color::Rgb(0x24, 0x83, 0x7b),
Color::Rgb(0xf2, 0xf0, 0xe5),
Color::Rgb(0x6f, 0x6e, 0x69),
Color::Rgb(0xd1, 0x4d, 0x41),
Color::Rgb(0x87, 0x9a, 0x39),
Color::Rgb(0xd0, 0xa2, 0x15),
Color::Rgb(0x43, 0x85, 0xbe),
Color::Rgb(0xce, 0x5d, 0x97),
Color::Rgb(0x3a, 0xa9, 0x9f),
Color::Rgb(0xff, 0xfc, 0xf0)],
}),
},
ThemeDefinition {
id: "flexoki-light",
display_name: "Flexoki Light",
mode: ThemeMode::Light,
origin: ThemeOrigin::Kitty,
native_palette: None,
seed: Some(ThemeSeed {
background: Color::Rgb(0xff, 0xfc, 0xf0),
text: Color::Rgb(0x10, 0x0f, 0x0f),
panel: Some(Color::Rgb(0xe6, 0xe4, 0xd9)),
muted: Some(Color::Rgb(0x6f, 0x6e, 0x69)),
active: Some(Color::Rgb(0xd1, 0x4d, 0x41)),
selection_background: Some(Color::Rgb(0xce, 0xcd, 0xc3)),
selection_text: Some(Color::Rgb(0x10, 0x0f, 0x0f)),
ansi: [Color::Rgb(0x10, 0x0f, 0x0f),
Color::Rgb(0xd1, 0x4d, 0x41),
Color::Rgb(0x87, 0x9a, 0x39),
Color::Rgb(0xd0, 0xa2, 0x15),
Color::Rgb(0x43, 0x85, 0xbe),
Color::Rgb(0xce, 0x5d, 0x97),
Color::Rgb(0x3a, 0xa9, 0x9f),
Color::Rgb(0xff, 0xfc, 0xf0),
Color::Rgb(0x6f, 0x6e, 0x69),
Color::Rgb(0xaf, 0x30, 0x29),
Color::Rgb(0x66, 0x80, 0x0b),
Color::Rgb(0xad, 0x83, 0x01),
Color::Rgb(0x20, 0x5e, 0xa6),
Color::Rgb(0xa0, 0x2f, 0x6f),
Color::Rgb(0x24, 0x83, 0x7b),
Color::Rgb(0xf2, 0xf0, 0xe5)],
}),
},
]

View file

@ -15,10 +15,18 @@ fn one_listing(effects: Vec<Effect>) -> ListingRequest {
fn one_preview(effects: Vec<Effect>) -> PreviewRequest {
let effects: [Effect; 1] = effects.try_into().expect("one preview effect");
let [Effect::LoadPreview(request)] = effects else {
let mut effects = effects.into_iter();
let Some(effect) = effects.next() else {
panic!("expected exactly one preview effect");
};
request
assert!(
effects.next().is_none(),
"expected exactly one preview effect"
);
match effect {
Effect::LoadPreview(request) | Effect::DebouncePreview(request) => request,
_ => panic!("expected a preview effect"),
}
}
async fn finish_listing(fs: &MemoryFs, app: &mut AppState, request: ListingRequest) -> Vec<Effect> {

View file

@ -19,10 +19,18 @@ fn one_listing(effects: Vec<Effect>) -> ListingRequest {
fn one_preview(effects: Vec<Effect>) -> PreviewRequest {
let effects: [Effect; 1] = effects.try_into().expect("one preview effect");
let [Effect::LoadPreview(request)] = effects else {
let mut effects = effects.into_iter();
let Some(effect) = effects.next() else {
panic!("expected exactly one preview effect");
};
request
assert!(
effects.next().is_none(),
"expected exactly one preview effect"
);
match effect {
Effect::LoadPreview(request) | Effect::DebouncePreview(request) => request,
_ => panic!("expected a preview effect"),
}
}
fn poll_preview(app: &mut AppState, entries: Vec<Entry>) -> PreviewRequest {
@ -36,6 +44,7 @@ fn request(target: Location) -> PreviewRequest {
generation: 7,
target,
session_epoch: None,
images_enabled: true,
}
}
@ -159,9 +168,14 @@ fn background_preview_requires_a_completed_result_for_the_same_target() {
// A poll cannot hide an initial request which has not produced content or an error yet.
let poll = one_listing(app.reduce(Command::RefreshPane(PaneId::Left)));
let pending = one_preview(app.reduce(Command::ListingFinished(
let duplicate = app.reduce(Command::ListingFinished(
poll.into_result(Ok(entries.clone())),
)));
));
assert!(
duplicate.is_empty(),
"an in-flight initial preview is not duplicated"
);
let pending = initial_preview.clone();
assert!(!app.active_pane().preview.background_refresh);
app.reduce(Command::PreviewFinished(
pending.into_result(Ok(preview_bytes(b"completed", false))),

147
tests/appearance_config.rs Normal file
View file

@ -0,0 +1,147 @@
use clap::Parser;
use rcom::cli::Cli;
use rcom::config::{config_path_at, load_from_path};
use rcom::ui::{IconMode, ThemeId};
use tempfile::TempDir;
#[test]
fn missing_config_uses_unicode_and_cli_overrides_without_a_write() {
let fixture = TempDir::new().unwrap();
let path = config_path_at(fixture.path());
let config = load_from_path(&path).unwrap();
assert_eq!(config.icons, IconMode::Unicode);
assert_eq!(config.selected_icon_mode(None), IconMode::Unicode);
assert_eq!(config.theme, ThemeId::NightOps);
assert!(config.images);
assert!(config.images_enabled(false));
assert!(!config.images_enabled(true));
assert_eq!(
config.selected_theme(Some(ThemeId::Dracula)),
ThemeId::Dracula
);
assert_eq!(
config.selected_icon_mode(Some(IconMode::Nerd)),
IconMode::Nerd
);
assert!(
Cli::try_parse_from(["rcom", "--no-images"])
.unwrap()
.no_images
);
assert!(!path.exists());
}
#[test]
fn every_documented_mode_is_parsed_and_unknown_fields_are_forward_compatible() {
let fixture = TempDir::new().unwrap();
let path = config_path_at(fixture.path());
for (source, expected) in [
("icons = \"unicode\"", IconMode::Unicode),
("icons = \"nerd\"", IconMode::Nerd),
("icons = \"ascii\"", IconMode::Ascii),
("icons = \"none\"", IconMode::None),
] {
std::fs::write(&path, source).unwrap();
assert_eq!(load_from_path(&path).unwrap().icons, expected);
}
std::fs::write(
&path,
"icons = \"ascii\"\ntheme = \"gruvbox-light\"\nfuture_setting = true",
)
.unwrap();
let config = load_from_path(&path).unwrap();
assert_eq!(config.icons, IconMode::Ascii);
assert_eq!(config.theme, ThemeId::GruvboxLight);
assert_eq!(
config.selected_icon_mode(Some(IconMode::Nerd)),
IconMode::Nerd
);
assert_eq!(
config.selected_theme(Some(ThemeId::Dracula)),
ThemeId::Dracula
);
std::fs::write(&path, "images = false\n").unwrap();
assert!(!load_from_path(&path).unwrap().images_enabled(false));
}
#[test]
fn malformed_toml_and_unknown_icon_mode_have_contextual_errors() {
let fixture = TempDir::new().unwrap();
let path = config_path_at(fixture.path());
for source in ["icons = [", "icons = \"private-use-maybe\""] {
std::fs::write(&path, source).unwrap();
let error = load_from_path(&path).unwrap_err().to_string();
assert!(error.contains("config"), "{error}");
assert!(error.contains("config.toml"), "{error}");
}
}
#[test]
fn cli_accepts_exactly_the_four_documented_icon_values() {
for value in ["unicode", "nerd", "ascii", "none"] {
let cli = Cli::try_parse_from(["rcom", "--icons", value]).unwrap();
assert_eq!(
cli.icons
.map(|mode| format!("{mode:?}").to_ascii_lowercase()),
Some(value.into())
);
}
assert!(Cli::try_parse_from(["rcom", "--icons", "auto"]).is_err());
for id in ThemeId::ALL {
let cli = Cli::try_parse_from(["rcom", "--theme", id.as_str()]).unwrap();
assert_eq!(cli.theme, Some(id));
}
assert!(Cli::try_parse_from(["rcom", "--theme", "unknown"]).is_err());
}
#[test]
fn list_themes_is_offline_and_unknown_config_lists_ids_before_terminal_setup() {
let fixture = TempDir::new().unwrap();
std::fs::write(config_path_at(fixture.path()), "theme = \"not-a-theme\"").unwrap();
let listed = std::process::Command::new(env!("CARGO_BIN_EXE_rcom"))
.env("RCOM_CONFIG_HOME", fixture.path())
.arg("--list-themes")
.output()
.unwrap();
assert!(listed.status.success());
let stdout = String::from_utf8(listed.stdout).unwrap();
assert_eq!(stdout.lines().count(), 20);
assert!(stdout.contains("night-ops\tNight Ops\tdark"));
assert!(
!stdout
.as_bytes()
.windows(8)
.any(|window| window == b"\x1b[?1049h")
);
let output = std::process::Command::new(env!("CARGO_BIN_EXE_rcom"))
.env("RCOM_CONFIG_HOME", fixture.path())
.output()
.unwrap();
assert!(!output.status.success());
let error = String::from_utf8_lossy(&output.stderr);
assert!(error.contains("available themes"), "{error}");
assert!(error.contains("night-ops"), "{error}");
assert!(
!error
.as_bytes()
.windows(8)
.any(|window| window == b"\x1b[?1049h")
);
assert_eq!(std::fs::read_dir(fixture.path()).unwrap().count(), 1);
}
#[test]
fn config_parse_error_happens_before_alternate_screen_or_host_access() {
let fixture = TempDir::new().unwrap();
std::fs::write(config_path_at(fixture.path()), "icons = \"unknown\"").unwrap();
let output = std::process::Command::new(env!("CARGO_BIN_EXE_rcom"))
.env("RCOM_CONFIG_HOME", fixture.path())
.output()
.unwrap();
assert!(!output.status.success());
let combined = [output.stdout, output.stderr].concat();
assert!(String::from_utf8_lossy(&combined).contains("Cannot parse config"));
assert!(!combined.windows(8).any(|window| window == b"\x1b[?1049h"));
assert_eq!(std::fs::read_dir(fixture.path()).unwrap().count(), 1);
}

View file

@ -217,9 +217,9 @@ fn snapshot_create_file_prompt_no_color_100x24() {
app.reduce(Command::EntryInput(character));
}
insta::assert_snapshot!(draw(&app, 100, 24), @r#"
RCOM dual-pane file manager SINGLE
╭▸ ACTIVE · LOCAL · /work───────────────────╮╭PREVIEW · old\nname──────────────────────────────────╮
│ TYPE NAME SIZE││NO PREVIEW │
RCOM dual-pane file manager SINGLE ? Help
╭▸ ACTIVE · LOCAL · /work───────────────────╮╭PREVIEW · 📄 old\nname───────────────────────────────╮
│ NAME SIZE││NO PREVIEW │
│▸╭CREATE FILE───────────────────────────────────────────────────────────────────────────────────╮ │
│ │Type: regular file │ │
│ │Location: local:/work │ │
@ -238,9 +238,9 @@ fn snapshot_create_file_prompt_no_color_100x24() {
│ │ │ │
│ │ │ │
│ ╰──────────────────────────────────────────────────────────────────────────────────────────────╯ │
│ ││ │
╰───────────────────────────────────────────╯╰─────────────────────────────────────────────────────╯
2 entries · Selected 1/2 · Dotfiles hidden
Space Select · y/x/p Yank/Cut/Paste · F5/F6 Copy/Move · t Tasks · ? Help · q Quit
"#);
}

View file

@ -0,0 +1,307 @@
use pretty_assertions::assert_eq;
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use ratatui::buffer::Buffer;
use ratatui::style::Color;
use rcom::app::{AppState, PaneId, PaneMode};
use rcom::domain::{Entry, EntryKind, Location};
use rcom::ui::{IconMode, Theme, render};
use unicode_width::UnicodeWidthStr;
fn draw(app: &AppState, width: u16, height: u16, theme: &Theme) -> Buffer {
let backend = TestBackend::new(width, height);
let mut terminal = Terminal::new(backend).unwrap();
terminal
.draw(|frame| render(frame, app, None, theme))
.unwrap();
terminal.backend().buffer().clone()
}
fn canonical_app() -> AppState {
let mut app = AppState::new(Location::local("/work"));
app.active_pane_mut().entries = vec![
Entry::new("docs", EntryKind::Directory),
Entry::new("Cargo.toml", EntryKind::File),
Entry::new("main.rs", EntryKind::File),
Entry::new("run", EntryKind::File).with_metadata(None, None, Some(0o755)),
Entry::new("latest", EntryKind::Symlink).with_link_target("main.rs".into()),
Entry::new(".config", EntryKind::Directory),
];
app.active_pane_mut().selection.set(Some(1), 6);
app.active_pane_mut()
.selection_set
.insert(Location::local("/work").entry_id("Cargo.toml"));
app
}
fn buffer_text(buffer: &Buffer) -> String {
(0..buffer.area.height)
.map(|y| {
(0..buffer.area.width)
.map(|x| buffer.cell((x, y)).unwrap().symbol())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n")
}
fn find_cell(buffer: &Buffer, symbol: &str) -> (u16, u16) {
(0..buffer.area.height)
.flat_map(|y| (0..buffer.area.width).map(move |x| (x, y)))
.find(|&(x, y)| y >= 2 && buffer.cell((x, y)).unwrap().symbol() == symbol)
.unwrap_or_else(|| panic!("missing {symbol}:\n{}", buffer_text(buffer)))
}
fn text_position(buffer: &Buffer, needle: &str) -> (u16, u16) {
(0..buffer.area.height)
.filter(|y| *y >= 2)
.find_map(|y| {
let row = (0..buffer.area.width)
.map(|x| buffer.cell((x, y)).unwrap().symbol())
.collect::<String>();
row.find(needle)
.map(|byte| (UnicodeWidthStr::width(&row[..byte]) as u16, y))
})
.unwrap_or_else(|| panic!("missing {needle}:\n{}", buffer_text(buffer)))
}
#[test]
fn canonical_night_ops_fixture_separates_icons_names_and_selected_marked_state() {
let app = canonical_app();
let before = app.clone();
let buffer = draw(&app, 140, 30, &Theme::night_ops());
assert_eq!(app, before, "render must stay read-only");
let text = buffer_text(&buffer);
for expected in [
"NAME",
"Cargo.toml",
"main.rs",
"run*",
"latest@",
"⚙",
".config",
"▸*",
] {
assert!(text.contains(expected), "missing {expected}:\n{text}");
}
let rust = find_cell(&buffer, "🦀");
assert_eq!(
buffer.cell(rust).unwrap().style().fg,
Some(Color::Rgb(0xde, 0xa5, 0x84))
);
let rust_name = (rust.0 + 1..buffer.area.width)
.map(|x| (x, rust.1))
.find(|&position| buffer.cell(position).unwrap().symbol() == "m")
.unwrap();
assert_eq!(
buffer.cell(rust_name).unwrap().style().fg,
Some(Color::Rgb(0xd8, 0xe0, 0xf0))
);
let selected_icon = find_cell(&buffer, "📦");
let style = buffer.cell(selected_icon).unwrap().style();
assert_eq!(style.bg, Some(Color::Rgb(0x62, 0x6e, 0x80)));
assert_eq!(style.fg, Some(Color::Rgb(0xff, 0xff, 0xff)));
let directory = find_cell(&buffer, "📚");
assert_eq!(
buffer.cell(directory).unwrap().style().fg,
Some(Color::Rgb(0x82, 0xaa, 0xff))
);
assert!(buffer.content().iter().any(|cell| {
cell.symbol() == "🚀" && cell.style().fg == Some(Color::Rgb(0x9e, 0xce, 0x6a))
}));
let symlink = find_cell(&buffer, "🔗");
assert_eq!(
buffer.cell(symlink).unwrap().style().fg,
Some(Color::Rgb(0x65, 0xd6, 0xe8))
);
}
#[test]
fn preview_title_uses_the_selected_icon_and_also_works_in_icons_off() {
let app = canonical_app();
let rich = draw(&app, 140, 30, &Theme::night_ops());
let title = (0..rich.area.width)
.map(|x| rich.cell((x, 1)).unwrap().symbol())
.collect::<String>();
assert!(title.contains("PREVIEW"));
assert!(title.contains("📦"));
assert!(title.contains("Cargo.toml"));
let plain = draw(
&app,
140,
30,
&Theme::no_color().with_icon_mode(IconMode::None),
);
let title = (0..plain.area.width)
.map(|x| plain.cell((x, 1)).unwrap().symbol())
.collect::<String>();
assert!(title.contains("PREVIEW"));
assert!(!title.contains("📦"));
assert!(title.contains("Cargo.toml"));
}
#[test]
fn all_icon_modes_preserve_selection_and_fallbacks_without_redundant_type_text() {
for mode in [
IconMode::Unicode,
IconMode::Nerd,
IconMode::Ascii,
IconMode::None,
] {
for colors in [true, false] {
let theme = Theme::with_capabilities(colors, false).with_icon_mode(mode);
let buffer = draw(&canonical_app(), 120, 24, &theme);
let text = buffer_text(&buffer);
if mode == IconMode::None {
assert!(text.contains("DIR"));
assert!(text.contains("FILE"));
assert!(text.contains("LINK"));
} else {
assert!(!text.contains("TYPE"));
assert!(!text.contains("DIR"));
assert!(!text.contains("FILE"));
}
assert!(text.contains("▸*"));
if !colors {
assert!(
buffer
.content()
.iter()
.all(|cell| { cell.style().fg.is_none_or(|color| color == Color::Reset) })
);
}
if mode == IconMode::Nerd {
assert!(text.contains('\u{e7a8}'));
} else {
assert!(
!text
.chars()
.any(|character| ('\u{e000}'..='\u{f8ff}').contains(&character))
);
}
}
}
let disabled = Theme::ascii().with_icon_mode(IconMode::None);
let text = buffer_text(&draw(&canonical_app(), 80, 24, &disabled));
assert!(!text.contains("🦀"));
assert!(text.contains("DIR"));
}
#[test]
fn copy_cut_and_executable_markers_survive_every_icon_mode() {
for mode in [
IconMode::Unicode,
IconMode::Nerd,
IconMode::Ascii,
IconMode::None,
] {
let theme = Theme::with_capabilities(false, false).with_icon_mode(mode);
let mut copied = canonical_app();
copied.reduce(rcom::app::Command::Yank);
let copied_text = buffer_text(&draw(&copied, 120, 24, &theme));
assert!(
copied_text.contains("▸±"),
"copy marker missing:\n{copied_text}"
);
assert!(copied_text.contains("run*"), "executable badge missing");
let mut cut = canonical_app();
cut.reduce(rcom::app::Command::Cut);
let cut_text = buffer_text(&draw(&cut, 120, 24, &theme));
assert!(cut_text.contains("▸∓"), "cut marker missing:\n{cut_text}");
assert_ne!(copied_text, cut_text);
copied.active_pane_mut().entries[2].permissions = Some(0o755);
let executable = buffer_text(&draw(&copied, 120, 24, &theme));
assert!(
executable.contains("main.rs*"),
"known-type executable lost its badge"
);
}
let mut copied = canonical_app();
copied.reduce(rcom::app::Command::Yank);
let copied_text = buffer_text(&draw(&copied, 120, 24, &Theme::ascii()));
assert!(copied_text.contains(">C"), "{copied_text}");
assert!(!copied_text.contains('±'));
let mut cut = canonical_app();
cut.reduce(rcom::app::Command::Cut);
let cut_text = buffer_text(&draw(&cut, 120, 24, &Theme::ascii()));
assert!(cut_text.contains(">X"), "{cut_text}");
assert!(!cut_text.contains('∓'));
}
#[test]
fn filename_extension_survives_icon_aware_truncation() {
let mut app = AppState::new(Location::local("/work"));
app.active_pane_mut().entries = vec![Entry::new(
"デ ー タ ー -αβγ-очень-длинное-имя.rs",
EntryKind::File,
)];
app.active_pane_mut().selection.set(Some(0), 1);
for mode in [IconMode::Unicode, IconMode::Ascii, IconMode::None] {
for (width, height) in [(40, 8), (80, 24), (120, 40), (160, 40)] {
let text = buffer_text(&draw(
&app,
width,
height,
&Theme::night_ops().with_icon_mode(mode),
));
assert!(
text.contains(".rs"),
"{mode:?} at {width}x{height}:\n{text}"
);
}
}
}
#[test]
fn icon_width_does_not_change_breakpoints_or_overflow_supported_frames() {
for mode in [
IconMode::Unicode,
IconMode::Nerd,
IconMode::Ascii,
IconMode::None,
] {
for (width, height) in [(40, 8), (80, 24), (120, 40), (160, 40)] {
let buffer = draw(
&canonical_app(),
width,
height,
&Theme::night_ops().with_icon_mode(mode),
);
let cargo = text_position(&buffer, "Cargo.toml");
let rust = text_position(&buffer, "main.rs");
assert_eq!(cargo.0, rust.0, "name columns diverged at {width}x{height}");
let text = buffer_text(&buffer);
assert!(text.contains("docs/"));
if width == 40 {
assert!(!text.contains("MODIFIED"));
} else {
assert!(text.contains("MODIFIED"));
}
}
for width in [71, 72] {
let mut app = canonical_app();
app.mode = PaneMode::Dual;
app.panes[1] = app.panes[0].clone();
let text = buffer_text(&draw(
&app,
width,
24,
&Theme::night_ops().with_icon_mode(mode),
));
if width == 71 {
assert!(text.contains("PANE 1/2"));
} else {
assert!(text.contains("PANE 2/2"));
}
assert_eq!(app.active, PaneId::Left);
}
}
}

267
tests/help_inventory.rs Normal file
View file

@ -0,0 +1,267 @@
use std::collections::BTreeMap;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use pretty_assertions::assert_eq;
use rcom::app::{
CollisionChoice, Command, HELP_INVENTORY, HelpContext, HelpViewport, QuitDecision,
};
use rcom::input::{InputOutcome, InputState};
// This fixture intentionally does not derive data from the renderer or input dispatcher. Adding a
// handler or changing its public aliases requires a conscious update of this independent contract.
const WORKSPACE: &[(&str, &str)] = &[
("workspace-next-entry", "j / Down"),
("workspace-previous-entry", "k / Up"),
("workspace-parent", "h / Left"),
("workspace-open-directory", "l / Right / Enter"),
("workspace-first-entry", "gg / Home"),
("workspace-last-entry", "G / End"),
("workspace-page-up", "PageUp / Ctrl-b"),
("workspace-page-down", "PageDown / Ctrl-f"),
("workspace-half-page-up", "Ctrl-u"),
("workspace-half-page-down", "Ctrl-d"),
("workspace-local-home", "~"),
("workspace-toggle-selection", "Space / Insert"),
("workspace-visual-selection", "v"),
("workspace-select-all", "Ctrl-a"),
("workspace-invert-selection", "I"),
("workspace-clear-selection", "U"),
("workspace-yank", "y"),
("workspace-cut", "x"),
("workspace-paste", "p"),
("workspace-copy", "F5"),
("workspace-move", "F6"),
("workspace-create-file", "a"),
("workspace-create-directory", "A / F7"),
("workspace-rename", "r / F2"),
("workspace-trash", "d"),
("workspace-permanent-delete", "D / F8"),
("workspace-undo", "u / Ctrl-z"),
("workspace-edit", "e / F4"),
("workspace-open-tasks", "t"),
("workspace-open-host-picker", "s"),
("workspace-switch-pane", "Tab / Shift-Tab"),
("workspace-toggle-pane-mode", "\\"),
("workspace-toggle-hidden", "."),
("workspace-refresh", "Ctrl-r"),
("workspace-open-preview", "F3"),
("workspace-exit-visual", "Esc"),
("workspace-error-details", "m"),
("workspace-open-theme-picker", "T"),
("workspace-open-help", "? / F1"),
("workspace-quit", "q"),
];
const HOST_PICKER: &[(&str, &str)] = &[
("host-picker-input", "Printable"),
("host-picker-backspace", "Backspace"),
("host-picker-select", "Up / Down"),
("host-picker-connect", "Enter"),
("host-picker-close", "Esc"),
];
const THEME_PICKER: &[(&str, &str)] = &[
("theme-next", "j / Down"),
("theme-previous", "k / Up"),
("theme-save", "Enter"),
("theme-cancel", "Esc"),
];
const TASKS: &[(&str, &str)] = &[
("tasks-next", "j / Down"),
("tasks-previous", "k / Up"),
("tasks-page-up", "PageUp / Ctrl-b"),
("tasks-page-down", "PageDown / Ctrl-f"),
("tasks-half-page-up", "Ctrl-u"),
("tasks-half-page-down", "Ctrl-d"),
("tasks-open-details", "m / Enter"),
("tasks-cancel", "c"),
("tasks-close", "Esc / q / t"),
];
const TASK_DETAILS: &[(&str, &str)] = &[
("details-line-down", "j / Down"),
("details-line-up", "k / Up"),
("details-page-up", "PageUp / Ctrl-b"),
("details-page-down", "PageDown / Ctrl-f"),
("details-half-page-up", "Ctrl-u"),
("details-half-page-down", "Ctrl-d"),
("details-cancel", "c"),
("details-close", "m / Enter / Esc / q / t"),
];
const PREVIEW: &[(&str, &str)] = &[("preview-close", "F3 / Esc / q")];
const HELP: &[(&str, &str)] = &[
("help-previous-category", "h / Left / Shift-Tab"),
("help-next-category", "l / Right / Tab"),
("help-line-down", "j / Down"),
("help-line-up", "k / Up"),
("help-page-up", "PageUp / Ctrl-b"),
("help-page-down", "PageDown / Ctrl-f"),
("help-half-page-up", "Ctrl-u"),
("help-half-page-down", "Ctrl-d"),
("help-close", "Esc / q / ? / F1"),
("help-enter-inert", "Enter"),
];
const DESTINATION: &[(&str, &str)] = &[
("destination-input", "Printable"),
("destination-backspace", "Backspace"),
("destination-submit", "Enter"),
("destination-cancel", "Esc"),
];
const CONFIRMATION: &[(&str, &str)] = &[
("operation-confirm", "Enter"),
("operation-cancel", "Esc / q"),
];
const COLLISION: &[(&str, &str)] = &[
("collision-next", "j / Down"),
("collision-previous", "k / Up"),
("collision-skip", "s / S"),
("collision-overwrite", "o / O"),
("collision-cancel", "Esc / Enter / q"),
];
const ENTRY_PROMPT: &[(&str, &str)] = &[
("entry-input", "Printable"),
("entry-backspace", "Backspace"),
("entry-submit", "Enter"),
("entry-cancel", "Esc"),
];
const ENTRY_CONFIRMATION: &[(&str, &str)] = &[
("entry-confirm", "Enter"),
("entry-confirmation-cancel", "Esc / q"),
];
const UNDO: &[(&str, &str)] = &[
("undo-confirm", "Enter"),
("undo-cancel", "Esc / q"),
("undo-dismiss-empty", "Enter"),
];
const EDITOR: &[(&str, &str)] = &[
("editor-confirm-upload", "Enter"),
("editor-cancel", "Esc / q"),
("editor-dismiss-notice", "Enter"),
];
const ERROR_DETAILS: &[(&str, &str)] = &[
("message-line-down", "j / Down"),
("message-line-up", "k / Up"),
("message-page-up", "PageUp / Ctrl-b"),
("message-page-down", "PageDown / Ctrl-f"),
("message-half-page-up", "Ctrl-u"),
("message-half-page-down", "Ctrl-d"),
("message-close", "Esc / q"),
];
const QUIT_CONFIRMATION: &[(&str, &str)] = &[
("quit-stay", "Esc / Enter"),
("quit-cancel-and-wait", "c"),
("quit-exit-with-warning", "x"),
];
const GLOBAL: &[(&str, &str)] = &[("global-quit", "F10")];
#[test]
fn independently_enumerated_input_contexts_match_every_inventory_action_and_alias() {
let expected = [
(HelpContext::Workspace, WORKSPACE),
(HelpContext::HostPicker, HOST_PICKER),
(HelpContext::ThemePicker, THEME_PICKER),
(HelpContext::Tasks, TASKS),
(HelpContext::TaskDetails, TASK_DETAILS),
(HelpContext::Preview, PREVIEW),
(HelpContext::Help, HELP),
(HelpContext::DestinationPrompt, DESTINATION),
(HelpContext::Confirmation, CONFIRMATION),
(HelpContext::Collision, COLLISION),
(HelpContext::EntryPrompt, ENTRY_PROMPT),
(HelpContext::EntryConfirmation, ENTRY_CONFIRMATION),
(HelpContext::Undo, UNDO),
(HelpContext::Editor, EDITOR),
(HelpContext::ErrorDetails, ERROR_DETAILS),
(HelpContext::QuitConfirmation, QUIT_CONFIRMATION),
(HelpContext::Global, GLOBAL),
];
let mut actual = BTreeMap::new();
for entry in HELP_INVENTORY {
actual
.entry(entry.context.label())
.or_insert_with(Vec::new)
.push((entry.id, entry.aliases));
}
let expected = expected
.into_iter()
.map(|(context, entries)| {
let mut entries = entries.to_vec();
entries.sort_unstable();
(context.label(), entries)
})
.collect::<BTreeMap<_, _>>();
for bindings in actual.values_mut() {
bindings.sort_unstable();
}
assert_eq!(actual, expected);
assert_eq!(
HELP_INVENTORY.len(),
WORKSPACE.len()
+ HOST_PICKER.len()
+ THEME_PICKER.len()
+ TASKS.len()
+ TASK_DETAILS.len()
+ PREVIEW.len()
+ HELP.len()
+ DESTINATION.len()
+ CONFIRMATION.len()
+ COLLISION.len()
+ ENTRY_PROMPT.len()
+ ENTRY_CONFIRMATION.len()
+ UNDO.len()
+ EDITOR.len()
+ ERROR_DETAILS.len()
+ QUIT_CONFIRMATION.len()
+ GLOBAL.len()
);
}
#[test]
fn context_specific_bindings_execute_only_their_documented_handler() {
let press = |code| KeyEvent::new(code, KeyModifiers::NONE);
let shifted = |character| KeyEvent::new(KeyCode::Char(character), KeyModifiers::SHIFT);
assert_eq!(
InputState::new().handle_key(press(KeyCode::Char('T')), 10),
InputOutcome::Command(Command::OpenThemePicker)
);
assert_eq!(
InputState::new().handle_confirmation_key(press(KeyCode::Enter)),
InputOutcome::Command(Command::ConfirmOperation)
);
assert_eq!(
InputState::new().handle_entry_confirmation_key(press(KeyCode::Enter)),
InputOutcome::Command(Command::ConfirmEntryAction)
);
for (key, choice, apply_to_all) in [
(press(KeyCode::Char('s')), CollisionChoice::Skip, false),
(shifted('S'), CollisionChoice::Skip, true),
(press(KeyCode::Char('o')), CollisionChoice::Overwrite, false),
(shifted('O'), CollisionChoice::Overwrite, true),
] {
assert_eq!(
InputState::new().handle_collision_key(key),
InputOutcome::Command(Command::ResolveCollision {
choice,
apply_to_all,
})
);
}
for (key, decision) in [
(press(KeyCode::Enter), QuitDecision::Stay),
(press(KeyCode::Esc), QuitDecision::Stay),
(press(KeyCode::Char('c')), QuitDecision::CancelAndWait),
(press(KeyCode::Char('x')), QuitDecision::ExitWithWarning),
] {
assert_eq!(
InputState::new().handle_quit_key(key),
InputOutcome::Command(Command::DecideQuit(decision))
);
}
assert_eq!(
InputState::new().handle_help_key(
press(KeyCode::Enter),
HelpViewport {
page_size: 4,
max_scroll: 10,
},
),
InputOutcome::Ignored
);
}

186
tests/icon_resolver.rs Normal file
View file

@ -0,0 +1,186 @@
use proptest::prelude::*;
use rcom::domain::{Entry, EntryKind};
use rcom::ui::{FileClass, IconMode, IconResolver};
fn entry(name: &str, kind: EntryKind) -> Entry {
Entry::new(name, kind)
}
#[test]
fn resolver_distinguishes_known_types_without_any_io() {
let resolver = IconResolver::new(IconMode::Nerd);
let cases = [
(
"directory",
entry("docs", EntryKind::Directory),
"directory-docs",
FileClass::Directory,
),
(
"configuration directory",
entry(".config", EntryKind::Directory),
"directory-config",
FileClass::Directory,
),
(
"directory with file extension",
entry("docs.rs", EntryKind::Directory),
"directory",
FileClass::Directory,
),
(
"glob explicitly overrides directory fallback",
entry("README.md", EntryKind::Directory),
"readme",
FileClass::Directory,
),
(
"exact project file",
entry("Cargo.toml", EntryKind::File),
"cargo",
FileClass::Regular,
),
(
"case-sensitive exact name uses extension",
entry("CARGO.TOML", EntryKind::File),
"config",
FileClass::Regular,
),
(
"case-insensitive glob",
entry("readme.md", EntryKind::File),
"readme",
FileClass::Document,
),
(
"case-insensitive extension",
entry("main.RS", EntryKind::File),
"rust",
FileClass::Regular,
),
(
"known-name symlink",
entry("main.rs", EntryKind::Symlink),
"rust",
FileClass::Symlink,
),
(
"executable Rust file",
entry("main.rs", EntryKind::File).with_metadata(None, None, Some(0o755)),
"rust",
FileClass::Executable,
),
(
"generic executable",
entry("run", EntryKind::File).with_metadata(None, None, Some(0o100)),
"executable",
FileClass::Executable,
),
(
"symlink",
entry("latest", EntryKind::Symlink),
"symlink",
FileClass::Symlink,
),
(
"special",
entry("socket", EntryKind::Other),
"special",
FileClass::Special,
),
(
"unknown",
entry("unknown", EntryKind::File),
"file",
FileClass::Regular,
),
];
for (label, entry, expected_id, expected_class) in cases {
let resolved = resolver.resolve(&entry);
assert_eq!(resolved.id, expected_id, "{label}");
assert_eq!(resolved.class, expected_class, "{label}");
}
}
#[test]
fn every_icon_mode_has_the_documented_glyph_and_filename_class_is_independent() {
let entry = entry("main.rs", EntryKind::File);
for (mode, glyph) in [
(IconMode::Unicode, "🦀"),
(IconMode::Nerd, "\u{e7a8}"),
(IconMode::Ascii, "R"),
(IconMode::None, ""),
] {
let resolved = IconResolver::new(mode).resolve(&entry);
assert_eq!(resolved.glyph, glyph);
assert_eq!(resolved.class, FileClass::Regular);
}
}
#[test]
fn nerd_mode_contains_real_private_use_glyphs_and_differs_from_none() {
let resolver = IconResolver::new(IconMode::Nerd);
for entry in [
entry("docs", EntryKind::Directory),
entry("Cargo.toml", EntryKind::File),
entry("main.rs", EntryKind::File),
entry("latest", EntryKind::Symlink),
entry("run", EntryKind::File).with_metadata(None, None, Some(0o755)),
entry("unknown", EntryKind::File),
] {
let rich = resolver.resolve(&entry);
assert!(!rich.glyph.is_empty());
assert!(
rich.glyph
.chars()
.all(|character| { ('\u{e000}'..='\u{f8ff}').contains(&character) })
);
assert_ne!(rich, IconResolver::new(IconMode::None).resolve(&entry));
}
}
#[test]
fn semantic_filename_classes_cover_media_documents_archives_and_special_files() {
let resolver = IconResolver::default();
for (name, expected) in [
("photo.png", FileClass::Image),
("movie.mp4", FileClass::Media),
("guide.pdf", FileClass::Document),
("bundle.tar.gz", FileClass::Archive),
("note.unknown", FileClass::Regular),
] {
assert_eq!(
resolver.resolve(&entry(name, EntryKind::File)).class,
expected
);
}
}
#[test]
fn large_synthetic_listing_uses_the_bounded_fast_path() {
let resolver = IconResolver::default();
let entries: Vec<_> = (0..20_000)
.map(|index| entry(&format!("source-{index}.rs"), EntryKind::File))
.collect();
let started = std::time::Instant::now();
let checksum: usize = entries
.iter()
.map(|entry| resolver.resolve(entry).id.len())
.sum();
let elapsed = started.elapsed();
assert_eq!(checksum, 20_000 * "rust".len());
eprintln!("resolved {} entries in {elapsed:?}", entries.len());
assert!(
elapsed.as_secs() < 10,
"unexpected resolver regression: {elapsed:?}"
);
}
proptest! {
#[test]
fn resolution_is_deterministic_and_never_uses_host_state(name in ".*") {
let entry = entry(&name, EntryKind::File);
let resolver = IconResolver::default();
prop_assert_eq!(resolver.resolve(&entry), resolver.resolve(&entry));
}
}

318
tests/image_preview.rs Normal file
View file

@ -0,0 +1,318 @@
use std::io::Cursor;
use image::{DynamicImage, GenericImageView, ImageBuffer, ImageFormat, Rgb, Rgba};
use ratatui::{
Terminal,
backend::TestBackend,
layout::{Rect, Size},
style::Color,
widgets::Widget,
};
use ratatui_image::picker::ProtocolType;
use rcom::app::PaneId;
use rcom::domain::Location;
use rcom::image_preview::{
FontMetrics, ImageDetectionGates, ImageEngine, ImagePreviewCache, ImagePreviewError,
MAX_IMAGE_BYTES, PreparedImage, PreparedImageIdentity, checked_dimensions, decode_static,
prepare_halfblocks, supported_format,
};
use rcom::preview::bounded_read;
fn encoded(format: ImageFormat, width: u32, height: u32) -> Vec<u8> {
let image = DynamicImage::ImageRgb8(ImageBuffer::from_pixel(width, height, Rgb([20, 80, 140])));
let mut cursor = Cursor::new(Vec::new());
image.write_to(&mut cursor, format).unwrap();
cursor.into_inner()
}
#[test]
fn content_magic_recognizes_exactly_the_five_enabled_formats() {
for (format, expected) in [
(ImageFormat::Png, "Png"),
(ImageFormat::Jpeg, "Jpeg"),
(ImageFormat::Gif, "Gif"),
(ImageFormat::Bmp, "Bmp"),
(ImageFormat::WebP, "WebP"),
] {
let bytes = encoded(format, 3, 2);
assert_eq!(format!("{:?}", supported_format(&bytes).unwrap()), expected);
let decoded = decode_static(bytes, false).unwrap();
assert_eq!((decoded.width(), decoded.height()), (3, 2));
}
assert!(supported_format(b"plain text").is_none());
assert!(matches!(
decode_static(b"not an image".to_vec(), false),
Err(ImagePreviewError::UnsupportedFormat)
));
}
#[test]
fn animated_gif_decodes_to_one_static_first_frame() {
use image::{Frame, codecs::gif::GifEncoder};
let first = ImageBuffer::from_pixel(2, 2, Rgba([255, 0, 0, 255]));
let second = ImageBuffer::from_pixel(2, 2, Rgba([0, 0, 255, 255]));
let mut bytes = Vec::new();
GifEncoder::new(&mut bytes)
.encode_frames([Frame::new(first), Frame::new(second)])
.unwrap();
let decoded = decode_static(bytes, false).unwrap();
assert_eq!(decoded.dimensions(), (2, 2));
assert_eq!(decoded.into_rgba8().get_pixel(0, 0).0, [255, 0, 0, 255]);
}
#[test]
fn corrupt_truncated_and_oversized_inputs_fail_before_rendering() {
let mut png = encoded(ImageFormat::Png, 4, 4);
png.truncate(png.len() / 2);
assert!(decode_static(png.clone(), false).is_err());
assert!(matches!(
decode_static(encoded(ImageFormat::Png, 1, 1), true),
Err(ImagePreviewError::EncodedTooLarge)
));
assert!(matches!(
decode_static(vec![0; MAX_IMAGE_BYTES + 1], false),
Err(ImagePreviewError::EncodedTooLarge)
));
assert!(decode_static(encoded(ImageFormat::Png, MAX_IMAGE_AXIS_PLUS_ONE, 1), false).is_err());
}
const MAX_IMAGE_AXIS_PLUS_ONE: u32 = 8193;
#[tokio::test]
async fn bounded_image_read_distinguishes_exact_cap_and_one_lookahead_byte() {
let exact = bounded_read(&vec![7; MAX_IMAGE_BYTES][..], MAX_IMAGE_BYTES)
.await
.unwrap();
assert_eq!(exact.bytes.len(), MAX_IMAGE_BYTES);
assert!(!exact.truncated);
let over = bounded_read(&vec![7; MAX_IMAGE_BYTES + 1][..], MAX_IMAGE_BYTES)
.await
.unwrap();
assert_eq!(over.bytes.len(), MAX_IMAGE_BYTES);
assert!(over.truncated);
}
#[test]
fn checked_geometry_rejects_zero_overflow_axis_and_pixel_budget() {
for dimensions in [
(0, 1),
(1, 0),
(8193, 1),
(1, 8193),
(u32::MAX, u32::MAX),
(8000, 4001),
] {
assert!(
checked_dimensions(dimensions.0, dimensions.1).is_err(),
"{dimensions:?}"
);
}
assert!(checked_dimensions(8192, 1).is_ok());
assert!(checked_dimensions(8000, 4000).is_ok());
}
#[test]
fn halfblocks_render_real_known_pixels_without_a_picker_or_terminal_probe() {
let mut pixels = ImageBuffer::from_pixel(10, 20, Rgba([255, 0, 0, 255]));
for pixel in pixels.enumerate_pixels_mut() {
if pixel.1 >= 10 {
*pixel.2 = Rgba([0, 0, 255, 255]);
}
}
let protocol = prepare_halfblocks(DynamicImage::ImageRgba8(pixels), Size::new(1, 1)).unwrap();
assert_eq!(protocol.size(), Size::new(1, 1));
let mut terminal = Terminal::new(TestBackend::new(3, 2)).unwrap();
terminal
.draw(|frame| {
ratatui_image::Image::new(&protocol).render(Rect::new(1, 0, 1, 1), frame.buffer_mut());
})
.unwrap();
let cell = terminal.backend().buffer().cell((1, 0)).unwrap();
assert_eq!(cell.symbol(), "▀");
assert_eq!(cell.fg, Color::Rgb(219, 0, 36));
assert_eq!(cell.bg, Color::Rgb(36, 0, 219));
assert_eq!(
terminal.backend().buffer().cell((0, 0)).unwrap().symbol(),
" "
);
assert_eq!(
terminal.backend().buffer().cell((2, 1)).unwrap().symbol(),
" "
);
}
#[test]
fn aspect_fit_never_upscales_or_panics_on_wide_tall_tiny_and_zero_areas() {
for (source, area) in [
((100, 10), Size::new(4, 4)),
((10, 100), Size::new(4, 4)),
((1, 1), Size::new(20, 20)),
((2, 2), Size::new(1, 1)),
] {
let image = DynamicImage::ImageRgb8(ImageBuffer::new(source.0, source.1));
let protocol = prepare_halfblocks(image, area).unwrap();
assert!(protocol.size().width <= area.width);
assert!(protocol.size().height <= area.height);
}
let image = DynamicImage::ImageRgb8(ImageBuffer::new(1, 1));
assert!(matches!(
prepare_halfblocks(image, Size::new(0, 1)),
Err(ImagePreviewError::EmptyArea)
));
}
fn gates() -> ImageDetectionGates {
ImageDetectionGates {
images: true,
colors: true,
ascii: false,
dumb: false,
tty: true,
tmux: false,
}
}
#[test]
fn disabled_and_tmux_gates_never_invoke_a_picker_or_probe() {
for mutate in [
(|gate: &mut ImageDetectionGates| gate.images = false) as fn(&mut _),
|gate| gate.colors = false,
|gate| gate.ascii = true,
|gate| gate.dumb = true,
|gate| gate.tty = false,
] {
let mut gate = gates();
mutate(&mut gate);
let engine = ImageEngine::detect_with(gate, || -> Result<_, ()> {
panic!("disabled mode must not query or construct a picker")
});
assert!(engine.factory().is_none());
}
let engine = ImageEngine::detect_with(
ImageDetectionGates {
tmux: true,
..gates()
},
|| -> Result<_, ()> { panic!("tmux must use direct halfblocks") },
);
assert_eq!(
engine.factory().unwrap().protocol_type(),
ProtocolType::Halfblocks
);
}
#[test]
fn failed_query_falls_back_once_to_halfblocks() {
let mut calls = 0;
let engine = ImageEngine::detect_with(gates(), || -> Result<_, &str> {
calls += 1;
Err("timeout")
});
assert_eq!(calls, 1);
assert_eq!(
engine.factory().unwrap().protocol_type(),
ProtocolType::Halfblocks
);
}
fn identity(pane: PaneId, generation: u64) -> PreparedImageIdentity {
PreparedImageIdentity {
pane,
generation,
target: Location::local(format!("/fixture/{generation}.png")),
session_epoch: None,
area: Size::new(1, 1),
font: FontMetrics {
width: 10,
height: 20,
},
protocol: ProtocolType::Halfblocks,
terminal_epoch: 0,
}
}
#[test]
fn native_protocol_factories_produce_bounded_structural_protocols_without_wire_snapshots() {
if std::env::var_os("TMUX").is_some()
|| std::env::var("TERM_PROGRAM").is_ok_and(|program| program.eq_ignore_ascii_case("tmux"))
|| std::env::var("TERM").is_ok_and(|term| term.starts_with("tmux"))
{
// Never call an upstream Picker constructor in a tmux test environment.
return;
}
for protocol in [
ProtocolType::Kitty,
ProtocolType::Iterm2,
ProtocolType::Sixel,
] {
let mut picker = ratatui_image::picker::Picker::halfblocks();
picker.set_protocol_type(protocol);
let factory = rcom::image_preview::ImageProtocolFactory::Picker(picker);
let prepared = factory
.prepare(
DynamicImage::ImageRgba8(ImageBuffer::from_pixel(10, 20, Rgba([1, 2, 3, 255]))),
Size::new(1, 1),
)
.unwrap();
assert_eq!(prepared.size(), Size::new(1, 1));
assert!(matches!(
(protocol, prepared),
(
ProtocolType::Kitty,
ratatui_image::protocol::Protocol::Kitty(_)
) | (
ProtocolType::Iterm2,
ratatui_image::protocol::Protocol::ITerm2(_)
) | (
ProtocolType::Sixel,
ratatui_image::protocol::Protocol::Sixel(_)
)
));
}
}
#[test]
fn prepared_cache_is_bounded_and_rejects_stale_identity_and_terminal_epochs() {
let mut cache = ImagePreviewCache::default();
for pane in [PaneId::Left, PaneId::Right] {
let id = identity(pane, 1);
let protocol = prepare_halfblocks(
DynamicImage::ImageRgb8(ImageBuffer::new(10, 20)),
Size::new(1, 1),
)
.unwrap();
cache.insert(PreparedImage {
identity: id.clone(),
protocol,
});
assert!(cache.current(&id).is_some());
let mut stale = id.clone();
stale.generation += 1;
assert!(cache.current(&stale).is_none());
let mut wrong_geometry = id.clone();
wrong_geometry.area = Size::new(2, 2);
assert!(cache.current(&wrong_geometry).is_none());
let mut wrong_terminal = id;
wrong_terminal.terminal_epoch = 1;
assert!(cache.current(&wrong_terminal).is_none());
}
assert_eq!(cache.len(), 2);
let replacement = identity(PaneId::Left, 2);
let protocol = prepare_halfblocks(
DynamicImage::ImageRgb8(ImageBuffer::new(10, 20)),
Size::new(1, 1),
)
.unwrap();
cache.insert(PreparedImage {
identity: replacement.clone(),
protocol,
});
assert_eq!(cache.len(), 2);
assert!(cache.current(&identity(PaneId::Left, 1)).is_none());
assert!(cache.current(&replacement).is_some());
cache.remove_pane(PaneId::Left);
assert_eq!(cache.len(), 1);
cache.clear();
assert!(cache.is_empty());
}

468
tests/image_runtime.rs Normal file
View file

@ -0,0 +1,468 @@
use std::io::Cursor;
use std::sync::Arc;
use std::time::Duration;
use image::{DynamicImage, ImageBuffer, ImageFormat, Rgba};
use ratatui::{Terminal, backend::TestBackend};
use rcom::app::{Command, Overlay, PaneId};
use rcom::domain::Location;
use rcom::fs::BackendRegistry;
use rcom::image_preview::{ImageEngine, ImageProtocolFactory, ImageRenderContext};
use rcom::preview::{EncodedImage, Preview, PreviewKind};
use rcom::session::Application;
use rcom::ssh::{ConnectionManager, DiscoveryResult, OpenSshConnector};
use rcom::test_support::MemoryFs;
use rcom::ui::{IconMode, Theme, render_with_context};
fn png() -> Vec<u8> {
let mut pixels = ImageBuffer::from_pixel(10, 20, Rgba([255, 0, 0, 255]));
for (x, y, pixel) in pixels.enumerate_pixels_mut() {
if y >= 10 {
*pixel = Rgba([0, 0, 255, 255]);
}
let _ = x;
}
let image = DynamicImage::ImageRgba8(pixels);
let mut cursor = Cursor::new(Vec::new());
image.write_to(&mut cursor, ImageFormat::Png).unwrap();
cursor.into_inner()
}
fn changed_png() -> Vec<u8> {
let mut pixels = ImageBuffer::from_pixel(10, 20, Rgba([0, 0, 255, 255]));
for (_, y, pixel) in pixels.enumerate_pixels_mut() {
if y >= 10 {
*pixel = Rgba([0, 255, 0, 255]);
}
}
let mut cursor = Cursor::new(Vec::new());
DynamicImage::ImageRgba8(pixels)
.write_to(&mut cursor, ImageFormat::Png)
.unwrap();
cursor.into_inner()
}
fn application() -> (Application, tokio::sync::mpsc::Receiver<Command>) {
let fs = MemoryFs::new().with_file(Location::local("/pixel.png"), png());
let registry = BackendRegistry::new(Arc::new(fs));
let connections = ConnectionManager::new(Arc::new(OpenSshConnector::default()), registry);
Application::new(
Location::local("/"),
connections,
DiscoveryResult::default(),
)
}
async fn dispatch_until(
app: &mut Application,
results: &mut tokio::sync::mpsc::Receiver<Command>,
predicate: impl Fn(&Command) -> bool,
) {
let command = tokio::time::timeout(Duration::from_secs(2), async {
loop {
let command = results.recv().await.unwrap();
if predicate(&command) {
return command;
}
app.dispatch(command);
}
})
.await
.unwrap();
app.dispatch(command);
}
fn draw(app: &Application) -> ratatui::buffer::Buffer {
let cache = app.image_cache();
let cache = cache.lock().unwrap();
let factory = app.image_factory().unwrap();
let context = ImageRenderContext {
cache: &cache,
factory: &factory,
};
let area = app.terminal_area();
let mut terminal = Terminal::new(TestBackend::new(area.width, area.height)).unwrap();
terminal
.draw(|frame| {
render_with_context(
frame,
app.state(),
None,
&Theme::default().with_icon_mode(IconMode::None),
Some(context),
);
})
.unwrap();
terminal.backend().buffer().clone()
}
fn has_pixels(buffer: &ratatui::buffer::Buffer) -> bool {
buffer
.content()
.iter()
.any(|cell| matches!(cell.symbol(), "▀" | "▄"))
}
fn install_current_image(app: &mut Application, pane: PaneId, name: &str) {
let target = Location::local(format!("/{name}"));
let state = app.state_mut_for_test();
state.panes[pane.index()].entries = vec![rcom::domain::Entry::new(
name,
rcom::domain::EntryKind::File,
)];
state.panes[pane.index()].selection.set(Some(0), 1);
state.panes[pane.index()].preview.target = Some(target);
state.panes[pane.index()].preview.content = Some(Preview {
kind: PreviewKind::Image,
lines: vec!["Preparing".into()],
truncated: false,
});
state.panes[pane.index()].preview.encoded_image = Some(EncodedImage {
bytes: Arc::new(png()),
format: rcom::image_preview::SupportedImageFormat::Png,
});
}
#[tokio::test]
async fn rapid_image_selection_uses_shared_debounce_before_preparation() {
let fs = MemoryFs::new()
.with_file(Location::local("/a.png"), png())
.with_file(Location::local("/b.png"), png());
let registry = BackendRegistry::new(Arc::new(fs));
let connections = ConnectionManager::new(Arc::new(OpenSshConnector::default()), registry);
let (mut app, mut results) = Application::new(
Location::local("/"),
connections,
DiscoveryResult::default(),
);
app.configure_images(ImageEngine::Enabled(ImageProtocolFactory::Halfblocks));
app.update_terminal_area(ratatui::layout::Rect::new(0, 0, 120, 30));
app.dispatch(Command::Refresh);
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::PreviewFinished(_))
})
.await;
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::ImagePrepared(_))
})
.await;
let start = std::time::Instant::now();
app.dispatch_at(Command::MoveSelection(1), start);
assert_eq!(app.pending_preview_count(), 1);
assert!(matches!(
results.try_recv(),
Err(tokio::sync::mpsc::error::TryRecvError::Empty)
));
app.expire_pending_at(start + Duration::from_millis(40));
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::PreviewFinished(_))
})
.await;
assert_eq!(
app.state().panes[0].preview.target,
Some(Location::local("/b.png"))
);
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::ImagePrepared(_))
})
.await;
assert!(has_pixels(&draw(&app)));
}
#[tokio::test]
async fn global_image_worker_has_max_active_one_across_panes() {
let (mut app, mut results) = application();
install_current_image(&mut app, PaneId::Left, "left.png");
install_current_image(&mut app, PaneId::Right, "right.png");
app.configure_images(ImageEngine::Enabled(ImageProtocolFactory::Halfblocks));
app.state_mut_for_test().mode = rcom::app::PaneMode::Dual;
app.state_mut_for_test().overlay = Overlay::Preview;
app.update_terminal_area(ratatui::layout::Rect::new(0, 0, 120, 30));
app.dispatch(Command::SwitchPane);
let mut prepared = 0;
while prepared < 2 {
let command = tokio::time::timeout(Duration::from_secs(2), results.recv())
.await
.unwrap()
.unwrap();
if matches!(command, Command::ImagePrepared(_)) {
prepared += 1;
}
app.dispatch(command);
}
assert_eq!(app.image_worker_metrics(), (0, 1));
}
#[tokio::test]
async fn image_job_cancelled_before_blocking_start_never_decodes_or_publishes() {
let (mut app, mut results) = application();
app.set_image_worker_permits_for_test(0);
install_current_image(&mut app, PaneId::Left, "left.png");
app.configure_images(ImageEngine::Enabled(ImageProtocolFactory::Halfblocks));
app.state_mut_for_test().overlay = Overlay::Preview;
app.update_terminal_area(ratatui::layout::Rect::new(0, 0, 120, 30));
app.dispatch(Command::ToggleHelp);
app.release_image_worker_permit_for_test();
tokio::time::sleep(Duration::from_millis(50)).await;
let received = results.try_recv();
assert!(
matches!(received, Err(tokio::sync::mpsc::error::TryRecvError::Empty)),
"{received:?}"
);
assert_eq!(app.image_worker_metrics(), (0, 0));
}
#[tokio::test]
async fn local_image_preview_prepares_and_renders_real_pixels_in_persistent_and_f3() {
let (mut app, mut results) = application();
app.configure_images(ImageEngine::Enabled(ImageProtocolFactory::Halfblocks));
app.update_terminal_area(ratatui::layout::Rect::new(0, 0, 120, 30));
app.dispatch(Command::Refresh);
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::PreviewFinished(_))
})
.await;
assert_eq!(
app.state().panes[0].preview.content.as_ref().unwrap().kind,
rcom::preview::PreviewKind::Image
);
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::ImagePrepared(_))
})
.await;
let buffer = draw(&app);
assert!(has_pixels(&buffer));
app.dispatch(Command::OpenPreview);
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::ImagePrepared(_))
})
.await;
assert_eq!(app.state().overlay, Overlay::Preview);
assert!(has_pixels(&draw(&app)));
app.dispatch(Command::CloseOverlay);
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::ImagePrepared(_))
})
.await;
assert!(has_pixels(&draw(&app)));
}
#[tokio::test]
async fn resize_editor_epoch_and_text_selection_invalidate_prepared_pixels() {
let (mut app, mut results) = application();
app.configure_images(ImageEngine::Enabled(ImageProtocolFactory::Halfblocks));
app.update_terminal_area(ratatui::layout::Rect::new(0, 0, 120, 30));
app.dispatch(Command::Refresh);
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::PreviewFinished(_))
})
.await;
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::ImagePrepared(_))
})
.await;
assert!(has_pixels(&draw(&app)));
app.update_terminal_area(ratatui::layout::Rect::new(0, 0, 100, 30));
assert!(
!has_pixels(&draw(&app)),
"old oversized protocol must not render"
);
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::ImagePrepared(_))
})
.await;
assert!(has_pixels(&draw(&app)));
app.resume_images();
assert!(app.image_cache().lock().unwrap().is_empty());
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::ImagePrepared(_))
})
.await;
assert!(has_pixels(&draw(&app)));
app.state_mut_for_test().panes[0].preview.encoded_image = None;
app.state_mut_for_test().panes[0].preview.content = None;
app.dispatch(Command::OpenMessage);
assert!(app.image_cache().lock().unwrap().is_empty());
}
#[tokio::test]
async fn background_image_refresh_prepares_accepted_new_bytes_instead_of_old_generation() {
let (mut app, mut results) = application();
app.configure_images(ImageEngine::Enabled(ImageProtocolFactory::Halfblocks));
app.update_terminal_area(ratatui::layout::Rect::new(0, 0, 120, 30));
app.dispatch(Command::Refresh);
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::PreviewFinished(_))
})
.await;
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::ImagePrepared(_))
})
.await;
let old_identity = app.current_image_identity(PaneId::Left).unwrap();
let background = app
.state_mut_for_test()
.reduce(Command::RefreshPane(PaneId::Left));
let [rcom::app::Effect::LoadListing(listing)] = background.as_slice() else {
panic!("background listing")
};
let background_preview =
app.state_mut_for_test()
.reduce(Command::ListingFinished(listing.clone().into_result(Ok(
vec![rcom::domain::Entry::new(
"pixel.png",
rcom::domain::EntryKind::File,
)],
))));
assert!(matches!(
background_preview.as_slice(),
[rcom::app::Effect::LoadPreview(_)]
));
assert!(app.state().panes[0].preview_generation > old_identity.generation);
assert_eq!(
app.current_image_identity(PaneId::Left).unwrap(),
old_identity
);
assert!(matches!(
results.try_recv(),
Err(tokio::sync::mpsc::error::TryRecvError::Empty)
));
let pane = &app.state().panes[0];
let request = rcom::app::PreviewRequest {
pane: PaneId::Left,
generation: pane.preview_generation,
target: pane.preview.target.clone().unwrap(),
session_epoch: pane.session_epoch,
images_enabled: true,
};
let mut response = request.into_result(Ok(Preview {
kind: PreviewKind::Image,
lines: vec!["Changed image".into()],
truncated: false,
}));
response.encoded_image = Some(EncodedImage {
bytes: Arc::new(changed_png()),
format: rcom::image_preview::SupportedImageFormat::Png,
});
app.dispatch(Command::PreviewFinished(response));
let new_identity = app.current_image_identity(PaneId::Left).unwrap();
assert_ne!(new_identity, old_identity);
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::ImagePrepared(_))
})
.await;
assert!(has_pixels(&draw(&app)));
}
#[tokio::test]
async fn stale_image_errors_after_resize_and_resume_never_replace_current_content() {
for resume in [false, true] {
let (mut app, _results) = application();
install_current_image(&mut app, PaneId::Left, "left.png");
app.configure_images(ImageEngine::Enabled(ImageProtocolFactory::Halfblocks));
app.state_mut_for_test().overlay = Overlay::Preview;
app.update_terminal_area(ratatui::layout::Rect::new(0, 0, 120, 30));
let stale = app.current_image_identity(PaneId::Left).unwrap();
if resume {
app.resume_images();
} else {
app.update_terminal_area(ratatui::layout::Rect::new(0, 0, 100, 30));
}
assert_ne!(app.current_image_identity(PaneId::Left).unwrap(), stale);
app.dispatch(Command::ImagePrepared(rcom::app::ImagePreparationResult {
identity: stale,
result: Err("stale error".into()),
}));
let preview = &app.state().panes[0].preview;
assert_eq!(preview.content.as_ref().unwrap().kind, PreviewKind::Image);
assert!(preview.encoded_image.is_some());
}
}
#[tokio::test]
async fn corrupt_current_image_becomes_visible_metadata_instead_of_preparing_forever() {
let bytes = png()[..40].to_vec();
let fs = MemoryFs::new().with_file(Location::local("/pixel.png"), bytes);
let registry = BackendRegistry::new(Arc::new(fs));
let connections = ConnectionManager::new(Arc::new(OpenSshConnector::default()), registry);
let (mut app, mut results) = Application::new(
Location::local("/"),
connections,
DiscoveryResult::default(),
);
app.configure_images(ImageEngine::Enabled(ImageProtocolFactory::Halfblocks));
app.update_terminal_area(ratatui::layout::Rect::new(0, 0, 120, 30));
app.dispatch(Command::Refresh);
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::PreviewFinished(_))
})
.await;
dispatch_until(&mut app, &mut results, |command| {
matches!(command, Command::ImagePrepared(_))
})
.await;
let preview = app.state().panes[0].preview.content.as_ref().unwrap();
assert_eq!(preview.kind, rcom::preview::PreviewKind::Metadata);
assert!(preview.lines[0].contains("unavailable"));
assert!(app.state().panes[0].preview.encoded_image.is_none());
}
#[test]
fn direct_halfblock_factory_needs_no_detection_and_zero_area_is_a_safe_placeholder() {
let image = DynamicImage::ImageRgb8(ImageBuffer::new(1, 1));
assert!(
ImageProtocolFactory::Halfblocks
.prepare(image, ratatui::layout::Size::new(0, 0))
.is_err()
);
}
#[tokio::test]
async fn disabled_images_have_explicit_fallback_and_no_large_second_read() {
let target = Location::local("/pixel.png");
let recording = rcom::test_support::RecordingFs::new(Arc::new(
MemoryFs::new().with_file(target.clone(), png()),
));
let request = rcom::app::PreviewRequest {
pane: PaneId::Left,
generation: 1,
target,
session_epoch: None,
images_enabled: false,
};
let result = rcom::app::preview::execute_preview(request, &recording).await;
let preview = result.result.unwrap();
assert_eq!(preview.kind, PreviewKind::Binary);
assert!(preview.lines[0].contains("unsupported"));
assert!(
preview
.lines
.iter()
.any(|line| line.contains("disabled or unavailable"))
);
assert!(result.encoded_image.is_none());
let operations = recording.operations();
assert_eq!(operations.len(), 2);
assert_eq!(operations[1].limit, Some(rcom::preview::MAX_PREVIEW_BYTES));
}
#[tokio::test]
async fn fake_ssh_image_uses_the_same_bounded_read_path_without_a_shell() {
let target = Location::ssh(rcom::domain::HostAlias::new("fake"), "/pixel.png");
let fs = MemoryFs::new().with_file(target.clone(), png());
let request = rcom::app::PreviewRequest {
pane: PaneId::Left,
generation: 1,
target,
session_epoch: Some(1),
images_enabled: true,
};
let result = rcom::app::preview::execute_preview(request, &fs).await;
assert!(result.result.is_ok());
assert!(result.encoded_image.is_some());
}

View file

@ -3,7 +3,7 @@ use std::time::{Duration, Instant};
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
use directories::UserDirs;
use pretty_assertions::assert_eq;
use rcom::app::{AppState, Command};
use rcom::app::{AppState, Command, HelpViewport};
use rcom::domain::{Entry, EntryKind, Location};
use rcom::input::{GG_TIMEOUT, InputOutcome, InputState, PendingKey};
use rcom::ssh::HostPickerState;
@ -44,6 +44,13 @@ fn command(input: &mut InputState, key: KeyEvent, page_size: usize) -> Command {
.unwrap_or_else(|| panic!("expected a command for {key:?}"))
}
fn help_viewport(page_size: usize) -> HelpViewport {
HelpViewport {
page_size,
max_scroll: 100,
}
}
#[test]
fn yazi_and_mc_aliases_map_to_the_same_application_commands() {
let cases = vec![
@ -359,7 +366,7 @@ fn overlays_capture_selection_clipboard_and_planner_keys() {
for key in selection_keys {
assert!(!matches!(
InputState::new().handle_help_key(key, 10),
InputState::new().handle_help_key(key, help_viewport(10)),
InputOutcome::Command(
Command::ToggleSelect
| Command::ToggleVisual
@ -513,37 +520,154 @@ fn entry_confirmation_and_deferred_overlays_never_repeat_actions() {
}
#[test]
fn help_overlay_handles_close_quit_and_scrolling_aliases() {
fn help_overlay_handles_categories_close_quit_and_body_scrolling_aliases() {
let cases = [
(press(KeyCode::Esc), Command::CloseOverlay),
(press(KeyCode::Char('q')), Command::CloseOverlay),
(shifted('?'), Command::ToggleHelp),
(press(KeyCode::F(1)), Command::ToggleHelp),
(press(KeyCode::F(10)), Command::Quit),
(press(KeyCode::Char('j')), Command::ScrollOverlay(1)),
(press(KeyCode::Down), Command::ScrollOverlay(1)),
(press(KeyCode::Char('k')), Command::ScrollOverlay(-1)),
(press(KeyCode::Up), Command::ScrollOverlay(-1)),
(press(KeyCode::PageDown), Command::ScrollOverlay(12)),
(press(KeyCode::PageUp), Command::ScrollOverlay(-12)),
(control('d'), Command::ScrollOverlay(6)),
(control('u'), Command::ScrollOverlay(-6)),
(control('f'), Command::ScrollOverlay(12)),
(control('b'), Command::ScrollOverlay(-12)),
(press(KeyCode::Char('h')), Command::SelectHelpCategory(-1)),
(press(KeyCode::Left), Command::SelectHelpCategory(-1)),
(press(KeyCode::BackTab), Command::SelectHelpCategory(-1)),
(press(KeyCode::Char('l')), Command::SelectHelpCategory(1)),
(press(KeyCode::Right), Command::SelectHelpCategory(1)),
(press(KeyCode::Tab), Command::SelectHelpCategory(1)),
(
press(KeyCode::Char('j')),
Command::ScrollHelp {
delta: 1,
max_scroll: 100,
},
),
(
press(KeyCode::Down),
Command::ScrollHelp {
delta: 1,
max_scroll: 100,
},
),
(
press(KeyCode::Char('k')),
Command::ScrollHelp {
delta: -1,
max_scroll: 100,
},
),
(
press(KeyCode::Up),
Command::ScrollHelp {
delta: -1,
max_scroll: 100,
},
),
(
press(KeyCode::PageDown),
Command::ScrollHelp {
delta: 12,
max_scroll: 100,
},
),
(
press(KeyCode::PageUp),
Command::ScrollHelp {
delta: -12,
max_scroll: 100,
},
),
(
control('d'),
Command::ScrollHelp {
delta: 6,
max_scroll: 100,
},
),
(
control('u'),
Command::ScrollHelp {
delta: -6,
max_scroll: 100,
},
),
(
control('f'),
Command::ScrollHelp {
delta: 12,
max_scroll: 100,
},
),
(
control('b'),
Command::ScrollHelp {
delta: -12,
max_scroll: 100,
},
),
];
for (key, expected) in cases {
let mut input = InputState::new();
assert_eq!(
input.handle_help_key(key, 12),
input.handle_help_key(key, help_viewport(12)),
InputOutcome::Command(expected)
);
}
let mut input = InputState::new();
assert_eq!(
input.handle_help_key(press(KeyCode::F(3)), 12),
InputOutcome::Ignored
);
for key in [
press(KeyCode::Enter),
event(KeyCode::Enter, KeyModifiers::NONE, KeyEventKind::Repeat),
press(KeyCode::F(3)),
] {
assert_eq!(
InputState::new().handle_help_key(key, help_viewport(12)),
InputOutcome::Ignored
);
}
}
#[test]
fn help_repeat_policy_separates_navigation_from_press_only_controls() {
for key in [
event(KeyCode::Char('h'), KeyModifiers::NONE, KeyEventKind::Repeat),
event(KeyCode::Char('l'), KeyModifiers::NONE, KeyEventKind::Repeat),
event(KeyCode::Left, KeyModifiers::NONE, KeyEventKind::Repeat),
event(KeyCode::Right, KeyModifiers::NONE, KeyEventKind::Repeat),
event(KeyCode::Down, KeyModifiers::NONE, KeyEventKind::Repeat),
event(KeyCode::PageDown, KeyModifiers::NONE, KeyEventKind::Repeat),
event(
KeyCode::Char('f'),
KeyModifiers::CONTROL,
KeyEventKind::Repeat,
),
] {
assert!(matches!(
InputState::new().handle_help_key(key, help_viewport(12)),
InputOutcome::Command(_)
));
}
for code in [
KeyCode::Tab,
KeyCode::BackTab,
KeyCode::Esc,
KeyCode::Char('q'),
KeyCode::Char('?'),
KeyCode::F(1),
KeyCode::F(10),
] {
assert_eq!(
InputState::new().handle_help_key(
event(code, KeyModifiers::NONE, KeyEventKind::Repeat),
help_viewport(12),
),
InputOutcome::Ignored
);
assert_eq!(
InputState::new().handle_help_key(
event(code, KeyModifiers::NONE, KeyEventKind::Release),
help_viewport(12),
),
InputOutcome::Ignored
);
}
}
#[test]

View file

@ -260,18 +260,93 @@ fn task_input_cancel_and_details_do_not_repeat() {
}
#[test]
fn help_and_header_expose_operation_keys_without_read_only_branding() {
fn task_details_vertical_aliases_scroll_without_selecting_behind_overlay() {
let cases = [
(KeyCode::Char('j'), KeyModifiers::NONE, 1),
(KeyCode::Down, KeyModifiers::NONE, 1),
(KeyCode::Char('k'), KeyModifiers::NONE, -1),
(KeyCode::Up, KeyModifiers::NONE, -1),
(KeyCode::PageDown, KeyModifiers::NONE, 8),
(KeyCode::PageUp, KeyModifiers::NONE, -8),
(KeyCode::Char('f'), KeyModifiers::CONTROL, 8),
(KeyCode::Char('b'), KeyModifiers::CONTROL, -8),
(KeyCode::Char('d'), KeyModifiers::CONTROL, 4),
(KeyCode::Char('u'), KeyModifiers::CONTROL, -4),
];
let mut input = InputState::new();
for (code, modifiers, delta) in cases {
for kind in [KeyEventKind::Press, KeyEventKind::Repeat] {
let key = KeyEvent {
code,
modifiers,
kind,
state: KeyEventState::NONE,
};
let mut app = AppState::new(Location::local("/source"));
app.overlay = rcom::app::Overlay::TaskDetails;
app.selected_task = Some(TaskId::new(7));
app.task_details = Some(TaskId::new(7));
assert_eq!(
input.handle_task_details_key(key, 8),
InputOutcome::Command(Command::ScrollOverlay(delta))
);
app.reduce(Command::ScrollOverlay(delta));
assert_eq!(app.selected_task, Some(TaskId::new(7)));
assert_eq!(app.task_details, Some(TaskId::new(7)));
}
}
for code in [
KeyCode::Char('m'),
KeyCode::Enter,
KeyCode::Esc,
KeyCode::Char('q'),
KeyCode::Char('t'),
] {
assert_eq!(
input.handle_task_details_key(key(code), 8),
InputOutcome::Command(Command::CloseOverlay)
);
}
assert_eq!(
input.handle_task_details_key(key(KeyCode::Char('c')), 8),
InputOutcome::Command(Command::CancelSelectedTask)
);
assert_eq!(
input.handle_task_details_key(
KeyEvent {
code: KeyCode::Char('j'),
modifiers: KeyModifiers::NONE,
kind: KeyEventKind::Release,
state: KeyEventState::NONE,
},
8,
),
InputOutcome::Ignored
);
}
#[test]
fn help_and_header_expose_operation_keys_without_persistent_hints() {
let mut app = AppState::new(Location::local("/source"));
app.reduce(Command::ToggleHelp);
let rendered = draw(&app, 120, 40);
assert!(rendered.contains("dual-pane file manager"));
assert!(rendered.contains("? Help"));
assert!(!rendered.contains("read-only workspace"));
for expected in ["Space Select", "y/x/p", "F5/F6 Copy/Move", "t Tasks"] {
assert!(
rendered.contains(expected),
"missing {expected:?}\n{rendered}"
);
assert!(!rendered.contains("Space Select · y/x/p Yank/Cut/Paste"));
app.reduce(Command::SelectHelpCategory(1));
let selection = draw(&app, 120, 40);
assert!(selection.contains("Space / Insert"));
app.reduce(Command::SelectHelpCategory(1));
let files = draw(&app, 120, 40);
for expected in ["Yank/copy selection", "F5", "F6", "NO UNDO"] {
assert!(files.contains(expected), "missing {expected:?}\n{files}");
}
app.reduce(Command::SelectHelpCategory(1));
let tasks = draw(&app, 120, 40);
assert!(tasks.contains("Open the task list"));
}
#[test]

469
tests/preview_debounce.rs Normal file
View file

@ -0,0 +1,469 @@
use std::sync::Arc;
use std::time::{Duration, Instant};
use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
use ratatui::{Terminal, backend::TestBackend};
use rcom::app::{Command, ConnectSshRequest, ListingRequest, Overlay, PaneId, PaneMode};
use rcom::domain::{Entry, EntryKind, HostAlias, Location};
use rcom::fs::{BackendRegistry, FsError};
use rcom::preview::PreviewKind;
use rcom::session::{Application, PREVIEW_DEBOUNCE};
use rcom::ssh::{ConnectionManager, DiscoveryResult, OpenSshConnector};
use rcom::test_support::{MemoryFs, RecordingFs};
use rcom::ui::{Theme, render};
use tokio::sync::mpsc;
fn entries() -> Vec<Entry> {
vec![
Entry::new("a.txt", EntryKind::File),
Entry::new("b.txt", EntryKind::File),
Entry::new("c.txt", EntryKind::File),
]
}
fn application() -> (Application, mpsc::Receiver<Command>, Arc<RecordingFs>) {
let mut memory = MemoryFs::new();
for name in ["a.txt", "b.txt", "c.txt"] {
memory = memory.with_file(
Location::local(format!("/{name}")),
format!("contents-{name}"),
);
}
let recording = Arc::new(RecordingFs::new(Arc::new(memory)));
let registry = BackendRegistry::new(recording.clone());
let connections = ConnectionManager::new(Arc::new(OpenSshConnector::default()), registry);
let (mut app, results) = Application::new(
Location::local("/"),
connections,
DiscoveryResult::default(),
);
let state = app.state_mut_for_test();
state.panes[0].entries = entries();
state.panes[0].selection.set(Some(0), 3);
(app, results, recording)
}
fn draw_buffer(app: &Application) -> ratatui::buffer::Buffer {
let mut terminal = Terminal::new(TestBackend::new(120, 30)).unwrap();
terminal
.draw(|frame| render(frame, app.state(), None, &Theme::default()))
.unwrap();
terminal.backend().buffer().clone()
}
fn draw(app: &Application) -> String {
let buffer = draw_buffer(app);
(0..30)
.map(|y| {
(0..120)
.map(|x| buffer.cell((x, y)).unwrap().symbol())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n")
}
fn preview_title(buffer: &ratatui::buffer::Buffer) -> String {
(54..120)
.map(|x| buffer.cell((x, 1)).unwrap().symbol())
.collect()
}
#[tokio::test]
async fn rapid_selection_has_no_intermediate_read_or_loading_and_starts_once_at_40ms() {
let (mut app, mut results, recording) = application();
let start = Instant::now();
app.state_mut_for_test().panes[0].preview.content = Some(rcom::preview::Preview {
kind: PreviewKind::Text,
lines: vec!["stale-old-preview".into()],
truncated: false,
});
app.dispatch_at(Command::MoveSelection(1), start);
assert_eq!(app.pending_preview_count(), 1);
assert!(app.state().panes[0].preview.debouncing);
assert!(!app.state().panes[0].preview.loading);
assert!(app.state().panes[0].preview.content.is_none());
let quiet = draw(&app);
assert!(!quiet.contains("LOADING PREVIEW"));
assert!(!quiet.contains("stale-old-preview"));
assert!(quiet.contains("b.txt"));
assert!(preview_title(&draw_buffer(&app)).contains("b.txt"));
app.expire_pending_at(start + Duration::from_millis(39));
assert_eq!(app.pending_preview_count(), 1);
assert!(!app.state().panes[0].preview.loading);
assert!(recording.operations().is_empty());
// A Repeat-style selection replaces the deadline instead of queueing a worker.
app.handle_key_at(
KeyEvent::new(KeyCode::Down, KeyModifiers::NONE),
10,
start + Duration::from_millis(39),
);
assert_eq!(app.pending_preview_count(), 1);
let quiet = draw(&app);
assert!(!quiet.contains("LOADING PREVIEW"));
assert!(preview_title(&draw_buffer(&app)).contains("c.txt"));
app.expire_pending_at(start + PREVIEW_DEBOUNCE);
assert_eq!(app.pending_preview_count(), 1);
app.expire_pending_at(start + Duration::from_millis(39) + PREVIEW_DEBOUNCE);
assert_eq!(app.pending_preview_count(), 0);
assert!(app.state().panes[0].preview.loading);
assert!(!app.state().panes[0].preview.debouncing);
let completed = tokio::time::timeout(Duration::from_secs(1), results.recv())
.await
.unwrap()
.unwrap();
let Command::PreviewFinished(result) = completed else {
panic!("expected one current preview")
};
assert_eq!(result.target, Location::local("/c.txt"));
assert_eq!(recording.operations().len(), 2);
app.dispatch(Command::PreviewFinished(result));
}
#[test]
fn initial_f3_and_pure_selection_effects_keep_their_distinct_modes() {
let mut state = rcom::app::AppState::new(Location::local("/"));
state.panes[0].entries = entries();
state.panes[0].selection.set(Some(0), 3);
let refresh = state.reduce(Command::Refresh);
let [rcom::app::Effect::LoadListing(listing)] = refresh.as_slice() else {
panic!("initial listing must be immediate")
};
let initial_effects = state.reduce(Command::ListingFinished(
listing.clone().into_result(Ok(entries())),
));
assert!(matches!(
initial_effects.as_slice(),
[rcom::app::Effect::LoadPreview(_)]
));
let initial = state.reduce(Command::OpenPreview);
assert!(matches!(
initial.as_slice(),
[rcom::app::Effect::LoadPreview(_)]
));
assert_eq!(state.overlay, Overlay::Preview);
let selected = state.reduce(Command::SelectLast);
assert!(matches!(
selected.as_slice(),
[rcom::app::Effect::DebouncePreview(_)]
));
}
#[tokio::test]
async fn same_target_background_completion_preserves_pending_and_running_preview() {
for complete_before_deadline in [true, false] {
let (mut app, _results, _recording) = application();
let start = Instant::now();
app.dispatch_at(Command::MoveSelection(1), start);
let generation = app.state().panes[0].preview_generation;
app.dispatch_at(
Command::RefreshPane(PaneId::Left),
start + Duration::from_millis(5),
);
let listing = ListingRequest {
pane: PaneId::Left,
generation: app.state().panes[0].listing_generation,
target: Location::local("/"),
session_epoch: None,
};
if complete_before_deadline {
app.dispatch_at(
Command::ListingFinished(listing.clone().into_result(Ok(entries()))),
start + Duration::from_millis(10),
);
assert_eq!(app.pending_preview_count(), 1);
assert!(app.state().panes[0].preview.debouncing);
assert!(!app.state().panes[0].preview.loading);
}
app.expire_pending_at(start + PREVIEW_DEBOUNCE);
assert!(app.state().panes[0].preview.loading);
let current_generation = app.state().panes[0].preview_generation;
assert_eq!(current_generation, generation);
if !complete_before_deadline {
app.dispatch_at(
Command::ListingFinished(listing.into_result(Ok(entries()))),
start + PREVIEW_DEBOUNCE + Duration::from_millis(1),
);
assert_eq!(app.state().panes[0].preview_generation, current_generation);
assert!(app.state().panes[0].preview.loading);
}
}
}
#[tokio::test]
async fn background_changed_selection_uses_immediate_current_preview() {
for after_deadline in [false, true] {
let (mut app, _results, _recording) = application();
let start = Instant::now();
app.dispatch_at(Command::MoveSelection(1), start);
if after_deadline {
app.expire_pending_at(start + PREVIEW_DEBOUNCE);
}
app.dispatch_at(Command::RefreshPane(PaneId::Left), start);
let listing = ListingRequest {
pane: PaneId::Left,
generation: app.state().panes[0].listing_generation,
target: Location::local("/"),
session_epoch: None,
};
app.dispatch_at(
Command::ListingFinished(
listing.into_result(Ok(vec![Entry::new("z.txt", EntryKind::File)])),
),
start + Duration::from_millis(1),
);
assert_eq!(app.pending_preview_count(), 0);
assert!(!app.state().panes[0].preview.debouncing);
assert!(app.state().panes[0].preview.loading);
assert_eq!(
app.state().panes[0].preview.target,
Some(Location::local("/z.txt"))
);
}
}
#[tokio::test]
async fn dual_clone_does_not_inherit_orphan_debounce_and_source_deadline_survives() {
let (mut app, _results, _recording) = application();
let start = Instant::now();
app.dispatch_at(Command::MoveSelection(1), start);
let deadline = app.next_preview_deadline();
app.dispatch_at(Command::TogglePaneMode, start + Duration::from_millis(1));
assert_eq!(app.state().mode, PaneMode::Dual);
assert!(!app.state().panes[1].preview.debouncing);
assert!(!app.state().panes[1].preview.loading);
assert_eq!(app.next_preview_deadline(), deadline);
app.expire_pending_at(start + PREVIEW_DEBOUNCE);
assert!(app.state().panes[0].preview.loading);
assert!(!app.state().panes[1].preview.loading);
}
#[test]
fn start_preview_rejects_wrong_generation_target_navigation_and_host_at_equal_epoch() {
let host = HostAlias::new("one");
let other = HostAlias::new("two");
let home = Location::ssh(host.clone(), "/home");
let mut state = rcom::app::AppState::new(home.clone());
state.reduce(Command::ConnectSsh(host.clone()));
let connect = ConnectSshRequest {
pane: PaneId::Left,
generation: 1,
host: host.clone(),
expected_session_epoch: None,
};
let effects = state.reduce(Command::ConnectSshFinished(connect.into_result(Ok(
rcom::app::SshConnection {
location: home.clone(),
session_epoch: 9,
},
))));
let [rcom::app::Effect::LoadListing(listing)] = effects.as_slice() else {
panic!("connect should request listing")
};
state.reduce(Command::ListingFinished(
listing.clone().into_result(Ok(entries())),
));
let selected = state.reduce(Command::SelectLast);
let [rcom::app::Effect::DebouncePreview(request)] = selected.as_slice() else {
panic!("selection should debounce")
};
let request = request.clone();
for invalid in [
rcom::app::PreviewRequest {
generation: request.generation + 1,
..request.clone()
},
rcom::app::PreviewRequest {
target: home.join("wrong"),
..request.clone()
},
rcom::app::PreviewRequest {
target: Location::ssh(other, "/home/c.txt"),
session_epoch: request.session_epoch,
..request.clone()
},
] {
assert!(
state
.reduce(Command::StartPreview {
navigation_generation: state.active_pane().navigation_generation,
request: invalid,
})
.is_empty()
);
}
assert!(
state
.reduce(Command::StartPreview {
navigation_generation: state.active_pane().navigation_generation + 1,
request: request.clone(),
})
.is_empty()
);
assert!(matches!(
state
.reduce(Command::StartPreview {
navigation_generation: state.active_pane().navigation_generation,
request,
})
.as_slice(),
[rcom::app::Effect::LoadPreview(_)]
));
}
#[tokio::test]
async fn every_selection_alias_and_repeat_coalesces_to_one_read() {
let press = |code| KeyEvent::new(code, KeyModifiers::NONE);
let mut keys = vec![
press(KeyCode::Char('j')),
press(KeyCode::Down),
press(KeyCode::Char('k')),
press(KeyCode::Up),
press(KeyCode::Home),
press(KeyCode::End),
press(KeyCode::PageUp),
press(KeyCode::PageDown),
KeyEvent::new(KeyCode::Char('b'), KeyModifiers::CONTROL),
KeyEvent::new(KeyCode::Char('f'), KeyModifiers::CONTROL),
KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL),
KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL),
press(KeyCode::Char(' ')),
press(KeyCode::Insert),
KeyEvent {
code: KeyCode::Char('j'),
modifiers: KeyModifiers::NONE,
kind: KeyEventKind::Repeat,
state: KeyEventState::NONE,
},
];
keys.push(press(KeyCode::Char('G')));
for key in keys {
let (mut app, mut results, recording) = application();
app.state_mut_for_test().panes[0].selection.set(Some(1), 3);
let start = Instant::now();
app.handle_key_at(key, 2, start);
assert_eq!(app.pending_preview_count(), 1, "{key:?}");
assert!(recording.operations().is_empty(), "{key:?}");
app.expire_pending_at(start + PREVIEW_DEBOUNCE);
let result = tokio::time::timeout(Duration::from_secs(1), results.recv())
.await
.unwrap()
.unwrap();
assert!(matches!(result, Command::PreviewFinished(_)), "{key:?}");
assert_eq!(recording.operations().len(), 2, "{key:?}");
}
// `gg` is the only two-key alias and uses the same deadline scheduler.
let (mut app, mut results, recording) = application();
let start = Instant::now();
app.state_mut_for_test().panes[0].selection.set(Some(1), 3);
app.handle_key_at(press(KeyCode::Char('g')), 2, start);
app.handle_key_at(
press(KeyCode::Char('g')),
2,
start + Duration::from_millis(1),
);
assert_eq!(app.pending_preview_count(), 1);
app.expire_pending_at(start + Duration::from_millis(1) + PREVIEW_DEBOUNCE);
assert!(matches!(
results.recv().await,
Some(Command::PreviewFinished(_))
));
assert_eq!(recording.operations().len(), 2);
}
#[test]
fn failed_parent_recovers_pending_and_running_selection_preview() {
for after_deadline in [false, true] {
let mut state = rcom::app::AppState::new(Location::local("/workspace"));
state.panes[0].entries = entries();
state.panes[0].selection.set(Some(0), 3);
let selected = state.reduce(Command::MoveSelection(1));
let [rcom::app::Effect::DebouncePreview(request)] = selected.as_slice() else {
panic!("selection should debounce")
};
let old_generation = request.generation;
if after_deadline {
let started = state.reduce(Command::StartPreview {
request: request.clone(),
navigation_generation: state.active_pane().navigation_generation,
});
assert!(matches!(
started.as_slice(),
[rcom::app::Effect::LoadPreview(_)]
));
}
let parent = state.reduce(Command::Parent);
let [rcom::app::Effect::LoadListing(listing)] = parent.as_slice() else {
panic!("parent should navigate")
};
let recovered = state.reduce(Command::ListingFinished(
listing.clone().into_result(Err(FsError::NotFound)),
));
assert!(matches!(
recovered.as_slice(),
[rcom::app::Effect::LoadPreview(request)] if request.generation > old_generation
));
assert!(!state.active_pane().preview.debouncing);
}
}
#[tokio::test]
async fn failed_navigation_and_connect_create_immediate_replacement_not_stale_pending() {
for connect in [false, true] {
for after_deadline in [false, true] {
let (mut app, _results, _recording) = application();
let start = Instant::now();
app.dispatch_at(Command::MoveSelection(1), start);
let old_generation = app.state().panes[0].preview_generation;
if after_deadline {
app.expire_pending_at(start + PREVIEW_DEBOUNCE);
assert!(app.state().panes[0].preview.selection_recovery);
assert!(app.state().panes[0].preview.loading);
}
if connect {
let host = HostAlias::new("other");
app.dispatch_at(
Command::ConnectSsh(host.clone()),
start + Duration::from_millis(1),
);
let request = ConnectSshRequest {
pane: PaneId::Left,
generation: app.state().panes[0].listing_generation,
host,
expected_session_epoch: None,
};
app.dispatch_at(
Command::ConnectSshFinished(request.into_result(Err(FsError::Disconnected))),
start + Duration::from_millis(2),
);
} else {
app.state_mut_for_test().panes[0].entries =
vec![Entry::new("dir", EntryKind::Directory)];
app.state_mut_for_test().panes[0].selection.set(Some(0), 1);
app.dispatch_at(Command::Enter, start + Duration::from_millis(1));
let request = ListingRequest {
pane: PaneId::Left,
generation: app.state().panes[0].listing_generation,
target: Location::local("/dir"),
session_epoch: None,
};
app.dispatch_at(
Command::ListingFinished(request.into_result(Err(FsError::NotFound))),
start + Duration::from_millis(2),
);
}
assert!(app.state().panes[0].preview.loading, "connect={connect}");
assert!(
!app.state().panes[0].preview.debouncing,
"connect={connect}"
);
assert!(app.state().panes[0].preview_generation > old_generation);
assert_eq!(app.pending_preview_count(), 0);
app.expire_pending_at(start + PREVIEW_DEBOUNCE);
assert_eq!(app.pending_preview_count(), 0);
}
}
}

View file

@ -20,6 +20,7 @@ fn request(target: Location) -> PreviewRequest {
generation: 1,
target,
session_epoch: None,
images_enabled: true,
}
}

View file

@ -38,6 +38,19 @@ fn fake_editor(directory: &std::path::Path, body: &str) -> std::path::PathBuf {
path
}
fn spawn_app_with_config(
path: &std::path::Path,
config_root: &std::path::Path,
) -> expectrl::session::OsSession {
let mut command = Command::new(env!("CARGO_BIN_EXE_rcom"));
command
.arg(path)
.env("TERM", "xterm-256color")
.env("NO_COLOR", "1")
.env("RCOM_CONFIG_HOME", config_root);
Session::spawn(command).unwrap()
}
fn assert_contains(output: &[u8], expected: &[u8]) {
assert!(
output
@ -72,6 +85,166 @@ fn quit_restores_terminal_and_returns_success() {
let _ = quit_and_expect_restore(&mut session, 0);
}
#[test]
fn help_close_reopen_aliases_preserve_terminal_lifecycle() {
let fixture = TempDir::new().unwrap();
fs::write(fixture.path().join("readme.txt"), "fixture").unwrap();
let mut session = spawn_app(fixture.path());
session.get_process_mut().set_window_size(40, 8).unwrap();
session.expect("readme.txt").unwrap();
for (open, close) in [
("?", "\x1b"),
("\x1bOP", "\x1bOP"),
("?", "?"),
("\x1bOP", "q"),
] {
session.send(open).unwrap();
session.expect("< 1/6 Navigation >").unwrap();
session.send(close).unwrap();
session.expect("readme.txt").unwrap();
}
session.send("\x1b[21~").unwrap(); // F10
let output = session.expect(Eof).unwrap();
let status = session.get_process_mut().wait().unwrap();
assert!(matches!(status, WaitStatus::Exited(_, 0)));
assert_contains(output.as_bytes(), b"\x1b[?1049l");
assert_contains(output.as_bytes(), b"\x1b[?25h");
}
#[test]
fn image_halfblocks_render_in_pty_without_calling_substitute_tmux() {
use std::io::Cursor;
use std::os::unix::fs::PermissionsExt;
let fixture = TempDir::new().unwrap();
let tools = TempDir::new().unwrap();
let marker = tools.path().join("tmux-called");
let fake_tmux = tools.path().join("tmux");
fs::write(
&fake_tmux,
format!("#!/bin/sh\ntouch '{}'\n", marker.display()),
)
.unwrap();
let mut permissions = fs::metadata(&fake_tmux).unwrap().permissions();
permissions.set_mode(0o700);
fs::set_permissions(&fake_tmux, permissions).unwrap();
let mut pixels = image::ImageBuffer::from_pixel(10, 20, image::Rgba([255, 0, 0, 255]));
for (_, y, pixel) in pixels.enumerate_pixels_mut() {
if y >= 10 {
*pixel = image::Rgba([0, 0, 255, 255]);
}
}
let mut bytes = Cursor::new(Vec::new());
image::DynamicImage::ImageRgba8(pixels)
.write_to(&mut bytes, image::ImageFormat::Png)
.unwrap();
fs::write(fixture.path().join("pixel.png"), bytes.into_inner()).unwrap();
let mut command = Command::new(env!("CARGO_BIN_EXE_rcom"));
command
.arg(fixture.path())
.env("TERM", "xterm-256color")
.env_remove("TMUX")
.env("TERM_PROGRAM", "tmux")
.env(
"PATH",
format!(
"{}:{}",
tools.path().display(),
std::env::var("PATH").unwrap()
),
)
.env_remove("NO_COLOR");
let mut session = Session::spawn(command).unwrap();
session.get_process_mut().set_window_size(120, 30).unwrap();
session.expect("pixel.png").unwrap();
session.expect("▀").unwrap();
let _ = quit_and_expect_restore(&mut session, 0);
assert!(
!marker.exists(),
"rcom must not invoke tmux or change allow-passthrough"
);
}
#[test]
fn rapid_selection_burst_coalesces_preview_and_restores_terminal() {
let fixture = TempDir::new().unwrap();
for name in ["a.txt", "b.txt", "c.txt"] {
fs::write(fixture.path().join(name), format!("contents-{name}")).unwrap();
}
let mut session = spawn_app(fixture.path());
session.get_process_mut().set_window_size(120, 30).unwrap();
session.expect("contents-a.txt").unwrap();
session.send("jj").unwrap();
let output = session.expect("contents-c.txt").unwrap();
let output = output.as_bytes();
let loading_frames = output
.windows(b"LOADING PREVIEW".len())
.filter(|window| *window == b"LOADING PREVIEW")
.count();
assert!(loading_frames <= 1, "loading frames: {loading_frames}");
assert_contains(output, b"c.txt");
let _ = quit_and_expect_restore(&mut session, 0);
}
#[test]
fn theme_picker_escape_rolls_back_and_f10_quits_without_saving() {
let fixture = TempDir::new().unwrap();
let config = TempDir::new().unwrap();
fs::write(fixture.path().join("readme.txt"), "fixture").unwrap();
let config_path = config.path().join("config.toml");
fs::write(&config_path, "icons = \"ascii\"\ntheme = \"night-ops\"\n").unwrap();
let original = fs::read(&config_path).unwrap();
let mut session = spawn_app_with_config(fixture.path(), config.path());
session.expect("readme.txt").unwrap();
session.send("T").unwrap();
session.expect("THEMES").unwrap();
session.send("k").unwrap();
session.expect("Gruvbox Light").unwrap();
session.send("\x1b").unwrap();
std::thread::sleep(std::time::Duration::from_millis(100));
session.send("T").unwrap();
session.expect("12/20").unwrap();
session.send("j").unwrap();
session.expect("One Half Dark").unwrap();
session.send("\x1b[21~").unwrap(); // F10
let output = session.expect(Eof).unwrap();
let status = session.get_process_mut().wait().unwrap();
assert!(matches!(status, WaitStatus::Exited(_, 0)));
assert_eq!(fs::read(&config_path).unwrap(), original);
assert_contains(output.as_bytes(), b"\x1b[?1049l");
assert_contains(output.as_bytes(), b"\x1b[?25h");
}
#[test]
fn theme_picker_enter_persists_only_the_selected_theme_and_restores_terminal() {
let fixture = TempDir::new().unwrap();
let config = TempDir::new().unwrap();
fs::write(fixture.path().join("readme.txt"), "fixture").unwrap();
let config_path = config.path().join("config.toml");
fs::write(&config_path, "icons = \"none\"\nfuture_setting = true\n").unwrap();
let mut session = spawn_app_with_config(fixture.path(), config.path());
session.expect("readme.txt").unwrap();
session.send("T").unwrap();
session.expect("12/20").unwrap();
session.send("j").unwrap();
session.expect("One Half Dark").unwrap();
session.send("\r").unwrap();
session.expect("readme.txt").unwrap();
session.send("T").unwrap();
session.expect("13/20").unwrap();
session.send("\x1b").unwrap();
std::thread::sleep(std::time::Duration::from_millis(100));
let _ = quit_and_expect_restore(&mut session, 0);
let saved = fs::read_to_string(&config_path).unwrap();
assert!(saved.contains("theme = \"one-half-dark\""), "{saved}");
assert!(saved.contains("icons = \"none\""), "{saved}");
assert!(saved.contains("future_setting = true"), "{saved}");
assert_eq!(fs::read_dir(config.path()).unwrap().count(), 1);
}
#[test]
fn backend_error_is_visible_and_does_not_prevent_clean_quit() {
let fixture = TempDir::new().unwrap();

View file

@ -305,6 +305,7 @@ async fn a_new_preview_aborts_the_previous_preview_task() {
generation: 1,
target: Location::local("/workspace/readme.txt"),
session_epoch: None,
images_enabled: true,
};
let second = PreviewRequest {
generation: 2,
@ -408,6 +409,7 @@ async fn late_old_epoch_disconnects_preserve_new_handle_for_both_panes() {
generation: 2,
target: preview_target.clone(),
session_epoch: Some(first.epoch),
images_enabled: true,
}));
tokio::time::timeout(Duration::from_secs(2), listing_started.notified())
.await
@ -451,6 +453,7 @@ async fn late_old_epoch_disconnects_preserve_new_handle_for_both_panes() {
generation: 4,
target: preview_target,
session_epoch: Some(reconnected.epoch),
images_enabled: true,
}));
let (listing, preview) = receive_listing_and_preview(&mut results).await;
assert!(listing.result.is_ok());
@ -479,6 +482,7 @@ async fn old_epoch_resolve_errors_preserve_new_handle_for_both_panes() {
generation: 6,
target: Location::ssh(host.clone(), "/home/user/welcome.txt"),
session_epoch: Some(first.epoch),
images_enabled: true,
}));
let (listing, preview) = receive_listing_and_preview(&mut results).await;
@ -667,6 +671,7 @@ async fn dropping_runner_aborts_all_listing_connect_and_preview_tasks() {
generation: 3,
target: Location::local("/workspace/readme.txt"),
session_epoch: None,
images_enabled: true,
}));
fs_stats.wait_for_started(2).await;
connect_stats.wait_for_started(1).await;

View file

@ -2,10 +2,10 @@
source: tests/operation_ui.rs
expression: "draw(&app, 120, 36)"
---
RCOM dual-pane file manager DUAL PANE 1/2
RCOM dual-pane file manager DUAL PANE 1/2 ? Help
╭▸ ACTIVE · PANE 1/2 · LOCAL · /source─────────────────────╮╭ PANE 2/2 · LOCAL · /destination─────────────────────────╮
│ TYPE NAME SIZE MODIFIED ││EMPTY DIRECTORY │
│▸ FI╭CONFIRM COPY────────────────────────────────────────────────────────────────────────────────────────────────╮ │
│ NAME SIZE MODIFIED ││EMPTY DIRECTORY │
│▸ 📄 CONFIRM COPY────────────────────────────────────────────────────────────────────────────────────────────────╮ │
│ │Plan #1 / generation 1 │ │
│ │Items: unknown · Size: unknown │ │
│ │Destination: local:/destination │ │
@ -35,6 +35,6 @@ expression: "draw(&app, 120, 36)"
│ │ │ │
│ │ │ │
│ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ │
│ ││ │
╰──────────────────────────────────────────────────────────╯╰──────────────────────────────────────────────────────────╯
1 entries · Selected 1/1 · Dotfiles hidden
Space Select · y/x/p Yank/Cut/Paste · F5/F6 Copy/Move · t Tasks · ? Help · q Quit

View file

@ -2,7 +2,7 @@
source: tests/operation_ui.rs
expression: "draw(&app, 120, 36)"
---
RCOM dual-pane file manager DUAL PANE 1/2
RCOM dual-pane file manager DUAL PANE 1/2 ? Help
╭TASK DETAILS──────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│Task #1 · COPY · running │
│Source(s): 1 │
@ -37,4 +37,4 @@ expression: "draw(&app, 120, 36)"
│ │
│ │
╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
Space Select · y/x/p Yank/Cut/Paste · F5/F6 Copy/Move · t Tasks · ? Help · q Quit
1 entries · Selected 1/1 · Dotfiles hidden

View file

@ -2,11 +2,11 @@
source: tests/ui_accessibility.rs
expression: "draw(&app, 40, 8)"
---
╭HELP · yazi + mc──────────────────────╮
│ │
│PANES │
│Tab / Shift-Tab Switch active pane │
│\ Toggle single / dual│
│. Toggle hidden files │
│12-16/33 · j/k PgUp/Dn · Esc/?/q Close│
╭HELP──────────────────────────────────╮
│ < 3/6 Files > │
│ other pane │
│F6 Workspace: Move │
│ selection to the │
│ other pane │
│12-15/102 h/l j/k/Pg Esc/q/?/F1 │
╰──────────────────────────────────────╯

View file

@ -2,13 +2,14 @@
source: tests/ui_layout.rs
expression: output
---
RCOM dual-pane file manager DUAL PANE 1/2
RCOM dual-pane file manager DUAL PANE 1/2 ? Help
╭▸ ACTIVE · PANE 1/2 · LOCAL · /workspace/project──────────────────────────────╮╭ PANE 2/2 · SSH edge-prod · /srv/releases────────────────────────────────────╮
│ TYPE NAME SIZE MODIFIED ││ TYPE NAME SIZE MODIFIED │
│ DIR docs/ 4.0 KiB 2023-11-14 22:13││▸ DIR docs/ 4.0 KiB 2023-11-14 22:13│
│▸ FILE README.md 12 KiB 2023-11-14 22:13││ FILE README.md 12 KiB 2023-11-14 22:13│
│ FILE デ ー タ ー -αβγ.txt 768 B 2023-11-14 22:13││ FILE デ ー タ ー -αβγ.txt 768 B 2023-11-14 22:13│
│ LINK latest@ — 2023-11-14 22:13││ LINK latest@ — 2023-11-14 22:13│
│ NAME SIZE MODIFIED ││ NAME SIZE MODIFIED │
│ 📚 docs/ 4.0 KiB 2023-11-14 22:13││▸ 📚 docs/ 4.0 KiB 2023-11-14 22:13│
│▸ 📖 README.md 12 KiB 2023-11-14 22:13││ 📖 README.md 12 KiB 2023-11-14 22:13│
│ 📄 デ ー タ ー -αβγ.txt 768 B 2023-11-14 22:13││ 📄 デ ー タ ー -αβγ.txt 768 B 2023-11-14 22:13│
│ 🔗 latest@ — 2023-11-14 22:13││ 🔗 latest@ — 2023-11-14 22:13│
│ ││ │
│ ││ │
│ ││ │
│ ││ │
@ -41,4 +42,3 @@ expression: output
│ ││ │
╰──────────────────────────────────────────────────────────────────────────────╯╰──────────────────────────────────────────────────────────────────────────────╯
4 entries · Selected 2/4 · Dotfiles hidden
Space Select · y/x/p Yank/Cut/Paste · F5/F6 Copy/Move · t Tasks · ? Help · q Quit

View file

@ -2,13 +2,13 @@
source: tests/ui_layout.rs
expression: "draw(&sample_app(PaneMode::Single), None, 40, 10, Theme::default())"
---
RCOM dual-pane file manager SINGLE
RCOM SINGLE ? Help
╭▸ ACTIVE · LOCAL · /workspace/project─╮
│ TYPE NAME SIZE│
│ DIR docs/ 4.0 KiB│
│▸ FILE README.md 12 KiB│
│ FILE デ ー タ ー -αβγ.txt 768 B│
│ LINK latest@ —│
│ NAME SIZE│
│ 📚 docs/ 4.0 KiB│
│▸ 📖 README.md 12 KiB│
│ 📄 デ ー タ ー -αβγ.txt 768 B│
│ 🔗 latest@ —│
│ │
╰──────────────────────────────────────╯
4 entries · Selected…4 · Dotfiles hidden
Space Select · y/x/p…s · ? Help · q Quit

View file

@ -2,13 +2,14 @@
source: tests/ui_layout.rs
expression: "draw(&sample_app(PaneMode::Single), None, 80, 24, Theme::default())"
---
RCOM dual-pane file manager SINGLE
RCOM dual-pane file manager SINGLE ? Help
╭▸ ACTIVE · LOCAL · /workspace/project─────────────────────────────────────────╮
│ TYPE NAME SIZE MODIFIED │
│ DIR docs/ 4.0 KiB 2023-11-14 22:13│
│▸ FILE README.md 12 KiB 2023-11-14 22:13│
│ FILE デ ー タ ー -αβγ.txt 768 B 2023-11-14 22:13│
│ LINK latest@ — 2023-11-14 22:13│
│ NAME SIZE MODIFIED │
│ 📚 docs/ 4.0 KiB 2023-11-14 22:13│
│▸ 📖 README.md 12 KiB 2023-11-14 22:13│
│ 📄 デ ー タ ー -αβγ.txt 768 B 2023-11-14 22:13│
│ 🔗 latest@ — 2023-11-14 22:13│
│ │
│ │
│ │
│ │
@ -25,4 +26,3 @@ expression: "draw(&sample_app(PaneMode::Single), None, 80, 24, Theme::default())
│ │
╰──────────────────────────────────────────────────────────────────────────────╯
4 entries · Selected 2/4 · Dotfiles hidden
Space Select · y/x/p Yank/Cut/Paste · F5…6 Copy/Move · t Tasks · ? Help · q Quit

Some files were not shown because too many files have changed in this diff Show more