Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
31a57dc7a7 | ||
|
|
630fe31b76 | ||
|
|
08a5b014e0 | ||
|
|
819bc7d223 | ||
|
|
c38bfdd9b1 | ||
|
|
1643303b47 | ||
|
|
4761624fbe | ||
|
|
86f1fae02a | ||
|
|
7cf315967a | ||
|
|
023991d0a3 | ||
|
|
0ddd0bc50e | ||
|
|
476d0e628f | ||
|
|
a5692e5430 | ||
|
|
6a043802d7 | ||
|
|
76968f9e58 | ||
|
|
b75858b43a | ||
|
|
5fafff5eaf | ||
|
|
d21fa91315 | ||
|
|
b00767b457 | ||
|
|
63ab6a3e5b | ||
|
|
3c793fe659 | ||
|
|
8bc29faddc | ||
|
|
8ea20aa783 | ||
|
|
1b30f2bd26 | ||
|
|
657a5ff16e | ||
|
|
8fddd9e2c3 | ||
|
|
1a98c9b8bb | ||
|
|
98b78d29e6 | ||
|
|
81ccd93438 | ||
|
|
cbf699b680 | ||
|
|
ade20ab3dc | ||
|
|
f24e7750e6 | ||
|
|
097933882c | ||
|
|
b3578175c2 | ||
|
|
1cb02bf8e9 | ||
|
|
26c4191e0f | ||
|
|
7d683d6e67 | ||
|
|
e399c357d8 | ||
|
|
dd702524ca | ||
|
|
20792ed34f | ||
|
|
b8d0260607 | ||
|
|
6c0db643c4 | ||
|
|
ec6a5259d5 | ||
|
|
c92bf16cbf | ||
|
|
57028dfbc6 | ||
|
|
6fb190cf79 | ||
|
|
1148851585 | ||
|
|
eef4cc6b2b |
No files matched your search
@@ -0,0 +1,7 @@
|
|||||||
|
# Gitea liest die Vorlagen aus .github/ISSUE_TEMPLATE; diese Datei ersetzt dort nur die
|
||||||
|
# Kontakt-Links (der Verweis auf Gitea selbst entfällt).
|
||||||
|
blank_issues_enabled: true
|
||||||
|
contact_links:
|
||||||
|
- name: "Sicherheitslücke melden / Report a security issue"
|
||||||
|
url: https://gitea.pansi.eu/harald/ink-notes/src/branch/main/SECURITY.md
|
||||||
|
about: "Bitte vertraulich per E-Mail, nicht als öffentliches Issue. / Please report privately by e-mail, not as a public issue."
|
||||||
@@ -48,6 +48,9 @@ jobs:
|
|||||||
# schlagen cargo fmt und cargo clippy in den Quality Gates sofort fehl
|
# schlagen cargo fmt und cargo clippy in den Quality Gates sofort fehl
|
||||||
components: rustfmt, clippy
|
components: rustfmt, clippy
|
||||||
cache: true
|
cache: true
|
||||||
|
# No global -D warnings: it would also apply to the vendored winit (vendor/winit),
|
||||||
|
# which is built as a path dependency. The quality gates run clippy with -D warnings.
|
||||||
|
rustflags: ""
|
||||||
|
|
||||||
- name: Install rsign2 (Release-Signatur)
|
- name: Install rsign2 (Release-Signatur)
|
||||||
# RUSTFLAGS leeren: die Toolchain-Action setzt -D warnings, das soll nicht für rsign2 gelten
|
# RUSTFLAGS leeren: die Toolchain-Action setzt -D warnings, das soll nicht für rsign2 gelten
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
name: "Fehler melden / Bug report"
|
||||||
|
about: "Etwas funktioniert nicht wie erwartet / Something does not work as expected"
|
||||||
|
title: ""
|
||||||
|
---
|
||||||
|
|
||||||
|
<!-- Sicherheitslücken bitte nicht hier melden, siehe SECURITY.md. / Please report security issues privately, see SECURITY.md. -->
|
||||||
|
|
||||||
|
**Was passiert? / What happens?**
|
||||||
|
|
||||||
|
|
||||||
|
**Was hättest du erwartet? / What did you expect?**
|
||||||
|
|
||||||
|
|
||||||
|
**Schritte zum Nachstellen / Steps to reproduce**
|
||||||
|
1.
|
||||||
|
2.
|
||||||
|
3.
|
||||||
|
|
||||||
|
**Umgebung / Environment**
|
||||||
|
- ink-notes-Version / version (☰ → Updates):
|
||||||
|
- Installiert als / installed as (.deb, AppImage, Flatpak, selbst gebaut / built from source):
|
||||||
|
- Distribution:
|
||||||
|
- Wayland oder / or X11:
|
||||||
|
- Eingabegerät / input device (Stift / pen, Finger / touch, Maus / mouse, Touchpad):
|
||||||
|
|
||||||
|
**Bildschirmfoto, Aufnahme oder Ausgabe im Terminal / Screenshot, recording or terminal output**
|
||||||
|
<!-- Wenn möglich: ink-notes im Terminal starten und die Ausgabe hier einfügen. / If possible, start ink-notes in a terminal and paste its output here. -->
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
blank_issues_enabled: true
|
||||||
|
contact_links:
|
||||||
|
- name: "Issues auf Gitea (Hauptrepository) / Issues on Gitea (main repository)"
|
||||||
|
url: https://gitea.pansi.eu/harald/ink-notes/issues
|
||||||
|
about: "GitHub ist ein Spiegel; Issues werden bevorzugt auf Gitea bearbeitet. / GitHub is a mirror; issues are preferably handled on Gitea."
|
||||||
|
- name: "Sicherheitslücke melden / Report a security issue"
|
||||||
|
url: https://gitea.pansi.eu/harald/ink-notes/src/branch/main/SECURITY.md
|
||||||
|
about: "Bitte vertraulich per E-Mail, nicht als öffentliches Issue. / Please report privately by e-mail, not as a public issue."
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
---
|
||||||
|
name: "Idee vorschlagen / Feature request"
|
||||||
|
about: "Eine neue Funktion oder Verbesserung / A new feature or improvement"
|
||||||
|
title: ""
|
||||||
|
---
|
||||||
|
|
||||||
|
**Was möchtest du tun können? / What would you like to be able to do?**
|
||||||
|
|
||||||
|
|
||||||
|
**Wie machst du es bisher, und was stört dich daran? / How do you do it today, and what bothers you about it?**
|
||||||
|
|
||||||
|
|
||||||
|
**Wie könnte es aussehen? / How could it work?**
|
||||||
|
<!-- Skizzen, Bildschirmfotos oder Beispiele aus anderen Apps helfen. / Sketches, screenshots or examples from other apps help. -->
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<!-- GitHub ist ein Spiegel von https://gitea.pansi.eu/harald/ink-notes; Pull Requests werden dort von Hand übernommen. / GitHub is a mirror; pull requests are applied on Gitea by hand. -->
|
||||||
|
|
||||||
|
**Was ändert sich und warum? / What changes and why?**
|
||||||
|
|
||||||
|
|
||||||
|
**Zugehöriges Issue / Related issue:** #
|
||||||
|
|
||||||
|
**Checkliste / Checklist**
|
||||||
|
- [ ] `cargo fmt --check`, `cargo clippy --all-targets -- -D warnings` und / and `cargo test` laufen durch / pass
|
||||||
|
- [ ] Tests für neue Funktionen oder behobene Fehler / tests for new features or fixes
|
||||||
|
- [ ] Neue Texte der Oberfläche auch auf Englisch (`src/i18n/`) / new UI texts translated to English
|
||||||
|
- [ ] Änderungen am Dateiformat in `docs/FILE_FORMAT.md` beschrieben / file format changes documented (falls nötig / if needed)
|
||||||
|
- [ ] Ich habe CONTRIBUTING.md gelesen / I have read CONTRIBUTING.md
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
|
||||||
|
# Contributor Covenant Code of Conduct
|
||||||
|
|
||||||
|
## Our Pledge
|
||||||
|
|
||||||
|
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
|
||||||
|
|
||||||
|
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
||||||
|
|
||||||
|
## Our Standards
|
||||||
|
|
||||||
|
Examples of behavior that contributes to a positive environment for our community include:
|
||||||
|
|
||||||
|
* Demonstrating empathy and kindness toward other people
|
||||||
|
* Being respectful of differing opinions, viewpoints, and experiences
|
||||||
|
* Giving and gracefully accepting constructive feedback
|
||||||
|
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
||||||
|
* Focusing on what is best not just for us as individuals, but for the overall community
|
||||||
|
|
||||||
|
Examples of unacceptable behavior include:
|
||||||
|
|
||||||
|
* The use of sexualized language or imagery, and sexual attention or advances of any kind
|
||||||
|
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||||
|
* Public or private harassment
|
||||||
|
* Publishing others' private information, such as a physical or email address, without their explicit permission
|
||||||
|
* Other conduct which could reasonably be considered inappropriate in a professional setting
|
||||||
|
|
||||||
|
## Enforcement Responsibilities
|
||||||
|
|
||||||
|
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
||||||
|
|
||||||
|
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
||||||
|
|
||||||
|
## Enforcement
|
||||||
|
|
||||||
|
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at harald@pansi.eu. All complaints will be reviewed and investigated promptly and fairly.
|
||||||
|
|
||||||
|
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
||||||
|
|
||||||
|
## Enforcement Guidelines
|
||||||
|
|
||||||
|
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
||||||
|
|
||||||
|
### 1. Correction
|
||||||
|
|
||||||
|
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
||||||
|
|
||||||
|
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
||||||
|
|
||||||
|
### 2. Warning
|
||||||
|
|
||||||
|
**Community Impact**: A violation through a single incident or series of actions.
|
||||||
|
|
||||||
|
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
||||||
|
|
||||||
|
### 3. Temporary Ban
|
||||||
|
|
||||||
|
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
||||||
|
|
||||||
|
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
||||||
|
|
||||||
|
### 4. Permanent Ban
|
||||||
|
|
||||||
|
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
||||||
|
|
||||||
|
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
||||||
|
|
||||||
|
## Attribution
|
||||||
|
|
||||||
|
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
||||||
|
|
||||||
|
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
||||||
|
|
||||||
|
For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
|
||||||
|
|
||||||
|
[homepage]: https://www.contributor-covenant.org
|
||||||
|
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
||||||
|
[Mozilla CoC]: https://github.com/mozilla/diversity
|
||||||
|
[FAQ]: https://www.contributor-covenant.org/faq
|
||||||
|
[translations]: https://www.contributor-covenant.org/translations
|
||||||
|
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# Mitmachen bei ink-notes
|
||||||
|
|
||||||
|
[English](CONTRIBUTING.md) · **Deutsch**
|
||||||
|
|
||||||
|
Danke, dass du ink-notes verbessern willst!
|
||||||
|
|
||||||
|
## Wo?
|
||||||
|
|
||||||
|
Das Hauptrepository liegt auf **Gitea**: <https://gitea.pansi.eu/harald/ink-notes>.
|
||||||
|
[GitHub](https://github.com/haraldpansi-gif/ink-notes) ist ein Spiegel davon – Issues und Pull Requests sind dort auch willkommen, Pull Requests werden aber von Hand nach Gitea übernommen.
|
||||||
|
|
||||||
|
## Fehler melden und Ideen vorschlagen
|
||||||
|
|
||||||
|
- Bitte zuerst nachsehen, ob es schon ein [Issue](https://gitea.pansi.eu/harald/ink-notes/issues) dazu gibt.
|
||||||
|
- Für Fehler die Vorlage „Fehler melden“ verwenden: Version (☰ → Updates), Distribution, Wayland oder X11, Eingabegerät (Stift, Finger, Maus, Touchpad) und die Schritte, mit denen der Fehler auftritt. Ein Bildschirmfoto oder eine kurze Aufnahme hilft oft sehr.
|
||||||
|
- Deutsch und Englisch sind beide in Ordnung.
|
||||||
|
- **Sicherheitslücken bitte nicht öffentlich melden**, sondern wie in [SECURITY.de.md](SECURITY.de.md) beschrieben.
|
||||||
|
|
||||||
|
## Code beitragen
|
||||||
|
|
||||||
|
1. Größere Änderungen am besten vorher in einem Issue absprechen.
|
||||||
|
2. Bauen und testen, wie im [README](README.de.md#entwicklung) beschrieben. Vor dem Einreichen müssen diese Prüfungen durchlaufen (die CI prüft sie ebenfalls):
|
||||||
|
```bash
|
||||||
|
cargo fmt --check
|
||||||
|
cargo clippy --all-targets -- -D warnings
|
||||||
|
cargo test
|
||||||
|
```
|
||||||
|
3. Neue Funktionen und behobene Fehler bekommen einen Test, wo das sinnvoll geht.
|
||||||
|
4. Änderungen am Dateiformat bitte in [docs/FILE_FORMAT.de.md](docs/FILE_FORMAT.de.md) nachtragen; ältere Notizbücher müssen weiter lesbar bleiben.
|
||||||
|
5. Commit-Nachrichten im Stil von [Conventional Commits](https://www.conventionalcommits.org/), z. B. `fix: …`, `feat: …`, `perf: …`, `docs: …`; ein Bezug auf ein Issue als `(Issue #28)`. Neue Code-Kommentare und Commit-Nachrichten werden auf Englisch geschrieben (älterer Code und die Historie enthalten noch Deutsch).
|
||||||
|
6. Texte der Oberfläche gibt es auf Deutsch und Englisch: Neue Texte mit `t!("…")` schreiben und die englische Übersetzung unter `src/i18n/` ergänzen.
|
||||||
|
|
||||||
|
Mit dem Einreichen stimmst du zu, dass dein Beitrag unter der [MIT-Lizenz](LICENSE) des Projekts steht. Für den Umgang miteinander gilt der [Code of Conduct](CODE_OF_CONDUCT.md).
|
||||||
|
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# Contributing to ink-notes
|
||||||
|
|
||||||
|
**English** · [Deutsch](CONTRIBUTING.de.md)
|
||||||
|
|
||||||
|
Thank you for wanting to improve ink-notes!
|
||||||
|
|
||||||
|
## Where?
|
||||||
|
|
||||||
|
The main repository is on **Gitea**: <https://gitea.pansi.eu/harald/ink-notes>.
|
||||||
|
[GitHub](https://github.com/haraldpansi-gif/ink-notes) is a mirror – issues and pull requests are welcome there too, but pull requests are applied to Gitea by hand.
|
||||||
|
|
||||||
|
## Reporting bugs and suggesting ideas
|
||||||
|
|
||||||
|
- Please check first whether there is already an [issue](https://gitea.pansi.eu/harald/ink-notes/issues) for it.
|
||||||
|
- For bugs, use the "Bug report" template: version (☰ → Updates), distribution, Wayland or X11, input device (pen, finger, mouse, touchpad) and the steps that trigger the bug. A screenshot or a short recording often helps a lot.
|
||||||
|
- English and German are both fine.
|
||||||
|
- **Please do not report security vulnerabilities publicly**; follow [SECURITY.md](SECURITY.md) instead.
|
||||||
|
|
||||||
|
## Contributing code
|
||||||
|
|
||||||
|
1. Discuss larger changes in an issue first.
|
||||||
|
2. Build and test as described in the [README](README.md#development). These checks must pass before submitting (CI checks them too):
|
||||||
|
```bash
|
||||||
|
cargo fmt --check
|
||||||
|
cargo clippy --all-targets -- -D warnings
|
||||||
|
cargo test
|
||||||
|
```
|
||||||
|
3. New features and bug fixes get a test where that makes sense.
|
||||||
|
4. Document changes to the file format in [docs/FILE_FORMAT.md](docs/FILE_FORMAT.md) (and its German version); older notebooks must remain readable.
|
||||||
|
5. Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/), e.g. `fix: …`, `feat: …`, `perf: …`, `docs: …`; refer to an issue as `(Issue #28)`. New code comments and commit messages are written in English (older code and history still contain German).
|
||||||
|
6. The interface is available in German and English: write new texts with `t!("…")` (the German text is the key) and add the English translation in `src/i18n/`.
|
||||||
|
|
||||||
|
By contributing you agree that your contribution is licensed under the project's [MIT License](LICENSE). Everyone taking part is expected to follow the [Code of Conduct](CODE_OF_CONDUCT.md).
|
||||||
Generated
+4
-3
@@ -1393,7 +1393,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ink-notes"
|
name = "ink-notes"
|
||||||
version = "0.22.0"
|
version = "0.32.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"ab_glyph",
|
"ab_glyph",
|
||||||
"arboard",
|
"arboard",
|
||||||
@@ -1418,6 +1418,9 @@ dependencies = [
|
|||||||
"tempfile",
|
"tempfile",
|
||||||
"ureq",
|
"ureq",
|
||||||
"url",
|
"url",
|
||||||
|
"wayland-backend",
|
||||||
|
"wayland-client",
|
||||||
|
"wayland-protocols",
|
||||||
"webbrowser",
|
"webbrowser",
|
||||||
"wgpu",
|
"wgpu",
|
||||||
"winit",
|
"winit",
|
||||||
@@ -3715,8 +3718,6 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
|||||||
[[package]]
|
[[package]]
|
||||||
name = "winit"
|
name = "winit"
|
||||||
version = "0.29.15"
|
version = "0.29.15"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "0d59ad965a635657faf09c8f062badd885748428933dad8e8bdd64064d92e5ca"
|
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"ahash",
|
"ahash",
|
||||||
"android-activity",
|
"android-activity",
|
||||||
|
|||||||
+11
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "ink-notes"
|
name = "ink-notes"
|
||||||
version = "0.22.0"
|
version = "0.32.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
description = "Notizbuch-App für Stift, Touch und Maus unter Linux"
|
description = "Notizbuch-App für Stift, Touch und Maus unter Linux"
|
||||||
repository = "https://gitea.pansi.eu/harald/ink-notes"
|
repository = "https://gitea.pansi.eu/harald/ink-notes"
|
||||||
@@ -51,6 +51,11 @@ hayro-svg = "0.8"
|
|||||||
# Text-Werkzeug: Schriftmetriken und Rasterung (Schriften aus egui)
|
# Text-Werkzeug: Schriftmetriken und Rasterung (Schriften aus egui)
|
||||||
ab_glyph = "0.2"
|
ab_glyph = "0.2"
|
||||||
|
|
||||||
|
# Bildschirmtastatur unter Wayland anfordern (eigenes text-input-Objekt, siehe src/osk.rs)
|
||||||
|
wayland-client = "0.31"
|
||||||
|
wayland-backend = { version = "0.3", features = ["client_system"] }
|
||||||
|
wayland-protocols = { version = "0.31", features = ["client", "unstable"] }
|
||||||
|
|
||||||
[profile.dev]
|
[profile.dev]
|
||||||
opt-level = 1 # Erhöht Rendering-Performance auch im Debug-Modus
|
opt-level = 1 # Erhöht Rendering-Performance auch im Debug-Modus
|
||||||
|
|
||||||
@@ -64,3 +69,8 @@ strip = true
|
|||||||
tempfile = "3.27.0"
|
tempfile = "3.27.0"
|
||||||
# Prüft den WGSL-Shader in den Tests (dieselbe Version wie in wgpu 0.19)
|
# Prüft den WGSL-Shader in den Tests (dieselbe Version wie in wgpu 0.19)
|
||||||
naga = { version = "0.19", features = ["wgsl-in"] }
|
naga = { version = "0.19", features = ["wgsl-in"] }
|
||||||
|
|
||||||
|
# winit 0.29 with touch support for the client-side title bar on Wayland (Issue #36),
|
||||||
|
# see vendor/winit/README.ink-notes.md
|
||||||
|
[patch.crates-io]
|
||||||
|
winit = { path = "vendor/winit" }
|
||||||
+254
@@ -0,0 +1,254 @@
|
|||||||
|
<p align="center">
|
||||||
|
<img src="assets/ink-notes-banner.svg" alt="ink-notes Banner" width="100%">
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<strong>Eine moderne Notizbuch-App für Linux zum Schreiben mit Stift, Touch und Maus</strong><br>
|
||||||
|
Geschrieben in <strong>Rust</strong> mit <strong>wgpu</strong>, <strong>winit</strong> und <strong>egui</strong>.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center"><a href="README.md">English</a> · <strong>Deutsch</strong></p>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
ink-notes speichert Handschrift als Vektoren, erkennt auf Wunsch Formen, kann PDFs zum Beschriften importieren, Bilder und Textfelder einfügen und alles wieder als PDF, PNG oder SVG exportieren. Gespeichert wird automatisch im Hintergrund.
|
||||||
|
|
||||||
|
Getestet wird vor allem unter Zorin OS 18 / Ubuntu 24.04 (Wayland und X11).
|
||||||
|
|
||||||
|
Die Oberfläche gibt es auf Deutsch und Englisch; ink-notes folgt der Systemsprache, umstellen lässt sie sich im ☰-Menü unter „Sprache / Language“.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Funktionen
|
||||||
|
|
||||||
|
### Schreiben und Zeichnen
|
||||||
|
- **Vier Stifte** in der Werkzeugleiste, jeder mit eigener Farbe und Stärke (0,15–5 mm, mit Druckstärke). Ändert man Farbe oder Stärke, merkt sich der gewählte Stift das – auch über einen Neustart hinweg. **Textmarker** (halbtransparent, 4–8 mm) in vier Farben; innerhalb eines Strichs wird er nicht dunkler, erst ein neuer Strich deckt stärker.
|
||||||
|
- **Eigene Farben:** Jede Farbe in der Werkzeugleiste (Stifte, Textmarker, Text) lässt sich anpassen – gewählte Farbe erneut antippen, eine Vorgabe oder mit 🎨 einen freien Farbton wählen. Die Leiste merkt sich die Farben. Am Bildschirm erscheinen sie genauso wie im PDF- und Bildexport.
|
||||||
|
- **Glättung in zwei Stufen:** Während des Schreibens glättet ein 1€-Filter das Zittern, die Linie erscheint sofort. Beim Absetzen wird der Strich nachbearbeitet: Ecken (Knicke über 65°) bleiben erhalten und werden rund verbunden, der Druckverlauf wird geglättet, überflüssige Punkte entfallen, die Enden werden rund.
|
||||||
|
- **Druckkurve** im ☰-Menü an den eigenen Stift anpassen (weicher/härter, Schwelle gegen Grundrauschen).
|
||||||
|
- **Tasten am Stift** im ☰-Menü belegen: Radieren (Standard), Auswählen, Textmarker, Stift oder nichts – gilt, solange die Taste gedrückt ist. Jede Taste erscheint dort nach dem ersten Drücken.
|
||||||
|
- **Radierer** in drei Modi: ganze Striche, nur den überstrichenen Teil (Teilstrich) oder nur Textmarker. Die Stiftrückseite radiert ebenfalls.
|
||||||
|
- **Virtuelles Lineal** (`L`): verschieben, am Griff drehen (rastet bei 15° ein); Striche entlang einer Kante werden gerade.
|
||||||
|
- **Nur ansehen** (👁 in der Werkzeugleiste): Stift, Finger und Maus scrollen und zoomen nur; die Werkzeuge verschwinden, nichts lässt sich versehentlich ändern. Erneut 👁 tippen, um zu schreiben.
|
||||||
|
- **Platz schaffen** (↕ in der Werkzeugleiste): aufs Blatt tippen und nach unten ziehen – alles darunter rutscht mit, auch auf den folgenden Seiten. Was über ein Seitenende rutschen würde, beginnt auf der nächsten Seite; fehlende Seiten werden angehängt. Nach oben ziehen schließt leeren Platz. Ein Schritt für Rückgängig.
|
||||||
|
|
||||||
|
### Formerkennung
|
||||||
|
- **Formen-Werkzeug** (`S`/`F`) oder **Halten** am Strichende (über 400 ms stillhalten): Die Skizze wird durch eine saubere Form in der Breite des gewählten Stifts bzw. Textmarkers ersetzt.
|
||||||
|
- Erkannt werden Linien, Pfeile, Kreise, Ellipsen, Rechtecke, Dreiecke, Rauten, Vielecke, Koordinatensysteme (L-Form), Achsenkreuze (ein „+“ in einem Zug oder zwei gekreuzte Geraden, Pfeilspitzen an allen vier Enden) und Oktaeder (Skizze als 3D-Körper).
|
||||||
|
- Die Erkennung arbeitet rein geometrisch (Bogenlänge, Douglas-Peucker, Kreis-Fit), ohne Machine Learning. Nicht alles wird erkannt – was nicht passt, bleibt Handschrift.
|
||||||
|
|
||||||
|
### Auswählen und Bearbeiten
|
||||||
|
- **Auswahlwerkzeug** (`V`): antippen oder Rahmen aufziehen, dann verschieben, an den Ecken skalieren, am Griff drehen oder mit `R` um 90° drehen. Funktioniert mit Maus, Finger und Stift.
|
||||||
|
- Auswahl über die Palette **umfärben**, **kopieren/einfügen** (`Strg + C/V`), **löschen** (`Entf`).
|
||||||
|
- `Strg + C` legt die Auswahl zusätzlich als Bild in die Zwischenablage, z. B. für Chat oder Mail.
|
||||||
|
- **Rückgängig/Wiederholen** (`Strg + Z/Y`) für alle Änderungen, je Seite.
|
||||||
|
|
||||||
|
### Text, Bilder und PDFs
|
||||||
|
- **Text-Werkzeug** (`T`): ins Blatt tippen und schreiben – normale oder Code-Schrift (feste Zeichenbreite, Tab rückt ein), 8–36 pt, Zeilenumbruch am Feldrand. Vorhandenen Text antippen zum Ändern, `Esc` beendet. Textfelder lassen sich wie Bilder verschieben, drehen und skalieren. In anderen Programmen kopierter Text wird mit `Strg + V` zum Textfeld.
|
||||||
|
- **Bilder** (PNG, JPEG, GIF, WebP, BMP) über `Strg + I`, aus der Zwischenablage oder per Ziehen ins Fenster einfügen.
|
||||||
|
- **Einfügen per Finger:** Lange (½ s) mit dem Finger aufs Blatt drücken öffnet ein Menü „Einfügen“ – Screenshot, kopierter Text oder kopierte Objekte landen genau an dieser Stelle.
|
||||||
|
- **PDF importieren** (☰-Menü): Jede PDF-Seite wird eine Notizbuchseite mit der PDF-Seite als Hintergrund. Hochformat-Seiten werden DIN A4, Querformat-Seiten (z. B. Folien) bekommen eine Querformat-Seite ohne leeren Streifen darunter. Beim Hineinzoomen werden PDF-Seiten schärfer nachgerendert.
|
||||||
|
|
||||||
|
### Seiten und Ansicht
|
||||||
|
- **Hintergründe:** blanko, kariert (5 mm), liniert (7,5 mm), Punktraster (5 mm). Die **Farbe von Karos, Linien und Punkten** ist wählbar (hell, mittel, kräftig, blau, grün) und gilt auch im Export.
|
||||||
|
- **Papierfarbe** der Anzeige: weiß, creme, dunkelgrau, schwarz; auf dunklem Papier werden dunkle Stiftfarben auf Wunsch aufgehellt. Gespeichert und exportiert wird immer auf weißem Papier.
|
||||||
|
- **Durchgehendes Scrollen, endlose Fläche oder feste Seiten, je Notizbuch:** Beim Anlegen wählbar (Vorgabe: durchgehend; oder endlos), im ☰-Menü umschaltbar – dort auch auf feste Seiten (Seite für Seite blättern mit Pfeilen in der Werkzeugleiste). Durchgehend hängen die Seiten lückenlos untereinander, eine dunkle Linie markiert die Grenze; schnelles Wischen gleitet nach, und mit der Bildlaufleiste am Rand gegenüber der Werkzeugleiste springt man samt Seitenzahl durch lange PDFs; wer im unteren Fünftel der letzten Seite schreibt, bekommt automatisch eine neue Seite. Endlos ist eine einzige Fläche ohne Rand, die oben links beginnt und nach rechts und unten beliebig weitergeht; der PDF-Export enthält nur den beschriebenen Bereich.
|
||||||
|
- **Seiten einfügen und löschen:** ➕ in der Werkzeugleiste fügt nach der aktuellen Seite eine leere Seite ein. Löschen im ☰-Menü (mit Rückfrage); die zuletzt gelöschte Seite lässt sich dort wiederherstellen, solange die App läuft.
|
||||||
|
- **Zoom** von 25 % bis 1000 % (`Strg + Mausrad`, zwei Finger, `Strg + +/-/0`), Verschieben mit mittlerer Maustaste, `Leertaste + Ziehen` oder einem Finger.
|
||||||
|
- **Seiten** anhängen oder direkt nach der aktuellen Seite einfügen, **Seitentitel** vergeben; die Seitenübersicht zeigt Vorschaubilder oder ein Inhaltsverzeichnis. Seitentitel werden im PDF zu Lesezeichen.
|
||||||
|
- **Werkzeugleiste** links oder rechts andocken (für Links- und Rechtshänder).
|
||||||
|
|
||||||
|
### Notizbücher und Speichern
|
||||||
|
- Mehrere **Notizbücher** anlegen, umbenennen, wechseln und löschen (gelöschte landen zunächst im Papierkorb und lassen sich wiederherstellen).
|
||||||
|
- **Ordner** für Notizbücher, beliebig verschachtelt (z. B. 3. Semester › Mathe): anlegen, umbenennen, löschen (der Inhalt rückt eine Ebene nach oben) und Notizbücher wie Ordner (samt Inhalt) mit 📂 verschieben. Neue Notizbücher landen im gerade geöffneten Ordner.
|
||||||
|
- **Automatisches Speichern** im Hintergrund: 1,5 Sekunden nach der letzten Änderung, bei ununterbrochenem Schreiben spätestens alle 10 Sekunden. Zeichnen wird dabei nicht unterbrochen.
|
||||||
|
- Jede Datei wird erst vollständig in eine temporäre Datei geschrieben und dann ersetzt – ein Absturz beim Speichern hinterlässt keine halbe Datei.
|
||||||
|
- **Beim Schließen** (Fenster oder `Strg + Q`) und beim Wechsel des Notizbuchs wird alles Ausstehende geschrieben, bevor es weitergeht. Schlägt das fehl, bleibt die App offen und bietet Wiederholen oder eine Notfall-Sicherung an.
|
||||||
|
- `Strg + S` speichert sofort. Der Punkt am ☰-Knopf zeigt den Stand: grün = gespeichert, orange = Änderungen warten, gelb = speichert gerade, rot = Fehler.
|
||||||
|
|
||||||
|
### Export
|
||||||
|
- **PDF** (`Strg + E`) nach `~/Documents/<Titel>.pdf`: Striche und Formen als Vektoren, Textfelder als echter, durchsuchbarer Text, importierte PDF-Seiten als Vektor-Unterlage, Seitentitel als Lesezeichen.
|
||||||
|
- **Einzelne Seite** als PNG (mit oder ohne Hintergrund) oder SVG über das ☰-Menü.
|
||||||
|
|
||||||
|
### Eingabegeräte
|
||||||
|
- Stifte über das Tablet-Protokoll von Wayland bzw. X11 (Druck, Stiftrückseite, Seitentaste).
|
||||||
|
- Solange der Stift aufliegt oder in der Nähe ist, werden Berührungen mit der Hand ignoriert.
|
||||||
|
- Finger: standardmäßig scrollen und zoomen; Zeichnen mit dem Finger lässt sich im ☰-Menü einschalten.
|
||||||
|
|
||||||
|
### Updates
|
||||||
|
- Die App prüft auf neue Versionen auf Gitea und installiert sie auf Wunsch. Installiert wird nur, wenn die Minisign-Signatur und die SHA-256-Prüfsumme stimmen (Details unten).
|
||||||
|
- Als Flatpak sucht ink-notes nicht selbst nach Updates; die kommen dann über die Software-Verwaltung (`flatpak update`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
Pakete gibt es unter [Releases](https://gitea.pansi.eu/harald/ink-notes/releases) als `.deb` und `.AppImage` (x86_64). `<version>` steht für die Versionsnummer, z. B. `0.11.0`.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Debian-Paket (Zorin OS 18 / Ubuntu 24.04)
|
||||||
|
sudo apt install ./ink-notes_<version>_amd64.deb
|
||||||
|
|
||||||
|
# oder AppImage
|
||||||
|
chmod +x ink-notes_<version>_x86_64.AppImage
|
||||||
|
./ink-notes_<version>_x86_64.AppImage
|
||||||
|
```
|
||||||
|
|
||||||
|
Hinweise:
|
||||||
|
- Benötigt `glibc >= 2.39` (Ubuntu 24.04, Zorin OS 18) und einen Grafiktreiber mit Vulkan oder OpenGL.
|
||||||
|
- Meldet das AppImage einen Fehler zu `libfuse.so.2`, entweder `sudo apt install libfuse2t64` installieren oder mit `--appimage-extract-and-run` starten.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tastenkürzel
|
||||||
|
|
||||||
|
| Aktion | Taste / Geste |
|
||||||
|
| :--- | :--- |
|
||||||
|
| Zeichnen | Stiftspitze, linke Maustaste (Finger, wenn eingeschaltet) |
|
||||||
|
| Radieren | `E` umschalten, rechte Maustaste, Stiftrückseite oder Seitentaste |
|
||||||
|
| Stift in Schwarz / Blau / Rot | `B` / `U` / `R` |
|
||||||
|
| Formen-Werkzeug | `S` oder `F` |
|
||||||
|
| Auswahlwerkzeug | `V` |
|
||||||
|
| Text-Werkzeug | `T`, dann ins Blatt klicken; `Esc` beendet die Eingabe |
|
||||||
|
| Lineal ein/aus | `L` |
|
||||||
|
| Hintergrund wechseln | `G` |
|
||||||
|
| Auswahl um 90° drehen | `R` (bei Auswahl) |
|
||||||
|
| Kopieren / Einfügen | `Strg + C` / `Strg + V` |
|
||||||
|
| Auswahl löschen | `Entf` oder `Rücktaste` |
|
||||||
|
| Rückgängig / Wiederholen | `Strg + Z` / `Strg + Y` oder `Strg + Umschalt + Z` |
|
||||||
|
| Bild einfügen | `Strg + I` |
|
||||||
|
| Scrollen | Mausrad (`Umschalt` = waagerecht), ein Finger |
|
||||||
|
| Zoomen | `Strg + Mausrad`, zwei Finger, `Strg + +` / `Strg + -` |
|
||||||
|
| Zoom zurücksetzen | `Strg + 0` |
|
||||||
|
| Verschieben | mittlere Maustaste oder `Leertaste + Ziehen` |
|
||||||
|
| Nächste / vorherige Seite | `Bild ab` oder `N` / `Bild auf` |
|
||||||
|
| Erste / letzte Seite | `Pos 1` / `Ende` |
|
||||||
|
| Jetzt speichern | `Strg + S` |
|
||||||
|
| PDF exportieren | `Strg + E` |
|
||||||
|
| Menüs schließen, Auswahl aufheben | `Esc` |
|
||||||
|
| Beenden (speichert vorher) | `Strg + Q` oder Fenster schließen |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Entwicklung
|
||||||
|
|
||||||
|
### Voraussetzungen
|
||||||
|
- Rust 1.92 oder neuer (`rustup update stable`)
|
||||||
|
- Vulkan- oder OpenGL-Treiber (z. B. `mesa-vulkan-drivers`)
|
||||||
|
- X11-/Wayland-Bibliotheken: `libx11-dev`, `libxcursor-dev`, `libxrandr-dev`, `libxi-dev`, `libxkbcommon-dev`
|
||||||
|
|
||||||
|
### Bauen, starten, testen
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://gitea.pansi.eu/harald/ink-notes.git
|
||||||
|
cd ink-notes
|
||||||
|
cargo run --release # oder ./run.sh
|
||||||
|
cargo test # Unit- und Integrationstests
|
||||||
|
```
|
||||||
|
|
||||||
|
Die CI prüft zusätzlich `cargo fmt --check` und `cargo clippy --all-targets -- -D warnings`.
|
||||||
|
|
||||||
|
### Projektstruktur
|
||||||
|
|
||||||
|
```text
|
||||||
|
src/
|
||||||
|
├── main.rs # Event-Loop (winit), Eingaben von Maus, Touch und Stift, Ablaufsteuerung
|
||||||
|
├── lib.rs # Bibliotheks-Exporte (für Tests)
|
||||||
|
├── canvas.rs # wgpu-Rendering: Papier, Muster, Bilder, Tinte, Nachbarseiten
|
||||||
|
├── shader.wgsl # Vertex- und Fragment-Shader
|
||||||
|
├── viewport.rs # Kamera (Zoom, Verschieben), Seitenstapel der durchgehenden Ansicht
|
||||||
|
├── filter.rs # 1€-Filter gegen Zittern
|
||||||
|
├── spline.rs # Catmull-Rom-Splines, Ecken-Erhaltung, Dreiecksstreifen
|
||||||
|
├── geometry.rs # Formerkennung (Douglas-Peucker, Kreis-Fit, …)
|
||||||
|
├── selection.rs # Auswahl, Griffe, Verschieben/Drehen/Skalieren
|
||||||
|
├── ruler.rs # Virtuelles Lineal
|
||||||
|
├── text.rs # Textfelder: Satz, Zeilenumbruch, Rasterung
|
||||||
|
├── background.rs # Papierfarben, Musterfarben, Karo/Linien/Punkte
|
||||||
|
├── image_layer.rs # Texturen für Bilder, PDF-Seiten und Text
|
||||||
|
├── assets.rs # Bilder und PDFs im Notizbuchordner
|
||||||
|
├── pdf_doc.rs # PDF lesen und rendern (hayro)
|
||||||
|
├── pdf_merge.rs # Importierte PDF-Seiten beim Export unterlegen
|
||||||
|
├── document.rs # Datenmodell: Notizbuch, Seiten, Striche, Seitengrößen
|
||||||
|
├── history.rs # Rückgängig/Wiederholen
|
||||||
|
├── storage.rs # Laden/Speichern (atomar), Notizbücher, Papierkorb
|
||||||
|
├── library.rs # Ordner der Notizbücher (library.json)
|
||||||
|
├── autosave.rs # Speichern im Hintergrund
|
||||||
|
├── export.rs # PDF-Export (printpdf)
|
||||||
|
├── page_export.rs # Seite als PNG/SVG, Auswahl als Bild
|
||||||
|
├── file_picker.rs # Eingebaute Dateiauswahl
|
||||||
|
├── settings.rs # Einstellungen (~/.config/ink-notes/ui.json)
|
||||||
|
├── platform.rs # Wayland/X11-Erkennung
|
||||||
|
├── updater.rs # Updates von Gitea (Signatur- und Prüfsummenprüfung)
|
||||||
|
└── ui.rs # Oberfläche (egui): Werkzeugleiste, Menüs, Dialoge
|
||||||
|
```
|
||||||
|
|
||||||
|
Mehr dazu in [`docs/ARCHITECTURE.de.md`](docs/ARCHITECTURE.de.md), das Speicherformat steht in [`docs/FILE_FORMAT.de.md`](docs/FILE_FORMAT.de.md).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Releases bauen und veröffentlichen
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./scripts/build-release.sh # .deb, .AppImage und SHA256SUMS.txt in target/
|
||||||
|
```
|
||||||
|
|
||||||
|
Veröffentlicht wird über Gitea Actions ([`.gitea/workflows/release.yaml`](.gitea/workflows/release.yaml)), sobald ein Tag `vX.Y.Z` gepusht wird: Tests, Pakete bauen, signieren, Release anlegen. Manuell geht es mit `GITEA_TOKEN=… ./scripts/publish-gitea-release.sh`.
|
||||||
|
|
||||||
|
### Flatpak
|
||||||
|
|
||||||
|
Das Manifest liegt in [`packaging/flatpak/`](packaging/flatpak/) (Runtime `org.freedesktop.Platform` 26.08, Rust aus der SDK-Erweiterung `rust-stable`). Lokal bauen und installieren:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
flatpak-builder --user --install --force-clean target/flatpak-build packaging/flatpak/eu.pansi.ink-notes.yml
|
||||||
|
flatpak run eu.pansi.ink-notes
|
||||||
|
```
|
||||||
|
|
||||||
|
Nach jeder Änderung an `Cargo.lock` muss `packaging/flatpak/cargo-sources.json` mit dem [flatpak-cargo-generator](https://github.com/flatpak/flatpak-builder-tools/tree/master/cargo) neu erzeugt werden (`python3 flatpak-cargo-generator.py Cargo.lock -o packaging/flatpak/cargo-sources.json`). In der Sandbox darf ink-notes Bilder, Downloads und Schreibtisch lesen und in den Dokumente-Ordner exportieren; die Notizbücher liegen unter `~/.var/app/eu.pansi.ink-notes/`.
|
||||||
|
|
||||||
|
### Release-Signatur einrichten (einmalig)
|
||||||
|
|
||||||
|
Updates werden in der App nur mit gültiger Minisign-Signatur installiert. Signiert wird mit [rsign2](https://crates.io/crates/rsign2) (`cargo install rsign2 --locked`). Schlüsselpaar ohne Passwort erzeugen (es wird nur als CI-Secret verwendet):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
rsign generate -W -p ink-notes.pub -s ink-notes.key
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Die zweite Zeile von `ink-notes.pub` (beginnt mit `RW`) in `src/updater.rs` als `UPDATE_SIGNING_PUBLIC_KEY` eintragen.
|
||||||
|
2. Den Inhalt von `ink-notes.key` in Gitea unter *Repository → Einstellungen → Actions → Secrets* als `MINISIGN_SECRET_KEY` hinterlegen.
|
||||||
|
3. `ink-notes.key` offline aufbewahren. Geht er verloren, können bestehende Installationen keine Updates mehr prüfen.
|
||||||
|
|
||||||
|
`rsign generate -W` verschlüsselt den Schlüssel mit leerem Passwort; das `minisign`-Programm (z. B. Ubuntu-Paket 0.11) kann ihn ohne Terminal nicht lesen, deshalb signieren Skript und CI mit `rsign`. In der CI ist die Signatur Pflicht (`INK_NOTES_REQUIRE_SIGNATURE=1`), und das Skript prüft, dass der geheime Schlüssel zum eingebauten öffentlichen passt.
|
||||||
|
|
||||||
|
### CI-Runner (act_runner)
|
||||||
|
|
||||||
|
Der Workflow läuft auf dem Label `ubuntu-latest`. Im `config.yaml` des Runners muss es zugeordnet sein, z. B.:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
runner:
|
||||||
|
labels:
|
||||||
|
- "ubuntu-latest:docker://catthehacker/ubuntu:act-latest"
|
||||||
|
```
|
||||||
|
|
||||||
|
Bleibt ein Job auf „Waiting to run“ stehen: Ist der Runner online (*Einstellungen → Aktionen → Runner*) und stimmt das Label mit `runs-on` überein? `sudo` verwendet der Workflow nur, wenn der Runner nicht als `root` läuft.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Sicherheit der Updates
|
||||||
|
|
||||||
|
1. **Signatur:** Jedes Release enthält `SHA256SUMS.txt.minisig`. Die App lädt `SHA256SUMS.txt` und die Signatur vor dem Paket und prüft sie gegen den eingebauten öffentlichen Schlüssel (`minisign-verify`). Ohne gültige Signatur wird nicht installiert.
|
||||||
|
2. **Prüfsumme:** Der SHA-256-Wert des heruntergeladenen Pakets muss zum Eintrag in der signierten Liste passen, sonst wird die Datei gelöscht.
|
||||||
|
3. **Nur HTTPS:** Auch Download-Links und Weiterleitungen müssen HTTPS sein. Bei Weiterleitungen auf einen anderen Server wird der `Authorization`-Header nicht mitgeschickt.
|
||||||
|
4. **Eigener Download-Ordner:** `~/.cache/ink-notes/updates` (Rechte `0700`); Dateinamen mit Pfadtrennern, `..` oder Steuerzeichen werden abgelehnt.
|
||||||
|
5. **AppImage-Austausch:** Die neue Datei wird neben der alten angelegt, die alte als `.bak` gesichert und dann per `rename` ersetzt – die laufende Datei wird nie überschrieben.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Mitmachen
|
||||||
|
|
||||||
|
Fehlermeldungen, Ideen und Beiträge sind willkommen – am liebsten als [Issue auf Gitea](https://gitea.pansi.eu/harald/ink-notes/issues); [GitHub](https://github.com/haraldpansi-gif/ink-notes) ist ein Spiegel. Details in [CONTRIBUTING.de.md](CONTRIBUTING.de.md), Sicherheitslücken bitte vertraulich wie in [SECURITY.de.md](SECURITY.de.md) beschrieben. Es gilt der [Code of Conduct](CODE_OF_CONDUCT.md).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Lizenz
|
||||||
|
|
||||||
|
[MIT](LICENSE), Copyright © 2026 Harald Pansi.
|
||||||
@@ -1,210 +1,229 @@
|
|||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="assets/ink-notes-banner.svg" alt="ink-notes Banner" width="100%">
|
<img src="assets/ink-notes-banner-en.svg" alt="ink-notes banner" width="100%">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<strong>Eine moderne Notizbuch-App für Linux zum Schreiben mit Stift, Touch und Maus</strong><br>
|
<strong>A modern notebook app for Linux for writing with pen, touch and mouse</strong><br>
|
||||||
Geschrieben in <strong>Rust</strong> mit <strong>wgpu</strong>, <strong>winit</strong> und <strong>egui</strong>.
|
Written in <strong>Rust</strong> with <strong>wgpu</strong>, <strong>winit</strong> and <strong>egui</strong>.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
---
|
<p align="center"><strong>English</strong> · <a href="README.de.md">Deutsch</a></p>
|
||||||
|
|
||||||
ink-notes speichert Handschrift als Vektoren, erkennt auf Wunsch Formen, kann PDFs zum Beschriften importieren, Bilder und Textfelder einfügen und alles wieder als PDF, PNG oder SVG exportieren. Gespeichert wird automatisch im Hintergrund.
|
|
||||||
|
|
||||||
Getestet wird vor allem unter Zorin OS 18 / Ubuntu 24.04 (Wayland und X11).
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Funktionen
|
ink-notes stores handwriting as vectors, can recognize shapes, imports PDFs for annotation, inserts images and text boxes, and exports everything again as PDF, PNG or SVG. Saving happens automatically in the background.
|
||||||
|
|
||||||
### Schreiben und Zeichnen
|
It is mainly tested on Zorin OS 18 / Ubuntu 24.04 (Wayland and X11).
|
||||||
- **Vier Stifte** in der Werkzeugleiste, jeder mit eigener Farbe und Stärke (0,15–5 mm, mit Druckstärke). Ändert man Farbe oder Stärke, merkt sich der gewählte Stift das – auch über einen Neustart hinweg. **Textmarker** (halbtransparent, 4–8 mm) in vier Farben; innerhalb eines Strichs wird er nicht dunkler, erst ein neuer Strich deckt stärker.
|
|
||||||
- **Eigene Farben:** Jede Farbe in der Werkzeugleiste (Stifte, Textmarker, Text) lässt sich anpassen – gewählte Farbe erneut antippen, eine Vorgabe oder mit 🎨 einen freien Farbton wählen. Die Leiste merkt sich die Farben. Am Bildschirm erscheinen sie genauso wie im PDF- und Bildexport.
|
|
||||||
- **Glättung in zwei Stufen:** Während des Schreibens glättet ein 1€-Filter das Zittern, die Linie erscheint sofort. Beim Absetzen wird der Strich nachbearbeitet: Ecken (Knicke über 65°) bleiben erhalten, der Druckverlauf wird geglättet, überflüssige Punkte entfallen, die Enden werden rund.
|
|
||||||
- **Druckkurve** im ☰-Menü an den eigenen Stift anpassen (weicher/härter, Schwelle gegen Grundrauschen).
|
|
||||||
- **Tasten am Stift** im ☰-Menü belegen: Radieren (Standard), Auswählen, Textmarker, Stift oder nichts – gilt, solange die Taste gedrückt ist. Jede Taste erscheint dort nach dem ersten Drücken.
|
|
||||||
- **Radierer** in drei Modi: ganze Striche, nur den überstrichenen Teil (Teilstrich) oder nur Textmarker. Die Stiftrückseite radiert ebenfalls.
|
|
||||||
- **Virtuelles Lineal** (`L`): verschieben, am Griff drehen (rastet bei 15° ein); Striche entlang einer Kante werden gerade.
|
|
||||||
- **Platz schaffen** (↕ in der Werkzeugleiste): aufs Blatt tippen und nach unten ziehen – alles darunter rutscht mit, auch auf den folgenden Seiten. Was über ein Seitenende rutschen würde, beginnt auf der nächsten Seite; fehlende Seiten werden angehängt. Nach oben ziehen schließt leeren Platz. Ein Schritt für Rückgängig.
|
|
||||||
|
|
||||||
### Formerkennung
|
The interface is available in English and German; ink-notes follows the system language, and you can switch it in the ☰ menu under "Sprache / Language".
|
||||||
- **Formen-Werkzeug** (`S`/`F`) oder **Halten** am Strichende (über 400 ms stillhalten): Die Skizze wird durch eine saubere Form ersetzt.
|
|
||||||
- Erkannt werden Linien, Pfeile, Kreise, Ellipsen, Rechtecke, Dreiecke, Rauten, Vielecke, Koordinatensysteme (L-Form), Achsenkreuze (ein „+“ in einem Zug, Pfeilspitzen an allen vier Enden) und Oktaeder (Skizze als 3D-Körper).
|
|
||||||
- Die Erkennung arbeitet rein geometrisch (Bogenlänge, Douglas-Peucker, Kreis-Fit), ohne Machine Learning. Nicht alles wird erkannt – was nicht passt, bleibt Handschrift.
|
|
||||||
|
|
||||||
### Auswählen und Bearbeiten
|
---
|
||||||
- **Auswahlwerkzeug** (`V`): antippen oder Rahmen aufziehen, dann verschieben, an den Ecken skalieren, am Griff drehen oder mit `R` um 90° drehen. Funktioniert mit Maus, Finger und Stift.
|
|
||||||
- Auswahl über die Palette **umfärben**, **kopieren/einfügen** (`Strg + C/V`), **löschen** (`Entf`).
|
|
||||||
- `Strg + C` legt die Auswahl zusätzlich als Bild in die Zwischenablage, z. B. für Chat oder Mail.
|
|
||||||
- **Rückgängig/Wiederholen** (`Strg + Z/Y`) für alle Änderungen, je Seite.
|
|
||||||
|
|
||||||
### Text, Bilder und PDFs
|
## Features
|
||||||
- **Text-Werkzeug** (`T`): ins Blatt tippen und schreiben – normale oder Code-Schrift (feste Zeichenbreite, Tab rückt ein), 8–36 pt, Zeilenumbruch am Feldrand. Vorhandenen Text antippen zum Ändern, `Esc` beendet. Textfelder lassen sich wie Bilder verschieben, drehen und skalieren. In anderen Programmen kopierter Text wird mit `Strg + V` zum Textfeld.
|
|
||||||
- **Bilder** (PNG, JPEG, GIF, WebP, BMP) über `Strg + I`, aus der Zwischenablage oder per Ziehen ins Fenster einfügen.
|
|
||||||
- **Einfügen per Finger:** Lange (½ s) mit dem Finger aufs Blatt drücken öffnet ein Menü „Einfügen“ – Screenshot, kopierter Text oder kopierte Objekte landen genau an dieser Stelle.
|
|
||||||
- **PDF importieren** (☰-Menü): Jede PDF-Seite wird eine Notizbuchseite mit der PDF-Seite als Hintergrund. Hochformat-Seiten werden DIN A4, Querformat-Seiten (z. B. Folien) bekommen eine Querformat-Seite ohne leeren Streifen darunter. Beim Hineinzoomen werden PDF-Seiten schärfer nachgerendert.
|
|
||||||
|
|
||||||
### Seiten und Ansicht
|
### Writing and drawing
|
||||||
- **Hintergründe:** blanko, kariert (5 mm), liniert (7,5 mm), Punktraster (5 mm). Die **Farbe von Karos, Linien und Punkten** ist wählbar (hell, mittel, kräftig, blau, grün) und gilt auch im Export.
|
- **Four pens** in the toolbar, each with its own color and width (0.15–5 mm, pressure-sensitive). When you change a pen's color or width, it remembers that – also across restarts. **Highlighter** (semi-transparent, 4–8 mm) in four colors; it does not get darker within one stroke, only a new stroke covers more strongly.
|
||||||
- **Papierfarbe** der Anzeige: weiß, creme, dunkelgrau, schwarz; auf dunklem Papier werden dunkle Stiftfarben auf Wunsch aufgehellt. Gespeichert und exportiert wird immer auf weißem Papier.
|
- **Custom colors:** Every color in the toolbar (pens, highlighter, text) can be changed – tap the selected color again and pick a preset or any shade with 🎨. The toolbar remembers the colors. They look the same on screen as in PDF and image exports.
|
||||||
- **Durchgehendes Scrollen:** Seiten hängen lückenlos untereinander, eine dunkle Linie markiert die Grenze; wer im unteren Fünftel der letzten Seite schreibt, bekommt automatisch eine neue Seite. Abschaltbar (dann Seite für Seite blättern, mit Pfeilen in der Werkzeugleiste).
|
- **Two-stage smoothing:** While you write, a 1€ filter removes jitter and the line appears immediately. When you lift the pen, the stroke is refined: corners (bends over 65°) are kept and drawn round, the pressure curve is smoothed, redundant points are dropped and the ends become round.
|
||||||
- **Seiten einfügen und löschen:** ➕ in der Werkzeugleiste fügt nach der aktuellen Seite eine leere Seite ein. Löschen im ☰-Menü (mit Rückfrage); die zuletzt gelöschte Seite lässt sich dort wiederherstellen, solange die App läuft.
|
- **Pressure curve** adjustable to your pen in the ☰ menu (softer/harder, threshold against base noise).
|
||||||
- **Zoom** von 25 % bis 1000 % (`Strg + Mausrad`, zwei Finger, `Strg + +/-/0`), Verschieben mit mittlerer Maustaste, `Leertaste + Ziehen` oder einem Finger.
|
- **Pen buttons** can be assigned in the ☰ menu: erase (default), select, highlighter, pen or nothing – active while the button is held. Each button appears there after it is pressed for the first time.
|
||||||
- **Seiten** anhängen oder direkt nach der aktuellen Seite einfügen, **Seitentitel** vergeben; die Seitenübersicht zeigt Vorschaubilder oder ein Inhaltsverzeichnis. Seitentitel werden im PDF zu Lesezeichen.
|
- **Eraser** with three modes: whole strokes, only the part you wipe over (partial stroke), or highlighter only. The back end of the pen erases too.
|
||||||
- **Werkzeugleiste** links oder rechts andocken (für Links- und Rechtshänder).
|
- **Virtual ruler** (`L`): move it, rotate it by its handle (snaps to 15°); strokes along an edge become straight.
|
||||||
|
- **View only** (👁 in the toolbar): pen, finger and mouse only scroll and zoom; the tools disappear and nothing can be changed by accident. Tap 👁 again to write.
|
||||||
|
- **Make space** (↕ in the toolbar): tap the page and drag down – everything below moves along, also on the following pages. Whatever would slide past the end of a page continues on the next one; missing pages are appended. Dragging up closes empty space. Undo reverts it in one step.
|
||||||
|
|
||||||
### Notizbücher und Speichern
|
### Shape recognition
|
||||||
- Mehrere **Notizbücher** anlegen, umbenennen, wechseln und löschen (gelöschte landen zunächst im Papierkorb und lassen sich wiederherstellen).
|
- **Shape tool** (`S`/`F`) or **hold** at the end of a stroke (keep still for more than 400 ms): the sketch is replaced by a clean shape in the width of the current pen or highlighter.
|
||||||
- **Ordner** für Notizbücher, beliebig verschachtelt (z. B. 3. Semester › Mathe): anlegen, umbenennen, löschen (der Inhalt rückt eine Ebene nach oben) und Notizbücher wie Ordner (samt Inhalt) mit 📂 verschieben. Neue Notizbücher landen im gerade geöffneten Ordner.
|
- Recognized shapes: lines, arrows, circles, ellipses, rectangles, triangles, rhombuses, polygons, coordinate systems (L shape), axis crosses (a "+" in one stroke or two crossing straight lines, arrowheads on all four ends) and octahedra (sketch as a 3D solid).
|
||||||
- **Automatisches Speichern** im Hintergrund: 1,5 Sekunden nach der letzten Änderung, bei ununterbrochenem Schreiben spätestens alle 10 Sekunden. Zeichnen wird dabei nicht unterbrochen.
|
- Recognition is purely geometric (arc length, Douglas-Peucker, circle fitting), without machine learning. Not everything is recognized – whatever does not fit stays handwriting.
|
||||||
- Jede Datei wird erst vollständig in eine temporäre Datei geschrieben und dann ersetzt – ein Absturz beim Speichern hinterlässt keine halbe Datei.
|
|
||||||
- **Beim Schließen** (Fenster oder `Strg + Q`) und beim Wechsel des Notizbuchs wird alles Ausstehende geschrieben, bevor es weitergeht. Schlägt das fehl, bleibt die App offen und bietet Wiederholen oder eine Notfall-Sicherung an.
|
### Selecting and editing
|
||||||
- `Strg + S` speichert sofort. Der Punkt am ☰-Knopf zeigt den Stand: grün = gespeichert, orange = Änderungen warten, gelb = speichert gerade, rot = Fehler.
|
- **Selection tool** (`V`): tap or drag a frame, then move, scale by the corners, rotate by the handle, or rotate by 90° with `R`. Works with mouse, finger and pen.
|
||||||
|
- **Recolor** the selection with the palette, **copy/paste** (`Ctrl + C/V`), **delete** (`Del`).
|
||||||
|
- `Ctrl + C` also puts the selection on the clipboard as an image, e.g. for chat or email.
|
||||||
|
- **Undo/redo** (`Ctrl + Z/Y`) for all changes, per page.
|
||||||
|
|
||||||
|
### Text, images and PDFs
|
||||||
|
- **Text tool** (`T`): tap the page and type – regular or code font (fixed character width, Tab indents), 8–36 pt, line wrapping at the box edge. Tap existing text to change it, `Esc` finishes. Text boxes can be moved, rotated and scaled like images. Text copied in other programs becomes a text box with `Ctrl + V`.
|
||||||
|
- **Images** (PNG, JPEG, GIF, WebP, BMP) via `Ctrl + I`, from the clipboard, or by dragging them into the window.
|
||||||
|
- **Paste with a finger:** Pressing the page with a finger for half a second opens a "Paste" menu – a screenshot, copied text or copied objects land exactly at that spot.
|
||||||
|
- **Import PDF** (☰ menu): Every PDF page becomes a notebook page with the PDF page as background. Portrait pages become A4; landscape pages (e.g. slides) get a landscape page without an empty strip below. When you zoom in, PDF pages are re-rendered more sharply.
|
||||||
|
|
||||||
|
### Pages and view
|
||||||
|
- **Backgrounds:** blank, squared (5 mm), ruled (7.5 mm), dot grid (5 mm). The **color of squares, lines and dots** is selectable (light, medium, strong, blue, green) and also applies to exports.
|
||||||
|
- **Paper color** on screen: white, cream, dark gray, black; on dark paper, dark pen colors can optionally be brightened. Saving and exporting always use white paper.
|
||||||
|
- **Continuous scrolling, endless canvas or fixed pages, per notebook:** chosen when creating a notebook (default: continuous; or endless) and switchable in the ☰ menu – where fixed pages are available too (page by page with arrows in the toolbar). In continuous mode the pages hang seamlessly below each other with a dark line marking the boundary. A quick swipe keeps gliding, and the scrollbar on the edge opposite the toolbar jumps through long PDFs with the page number shown. Writing in the bottom fifth of the last page adds a new page automatically. Endless is a single borderless canvas that grows to the right and down as far as you like, starting at the top left; the PDF export only contains the area you used.
|
||||||
|
- **Insert and delete pages:** ➕ in the toolbar inserts an empty page after the current one. Delete it in the ☰ menu (with confirmation); the most recently deleted page can be restored there while the app is running.
|
||||||
|
- **Zoom** from 25 % to 1000 % (`Ctrl + mouse wheel`, two fingers, `Ctrl + +/-/0`), pan with the middle mouse button, `Space + drag` or one finger.
|
||||||
|
- **Pages** can be appended or inserted right after the current page, and given **page titles**; the page overview shows thumbnails or a table of contents. Page titles become bookmarks in the PDF.
|
||||||
|
- **Toolbar** can be docked left or right (for left- and right-handed use).
|
||||||
|
|
||||||
|
### Notebooks and saving
|
||||||
|
- Create, rename, switch and delete multiple **notebooks** (deleted ones go to the trash first and can be restored).
|
||||||
|
- **Folders** for notebooks, nested as deep as you like (e.g. Semester 3 › Math): create, rename, delete (the content moves up one level), and move notebooks and folders (with their content) with 📂. New notebooks are created in the folder that is currently open.
|
||||||
|
- **Automatic saving** in the background: 1.5 seconds after the last change, and at least every 10 seconds while you keep writing. Drawing is never interrupted.
|
||||||
|
- Every file is first written completely to a temporary file and then replaced – a crash while saving never leaves a half-written file.
|
||||||
|
- **When closing** (window or `Ctrl + Q`) and when switching notebooks, everything pending is written before continuing. If that fails, the app stays open and offers to retry or to make an emergency backup.
|
||||||
|
- `Ctrl + S` saves immediately. The dot on the ☰ button shows the state: green = saved, orange = changes pending, yellow = saving, red = error.
|
||||||
|
|
||||||
### Export
|
### Export
|
||||||
- **PDF** (`Strg + E`) nach `~/Documents/<Titel>.pdf`: Striche und Formen als Vektoren, Textfelder als echter, durchsuchbarer Text, importierte PDF-Seiten als Vektor-Unterlage, Seitentitel als Lesezeichen.
|
- **PDF** (`Ctrl + E`) to `~/Documents/<title>.pdf`: strokes and shapes as vectors, text boxes as real, searchable text, imported PDF pages as vector background, page titles as bookmarks.
|
||||||
- **Einzelne Seite** als PNG (mit oder ohne Hintergrund) oder SVG über das ☰-Menü.
|
- **Single page** as PNG (with or without background) or SVG via the ☰ menu.
|
||||||
|
|
||||||
### Eingabegeräte
|
### Input devices
|
||||||
- Stifte über das Tablet-Protokoll von Wayland bzw. X11 (Druck, Stiftrückseite, Seitentaste).
|
- Pens via the Wayland or X11 tablet protocol (pressure, eraser end, side button).
|
||||||
- Solange der Stift aufliegt oder in der Nähe ist, werden Berührungen mit der Hand ignoriert.
|
- While the pen touches the screen or hovers nearby, touches by the hand are ignored.
|
||||||
- Finger: standardmäßig scrollen und zoomen; Zeichnen mit dem Finger lässt sich im ☰-Menü einschalten.
|
- Fingers: scroll and zoom by default; drawing with a finger can be enabled in the ☰ menu.
|
||||||
|
|
||||||
### Updates
|
### Updates
|
||||||
- Die App prüft auf neue Versionen auf Gitea und installiert sie auf Wunsch. Installiert wird nur, wenn die Minisign-Signatur und die SHA-256-Prüfsumme stimmen (Details unten).
|
- The app checks Gitea for new versions and installs them on request. It only installs when the Minisign signature and the SHA-256 checksum match (details below).
|
||||||
|
- As a Flatpak, ink-notes does not look for updates itself; they come through the software manager (`flatpak update`).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
Pakete gibt es unter [Releases](https://gitea.pansi.eu/harald/ink-notes/releases) als `.deb` und `.AppImage` (x86_64). `<version>` steht für die Versionsnummer, z. B. `0.11.0`.
|
Packages are available under [Releases](https://gitea.pansi.eu/harald/ink-notes/releases) as `.deb` and `.AppImage` (x86_64). `<version>` stands for the version number, e.g. `0.30.2`.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Debian-Paket (Zorin OS 18 / Ubuntu 24.04)
|
# Debian package (Zorin OS 18 / Ubuntu 24.04)
|
||||||
sudo apt install ./ink-notes_<version>_amd64.deb
|
sudo apt install ./ink-notes_<version>_amd64.deb
|
||||||
|
|
||||||
# oder AppImage
|
# or AppImage
|
||||||
chmod +x ink-notes_<version>_x86_64.AppImage
|
chmod +x ink-notes_<version>_x86_64.AppImage
|
||||||
./ink-notes_<version>_x86_64.AppImage
|
./ink-notes_<version>_x86_64.AppImage
|
||||||
```
|
```
|
||||||
|
|
||||||
Hinweise:
|
Notes:
|
||||||
- Benötigt `glibc >= 2.39` (Ubuntu 24.04, Zorin OS 18) und einen Grafiktreiber mit Vulkan oder OpenGL.
|
- Requires `glibc >= 2.39` (Ubuntu 24.04, Zorin OS 18) and a graphics driver with Vulkan or OpenGL.
|
||||||
- Meldet das AppImage einen Fehler zu `libfuse.so.2`, entweder `sudo apt install libfuse2t64` installieren oder mit `--appimage-extract-and-run` starten.
|
- If the AppImage reports an error about `libfuse.so.2`, either install `sudo apt install libfuse2t64` or start it with `--appimage-extract-and-run`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Tastenkürzel
|
## Keyboard shortcuts
|
||||||
|
|
||||||
| Aktion | Taste / Geste |
|
| Action | Key / gesture |
|
||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
| Zeichnen | Stiftspitze, linke Maustaste (Finger, wenn eingeschaltet) |
|
| Draw | Pen tip, left mouse button (finger, if enabled) |
|
||||||
| Radieren | `E` umschalten, rechte Maustaste, Stiftrückseite oder Seitentaste |
|
| Erase | toggle with `E`, right mouse button, pen eraser end or side button |
|
||||||
| Stift in Schwarz / Blau / Rot | `B` / `U` / `R` |
|
| Pen in black / blue / red | `B` / `U` / `R` |
|
||||||
| Formen-Werkzeug | `S` oder `F` |
|
| Shape tool | `S` or `F` |
|
||||||
| Auswahlwerkzeug | `V` |
|
| Selection tool | `V` |
|
||||||
| Text-Werkzeug | `T`, dann ins Blatt klicken; `Esc` beendet die Eingabe |
|
| Text tool | `T`, then click on the page; `Esc` finishes typing |
|
||||||
| Lineal ein/aus | `L` |
|
| Ruler on/off | `L` |
|
||||||
| Hintergrund wechseln | `G` |
|
| Change background | `G` |
|
||||||
| Auswahl um 90° drehen | `R` (bei Auswahl) |
|
| Rotate selection by 90° | `R` (with a selection) |
|
||||||
| Kopieren / Einfügen | `Strg + C` / `Strg + V` |
|
| Copy / paste | `Ctrl + C` / `Ctrl + V` |
|
||||||
| Auswahl löschen | `Entf` oder `Rücktaste` |
|
| Delete selection | `Del` or `Backspace` |
|
||||||
| Rückgängig / Wiederholen | `Strg + Z` / `Strg + Y` oder `Strg + Umschalt + Z` |
|
| Undo / redo | `Ctrl + Z` / `Ctrl + Y` or `Ctrl + Shift + Z` |
|
||||||
| Bild einfügen | `Strg + I` |
|
| Insert image | `Ctrl + I` |
|
||||||
| Scrollen | Mausrad (`Umschalt` = waagerecht), ein Finger |
|
| Scroll | mouse wheel (`Shift` = horizontal), one finger |
|
||||||
| Zoomen | `Strg + Mausrad`, zwei Finger, `Strg + +` / `Strg + -` |
|
| Zoom | `Ctrl + mouse wheel`, two fingers, `Ctrl + +` / `Ctrl + -` |
|
||||||
| Zoom zurücksetzen | `Strg + 0` |
|
| Reset zoom | `Ctrl + 0` |
|
||||||
| Verschieben | mittlere Maustaste oder `Leertaste + Ziehen` |
|
| Pan | middle mouse button or `Space + drag` |
|
||||||
| Nächste / vorherige Seite | `Bild ab` oder `N` / `Bild auf` |
|
| Next / previous page | `Page Down` or `N` / `Page Up` |
|
||||||
| Erste / letzte Seite | `Pos 1` / `Ende` |
|
| First / last page | `Home` / `End` |
|
||||||
| Jetzt speichern | `Strg + S` |
|
| Save now | `Ctrl + S` |
|
||||||
| PDF exportieren | `Strg + E` |
|
| Export PDF | `Ctrl + E` |
|
||||||
| Menüs schließen, Auswahl aufheben | `Esc` |
|
| Close menus, clear selection | `Esc` |
|
||||||
| Beenden (speichert vorher) | `Strg + Q` oder Fenster schließen |
|
| Quit (saves first) | `Ctrl + Q` or close the window |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Entwicklung
|
## Development
|
||||||
|
|
||||||
### Voraussetzungen
|
### Requirements
|
||||||
- Rust 1.92 oder neuer (`rustup update stable`)
|
- Rust 1.92 or newer (`rustup update stable`)
|
||||||
- Vulkan- oder OpenGL-Treiber (z. B. `mesa-vulkan-drivers`)
|
- Vulkan or OpenGL driver (e.g. `mesa-vulkan-drivers`)
|
||||||
- X11-/Wayland-Bibliotheken: `libx11-dev`, `libxcursor-dev`, `libxrandr-dev`, `libxi-dev`, `libxkbcommon-dev`
|
- X11/Wayland libraries: `libx11-dev`, `libxcursor-dev`, `libxrandr-dev`, `libxi-dev`, `libxkbcommon-dev`
|
||||||
|
|
||||||
### Bauen, starten, testen
|
### Build, run, test
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://gitea.pansi.eu/harald/ink-notes.git
|
git clone https://gitea.pansi.eu/harald/ink-notes.git
|
||||||
cd ink-notes
|
cd ink-notes
|
||||||
cargo run --release # oder ./run.sh
|
cargo run --release # or ./run.sh
|
||||||
cargo test # Unit- und Integrationstests
|
cargo test # unit and integration tests
|
||||||
```
|
```
|
||||||
|
|
||||||
Die CI prüft zusätzlich `cargo fmt --check` und `cargo clippy --all-targets -- -D warnings`.
|
CI additionally checks `cargo fmt --check` and `cargo clippy --all-targets -- -D warnings`.
|
||||||
|
|
||||||
### Projektstruktur
|
New code comments and commit messages are written in English; older code and history still contain German.
|
||||||
|
|
||||||
|
### Project structure
|
||||||
|
|
||||||
```text
|
```text
|
||||||
src/
|
src/
|
||||||
├── main.rs # Event-Loop (winit), Eingaben von Maus, Touch und Stift, Ablaufsteuerung
|
├── main.rs # Event loop (winit), mouse, touch and pen input, control flow
|
||||||
├── lib.rs # Bibliotheks-Exporte (für Tests)
|
├── lib.rs # Library exports (for tests)
|
||||||
├── canvas.rs # wgpu-Rendering: Papier, Muster, Bilder, Tinte, Nachbarseiten
|
├── canvas.rs # wgpu rendering: paper, patterns, images, ink, neighboring pages
|
||||||
├── shader.wgsl # Vertex- und Fragment-Shader
|
├── shader.wgsl # Vertex and fragment shaders
|
||||||
├── viewport.rs # Kamera (Zoom, Verschieben), Seitenstapel der durchgehenden Ansicht
|
├── viewport.rs # Camera (zoom, pan), page stack of the continuous view, swipe momentum
|
||||||
├── filter.rs # 1€-Filter gegen Zittern
|
├── filter.rs # 1€ filter against jitter
|
||||||
├── spline.rs # Catmull-Rom-Splines, Ecken-Erhaltung, Dreiecksstreifen
|
├── spline.rs # Catmull-Rom splines, corner preservation, triangle strips
|
||||||
├── geometry.rs # Formerkennung (Douglas-Peucker, Kreis-Fit, …)
|
├── geometry.rs # Shape recognition (Douglas-Peucker, circle fitting, …)
|
||||||
├── selection.rs # Auswahl, Griffe, Verschieben/Drehen/Skalieren
|
├── selection.rs # Selection, handles, move/rotate/scale
|
||||||
├── ruler.rs # Virtuelles Lineal
|
├── ruler.rs # Virtual ruler
|
||||||
├── text.rs # Textfelder: Satz, Zeilenumbruch, Rasterung
|
├── text.rs # Text boxes: layout, line wrapping, rasterization
|
||||||
├── background.rs # Papierfarben, Musterfarben, Karo/Linien/Punkte
|
├── background.rs # Paper colors, pattern colors, squares/lines/dots
|
||||||
├── image_layer.rs # Texturen für Bilder, PDF-Seiten und Text
|
├── image_layer.rs # Textures for images, PDF pages and text
|
||||||
├── assets.rs # Bilder und PDFs im Notizbuchordner
|
├── assets.rs # Images and PDFs in the notebook folder
|
||||||
├── pdf_doc.rs # PDF lesen und rendern (hayro)
|
├── pdf_doc.rs # Reading and rendering PDFs (hayro)
|
||||||
├── pdf_merge.rs # Importierte PDF-Seiten beim Export unterlegen
|
├── pdf_merge.rs # Underlaying imported PDF pages on export
|
||||||
├── document.rs # Datenmodell: Notizbuch, Seiten, Striche, Seitengrößen
|
├── document.rs # Data model: notebook, pages, strokes, page sizes
|
||||||
├── history.rs # Rückgängig/Wiederholen
|
├── history.rs # Undo/redo
|
||||||
├── storage.rs # Laden/Speichern (atomar), Notizbücher, Papierkorb
|
├── storage.rs # Loading/saving (atomic), notebooks, trash
|
||||||
├── library.rs # Ordner der Notizbücher (library.json)
|
├── library.rs # Notebook folders (library.json)
|
||||||
├── autosave.rs # Speichern im Hintergrund
|
├── autosave.rs # Saving in the background
|
||||||
├── export.rs # PDF-Export (printpdf)
|
├── export.rs # PDF export (printpdf)
|
||||||
├── page_export.rs # Seite als PNG/SVG, Auswahl als Bild
|
├── page_export.rs # Page as PNG/SVG, selection as image
|
||||||
├── file_picker.rs # Eingebaute Dateiauswahl
|
├── file_picker.rs # Built-in file picker
|
||||||
├── settings.rs # Einstellungen (~/.config/ink-notes/ui.json)
|
├── settings.rs # Settings (~/.config/ink-notes/ui.json)
|
||||||
├── platform.rs # Wayland/X11-Erkennung
|
├── platform.rs # Wayland/X11 detection
|
||||||
├── updater.rs # Updates von Gitea (Signatur- und Prüfsummenprüfung)
|
├── updater.rs # Updates from Gitea (signature and checksum verification)
|
||||||
└── ui.rs # Oberfläche (egui): Werkzeugleiste, Menüs, Dialoge
|
└── ui.rs # Interface (egui): toolbar, menus, dialogs
|
||||||
```
|
```
|
||||||
|
|
||||||
Mehr dazu in [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md), das Speicherformat steht in [`docs/FILE_FORMAT.md`](docs/FILE_FORMAT.md).
|
More in [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md); the storage format is described in [`docs/FILE_FORMAT.md`](docs/FILE_FORMAT.md).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Releases bauen und veröffentlichen
|
## Building and publishing releases
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
./scripts/build-release.sh # .deb, .AppImage und SHA256SUMS.txt in target/
|
./scripts/build-release.sh # .deb, .AppImage and SHA256SUMS.txt in target/
|
||||||
```
|
```
|
||||||
|
|
||||||
Veröffentlicht wird über Gitea Actions ([`.gitea/workflows/release.yaml`](.gitea/workflows/release.yaml)), sobald ein Tag `vX.Y.Z` gepusht wird: Tests, Pakete bauen, signieren, Release anlegen. Manuell geht es mit `GITEA_TOKEN=… ./scripts/publish-gitea-release.sh`.
|
Releases are published by Gitea Actions ([`.gitea/workflows/release.yaml`](.gitea/workflows/release.yaml)) as soon as a tag `vX.Y.Z` is pushed: tests, build packages, sign, create the release. To do it manually: `GITEA_TOKEN=… ./scripts/publish-gitea-release.sh`.
|
||||||
|
|
||||||
### Release-Signatur einrichten (einmalig)
|
### Flatpak
|
||||||
|
|
||||||
Updates werden in der App nur mit gültiger Minisign-Signatur installiert. Signiert wird mit [rsign2](https://crates.io/crates/rsign2) (`cargo install rsign2 --locked`). Schlüsselpaar ohne Passwort erzeugen (es wird nur als CI-Secret verwendet):
|
The manifest is in [`packaging/flatpak/`](packaging/flatpak/) (runtime `org.freedesktop.Platform` 26.08, Rust from the SDK extension `rust-stable`). Build and install locally:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
flatpak-builder --user --install --force-clean target/flatpak-build packaging/flatpak/eu.pansi.ink-notes.yml
|
||||||
|
flatpak run eu.pansi.ink-notes
|
||||||
|
```
|
||||||
|
|
||||||
|
After every change to `Cargo.lock`, `packaging/flatpak/cargo-sources.json` must be regenerated with the [flatpak-cargo-generator](https://github.com/flatpak/flatpak-builder-tools/tree/master/cargo) (`python3 flatpak-cargo-generator.py Cargo.lock -o packaging/flatpak/cargo-sources.json`). In the sandbox, ink-notes may read Pictures, Downloads and Desktop and export to the Documents folder; the notebooks live under `~/.var/app/eu.pansi.ink-notes/`.
|
||||||
|
|
||||||
|
### Setting up the release signature (once)
|
||||||
|
|
||||||
|
The app only installs updates with a valid Minisign signature. Signing uses [rsign2](https://crates.io/crates/rsign2) (`cargo install rsign2 --locked`). Generate a key pair without a password (it is only used as a CI secret):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
rsign generate -W -p ink-notes.pub -s ink-notes.key
|
rsign generate -W -p ink-notes.pub -s ink-notes.key
|
||||||
```
|
```
|
||||||
|
|
||||||
1. Die zweite Zeile von `ink-notes.pub` (beginnt mit `RW`) in `src/updater.rs` als `UPDATE_SIGNING_PUBLIC_KEY` eintragen.
|
1. Put the second line of `ink-notes.pub` (starting with `RW`) into `src/updater.rs` as `UPDATE_SIGNING_PUBLIC_KEY`.
|
||||||
2. Den Inhalt von `ink-notes.key` in Gitea unter *Repository → Einstellungen → Actions → Secrets* als `MINISIGN_SECRET_KEY` hinterlegen.
|
2. Store the content of `ink-notes.key` in Gitea under *Repository → Settings → Actions → Secrets* as `MINISIGN_SECRET_KEY`.
|
||||||
3. `ink-notes.key` offline aufbewahren. Geht er verloren, können bestehende Installationen keine Updates mehr prüfen.
|
3. Keep `ink-notes.key` offline. If it is lost, existing installations can no longer verify updates.
|
||||||
|
|
||||||
`rsign generate -W` verschlüsselt den Schlüssel mit leerem Passwort; das `minisign`-Programm (z. B. Ubuntu-Paket 0.11) kann ihn ohne Terminal nicht lesen, deshalb signieren Skript und CI mit `rsign`. In der CI ist die Signatur Pflicht (`INK_NOTES_REQUIRE_SIGNATURE=1`), und das Skript prüft, dass der geheime Schlüssel zum eingebauten öffentlichen passt.
|
`rsign generate -W` encrypts the key with an empty password; the `minisign` program (e.g. Ubuntu package 0.11) cannot read it without a terminal, which is why the script and CI sign with `rsign`. In CI the signature is mandatory (`INK_NOTES_REQUIRE_SIGNATURE=1`), and the script checks that the secret key matches the built-in public key.
|
||||||
|
|
||||||
### CI-Runner (act_runner)
|
### CI runner (act_runner)
|
||||||
|
|
||||||
Der Workflow läuft auf dem Label `ubuntu-latest`. Im `config.yaml` des Runners muss es zugeordnet sein, z. B.:
|
The workflow runs on the label `ubuntu-latest`. It must be mapped in the runner's `config.yaml`, e.g.:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
runner:
|
runner:
|
||||||
@@ -212,20 +231,26 @@ runner:
|
|||||||
- "ubuntu-latest:docker://catthehacker/ubuntu:act-latest"
|
- "ubuntu-latest:docker://catthehacker/ubuntu:act-latest"
|
||||||
```
|
```
|
||||||
|
|
||||||
Bleibt ein Job auf „Waiting to run“ stehen: Ist der Runner online (*Einstellungen → Aktionen → Runner*) und stimmt das Label mit `runs-on` überein? `sudo` verwendet der Workflow nur, wenn der Runner nicht als `root` läuft.
|
If a job stays at "Waiting to run": is the runner online (*Settings → Actions → Runners*) and does the label match `runs-on`? The workflow only uses `sudo` when the runner does not run as `root`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Sicherheit der Updates
|
## Update security
|
||||||
|
|
||||||
1. **Signatur:** Jedes Release enthält `SHA256SUMS.txt.minisig`. Die App lädt `SHA256SUMS.txt` und die Signatur vor dem Paket und prüft sie gegen den eingebauten öffentlichen Schlüssel (`minisign-verify`). Ohne gültige Signatur wird nicht installiert.
|
1. **Signature:** Every release contains `SHA256SUMS.txt.minisig`. The app downloads `SHA256SUMS.txt` and the signature before the package and verifies them against the built-in public key (`minisign-verify`). Without a valid signature, nothing is installed.
|
||||||
2. **Prüfsumme:** Der SHA-256-Wert des heruntergeladenen Pakets muss zum Eintrag in der signierten Liste passen, sonst wird die Datei gelöscht.
|
2. **Checksum:** The SHA-256 of the downloaded package must match the entry in the signed list, otherwise the file is deleted.
|
||||||
3. **Nur HTTPS:** Auch Download-Links und Weiterleitungen müssen HTTPS sein. Bei Weiterleitungen auf einen anderen Server wird der `Authorization`-Header nicht mitgeschickt.
|
3. **HTTPS only:** Download links and redirects must be HTTPS too. On redirects to a different server, the `Authorization` header is not sent along.
|
||||||
4. **Eigener Download-Ordner:** `~/.cache/ink-notes/updates` (Rechte `0700`); Dateinamen mit Pfadtrennern, `..` oder Steuerzeichen werden abgelehnt.
|
4. **Dedicated download folder:** `~/.cache/ink-notes/updates` (permissions `0700`); file names with path separators, `..` or control characters are rejected.
|
||||||
5. **AppImage-Austausch:** Die neue Datei wird neben der alten angelegt, die alte als `.bak` gesichert und dann per `rename` ersetzt – die laufende Datei wird nie überschrieben.
|
5. **AppImage replacement:** The new file is created next to the old one, the old one is kept as `.bak` and then replaced with `rename` – the running file is never overwritten.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Lizenz
|
## Contributing
|
||||||
|
|
||||||
|
Bug reports, ideas and contributions are welcome – preferably as an [issue on Gitea](https://gitea.pansi.eu/harald/ink-notes/issues); [GitHub](https://github.com/haraldpansi-gif/ink-notes) is a mirror. Issues may be written in English or German. Details in [CONTRIBUTING.md](CONTRIBUTING.md); please report security vulnerabilities privately as described in [SECURITY.md](SECURITY.md). The [Code of Conduct](CODE_OF_CONDUCT.md) applies.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
[MIT](LICENSE), Copyright © 2026 Harald Pansi.
|
[MIT](LICENSE), Copyright © 2026 Harald Pansi.
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
# Sicherheit
|
||||||
|
|
||||||
|
[English](SECURITY.md) · **Deutsch**
|
||||||
|
|
||||||
|
## Unterstützte Versionen
|
||||||
|
|
||||||
|
Sicherheitskorrekturen gibt es nur für die jeweils **neueste Version** (siehe [Releases](https://gitea.pansi.eu/harald/ink-notes/releases)). Die App bietet Updates selbst an (☰ → Updates); als Flatpak kommen sie über die Software-Verwaltung.
|
||||||
|
|
||||||
|
## Sicherheitslücke melden
|
||||||
|
|
||||||
|
Bitte Sicherheitslücken **nicht** in einem öffentlichen Issue melden, sondern per E-Mail an **harald@pansi.eu** – möglichst mit:
|
||||||
|
|
||||||
|
- betroffener Version und Installationsart (.deb, AppImage, Flatpak, selbst gebaut),
|
||||||
|
- einer Beschreibung, was passieren kann,
|
||||||
|
- den Schritten oder einer Datei (z. B. ein präpariertes Notizbuch oder PDF), mit denen es sich nachstellen lässt.
|
||||||
|
|
||||||
|
Du bekommst innerhalb einer Woche eine Antwort. Ist die Lücke bestätigt, erscheint die Korrektur als neue Version; auf Wunsch wirst du in den Release-Notes genannt.
|
||||||
|
|
||||||
|
## Besonders interessant
|
||||||
|
|
||||||
|
- **Updates:** Prüfung der Minisign-Signatur und der SHA-256-Prüfsummen, Download und Austausch der Pakete (siehe „Sicherheit der Updates“ im [README](README.de.md#sicherheit-der-updates)).
|
||||||
|
- **Dateien öffnen:** importierte PDFs und Bilder, Notizbuch-Dateien ([Dateiformat](docs/FILE_FORMAT.de.md)) – z. B. Abstürze oder Schreiben außerhalb des Datenordners durch präparierte Dateien.
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
# Security Policy
|
||||||
|
|
||||||
|
**English** · [Deutsch](SECURITY.de.md)
|
||||||
|
|
||||||
|
## Supported versions
|
||||||
|
|
||||||
|
Security fixes are only provided for the **latest release** (see [Releases](https://gitea.pansi.eu/harald/ink-notes/releases)). The app offers updates itself (☰ → Updates); the Flatpak is updated through the software manager.
|
||||||
|
|
||||||
|
## Reporting a vulnerability
|
||||||
|
|
||||||
|
Please do **not** report vulnerabilities in a public issue. Send an e-mail to **harald@pansi.eu** instead, ideally with:
|
||||||
|
|
||||||
|
- the affected version and installation type (.deb, AppImage, Flatpak, built from source),
|
||||||
|
- a description of what can happen,
|
||||||
|
- steps or a file (e.g. a crafted notebook or PDF) to reproduce it.
|
||||||
|
|
||||||
|
You will get an answer within a week. Confirmed issues are fixed in a new release; on request you will be credited in the release notes. Reports in English or German are both fine.
|
||||||
|
|
||||||
|
## Areas of interest
|
||||||
|
|
||||||
|
- **Updates:** verification of the Minisign signature and SHA-256 checksums, downloading and replacing packages (see "Update security" in the [README](README.md#update-security)).
|
||||||
|
- **Opening files:** imported PDFs and images, notebook files ([file format](docs/FILE_FORMAT.md)) – e.g. crashes or writes outside the data folder caused by crafted files.
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 360" width="1200" height="360">
|
||||||
|
<defs>
|
||||||
|
<!-- Haupt-Hintergrund-Verlauf -->
|
||||||
|
<linearGradient id="bannerBg" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#0f1420"/>
|
||||||
|
<stop offset="40%" stop-color="#141a29"/>
|
||||||
|
<stop offset="100%" stop-color="#090b12"/>
|
||||||
|
</linearGradient>
|
||||||
|
|
||||||
|
<!-- Subtiles Ambient Glow -->
|
||||||
|
<radialGradient id="ambientGlow" cx="15%" cy="50%" r="45%">
|
||||||
|
<stop offset="0%" stop-color="#3b82f6" stop-opacity="0.22"/>
|
||||||
|
<stop offset="70%" stop-color="#1d4ed8" stop-opacity="0.05"/>
|
||||||
|
<stop offset="100%" stop-color="#1d4ed8" stop-opacity="0"/>
|
||||||
|
</radialGradient>
|
||||||
|
|
||||||
|
<radialGradient id="ambientGlowRight" cx="85%" cy="30%" r="40%">
|
||||||
|
<stop offset="0%" stop-color="#38bdf8" stop-opacity="0.10"/>
|
||||||
|
<stop offset="100%" stop-color="#38bdf8" stop-opacity="0"/>
|
||||||
|
</radialGradient>
|
||||||
|
|
||||||
|
<!-- Icon Hintergrund-Verlauf -->
|
||||||
|
<linearGradient id="bgGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#1e2638"/>
|
||||||
|
<stop offset="50%" stop-color="#141824"/>
|
||||||
|
<stop offset="100%" stop-color="#0c0e17"/>
|
||||||
|
</linearGradient>
|
||||||
|
|
||||||
|
<!-- Stiftkörper-Verlauf -->
|
||||||
|
<linearGradient id="penBody" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#3b82f6"/>
|
||||||
|
<stop offset="100%" stop-color="#1d4ed8"/>
|
||||||
|
</linearGradient>
|
||||||
|
|
||||||
|
<!-- Goldene Feder-Spitze -->
|
||||||
|
<linearGradient id="nibGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#fbbf24"/>
|
||||||
|
<stop offset="50%" stop-color="#f59e0b"/>
|
||||||
|
<stop offset="100%" stop-color="#d97706"/>
|
||||||
|
</linearGradient>
|
||||||
|
|
||||||
|
<!-- Tintenspur-Verlauf -->
|
||||||
|
<linearGradient id="inkGrad" x1="0%" y1="0%" x2="100%" y2="100%">
|
||||||
|
<stop offset="0%" stop-color="#60a5fa" stop-opacity="0.95"/>
|
||||||
|
<stop offset="50%" stop-color="#3b82f6" stop-opacity="0.85"/>
|
||||||
|
<stop offset="100%" stop-color="#2563eb" stop-opacity="0.4"/>
|
||||||
|
</linearGradient>
|
||||||
|
|
||||||
|
<!-- Text Ink Gradient -->
|
||||||
|
<linearGradient id="textInkGrad" x1="0%" y1="0%" x2="100%" y2="0%">
|
||||||
|
<stop offset="0%" stop-color="#60a5fa"/>
|
||||||
|
<stop offset="100%" stop-color="#38bdf8"/>
|
||||||
|
</linearGradient>
|
||||||
|
|
||||||
|
<!-- Leucht-Effekt -->
|
||||||
|
<filter id="glow" x="-20%" y="-20%" width="140%" height="140%">
|
||||||
|
<feGaussianBlur stdDeviation="8" result="blur" />
|
||||||
|
<feComposite in="SourceGraphic" in2="blur" operator="over" />
|
||||||
|
</filter>
|
||||||
|
|
||||||
|
<filter id="iconShadow" x="-10%" y="-10%" width="120%" height="130%">
|
||||||
|
<feDropShadow dx="0" dy="12" stdDeviation="16" flood-color="#000000" flood-opacity="0.6"/>
|
||||||
|
</filter>
|
||||||
|
|
||||||
|
<!-- Gitter-Muster für Hintergrund -->
|
||||||
|
<pattern id="gridPattern" width="30" height="30" patternUnits="userSpaceOnUse">
|
||||||
|
<path d="M 30 0 L 0 0 0 30" fill="none" stroke="#94a3b8" stroke-width="0.8" opacity="0.07"/>
|
||||||
|
</pattern>
|
||||||
|
</defs>
|
||||||
|
|
||||||
|
<!-- Banner-Rahmen & Hintergrund -->
|
||||||
|
<rect width="1200" height="360" rx="20" fill="url(#bannerBg)" stroke="#27324b" stroke-width="2"/>
|
||||||
|
|
||||||
|
<!-- Hintergrund-Gitter (Notizbuch-Raster) -->
|
||||||
|
<rect width="1200" height="360" rx="20" fill="url(#gridPattern)"/>
|
||||||
|
|
||||||
|
<!-- Subtile Glows -->
|
||||||
|
<rect width="1200" height="360" rx="20" fill="url(#ambientGlow)"/>
|
||||||
|
<rect width="1200" height="360" rx="20" fill="url(#ambientGlowRight)"/>
|
||||||
|
|
||||||
|
<!-- ==================== LINKER BEREICH: APP-ICON ==================== -->
|
||||||
|
<g transform="translate(65, 55) scale(0.488)" filter="url(#iconShadow)">
|
||||||
|
<!-- App-Icon Hintergrund (Squircle) -->
|
||||||
|
<rect x="24" y="24" width="464" height="464" rx="104" ry="104" fill="url(#bgGrad)" stroke="#384260" stroke-width="4"/>
|
||||||
|
|
||||||
|
<!-- DIN-A4 Dokumenten-Gitter im Icon -->
|
||||||
|
<g opacity="0.14" stroke="#94a3b8" stroke-width="2">
|
||||||
|
<line x1="80" y1="160" x2="432" y2="160" />
|
||||||
|
<line x1="80" y1="220" x2="432" y2="220" />
|
||||||
|
<line x1="80" y1="280" x2="432" y2="280" />
|
||||||
|
<line x1="80" y1="340" x2="432" y2="340" />
|
||||||
|
<line x1="80" y1="400" x2="432" y2="400" />
|
||||||
|
|
||||||
|
<line x1="140" y1="100" x2="140" y2="430" />
|
||||||
|
<line x1="200" y1="100" x2="200" y2="430" />
|
||||||
|
<line x1="260" y1="100" x2="260" y2="430" />
|
||||||
|
<line x1="320" y1="100" x2="320" y2="430" />
|
||||||
|
<line x1="380" y1="100" x2="380" y2="430" />
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<!-- Tintenspur -->
|
||||||
|
<path d="M 110 390 C 180 430, 260 380, 240 310 C 220 240, 280 190, 340 220"
|
||||||
|
fill="none" stroke="url(#inkGrad)" stroke-width="26" stroke-linecap="round" filter="url(#glow)"/>
|
||||||
|
<path d="M 110 390 C 180 430, 260 380, 240 310 C 220 240, 280 190, 340 220"
|
||||||
|
fill="none" stroke="#93c5fd" stroke-width="12" stroke-linecap="round"/>
|
||||||
|
|
||||||
|
<!-- Stylus / Füllfederhalter -->
|
||||||
|
<g transform="translate(240, 110) rotate(45)">
|
||||||
|
<rect x="-24" y="-140" width="48" height="150" rx="8" fill="url(#penBody)" stroke="#60a5fa" stroke-width="3"/>
|
||||||
|
<rect x="-22" y="10" width="44" height="26" rx="4" fill="#1e293b" stroke="#cbd5e1" stroke-width="2"/>
|
||||||
|
<rect x="-25" y="6" width="50" height="6" fill="#f8fafc"/>
|
||||||
|
<path d="M -20 36 L 20 36 L 12 85 L 0 115 L -12 85 Z" fill="url(#nibGrad)" stroke="#fef08a" stroke-width="2"/>
|
||||||
|
<line x1="0" y1="46" x2="0" y2="108" stroke="#78350f" stroke-width="3" stroke-linecap="round"/>
|
||||||
|
<circle cx="0" cy="65" r="4" fill="#78350f"/>
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<!-- Glanzpunkt -->
|
||||||
|
<circle cx="110" cy="390" r="14" fill="#60a5fa" filter="url(#glow)"/>
|
||||||
|
<circle cx="110" cy="390" r="8" fill="#ffffff"/>
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<!-- ==================== RECHTER BEREICH: TYPOGRAFIE & BADGES ==================== -->
|
||||||
|
<g transform="translate(360, 0)">
|
||||||
|
<!-- Version & Platform Pill -->
|
||||||
|
<g transform="translate(0, 68)">
|
||||||
|
<rect width="214" height="30" rx="15" fill="#1e293b" stroke="#334155" stroke-width="1.2"/>
|
||||||
|
<circle cx="16" cy="15" r="4" fill="#22c55e"/>
|
||||||
|
<text x="28" y="20" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Ubuntu, sans-serif" font-size="13" font-weight="600" fill="#cbd5e1" letter-spacing="0.5">
|
||||||
|
LINUX • RUST & WGPU
|
||||||
|
</text>
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<!-- Haupttitel: ink-notes -->
|
||||||
|
<text x="0" y="162" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Ubuntu, sans-serif" font-weight="800" font-size="64" letter-spacing="-1">
|
||||||
|
<tspan fill="url(#textInkGrad)">ink</tspan><tspan fill="#f8fafc">-notes</tspan>
|
||||||
|
</text>
|
||||||
|
|
||||||
|
<!-- Subtitle / Tagline -->
|
||||||
|
<text x="0" y="206" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Ubuntu, sans-serif" font-weight="400" font-size="22" fill="#94a3b8">
|
||||||
|
Notebook & PDF annotation app for pen, touch and mouse
|
||||||
|
</text>
|
||||||
|
|
||||||
|
<!-- Feature Pills / Highlights -->
|
||||||
|
<g transform="translate(0, 248)">
|
||||||
|
<!-- Pill 1: Niedrige Latenz -->
|
||||||
|
<g transform="translate(0, 0)">
|
||||||
|
<rect width="152" height="36" rx="10" fill="#182236" stroke="#253554" stroke-width="1"/>
|
||||||
|
<text x="14" y="23" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Ubuntu, sans-serif" font-size="13.5" font-weight="500" fill="#93c5fd">
|
||||||
|
⚡ Fast wgpu inking
|
||||||
|
</text>
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<!-- Pill 2: Stylus mit Druck -->
|
||||||
|
<g transform="translate(164, 0)">
|
||||||
|
<rect width="214" height="36" rx="10" fill="#182236" stroke="#253554" stroke-width="1"/>
|
||||||
|
<text x="14" y="23" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Ubuntu, sans-serif" font-size="13.5" font-weight="500" fill="#93c5fd">
|
||||||
|
🖊️ Pressure & palm rejection
|
||||||
|
</text>
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<!-- Pill 3: Formerkennung -->
|
||||||
|
<g transform="translate(390, 0)">
|
||||||
|
<rect width="216" height="36" rx="10" fill="#182236" stroke="#253554" stroke-width="1"/>
|
||||||
|
<text x="14" y="23" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Ubuntu, sans-serif" font-size="13.5" font-weight="500" fill="#93c5fd">
|
||||||
|
📐 Shape recognition & ruler
|
||||||
|
</text>
|
||||||
|
</g>
|
||||||
|
|
||||||
|
<!-- Pill 4: 100% lokal -->
|
||||||
|
<g transform="translate(618, 0)">
|
||||||
|
<rect width="188" height="36" rx="10" fill="#182236" stroke="#253554" stroke-width="1"/>
|
||||||
|
<text x="14" y="23" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Ubuntu, sans-serif" font-size="13.5" font-weight="500" fill="#93c5fd">
|
||||||
|
🔒 100% local & atomic
|
||||||
|
</text>
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 8.2 KiB |
@@ -0,0 +1,208 @@
|
|||||||
|
# Architektur von ink-notes
|
||||||
|
|
||||||
|
[English](ARCHITECTURE.md) · **Deutsch**
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt, wie ink-notes intern aufgebaut ist: Eingabe und Strichverarbeitung, Rendering, Seiten und Ansicht, Formerkennung, Speichern und Export. Das Speicherformat steht in [`FILE_FORMAT.de.md`](FILE_FORMAT.de.md).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Überblick
|
||||||
|
|
||||||
|
ink-notes ist ein einzelnes Programm mit einem Event-Loop (`winit`) im Haupt-Thread. Dazu kommen drei Hintergrund-Threads:
|
||||||
|
|
||||||
|
| Thread | Aufgabe |
|
||||||
|
| :--- | :--- |
|
||||||
|
| Haupt-Thread | Eingaben, Datenmodell, Rendering (`wgpu`), Oberfläche (`egui`) |
|
||||||
|
| Autosave | Seiten und Manifest auf die Festplatte schreiben (`autosave.rs`) |
|
||||||
|
| PDF-Rendering | Importierte PDF-Seiten zu Texturen rendern (`pdf_doc.rs`, `hayro`) |
|
||||||
|
| Export | PDF/PNG/SVG-Export, damit die Oberfläche nicht hängt (`main.rs`) |
|
||||||
|
|
||||||
|
Stifteingaben kommen über `octotablet` (Tablet-Protokoll von Wayland bzw. X11), Maus und Touch über `winit`. Die Oberfläche (Werkzeugleiste, Menüs, Dialoge, Textbearbeitung) ist mit `egui` gebaut und wird im selben Render-Durchgang über das Blatt gezeichnet.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Vom Stift zum Strich
|
||||||
|
|
||||||
|
```
|
||||||
|
[Stift / Touch / Maus]
|
||||||
|
│ Bildschirmposition, Druck, Zeit
|
||||||
|
▼
|
||||||
|
[Bildschirm → Seitenkoordinaten] (viewport.rs)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[Druckkurve] (settings.rs, vom Nutzer einstellbar)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[1€-Filter] (filter.rs)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[Dreiecksstreifen wie beim fertigen Strich] (spline.rs) → Live-Puffer auf der GPU
|
||||||
|
│ Stift abgehoben
|
||||||
|
▼
|
||||||
|
[Nachbearbeitung] (spline.rs: finalize_stroke)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[Strich auf der Seite + Undo-Eintrag] (document.rs, history.rs)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.1 1€-Filter
|
||||||
|
Langsame Bewegungen zittern, schnelle sollen nicht nachhinken. Der 1€-Filter (`filter.rs`) passt seine Grenzfrequenz an die Geschwindigkeit an:
|
||||||
|
|
||||||
|
$$f_c = f_{c,\min} + \beta \cdot |\dot{x}|$$
|
||||||
|
|
||||||
|
Bei langsamer Bewegung glättet er stark, bei schneller kaum.
|
||||||
|
|
||||||
|
### 2.2 Zentripetaler Catmull-Rom-Spline
|
||||||
|
Die gefilterten Punkte werden mit einem zentripetalen Catmull-Rom-Spline ($\alpha = 0{,}5$) interpoliert:
|
||||||
|
|
||||||
|
$$t_{i+1} = t_i + \lVert P_{i+1} - P_i \rVert^{\alpha}$$
|
||||||
|
|
||||||
|
Diese Parametrisierung erzeugt bei engen Kurven keine Schlaufen oder Spitzen und ist an den Stützstellen $C^1$-stetig.
|
||||||
|
|
||||||
|
### 2.3 Dreiecksstreifen
|
||||||
|
Aus den Spline-Punkten mit Radius $r_i$ (aus Druck und Strichstärke) entsteht ein Dreiecksstreifen:
|
||||||
|
|
||||||
|
$$V_{i,\text{links}} = P_i + N_i \cdot r_i, \qquad V_{i,\text{rechts}} = P_i - N_i \cdot r_i$$
|
||||||
|
|
||||||
|
$N_i$ ist die Normale der Laufrichtung; an inneren Punkten wird über benachbarte Segmente gemittelt.
|
||||||
|
|
||||||
|
### 2.4 Zwei Stufen
|
||||||
|
1. **Während des Schreibens:** Der Filter arbeitet nur mit bisherigen Punkten; der Strich wird bei jedem neuen Punkt mit derselben Tessellierung wie beim Absetzen (ausdünnen, Ecken, runde Kappen) in einen eigenen Live-Puffer geschrieben, damit er beim Abheben nicht springt.
|
||||||
|
2. **Beim Absetzen** wird der ganze Strich noch einmal bearbeitet (`finalize_stroke`):
|
||||||
|
- Druckverlauf mit dem Fenster $[0{,}25;\ 0{,}5;\ 0{,}25]$ glätten,
|
||||||
|
- Punkte mit Ramer-Douglas-Peucker ausdünnen ($\varepsilon = 0{,}75$ Einheiten $= 0{,}075$ mm),
|
||||||
|
- an Knicken über 65° den Spline auftrennen, damit Ecken spitz bleiben, und die Teile rund verbinden (ein Kreis um den Knick), damit die Spitze nicht abgeschnitten wirkt,
|
||||||
|
- runde Endkappen anfügen.
|
||||||
|
|
||||||
|
Danach wird der Live-Puffer geleert und der Strich in die Seite übernommen.
|
||||||
|
|
||||||
|
### 2.5 Lineal
|
||||||
|
Beginnt ein Strich nahe einer Linealkante (`ruler.rs`), werden alle seine Punkte auf diese Kante projiziert, bis der Stift abgehoben wird.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Koordinaten, Seiten und Ansicht
|
||||||
|
|
||||||
|
### 3.1 Seitenkoordinaten
|
||||||
|
Gerechnet wird in Seiteneinheiten: **10 Einheiten = 1 mm**. Eine DIN-A4-Seite ist 2100 × 2970 Einheiten groß. Jede Seite hat ihre eigene Größe (`Page::size`): Standard ist A4 hoch; beim PDF-Import bekommen Querformat-Seiten 2970 Einheiten Breite und eine Höhe nach Seitenverhältnis (`document::pdf_page_size`). Neue Seiten übernehmen die Größe der aktuellen.
|
||||||
|
|
||||||
|
### 3.2 Maßstab und Kamera
|
||||||
|
- `PageViewport` (`document.rs`) passt einen Rahmen, in den alle Seiten des Notizbuchs passen (`Notebook::fit_box`), ins Fenster ein. Daraus ergibt sich ein Maßstab (Bildschirmpixel je Einheit), der für alle Seiten gilt. Die aktuelle Seite liegt waagerecht zentriert und oben im Rahmen. Den Platz der Werkzeugleiste rechnet der Viewport heraus.
|
||||||
|
- `ViewportState` (`viewport.rs`) ergänzt Zoom (25 % bis 1000 %) und Verschiebung (Pan). Beim Zoomen bleibt der Punkt unter dem Mauszeiger stehen:
|
||||||
|
|
||||||
|
$$\vec{p}_{\text{neu}} = \vec{c} - (\vec{c} - \vec{p}_{\text{alt}}) \cdot \frac{z_{\text{neu}}}{z_{\text{alt}}}$$
|
||||||
|
|
||||||
|
- Im Shader wird jeder Punkt mit `transform_scale` und `transform_offset` (aus `CameraUniforms`) direkt in Gerätekoordinaten umgerechnet.
|
||||||
|
|
||||||
|
### 3.3 Durchgehende Ansicht
|
||||||
|
Ob ein Notizbuch Seite für Seite, durchgehend oder als endlose Fläche angezeigt wird, steht in seinem Manifest (`layout`, siehe [`FILE_FORMAT.de.md`](FILE_FORMAT.de.md)).
|
||||||
|
|
||||||
|
Alle Koordinaten beziehen sich auf die **aktuelle Seite**. `PageStack` (`viewport.rs`) legt die übrigen Seiten lückenlos darunter bzw. darüber (die Grenze zeichnet die Oberfläche als dunkle Linie), waagerecht zur aktuellen Seite zentriert. Jede sichtbare Nachbarseite wird mit einer eigenen Kamera gezeichnet, die um die Lage der Seite verschoben ist (höchstens 12 Nachbarseiten).
|
||||||
|
|
||||||
|
Nach dem Scrollen wird die Seite in der Fenstermitte zur aktuellen Seite; die Kamera wird dabei so verschoben, dass sich das Bild nicht bewegt. Während eines Strichs, einer Auswahl, beim Ziehen des Lineals oder beim Schreiben von Text wird nicht gewechselt. Wer auf einer sichtbaren Nachbarseite zu zeichnen beginnt, wechselt zuerst auf diese Seite.
|
||||||
|
|
||||||
|
Schnelles Wischen mit dem Finger gleitet nach (`Fling` in `viewport.rs`): Die Geschwindigkeit wird über die letzten 100 ms vor dem Abheben gemessen und nimmt danach exponentiell ab. Die Bildlaufleiste am Rand gegenüber der Werkzeugleiste springt direkt an eine Stelle im Notizbuch.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3.4 Endlose Fläche
|
||||||
|
Ein endloses Notizbuch hat eine einzige Seite von 10 × 10 m (`ENDLESS_PAGE_SIZE`). Damit bleibt alles wie bei jeder anderen Seite – Eingabe, Treffertests, Undo, Speichern –, nur der Rand ist praktisch unerreichbar. `PageViewport::calculate_endless` wählt Maßstab und Lage so, als läge eine DIN-A4-Seite am Startausschnitt (`ENDLESS_HOME`, ein A4-Rahmen in der Mitte); 100 % Zoom und „Ansicht zurücksetzen“ zeigen also diesen Rahmen. Bilder und Textfelder richten ihre Größe bzw. ihren Umbruch an DIN A4 aus (`Page::reference_size`, `Page::text_right_edge`).
|
||||||
|
|
||||||
|
Die Fläche wächst nur nach rechts und unten: Nach jedem Verschieben oder Zoomen hält `CanvasState::clamp_endless` die linke obere Ecke des sichtbaren Bereichs auf oder hinter `Page::endless_scroll_limit` – 10 mm links und oberhalb des Startausschnitts bzw. von Inhalt, der weiter oben oder links liegt (in Notizbüchern aus 0.29/0.30).
|
||||||
|
|
||||||
|
Beim Wechsel von und zu Seiten (`Notebook::make_endless`/`make_paged`) wird der Inhalt um `ENDLESS_HOME` verschoben und der Verlauf der Seite geleert. Zurück zu Seiten geht nur, solange alles im Startausschnitt liegt. Export und Bilder einer Auswahl rastern bzw. exportieren nur einen Ausschnitt (`Page::cropped`), beim Export auf das Musterraster gelegt (`Page::endless_export_bounds`).
|
||||||
|
|
||||||
|
## 4. Rendering
|
||||||
|
|
||||||
|
Ein Frame besteht aus einem Render-Durchgang auf die Fensterfläche (`canvas.rs`):
|
||||||
|
|
||||||
|
1. Für jede sichtbare Nachbarseite: Papier und Muster, Bilder/PDF-Seite/Text, Tinte.
|
||||||
|
2. Für die aktuelle Seite: Papier, Muster (Karo, Linien, Punkte), Bildebene, gespeicherte Striche, Live-Strich.
|
||||||
|
3. Die `egui`-Oberfläche: Werkzeugleiste, Menüs, Seitengrenzen, Auswahlrahmen und Griffe, Lineal, Textbearbeitung.
|
||||||
|
|
||||||
|
Jeder Strich ist ein eigener Draw-Call mit eigener Nummer im Stencil-Puffer: Ein Pixel, das der Strich schon gefärbt hat, wird kein zweites Mal gefärbt. So bleibt halbtransparente Tinte (Textmarker) gleichmäßig, auch wo sich der Strich selbst überlappt (Anfangskappe, Kehren, langsames Hin- und Herfahren); erst ein neuer Strich deckt stärker. Nach 255 Strichen setzt ein bildschirmfüllendes Dreieck den Stencil-Puffer zurück.
|
||||||
|
|
||||||
|
### 4.1 Bildebene
|
||||||
|
`image_layer.rs` zeichnet texturierte Vierecke unter der Tinte: importierte PDF-Seiten, eingefügte Bilder und Textfelder. Texturen werden beim ersten Bedarf geladen, bekommen Mipmaps und werden freigegeben, wenn mehr als 384 MB belegt sind.
|
||||||
|
- **PDF-Seiten** rendert ein Hintergrund-Thread mit `hayro` (längste Kante 2560 Pixel, beim starken Hineinzoomen 5120 Pixel). Bis die schärfere Fassung fertig ist, bleibt die vorhandene sichtbar.
|
||||||
|
- **Textfelder** werden mit `ab_glyph` gerastert, in einer Auflösung, die dem Zoom folgt (in Vierteln einer Zweierpotenz, höchstens 8 Pixel je Einheit). Der Texturschlüssel enthält einen Hash von Inhalt, Schrift und Farbe; jede Änderung erzeugt eine neue Textur.
|
||||||
|
|
||||||
|
### 4.2 Papier- und Musterfarben
|
||||||
|
Papierfarbe (`PaperTheme`) und Musterfarbe (`PatternColor`) stehen in `background.rs`; sie sind linear angegeben und werden im Shader nach sRGB umgerechnet. Tintenfarben (Striche, Text) sind sRGB-Werte – dieselben Zahlen landen im PDF und in den Farbpunkten der Oberfläche. Gezeichnet wird ohne sRGB-Umrechnung der GPU (`render_format`), Texturen sind `Rgba8Unorm`: So wird halbtransparente Tinte wie im PDF in sRGB gemischt und sieht am Bildschirm genauso aus wie im Export. Auf dunklem Papier kann der Shader dunkle Tinte aufhellen (`ink_params` in `CameraUniforms`), gespeichert werden immer die Originalfarben.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Objekte auf der Seite
|
||||||
|
|
||||||
|
Alles auf einer Seite ist ein `Stroke` (`document.rs`):
|
||||||
|
- **Tinte:** Abtastpunkte, Werkzeug (Stift, Textmarker, Form), Breite, Farbe; die Dreiecke werden beim Laden aus den Punkten neu berechnet.
|
||||||
|
- **Formen:** zusätzlich eine `RecognizedShape` (siehe Abschnitt 6).
|
||||||
|
- **Bilder und Textfelder:** vier Eckpunkte (oben links, oben rechts, unten rechts, unten links) plus Verweis auf die Bilddatei bzw. ein `TextBox`. Weil die Ecken normale Punkte sind, wirken Verschieben, Drehen und Skalieren der Auswahl ohne Sonderfälle.
|
||||||
|
|
||||||
|
### 5.1 Textfelder
|
||||||
|
`text.rs` setzt den Text selbst: Zeilenumbruch an Leerzeichen (zu lange Wörter zeichenweise), Unterschneidung, Tabulator = 4 Leerzeichen. Bildschirm-Textur, PDF-Export und Bearbeitung verwenden dieselben Schriften (Ubuntu Light und Hack aus den eingebauten `egui`-Schriften) und denselben Umbruch. Bearbeitet wird in einem `egui`-Textfeld an der Stelle des Felds; danach wird die Höhe des Felds an den Text angepasst, Lage, Drehung und Skalierung bleiben.
|
||||||
|
|
||||||
|
### 5.2 Rückgängig
|
||||||
|
Jede Seite hat einen eigenen Verlauf (`history.rs`): Hinzufügen, Entfernen, Ersetzen und Ändern von Strichen. Verschieben/Drehen/Skalieren einer Auswahl, ein Radierzug mit dem Teilstrich-Radierer und eine Textbearbeitung sind jeweils ein Schritt.
|
||||||
|
|
||||||
|
**Platz schaffen** (`Notebook::make_space`) betrifft mehrere Seiten: Die Seite, auf der angesetzt wurde, und die folgenden bis vor die nächste PDF-Seite gelten als durchgehende Spalte. Alles unterhalb der Ansatzhöhe rutscht um denselben Betrag; ein Objekt, das über ein Seitenende ragen würde, beginnt 10 mm unter dem Anfang der nächsten Seite, und alles danach rutscht entsprechend weiter. Fehlende Seiten werden eingefügt. Der Schritt (`SpaceShift`: jeder verschobene Strich vorher/nachher mit Seite) landet im Verlauf der Seite, auf der angesetzt wurde; `Notebook::undo`/`redo` buchen ihn über alle Seiten zurück (später geänderte Striche bleiben unberührt) und entfernen dafür angelegte, leer gebliebene Seiten wieder.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Formerkennung
|
||||||
|
|
||||||
|
`geometry.rs` erkennt Formen rein geometrisch, ohne Machine Learning. Zuerst wird auf ein Achsenkreuz geprüft (alle Teilstücke liegen auf einer waagerechten und einer senkrechten Linie, beide reichen auf beiden Seiten über den Schnittpunkt hinaus). Geschlossene Formen (Kreis, Ellipse, Dreieck, Rechteck, Raute) treten gegeneinander an; gewählt wird die, deren Umriss am besten zu den Punkten passt. Danach folgen Vielecke, Pfeile, Koordinatensysteme und Linien. Übernommen wird eine Form nur, wenn der Strich im Mittel höchstens 4 % seiner Diagonale von ihr abweicht – sonst bleibt er Handschrift.
|
||||||
|
|
||||||
|
- **Linie:** Verhältnis von Abstand Anfang–Ende zur Strichlänge über 0,92.
|
||||||
|
- **Kreis, Ellipse:** Kreis- bzw. Ellipsen-Fit über die Punkte.
|
||||||
|
- **Rechteck, Dreieck, Raute, Vieleck, Pfeil:** Analyse der mit Douglas-Peucker vereinfachten Kontur (Eckenzahl, Winkel, Seitenverhältnisse).
|
||||||
|
- **Koordinatensystem:** zwei etwa rechtwinklige Achsen; der Winkel wird auf 90° gesetzt.
|
||||||
|
- **Achsenkreuz:** ein „+“ in einem Zug; die Achsen werden waagerecht und senkrecht ausgerichtet und bekommen an allen vier Enden Pfeilspitzen.
|
||||||
|
- **Oktaeder:** Skizze einer Doppelpyramide als 3D-Kantenmodell; nur, wenn kein einfacher Umriss passt.
|
||||||
|
|
||||||
|
**Halten am Strichende:** Bleibt der Stift über 400 ms innerhalb von 3 Pixeln ruhig, wird die erkannte Form schon vor dem Absetzen angezeigt und beim Absetzen übernommen – in der Breite des gewählten Stifts bzw. Textmarkers; ein eingerasteter Textmarker bleibt Textmarker. Mit dem Formen-Werkzeug wird jeder Strich beim Absetzen geprüft.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Speichern
|
||||||
|
|
||||||
|
```
|
||||||
|
[Änderung]
|
||||||
|
│ mark_page_dirty / mark_manifest_dirty
|
||||||
|
▼
|
||||||
|
[AutosaveController] ── 1,5 s nach der letzten Änderung, spätestens nach 10 s ──► [Autosave-Thread]
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[temporäre Datei schreiben + fsync]
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
[rename über die alte Datei, Ordner-fsync]
|
||||||
|
```
|
||||||
|
|
||||||
|
- Der Haupt-Thread schreibt nie selbst; er übergibt fertige Seitendaten an den Autosave-Thread.
|
||||||
|
- Schlägt ein Schreibvorgang fehl, wird die Seite mit wachsendem Abstand (1 s bis 30 s) erneut versucht; der Status wird rot.
|
||||||
|
- `flush()` schreibt alles Ausstehende und wartet darauf. Es läuft bei `Strg + S`, beim Wechsel des Notizbuchs und beim Beenden. Schlägt es beim Beenden fehl, bleibt die App offen und bietet Wiederholen oder einen Notfall-Export der ungespeicherten Seiten an (`~/.local/share/ink-notes/recovery/`).
|
||||||
|
- Seiten werden erst beim Anzeigen geladen (Lazy Loading); Titel, Hintergrund und Größe stehen im Manifest, damit Seitenübersicht und durchgehende Ansicht sie vorher kennen.
|
||||||
|
- Ein zweites Fenster mit demselben Notizbuch öffnet es schreibgeschützt (Sperrdatei).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Export
|
||||||
|
|
||||||
|
`export.rs` erzeugt das PDF mit `printpdf`. Jede Seite bekommt ihre eigene Größe und diese Ebenen:
|
||||||
|
|
||||||
|
1. **Background:** Karo, Linien oder Punkte in der gewählten Musterfarbe (immer auf weißem Papier).
|
||||||
|
2. **PDF** (nur im Notfall): importierte PDF-Seite als Bild, falls sie sich nicht als Vektor übernehmen lässt.
|
||||||
|
3. **Images:** eingefügte Bilder (höchstens 300 dpi).
|
||||||
|
4. **Text:** Textfelder als echter Text mit eingebetteter Schrift (durchsuchbar, kopierbar). Jedes Feld liegt in einem eigenen Koordinatensystem, das eine Transformationsmatrix auf seine Ecken abbildet.
|
||||||
|
5. **Ink:** Striche als gefüllte Polygone, Formen als Pfade. Halbtransparente Striche (Textmarker) bekommen einen Grafikzustand mit Deckkraft (`ca`/`CA`); printpdf kann solche Zustände nicht anlegen, deshalb trägt `add_alpha_states` sie nach dem Speichern mit `lopdf` in die Seitenressourcen ein. Jeder Strich ist ein einziger Pfad und deckt sich daher nicht selbst doppelt.
|
||||||
|
|
||||||
|
Importierte PDF-Seiten werden anschließend als Form-XObject unter die Seite gelegt (`pdf_merge.rs`), bleiben also Vektorgrafik. Seitentitel werden zu Lesezeichen.
|
||||||
|
|
||||||
|
PNG und SVG einer Seite (`page_export.rs`) entstehen aus diesem PDF: `hayro` rastert es bzw. wandelt es in SVG um. So sehen alle Exporte gleich aus.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Updates
|
||||||
|
|
||||||
|
`updater.rs` fragt die Gitea-Releases ab, vergleicht die Version (SemVer) und lädt auf Wunsch das passende Paket. Vor der Installation prüft er die Minisign-Signatur von `SHA256SUMS.txt` gegen den eingebauten Schlüssel und danach die SHA-256-Prüfsumme des Pakets. Ein AppImage wird per `rename` ersetzt; ein `.deb`-Paket wird mit `xdg-open` an die Softwareinstallation des Systems übergeben. Details im [README](../README.de.md#sicherheit-der-updates) unter „Sicherheit der Updates“.
|
||||||
+113
-100
@@ -1,195 +1,208 @@
|
|||||||
# Architektur von ink-notes
|
# ink-notes architecture
|
||||||
|
|
||||||
Dieses Dokument beschreibt, wie ink-notes intern aufgebaut ist: Eingabe und Strichverarbeitung, Rendering, Seiten und Ansicht, Formerkennung, Speichern und Export. Das Speicherformat steht in [`FILE_FORMAT.md`](FILE_FORMAT.md).
|
**English** · [Deutsch](ARCHITECTURE.de.md)
|
||||||
|
|
||||||
|
This document describes how ink-notes is built internally: input and stroke processing, rendering, pages and view, shape recognition, saving and export. The storage format is described in [`FILE_FORMAT.md`](FILE_FORMAT.md).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Überblick
|
## 1. Overview
|
||||||
|
|
||||||
ink-notes ist ein einzelnes Programm mit einem Event-Loop (`winit`) im Haupt-Thread. Dazu kommen drei Hintergrund-Threads:
|
ink-notes is a single program with an event loop (`winit`) on the main thread, plus three background threads:
|
||||||
|
|
||||||
| Thread | Aufgabe |
|
| Thread | Task |
|
||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
| Haupt-Thread | Eingaben, Datenmodell, Rendering (`wgpu`), Oberfläche (`egui`) |
|
| Main thread | Input, data model, rendering (`wgpu`), interface (`egui`) |
|
||||||
| Autosave | Seiten und Manifest auf die Festplatte schreiben (`autosave.rs`) |
|
| Autosave | Writes pages and manifest to disk (`autosave.rs`) |
|
||||||
| PDF-Rendering | Importierte PDF-Seiten zu Texturen rendern (`pdf_doc.rs`, `hayro`) |
|
| PDF rendering | Renders imported PDF pages to textures (`pdf_doc.rs`, `hayro`) |
|
||||||
| Export | PDF/PNG/SVG-Export, damit die Oberfläche nicht hängt (`main.rs`) |
|
| Export | PDF/PNG/SVG export, so the interface does not freeze (`main.rs`) |
|
||||||
|
|
||||||
Stifteingaben kommen über `octotablet` (Tablet-Protokoll von Wayland bzw. X11), Maus und Touch über `winit`. Die Oberfläche (Werkzeugleiste, Menüs, Dialoge, Textbearbeitung) ist mit `egui` gebaut und wird im selben Render-Durchgang über das Blatt gezeichnet.
|
Pen input arrives via `octotablet` (the Wayland or X11 tablet protocol), mouse and touch via `winit`. The interface (toolbar, menus, dialogs, text editing) is built with `egui` and drawn over the page in the same render pass.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 2. Vom Stift zum Strich
|
## 2. From pen to stroke
|
||||||
|
|
||||||
```
|
```
|
||||||
[Stift / Touch / Maus]
|
[Pen / touch / mouse]
|
||||||
│ Bildschirmposition, Druck, Zeit
|
│ screen position, pressure, time
|
||||||
▼
|
▼
|
||||||
[Bildschirm → Seitenkoordinaten] (viewport.rs)
|
[Screen → page coordinates] (viewport.rs)
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
[Druckkurve] (settings.rs, vom Nutzer einstellbar)
|
[Pressure curve] (settings.rs, user-adjustable)
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
[1€-Filter] (filter.rs)
|
[1€ filter] (filter.rs)
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
[Catmull-Rom-Spline + Dreiecksstreifen] (spline.rs) → Live-Puffer auf der GPU
|
[Triangle strip as for the final stroke] (spline.rs) → live buffer on the GPU
|
||||||
│ Stift abgehoben
|
│ pen lifted
|
||||||
▼
|
▼
|
||||||
[Nachbearbeitung] (spline.rs: finalize_stroke)
|
[Post-processing] (spline.rs: finalize_stroke)
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
[Strich auf der Seite + Undo-Eintrag] (document.rs, history.rs)
|
[Stroke on the page + undo entry] (document.rs, history.rs)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2.1 1€-Filter
|
### 2.1 1€ filter
|
||||||
Langsame Bewegungen zittern, schnelle sollen nicht nachhinken. Der 1€-Filter (`filter.rs`) passt seine Grenzfrequenz an die Geschwindigkeit an:
|
Slow movements jitter, fast ones should not lag behind. The 1€ filter (`filter.rs`) adapts its cutoff frequency to the speed:
|
||||||
|
|
||||||
$$f_c = f_{c,\min} + \beta \cdot |\dot{x}|$$
|
$$f_c = f_{c,\min} + \beta \cdot |\dot{x}|$$
|
||||||
|
|
||||||
Bei langsamer Bewegung glättet er stark, bei schneller kaum.
|
It smooths strongly during slow movement and hardly at all during fast movement.
|
||||||
|
|
||||||
### 2.2 Zentripetaler Catmull-Rom-Spline
|
### 2.2 Centripetal Catmull-Rom spline
|
||||||
Die gefilterten Punkte werden mit einem zentripetalen Catmull-Rom-Spline ($\alpha = 0{,}5$) interpoliert:
|
The filtered points are interpolated with a centripetal Catmull-Rom spline ($\alpha = 0.5$):
|
||||||
|
|
||||||
$$t_{i+1} = t_i + \lVert P_{i+1} - P_i \rVert^{\alpha}$$
|
$$t_{i+1} = t_i + \lVert P_{i+1} - P_i \rVert^{\alpha}$$
|
||||||
|
|
||||||
Diese Parametrisierung erzeugt bei engen Kurven keine Schlaufen oder Spitzen und ist an den Stützstellen $C^1$-stetig.
|
This parametrization does not create loops or cusps in tight curves and is $C^1$-continuous at the control points.
|
||||||
|
|
||||||
### 2.3 Dreiecksstreifen
|
### 2.3 Triangle strip
|
||||||
Aus den Spline-Punkten mit Radius $r_i$ (aus Druck und Strichstärke) entsteht ein Dreiecksstreifen:
|
From the spline points with radius $r_i$ (from pressure and stroke width), a triangle strip is built:
|
||||||
|
|
||||||
$$V_{i,\text{links}} = P_i + N_i \cdot r_i, \qquad V_{i,\text{rechts}} = P_i - N_i \cdot r_i$$
|
$$V_{i,\text{left}} = P_i + N_i \cdot r_i, \qquad V_{i,\text{right}} = P_i - N_i \cdot r_i$$
|
||||||
|
|
||||||
$N_i$ ist die Normale der Laufrichtung; an inneren Punkten wird über benachbarte Segmente gemittelt.
|
$N_i$ is the normal of the direction of travel; at inner points it is averaged over neighboring segments.
|
||||||
|
|
||||||
### 2.4 Zwei Stufen
|
### 2.4 Two stages
|
||||||
1. **Während des Schreibens:** Filter und Spline arbeiten nur mit bisherigen Punkten; der Strich wird sofort in einen eigenen Live-Puffer geschrieben.
|
1. **While writing:** The filter only works with the points so far; with every new point the stroke is written into its own live buffer using the same tessellation as when the pen is lifted (thinning, corners, round caps), so it does not jump when the pen lifts.
|
||||||
2. **Beim Absetzen** wird der ganze Strich noch einmal bearbeitet (`finalize_stroke`):
|
2. **When the pen is lifted**, the whole stroke is processed once more (`finalize_stroke`):
|
||||||
- Druckverlauf mit dem Fenster $[0{,}25;\ 0{,}5;\ 0{,}25]$ glätten,
|
- smooth the pressure curve with the window $[0.25;\ 0.5;\ 0.25]$,
|
||||||
- Punkte mit Ramer-Douglas-Peucker ausdünnen ($\varepsilon = 0{,}75$ Einheiten $= 0{,}075$ mm),
|
- thin out points with Ramer-Douglas-Peucker ($\varepsilon = 0.75$ units $= 0.075$ mm),
|
||||||
- an Knicken über 65° den Spline auftrennen, damit Ecken nicht abgerundet werden,
|
- split the spline at bends over 65° so corners stay sharp, and join the parts round (a circle around the bend) so the tip does not look cut off,
|
||||||
- runde Endkappen anfügen.
|
- add round end caps.
|
||||||
|
|
||||||
Danach wird der Live-Puffer geleert und der Strich in die Seite übernommen.
|
Then the live buffer is cleared and the stroke is added to the page.
|
||||||
|
|
||||||
### 2.5 Lineal
|
### 2.5 Ruler
|
||||||
Beginnt ein Strich nahe einer Linealkante (`ruler.rs`), werden alle seine Punkte auf diese Kante projiziert, bis der Stift abgehoben wird.
|
If a stroke starts near a ruler edge (`ruler.rs`), all its points are projected onto that edge until the pen is lifted.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Koordinaten, Seiten und Ansicht
|
## 3. Coordinates, pages and view
|
||||||
|
|
||||||
### 3.1 Seitenkoordinaten
|
### 3.1 Page coordinates
|
||||||
Gerechnet wird in Seiteneinheiten: **10 Einheiten = 1 mm**. Eine DIN-A4-Seite ist 2100 × 2970 Einheiten groß. Jede Seite hat ihre eigene Größe (`Page::size`): Standard ist A4 hoch; beim PDF-Import bekommen Querformat-Seiten 2970 Einheiten Breite und eine Höhe nach Seitenverhältnis (`document::pdf_page_size`). Neue Seiten übernehmen die Größe der aktuellen.
|
Everything is computed in page units: **10 units = 1 mm**. An A4 page is 2100 × 2970 units. Each page has its own size (`Page::size`): the default is A4 portrait; on PDF import, landscape pages get a width of 2970 units and a height according to the aspect ratio (`document::pdf_page_size`). New pages take over the size of the current one.
|
||||||
|
|
||||||
### 3.2 Maßstab und Kamera
|
### 3.2 Scale and camera
|
||||||
- `PageViewport` (`document.rs`) passt einen Rahmen, in den alle Seiten des Notizbuchs passen (`Notebook::fit_box`), ins Fenster ein. Daraus ergibt sich ein Maßstab (Bildschirmpixel je Einheit), der für alle Seiten gilt. Die aktuelle Seite liegt waagerecht zentriert und oben im Rahmen. Den Platz der Werkzeugleiste rechnet der Viewport heraus.
|
- `PageViewport` (`document.rs`) fits a box that holds all pages of the notebook (`Notebook::fit_box`) into the window. This yields one scale (screen pixels per unit) that applies to all pages. The current page is centered horizontally and placed at the top of the box. The viewport subtracts the space taken by the toolbar.
|
||||||
- `ViewportState` (`viewport.rs`) ergänzt Zoom (25 % bis 1000 %) und Verschiebung (Pan). Beim Zoomen bleibt der Punkt unter dem Mauszeiger stehen:
|
- `ViewportState` (`viewport.rs`) adds zoom (25 % to 1000 %) and panning. When zooming, the point under the mouse cursor stays in place:
|
||||||
|
|
||||||
$$\vec{p}_{\text{neu}} = \vec{c} - (\vec{c} - \vec{p}_{\text{alt}}) \cdot \frac{z_{\text{neu}}}{z_{\text{alt}}}$$
|
$$\vec{p}_{\text{new}} = \vec{c} - (\vec{c} - \vec{p}_{\text{old}}) \cdot \frac{z_{\text{new}}}{z_{\text{old}}}$$
|
||||||
|
|
||||||
- Im Shader wird jeder Punkt mit `transform_scale` und `transform_offset` (aus `CameraUniforms`) direkt in Gerätekoordinaten umgerechnet.
|
- In the shader, every point is converted directly to device coordinates with `transform_scale` and `transform_offset` (from `CameraUniforms`).
|
||||||
|
|
||||||
### 3.3 Durchgehende Ansicht
|
### 3.3 Continuous view
|
||||||
Alle Koordinaten beziehen sich auf die **aktuelle Seite**. `PageStack` (`viewport.rs`) legt die übrigen Seiten lückenlos darunter bzw. darüber (die Grenze zeichnet die Oberfläche als dunkle Linie), waagerecht zur aktuellen Seite zentriert. Jede sichtbare Nachbarseite wird mit einer eigenen Kamera gezeichnet, die um die Lage der Seite verschoben ist (höchstens 12 Nachbarseiten).
|
Whether a notebook is shown page by page, continuously or as an endless canvas is stored in its manifest (`layout`, see [`FILE_FORMAT.md`](FILE_FORMAT.md)).
|
||||||
|
|
||||||
Nach dem Scrollen wird die Seite in der Fenstermitte zur aktuellen Seite; die Kamera wird dabei so verschoben, dass sich das Bild nicht bewegt. Während eines Strichs, einer Auswahl, beim Ziehen des Lineals oder beim Schreiben von Text wird nicht gewechselt. Wer auf einer sichtbaren Nachbarseite zu zeichnen beginnt, wechselt zuerst auf diese Seite.
|
All coordinates refer to the **current page**. `PageStack` (`viewport.rs`) places the other pages seamlessly below and above it (the interface draws the boundary as a dark line), centered horizontally on the current page. Each visible neighboring page is drawn with its own camera, shifted by the page's position (at most 12 neighboring pages).
|
||||||
|
|
||||||
|
After scrolling, the page in the middle of the window becomes the current page; the camera is shifted so that the picture does not move. There is no switch during a stroke, a selection, while dragging the ruler or while typing text. Starting to draw on a visible neighboring page switches to that page first.
|
||||||
|
|
||||||
|
A quick finger swipe keeps gliding (`Fling` in `viewport.rs`): the speed is measured over the last 100 ms before the finger lifts and then decays exponentially. The scrollbar on the edge opposite the toolbar jumps directly to a position in the notebook.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
### 3.4 Endless canvas
|
||||||
|
An endless notebook has a single page of 10 × 10 m (`ENDLESS_PAGE_SIZE`). This keeps everything the same as with any other page – input, hit tests, undo, saving – only the edge is practically unreachable. `PageViewport::calculate_endless` chooses scale and position as if an A4 page lay at the starting area (`ENDLESS_HOME`, an A4 frame in the middle); 100 % zoom and "Reset view" therefore show this frame. Images and text boxes base their size and wrapping on A4 (`Page::reference_size`, `Page::text_right_edge`).
|
||||||
|
|
||||||
|
The canvas only grows to the right and down: after every pan or zoom, `CanvasState::clamp_endless` keeps the top left corner of the visible area at or beyond `Page::endless_scroll_limit` – 10 mm above and left of the starting area, or of content lying further up or left (in notebooks from 0.29/0.30).
|
||||||
|
|
||||||
|
When switching to and from pages (`Notebook::make_endless`/`make_paged`), the content is shifted by `ENDLESS_HOME` and the page's history is cleared. Switching back to pages is only possible while everything lies within the starting area. Export and images of a selection only rasterize or export a section (`Page::cropped`), aligned to the pattern grid on export (`Page::endless_export_bounds`).
|
||||||
|
|
||||||
## 4. Rendering
|
## 4. Rendering
|
||||||
|
|
||||||
Ein Frame besteht aus einem Render-Durchgang auf die Fensterfläche (`canvas.rs`):
|
A frame consists of one render pass onto the window surface (`canvas.rs`):
|
||||||
|
|
||||||
1. Für jede sichtbare Nachbarseite: Papier und Muster, Bilder/PDF-Seite/Text, Tinte.
|
1. For each visible neighboring page: paper and pattern, images/PDF page/text, ink.
|
||||||
2. Für die aktuelle Seite: Papier, Muster (Karo, Linien, Punkte), Bildebene, gespeicherte Striche, Live-Strich.
|
2. For the current page: paper, pattern (squares, lines, dots), image layer, stored strokes, live stroke.
|
||||||
3. Die `egui`-Oberfläche: Werkzeugleiste, Menüs, Seitengrenzen, Auswahlrahmen und Griffe, Lineal, Textbearbeitung.
|
3. The `egui` interface: toolbar, menus, page boundaries, selection frame and handles, ruler, text editing.
|
||||||
|
|
||||||
Jeder Strich ist ein eigener Draw-Call mit eigener Nummer im Stencil-Puffer: Ein Pixel, das der Strich schon gefärbt hat, wird kein zweites Mal gefärbt. So bleibt halbtransparente Tinte (Textmarker) gleichmäßig, auch wo sich der Strich selbst überlappt (Anfangskappe, Kehren, langsames Hin- und Herfahren); erst ein neuer Strich deckt stärker. Nach 255 Strichen setzt ein bildschirmfüllendes Dreieck den Stencil-Puffer zurück.
|
Each stroke is its own draw call with its own number in the stencil buffer: a pixel the stroke has already colored is not colored a second time. This keeps semi-transparent ink (highlighter) even where the stroke overlaps itself (start cap, turns, slow back-and-forth); only a new stroke covers more strongly. After 255 strokes, a full-screen triangle resets the stencil buffer.
|
||||||
|
|
||||||
### 4.1 Bildebene
|
### 4.1 Image layer
|
||||||
`image_layer.rs` zeichnet texturierte Vierecke unter der Tinte: importierte PDF-Seiten, eingefügte Bilder und Textfelder. Texturen werden beim ersten Bedarf geladen, bekommen Mipmaps und werden freigegeben, wenn mehr als 384 MB belegt sind.
|
`image_layer.rs` draws textured quads below the ink: imported PDF pages, inserted images and text boxes. Textures are loaded when first needed, get mipmaps, and are released when more than 384 MB are in use.
|
||||||
- **PDF-Seiten** rendert ein Hintergrund-Thread mit `hayro` (längste Kante 2560 Pixel, beim starken Hineinzoomen 5120 Pixel). Bis die schärfere Fassung fertig ist, bleibt die vorhandene sichtbar.
|
- **PDF pages** are rendered by a background thread with `hayro` (longest edge 2560 pixels, 5120 pixels when zoomed in strongly). Until the sharper version is ready, the existing one stays visible.
|
||||||
- **Textfelder** werden mit `ab_glyph` gerastert, in einer Auflösung, die dem Zoom folgt (in Vierteln einer Zweierpotenz, höchstens 8 Pixel je Einheit). Der Texturschlüssel enthält einen Hash von Inhalt, Schrift und Farbe; jede Änderung erzeugt eine neue Textur.
|
- **Text boxes** are rasterized with `ab_glyph` at a resolution that follows the zoom (in quarters of a power of two, at most 8 pixels per unit). The texture key contains a hash of content, font and color; every change creates a new texture.
|
||||||
|
|
||||||
### 4.2 Papier- und Musterfarben
|
### 4.2 Paper and pattern colors
|
||||||
Papierfarbe (`PaperTheme`) und Musterfarbe (`PatternColor`) stehen in `background.rs`; sie sind linear angegeben und werden im Shader nach sRGB umgerechnet. Tintenfarben (Striche, Text) sind sRGB-Werte – dieselben Zahlen landen im PDF und in den Farbpunkten der Oberfläche. Gezeichnet wird ohne sRGB-Umrechnung der GPU (`render_format`), Texturen sind `Rgba8Unorm`: So wird halbtransparente Tinte wie im PDF in sRGB gemischt und sieht am Bildschirm genauso aus wie im Export. Auf dunklem Papier kann der Shader dunkle Tinte aufhellen (`ink_params` in `CameraUniforms`), gespeichert werden immer die Originalfarben.
|
Paper color (`PaperTheme`) and pattern color (`PatternColor`) are defined in `background.rs`; they are given in linear space and converted to sRGB in the shader. Ink colors (strokes, text) are sRGB values – the same numbers end up in the PDF and in the color dots of the interface. Drawing happens without the GPU's sRGB conversion (`render_format`), and textures are `Rgba8Unorm`: this way semi-transparent ink is blended in sRGB like in the PDF and looks the same on screen as in the export. On dark paper the shader can brighten dark ink (`ink_params` in `CameraUniforms`); the original colors are always what gets saved.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. Objekte auf der Seite
|
## 5. Objects on the page
|
||||||
|
|
||||||
Alles auf einer Seite ist ein `Stroke` (`document.rs`):
|
Everything on a page is a `Stroke` (`document.rs`):
|
||||||
- **Tinte:** Abtastpunkte, Werkzeug (Stift, Textmarker, Form), Breite, Farbe; die Dreiecke werden beim Laden aus den Punkten neu berechnet.
|
- **Ink:** sample points, tool (pen, highlighter, shape), width, color; the triangles are recomputed from the points when loading.
|
||||||
- **Formen:** zusätzlich eine `RecognizedShape` (siehe Abschnitt 6).
|
- **Shapes:** additionally a `RecognizedShape` (see section 6).
|
||||||
- **Bilder und Textfelder:** vier Eckpunkte (oben links, oben rechts, unten rechts, unten links) plus Verweis auf die Bilddatei bzw. ein `TextBox`. Weil die Ecken normale Punkte sind, wirken Verschieben, Drehen und Skalieren der Auswahl ohne Sonderfälle.
|
- **Images and text boxes:** four corner points (top left, top right, bottom right, bottom left) plus a reference to the image file or a `TextBox`. Because the corners are ordinary points, moving, rotating and scaling a selection work without special cases.
|
||||||
|
|
||||||
### 5.1 Textfelder
|
### 5.1 Text boxes
|
||||||
`text.rs` setzt den Text selbst: Zeilenumbruch an Leerzeichen (zu lange Wörter zeichenweise), Unterschneidung, Tabulator = 4 Leerzeichen. Bildschirm-Textur, PDF-Export und Bearbeitung verwenden dieselben Schriften (Ubuntu Light und Hack aus den eingebauten `egui`-Schriften) und denselben Umbruch. Bearbeitet wird in einem `egui`-Textfeld an der Stelle des Felds; danach wird die Höhe des Felds an den Text angepasst, Lage, Drehung und Skalierung bleiben.
|
`text.rs` lays out the text itself: line wrapping at spaces (overlong words character by character), kerning, tab = 4 spaces. The screen texture, the PDF export and editing use the same fonts (Ubuntu Light and Hack from the fonts built into `egui`) and the same wrapping. Editing happens in an `egui` text field at the position of the box; afterwards the box height is adapted to the text, while position, rotation and scaling stay.
|
||||||
|
|
||||||
### 5.2 Rückgängig
|
### 5.2 Undo
|
||||||
Jede Seite hat einen eigenen Verlauf (`history.rs`): Hinzufügen, Entfernen, Ersetzen und Ändern von Strichen. Verschieben/Drehen/Skalieren einer Auswahl, ein Radierzug mit dem Teilstrich-Radierer und eine Textbearbeitung sind jeweils ein Schritt.
|
Each page has its own history (`history.rs`): adding, removing, replacing and modifying strokes. Moving/rotating/scaling a selection, one stroke of the partial-stroke eraser and one text edit are each a single step.
|
||||||
|
|
||||||
**Platz schaffen** (`Notebook::make_space`) betrifft mehrere Seiten: Die Seite, auf der angesetzt wurde, und die folgenden bis vor die nächste PDF-Seite gelten als durchgehende Spalte. Alles unterhalb der Ansatzhöhe rutscht um denselben Betrag; ein Objekt, das über ein Seitenende ragen würde, beginnt 10 mm unter dem Anfang der nächsten Seite, und alles danach rutscht entsprechend weiter. Fehlende Seiten werden eingefügt. Der Schritt (`SpaceShift`: jeder verschobene Strich vorher/nachher mit Seite) landet im Verlauf der Seite, auf der angesetzt wurde; `Notebook::undo`/`redo` buchen ihn über alle Seiten zurück (später geänderte Striche bleiben unberührt) und entfernen dafür angelegte, leer gebliebene Seiten wieder.
|
**Make space** (`Notebook::make_space`) affects several pages: the page where you started and the following ones up to the next PDF page count as one continuous column. Everything below the starting height moves by the same amount; an object that would extend past the end of a page starts 10 mm below the top of the next page, and everything after it moves further accordingly. Missing pages are inserted. The step (`SpaceShift`: every moved stroke before/after, with its page) goes into the history of the page where you started; `Notebook::undo`/`redo` apply it back across all pages (strokes changed later stay untouched) and remove pages that were created for it and stayed empty.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 6. Formerkennung
|
## 6. Shape recognition
|
||||||
|
|
||||||
`geometry.rs` erkennt Formen rein geometrisch, ohne Machine Learning. Zuerst wird auf ein Achsenkreuz geprüft (alle Teilstücke liegen auf einer waagerechten und einer senkrechten Linie, beide reichen auf beiden Seiten über den Schnittpunkt hinaus). Geschlossene Formen (Kreis, Ellipse, Dreieck, Rechteck, Raute) treten gegeneinander an; gewählt wird die, deren Umriss am besten zu den Punkten passt. Danach folgen Vielecke, Pfeile, Koordinatensysteme und Linien. Übernommen wird eine Form nur, wenn der Strich im Mittel höchstens 4 % seiner Diagonale von ihr abweicht – sonst bleibt er Handschrift.
|
`geometry.rs` recognizes shapes purely geometrically, without machine learning. It first checks for an axis cross (all segments lie on one horizontal and one vertical line, both extending past the intersection on both sides). Closed shapes (circle, ellipse, triangle, rectangle, rhombus) compete with each other; the one whose outline fits the points best wins. Then polygons, arrows, coordinate systems and lines follow. A shape is only accepted if the stroke deviates from it by at most 4 % of its diagonal on average – otherwise it stays handwriting.
|
||||||
|
|
||||||
- **Linie:** Verhältnis von Abstand Anfang–Ende zur Strichlänge über 0,92.
|
- **Line:** ratio of start–end distance to stroke length above 0.92.
|
||||||
- **Kreis, Ellipse:** Kreis- bzw. Ellipsen-Fit über die Punkte.
|
- **Circle, ellipse:** circle or ellipse fit through the points.
|
||||||
- **Rechteck, Dreieck, Raute, Vieleck, Pfeil:** Analyse der mit Douglas-Peucker vereinfachten Kontur (Eckenzahl, Winkel, Seitenverhältnisse).
|
- **Rectangle, triangle, rhombus, polygon, arrow:** analysis of the contour simplified with Douglas-Peucker (number of corners, angles, aspect ratios).
|
||||||
- **Koordinatensystem:** zwei etwa rechtwinklige Achsen; der Winkel wird auf 90° gesetzt.
|
- **Coordinate system:** two roughly perpendicular axes; the angle is set to 90°.
|
||||||
- **Achsenkreuz:** ein „+“ in einem Zug; die Achsen werden waagerecht und senkrecht ausgerichtet und bekommen an allen vier Enden Pfeilspitzen.
|
- **Axis cross:** a "+" in one stroke; the axes are aligned horizontally and vertically and get arrowheads at all four ends.
|
||||||
- **Oktaeder:** Skizze einer Doppelpyramide als 3D-Kantenmodell; nur, wenn kein einfacher Umriss passt.
|
- **Octahedron:** sketch of a double pyramid as a 3D edge model; only if no simple outline fits.
|
||||||
|
|
||||||
**Halten am Strichende:** Bleibt der Stift über 400 ms innerhalb von 3 Pixeln ruhig, wird die erkannte Form schon vor dem Absetzen angezeigt und beim Absetzen übernommen. Mit dem Formen-Werkzeug wird jeder Strich beim Absetzen geprüft.
|
**Holding at the end of a stroke:** If the pen stays within 3 pixels for more than 400 ms, the recognized shape is shown before lifting and taken over when the pen is lifted. It uses the width of the selected pen or highlighter; a snapped highlighter stays a highlighter. With the shape tool, every stroke is checked when the pen is lifted.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 7. Speichern
|
## 7. Saving
|
||||||
|
|
||||||
```
|
```
|
||||||
[Änderung]
|
[Change]
|
||||||
│ mark_page_dirty / mark_manifest_dirty
|
│ mark_page_dirty / mark_manifest_dirty
|
||||||
▼
|
▼
|
||||||
[AutosaveController] ── 1,5 s nach der letzten Änderung, spätestens nach 10 s ──► [Autosave-Thread]
|
[AutosaveController] ── 1.5 s after the last change, at the latest after 10 s ──► [Autosave thread]
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
[temporäre Datei schreiben + fsync]
|
[write temporary file + fsync]
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
[rename über die alte Datei, Ordner-fsync]
|
[rename over the old file, folder fsync]
|
||||||
```
|
```
|
||||||
|
|
||||||
- Der Haupt-Thread schreibt nie selbst; er übergibt fertige Seitendaten an den Autosave-Thread.
|
- The main thread never writes itself; it hands finished page data to the autosave thread.
|
||||||
- Schlägt ein Schreibvorgang fehl, wird die Seite mit wachsendem Abstand (1 s bis 30 s) erneut versucht; der Status wird rot.
|
- If a write fails, the page is retried with increasing delay (1 s to 30 s); the status turns red.
|
||||||
- `flush()` schreibt alles Ausstehende und wartet darauf. Es läuft bei `Strg + S`, beim Wechsel des Notizbuchs und beim Beenden. Schlägt es beim Beenden fehl, bleibt die App offen und bietet Wiederholen oder einen Notfall-Export der ungespeicherten Seiten an (`~/.local/share/ink-notes/recovery/`).
|
- `flush()` writes everything pending and waits for it. It runs on `Ctrl + S`, when switching notebooks and when quitting. If it fails when quitting, the app stays open and offers to retry or to make an emergency export of the unsaved pages (`~/.local/share/ink-notes/recovery/`).
|
||||||
- Seiten werden erst beim Anzeigen geladen (Lazy Loading); Titel, Hintergrund und Größe stehen im Manifest, damit Seitenübersicht und durchgehende Ansicht sie vorher kennen.
|
- Pages are only loaded when shown (lazy loading); title, background and size are in the manifest, so the page overview and the continuous view know them in advance.
|
||||||
- Ein zweites Fenster mit demselben Notizbuch öffnet es schreibgeschützt (Sperrdatei).
|
- A second window with the same notebook opens it read-only (lock file).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 8. Export
|
## 8. Export
|
||||||
|
|
||||||
`export.rs` erzeugt das PDF mit `printpdf`. Jede Seite bekommt ihre eigene Größe und diese Ebenen:
|
`export.rs` creates the PDF with `printpdf`. Each page gets its own size and these layers:
|
||||||
|
|
||||||
1. **Background:** Karo, Linien oder Punkte in der gewählten Musterfarbe (immer auf weißem Papier).
|
1. **Background:** squares, lines or dots in the chosen pattern color (always on white paper).
|
||||||
2. **PDF** (nur im Notfall): importierte PDF-Seite als Bild, falls sie sich nicht als Vektor übernehmen lässt.
|
2. **PDF** (fallback only): imported PDF page as an image, if it cannot be taken over as vectors.
|
||||||
3. **Images:** eingefügte Bilder (höchstens 300 dpi).
|
3. **Images:** inserted images (at most 300 dpi).
|
||||||
4. **Text:** Textfelder als echter Text mit eingebetteter Schrift (durchsuchbar, kopierbar). Jedes Feld liegt in einem eigenen Koordinatensystem, das eine Transformationsmatrix auf seine Ecken abbildet.
|
4. **Text:** text boxes as real text with embedded font (searchable, copyable). Each box lives in its own coordinate system that a transformation matrix maps onto its corners.
|
||||||
5. **Ink:** Striche als gefüllte Polygone, Formen als Pfade. Halbtransparente Striche (Textmarker) bekommen einen Grafikzustand mit Deckkraft (`ca`/`CA`); printpdf kann solche Zustände nicht anlegen, deshalb trägt `add_alpha_states` sie nach dem Speichern mit `lopdf` in die Seitenressourcen ein. Jeder Strich ist ein einziger Pfad und deckt sich daher nicht selbst doppelt.
|
5. **Ink:** strokes as filled polygons, shapes as paths. Semi-transparent strokes (highlighter) get a graphics state with opacity (`ca`/`CA`); printpdf cannot create such states, so `add_alpha_states` adds them to the page resources with `lopdf` after saving. Each stroke is a single path and therefore does not cover itself twice.
|
||||||
|
|
||||||
Importierte PDF-Seiten werden anschließend als Form-XObject unter die Seite gelegt (`pdf_merge.rs`), bleiben also Vektorgrafik. Seitentitel werden zu Lesezeichen.
|
Imported PDF pages are then placed under the page as a form XObject (`pdf_merge.rs`), so they stay vector graphics. Page titles become bookmarks.
|
||||||
|
|
||||||
PNG und SVG einer Seite (`page_export.rs`) entstehen aus diesem PDF: `hayro` rastert es bzw. wandelt es in SVG um. So sehen alle Exporte gleich aus.
|
PNG and SVG of a page (`page_export.rs`) are created from this PDF: `hayro` rasterizes it or converts it to SVG. This way all exports look the same.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 9. Updates
|
## 9. Updates
|
||||||
|
|
||||||
`updater.rs` fragt die Gitea-Releases ab, vergleicht die Version (SemVer) und lädt auf Wunsch das passende Paket. Vor der Installation prüft er die Minisign-Signatur von `SHA256SUMS.txt` gegen den eingebauten Schlüssel und danach die SHA-256-Prüfsumme des Pakets. Ein AppImage wird per `rename` ersetzt; ein `.deb`-Paket wird mit `xdg-open` an die Softwareinstallation des Systems übergeben. Details im README unter „Sicherheit der Updates“.
|
`updater.rs` queries the Gitea releases, compares the version (SemVer) and downloads the matching package on request. Before installing, it verifies the Minisign signature of `SHA256SUMS.txt` against the built-in key and then the SHA-256 checksum of the package. An AppImage is replaced via `rename`; a `.deb` package is handed to the system's software installer with `xdg-open`. Details in the [README](../README.md#update-security) under "Update security".
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
# Dateiformat von ink-notes
|
||||||
|
|
||||||
|
[English](FILE_FORMAT.md) · **Deutsch**
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt, wo und wie ink-notes Notizbücher speichert, und die Versionen des Dateiformats. Aktuell ist **Version 9**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Ordner
|
||||||
|
|
||||||
|
```text
|
||||||
|
~/.local/share/ink-notes/ ($XDG_DATA_HOME/ink-notes)
|
||||||
|
├── notebooks/
|
||||||
|
│ ├── library.json Ordner der Notizbücher (siehe unten)
|
||||||
|
│ ├── <notizbuch-id>/
|
||||||
|
│ │ ├── manifest.json Metadaten und Seitenreihenfolge
|
||||||
|
│ │ ├── manifest.json.bak Kopie des vorherigen Manifests
|
||||||
|
│ │ ├── page_1.json eine Datei je Seite
|
||||||
|
│ │ ├── page_2.json
|
||||||
|
│ │ ├── page_7.json.corrupt-<ts> beiseitegelegte beschädigte Seite (falls vorgekommen)
|
||||||
|
│ │ ├── assets/ eingefügte Bilder und importierte PDFs
|
||||||
|
│ │ │ ├── <sha256>.png
|
||||||
|
│ │ │ └── <sha256>.pdf
|
||||||
|
│ │ └── .lock Sperrdatei, solange das Notizbuch geöffnet ist
|
||||||
|
│ └── .trash/ gelöschte Notizbücher (<id>_<zeitstempel>)
|
||||||
|
└── recovery/ Notfall-Sicherungen ungespeicherter Seiten
|
||||||
|
|
||||||
|
~/.config/ink-notes/ui.json ($XDG_CONFIG_HOME) Einstellungen der Oberfläche
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Notizbuch-IDs** werden aus dem Titel und dem Zeitpunkt gebildet (z. B. `mathematik_1775460000`); das erste Notizbuch heißt `default`.
|
||||||
|
- **Assets** sind nach dem SHA-256-Hash ihres Inhalts benannt; dasselbe Bild wird nur einmal gespeichert. Bilder werden als PNG oder (unverändert) JPEG abgelegt, PDFs unverändert.
|
||||||
|
- Alle Dateien werden mit Rechten `0600`, Ordner mit `0700` angelegt.
|
||||||
|
|
||||||
|
### Ordner (`library.json`)
|
||||||
|
Ordner wie „3. Semester › Mathe“ sind rein logisch: Die Notizbücher bleiben in ihren Verzeichnissen, `library.json` hält nur fest, welcher Ordner welches Notizbuch enthält. Umbenennen, Verschieben (samt Inhalt) und Löschen von Ordnern ändern deshalb nie eine Notizbuch-Datei.
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"folders": ["3. Semester", "3. Semester/Mathe", "4. Semester"],
|
||||||
|
"notebooks": { "analysis_1775460000": "3. Semester/Mathe" }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Ordner sind Pfade mit `/` als Trenner; Namen enthalten selbst kein `/` und höchstens 80 Zeichen.
|
||||||
|
- Notizbücher ohne Eintrag liegen auf der obersten Ebene.
|
||||||
|
- Wird ein Ordner gelöscht, rücken seine Notizbücher und Unterordner eine Ebene nach oben.
|
||||||
|
- Fehlt die Datei oder ist sie unlesbar, liegen alle Notizbücher auf der obersten Ebene; fehlende übergeordnete Ordner werden beim Laden ergänzt.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Manifest (`manifest.json`)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"format_version": 9,
|
||||||
|
"id": "vorlesung_1775460000",
|
||||||
|
"title": "Vorlesung",
|
||||||
|
"created_at": 1775460000,
|
||||||
|
"modified_at": 1775463600,
|
||||||
|
"current_page_index": 0,
|
||||||
|
"pages": [
|
||||||
|
{ "id": 1, "background": "Blank", "title": "Einführung", "size": [2970.0, 1671.0] },
|
||||||
|
{ "id": 2, "background": "Grid5mm" }
|
||||||
|
],
|
||||||
|
"page_ids": [1, 2],
|
||||||
|
"next_stroke_id": 42,
|
||||||
|
"next_page_id": 3,
|
||||||
|
"layout": "Paged"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Feld | Bedeutung |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `format_version` | Formatversion (siehe Abschnitt 5) |
|
||||||
|
| `id`, `title` | ID (= Ordnername) und Anzeigename |
|
||||||
|
| `created_at`, `modified_at` | UNIX-Zeit in Sekunden |
|
||||||
|
| `current_page_index` | zuletzt geöffnete Seite |
|
||||||
|
| `pages` | Seiten in ihrer Reihenfolge: `id`, `background`, optional `title` und `size` (siehe unten) – damit Seitenübersicht und Ansicht sie kennen, ohne jede Seite zu laden |
|
||||||
|
| `page_ids` | dieselbe Reihenfolge als reine ID-Liste (für ältere Versionen) |
|
||||||
|
| `next_stroke_id`, `next_page_id` | nächste freie IDs |
|
||||||
|
| `layout` | Anordnung der Seiten: `Paged` (Seite für Seite), `Continuous` (durchgehend untereinander) oder `Endless` (endlose Fläche, siehe unten). Seit 0.28; fehlt das Feld, gilt die frühere globale Einstellung `continuous_scroll` aus `ui.json`. Seit 0.30 werden neue Notizbücher als `Continuous` angelegt |
|
||||||
|
|
||||||
|
**Endlose Notizbücher** (Version 9) haben genau eine Seite der Größe `[100000.0, 100000.0]` (10 × 10 m). Der Startausschnitt ist ein DIN-A4-Rahmen in ihrer Mitte (ab `[48950, 48515]`); Koordinaten bleiben positiv. Beim Export wird nur der beschriebene Bereich mit 10 mm Rand zur PDF-Seite.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Seite (`page_<id>.json`)
|
||||||
|
|
||||||
|
Jede Seite liegt in einer eigenen Datei (kompaktes JSON, hier zur Lesbarkeit umbrochen):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"format_version": 8,
|
||||||
|
"id": 1,
|
||||||
|
"background": "Blank",
|
||||||
|
"title": "Einführung",
|
||||||
|
"size": [2970.0, 1671.0],
|
||||||
|
"pdf_background": { "asset": "<sha256>.pdf", "page": 0, "width_pt": 960.0, "height_pt": 540.0 },
|
||||||
|
"strokes": [ … ]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Feld | Bedeutung |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `background` | Muster: `Blank`, `Grid5mm`, `Lined`, `DotGrid` |
|
||||||
|
| `title` | Seitentitel (optional) |
|
||||||
|
| `size` | Seitengröße `[breite, höhe]` in Seiteneinheiten (10 = 1 mm); fehlt bei DIN A4 hoch (`[2100, 2970]`). Höchstens 2 × 2 m, außer der endlosen Seite `[100000, 100000]` |
|
||||||
|
| `pdf_background` | importierte PDF-Seite als Hintergrund (optional): Datei, Seitennummer ab 0, Größe in Punkt |
|
||||||
|
| `strokes` | alle Objekte der Seite, von unten nach oben |
|
||||||
|
|
||||||
|
### 3.1 Objekte (`strokes`)
|
||||||
|
|
||||||
|
Jedes Objekt hat eine `id`, eine `color` (RGBA, sRGB, Werte 0–1) und `samples`: Punkte mit `x`, `y` (Seiteneinheiten), `p` (Druck 0–1) und `t` (Zeit in Sekunden). Die Dreiecke für die Anzeige werden beim Laden aus den Punkten berechnet und nicht gespeichert.
|
||||||
|
|
||||||
|
**Tinte**
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "id": 7, "color": [0.12, 0.12, 0.14, 1.0],
|
||||||
|
"samples": [{ "x": 350.2, "y": 420.5, "p": 0.65, "t": 12.345 }, …],
|
||||||
|
"tool": "pen", "width": 5.0, "finalized": true }
|
||||||
|
```
|
||||||
|
|
||||||
|
- `tool`: `pen`, `highlighter` oder `shape` (ein zu einer Form eingerasteter Textmarker bleibt `highlighter` und hat zusätzlich `shape`)
|
||||||
|
- `width`: Strichbreite in Seiteneinheiten (5.0 = 0,5 mm)
|
||||||
|
- `finalized`: Der Strich wurde nach dem Absetzen nachbearbeitet (Glättung, Ecken, Endkappen)
|
||||||
|
|
||||||
|
**Formen** haben zusätzlich `shape`, z. B.:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"shape": { "Rectangle": { "corners": [[500, 600], [800, 600], [800, 800], [500, 800]] } }
|
||||||
|
```
|
||||||
|
|
||||||
|
Mögliche Formen: `Line { start, end }`, `Arrow { start, end, double }`, `Circle { center, radius }`, `Ellipse { center, radius_x, radius_y, rotation }`, `Rectangle { corners }`, `Triangle { corners }`, `Rhombus { corners }`, `Polygon { vertices }`, `CoordinateSystem { origin, x_axis_end, y_axis_end, with_arrows, negative_ends? }`, `Octahedron { … }`. Punkte sind `[x, y]`. Beim Achsenkreuz enthält `negative_ends` die Enden der x- und der y-Achse auf der anderen Seite des Ursprungs; ältere Versionen ignorieren das Feld und zeigen ein L-förmiges Koordinatensystem.
|
||||||
|
|
||||||
|
**Bilder** haben `image` (Dateiname in `assets/`); die vier `samples` sind die Ecken oben links, oben rechts, unten rechts, unten links:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "id": 9, "color": [1, 1, 1, 1], "samples": [ …4 Ecken… ], "width": 0.0, "image": "<sha256>.png" }
|
||||||
|
```
|
||||||
|
|
||||||
|
**Textfelder** haben `text`; die vier `samples` sind wie bei Bildern die Ecken des Felds:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"text": { "content": "Überschrift\nzweite Zeile", "size": 42.3, "font": "Sans", "wrap_width": 1500.0 }
|
||||||
|
```
|
||||||
|
|
||||||
|
- `size`: Schriftgröße (Em) in Seiteneinheiten (12 pt ≈ 42,3)
|
||||||
|
- `font`: `Sans` (Ubuntu Light) oder `Mono` (Hack)
|
||||||
|
- `wrap_width`: Umbruchbreite in Seiteneinheiten; die Ecken bilden das Feld dieser Breite (und der Höhe des gesetzten Texts) ab, Drehung und Skalierung stecken in den Ecken
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Sicherheit beim Speichern
|
||||||
|
|
||||||
|
### Atomares Schreiben
|
||||||
|
1. Der Inhalt wird in `<datei>.tmp.<pid>.<nanosekunden>` geschrieben und mit `fsync` auf den Datenträger gebracht.
|
||||||
|
2. `rename` ersetzt die alte Datei in einem Schritt.
|
||||||
|
3. Danach wird auch der Ordner mit `fsync` gesichert.
|
||||||
|
|
||||||
|
Ein Absturz während des Speicherns hinterlässt deshalb entweder die alte oder die neue Datei, nie eine halbe.
|
||||||
|
|
||||||
|
### Beschädigte Dateien
|
||||||
|
- Lässt sich eine Seite nicht lesen, wird sie nach `page_<id>.json.corrupt-<zeitstempel>` verschoben (nicht gelöscht) und die Seite schreibgeschützt angezeigt.
|
||||||
|
- Ist `manifest.json` beschädigt oder fehlt, wird `manifest.json.bak` verwendet.
|
||||||
|
|
||||||
|
### Gelöschte Seiten
|
||||||
|
Eine gelöschte Seite verschwindet aus `manifest.json`; ihre Datei `page_<id>.json` bleibt im Ordner liegen. Seitenkennungen werden nie wiederverwendet (`next_page_id`), die Datei kann also mit keiner neuen Seite kollidieren. Wird die Seite in derselben Sitzung wiederhergestellt, schreibt die App sie neu.
|
||||||
|
|
||||||
|
### Neuere Versionen
|
||||||
|
Dateien mit einer höheren `format_version` als der unterstützten werden nicht geöffnet – so kann eine ältere App-Version keine Inhalte verlieren, die sie nicht kennt.
|
||||||
|
|
||||||
|
### Migration
|
||||||
|
Beim ersten Speichern einer unversionierten Datei (Version 0) wird vorher eine Kopie `*.v0.bak` angelegt.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Versionen
|
||||||
|
|
||||||
|
| Version | App | Änderung |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| 0 | – | ohne `format_version` |
|
||||||
|
| 1 | – | `format_version`, Hintergründe im Manifest |
|
||||||
|
| 2 | – | `tool`, `width`, `finalized` an Strichen; kompaktes JSON |
|
||||||
|
| 3 | 0.3.7 | Formen `Ellipse` und `Arrow` |
|
||||||
|
| 4 | 0.5 | Bilder (`image`, Ordner `assets/`) |
|
||||||
|
| 5 | 0.6.1 | importierte PDF-Seiten (`pdf_background`) |
|
||||||
|
| 6 | 0.7 | Seitentitel (`title` in Seite und Manifest) |
|
||||||
|
| 7 | 0.10 | Textfelder (`text`) |
|
||||||
|
| 8 | 0.11 | Seitengröße je Seite (`size` in Seite und Manifest) |
|
||||||
|
| 9 | 0.29 | Seitenanordnung je Notizbuch (`layout` im Manifest), endlose Notizbücher |
|
||||||
|
|
||||||
|
Jede neue Version ändert nur Ergänzungen; ältere Dateien werden ohne Umwandlung gelesen und beim nächsten Speichern mit der aktuellen Versionsnummer geschrieben.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Warum JSON
|
||||||
|
|
||||||
|
Ein Binärformat (z. B. `postcard`) würde Dateien um weitere 20–30 % verkleinern. JSON bleibt trotzdem, weil es sich ansehen, vergleichen und im Notfall von Hand reparieren lässt und das Speichern einer Seite auch bei vielen Strichen deutlich unter einer Millisekunde dauert.
|
||||||
+91
-84
@@ -1,37 +1,39 @@
|
|||||||
# Dateiformat von ink-notes
|
# ink-notes file format
|
||||||
|
|
||||||
Dieses Dokument beschreibt, wo und wie ink-notes Notizbücher speichert, und die Versionen des Dateiformats. Aktuell ist **Version 8**.
|
**English** · [Deutsch](FILE_FORMAT.de.md)
|
||||||
|
|
||||||
|
This document describes where and how ink-notes stores notebooks, and the versions of the file format. The current version is **9**.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Ordner
|
## 1. Folders
|
||||||
|
|
||||||
```text
|
```text
|
||||||
~/.local/share/ink-notes/ ($XDG_DATA_HOME/ink-notes)
|
~/.local/share/ink-notes/ ($XDG_DATA_HOME/ink-notes)
|
||||||
├── notebooks/
|
├── notebooks/
|
||||||
│ ├── library.json Ordner der Notizbücher (siehe unten)
|
│ ├── library.json notebook folders (see below)
|
||||||
│ ├── <notizbuch-id>/
|
│ ├── <notebook-id>/
|
||||||
│ │ ├── manifest.json Metadaten und Seitenreihenfolge
|
│ │ ├── manifest.json metadata and page order
|
||||||
│ │ ├── manifest.json.bak Kopie des vorherigen Manifests
|
│ │ ├── manifest.json.bak copy of the previous manifest
|
||||||
│ │ ├── page_1.json eine Datei je Seite
|
│ │ ├── page_1.json one file per page
|
||||||
│ │ ├── page_2.json
|
│ │ ├── page_2.json
|
||||||
│ │ ├── page_7.json.corrupt-<ts> beiseitegelegte beschädigte Seite (falls vorgekommen)
|
│ │ ├── page_7.json.corrupt-<ts> damaged page set aside (if it ever happened)
|
||||||
│ │ ├── assets/ eingefügte Bilder und importierte PDFs
|
│ │ ├── assets/ inserted images and imported PDFs
|
||||||
│ │ │ ├── <sha256>.png
|
│ │ │ ├── <sha256>.png
|
||||||
│ │ │ └── <sha256>.pdf
|
│ │ │ └── <sha256>.pdf
|
||||||
│ │ └── .lock Sperrdatei, solange das Notizbuch geöffnet ist
|
│ │ └── .lock lock file while the notebook is open
|
||||||
│ └── .trash/ gelöschte Notizbücher (<id>_<zeitstempel>)
|
│ └── .trash/ deleted notebooks (<id>_<timestamp>)
|
||||||
└── recovery/ Notfall-Sicherungen ungespeicherter Seiten
|
└── recovery/ emergency backups of unsaved pages
|
||||||
|
|
||||||
~/.config/ink-notes/ui.json ($XDG_CONFIG_HOME) Einstellungen der Oberfläche
|
~/.config/ink-notes/ui.json ($XDG_CONFIG_HOME) interface settings
|
||||||
```
|
```
|
||||||
|
|
||||||
- **Notizbuch-IDs** werden aus dem Titel und dem Zeitpunkt gebildet (z. B. `mathematik_1775460000`); das erste Notizbuch heißt `default`.
|
- **Notebook IDs** are built from the title and the time (e.g. `mathematik_1775460000`); the first notebook is called `default`.
|
||||||
- **Assets** sind nach dem SHA-256-Hash ihres Inhalts benannt; dasselbe Bild wird nur einmal gespeichert. Bilder werden als PNG oder (unverändert) JPEG abgelegt, PDFs unverändert.
|
- **Assets** are named after the SHA-256 hash of their content; the same image is stored only once. Images are stored as PNG or (unchanged) JPEG, PDFs unchanged.
|
||||||
- Alle Dateien werden mit Rechten `0600`, Ordner mit `0700` angelegt.
|
- All files are created with permissions `0600`, folders with `0700`.
|
||||||
|
|
||||||
### Ordner (`library.json`)
|
### Folders (`library.json`)
|
||||||
Ordner wie „3. Semester › Mathe“ sind rein logisch: Die Notizbücher bleiben in ihren Verzeichnissen, `library.json` hält nur fest, welcher Ordner welches Notizbuch enthält. Umbenennen, Verschieben (samt Inhalt) und Löschen von Ordnern ändern deshalb nie eine Notizbuch-Datei.
|
Folders such as "Semester 3 › Math" are purely logical: notebooks stay in their directories, and `library.json` only records which folder contains which notebook. Renaming, moving (with content) and deleting folders therefore never changes a notebook file.
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -40,10 +42,10 @@ Ordner wie „3. Semester › Mathe“ sind rein logisch: Die Notizbücher bleib
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- Ordner sind Pfade mit `/` als Trenner; Namen enthalten selbst kein `/` und höchstens 80 Zeichen.
|
- Folders are paths with `/` as separator; names themselves contain no `/` and at most 80 characters.
|
||||||
- Notizbücher ohne Eintrag liegen auf der obersten Ebene.
|
- Notebooks without an entry are on the top level.
|
||||||
- Wird ein Ordner gelöscht, rücken seine Notizbücher und Unterordner eine Ebene nach oben.
|
- When a folder is deleted, its notebooks and subfolders move up one level.
|
||||||
- Fehlt die Datei oder ist sie unlesbar, liegen alle Notizbücher auf der obersten Ebene; fehlende übergeordnete Ordner werden beim Laden ergänzt.
|
- If the file is missing or unreadable, all notebooks are on the top level; missing parent folders are added when loading.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -51,7 +53,7 @@ Ordner wie „3. Semester › Mathe“ sind rein logisch: Die Notizbücher bleib
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"format_version": 8,
|
"format_version": 9,
|
||||||
"id": "vorlesung_1775460000",
|
"id": "vorlesung_1775460000",
|
||||||
"title": "Vorlesung",
|
"title": "Vorlesung",
|
||||||
"created_at": 1775460000,
|
"created_at": 1775460000,
|
||||||
@@ -63,25 +65,29 @@ Ordner wie „3. Semester › Mathe“ sind rein logisch: Die Notizbücher bleib
|
|||||||
],
|
],
|
||||||
"page_ids": [1, 2],
|
"page_ids": [1, 2],
|
||||||
"next_stroke_id": 42,
|
"next_stroke_id": 42,
|
||||||
"next_page_id": 3
|
"next_page_id": 3,
|
||||||
|
"layout": "Paged"
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
| Feld | Bedeutung |
|
| Field | Meaning |
|
||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
| `format_version` | Formatversion (siehe Abschnitt 5) |
|
| `format_version` | format version (see section 5) |
|
||||||
| `id`, `title` | ID (= Ordnername) und Anzeigename |
|
| `id`, `title` | ID (= folder name) and display name |
|
||||||
| `created_at`, `modified_at` | UNIX-Zeit in Sekunden |
|
| `created_at`, `modified_at` | UNIX time in seconds |
|
||||||
| `current_page_index` | zuletzt geöffnete Seite |
|
| `current_page_index` | page opened last |
|
||||||
| `pages` | Seiten in ihrer Reihenfolge: `id`, `background`, optional `title` und `size` (siehe unten) – damit Seitenübersicht und Ansicht sie kennen, ohne jede Seite zu laden |
|
| `pages` | pages in their order: `id`, `background`, optional `title` and `size` (see below) – so the page overview and the view know them without loading every page |
|
||||||
| `page_ids` | dieselbe Reihenfolge als reine ID-Liste (für ältere Versionen) |
|
| `page_ids` | the same order as a plain ID list (for older versions) |
|
||||||
| `next_stroke_id`, `next_page_id` | nächste freie IDs |
|
| `next_stroke_id`, `next_page_id` | next free IDs |
|
||||||
|
| `layout` | page arrangement: `Paged` (page by page), `Continuous` (seamlessly below each other) or `Endless` (endless canvas, see below). Since 0.28; if the field is missing, the former global setting `continuous_scroll` from `ui.json` applies. Since 0.30, new notebooks are created as `Continuous` |
|
||||||
|
|
||||||
|
**Endless notebooks** (version 9) have exactly one page of size `[100000.0, 100000.0]` (10 × 10 m). The starting area is an A4 frame in its middle (from `[48950, 48515]`); coordinates stay positive. On export, only the used area plus a 10 mm margin becomes the PDF page.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Seite (`page_<id>.json`)
|
## 3. Page (`page_<id>.json`)
|
||||||
|
|
||||||
Jede Seite liegt in einer eigenen Datei (kompaktes JSON, hier zur Lesbarkeit umbrochen):
|
Each page is stored in its own file (compact JSON, wrapped here for readability):
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -95,19 +101,19 @@ Jede Seite liegt in einer eigenen Datei (kompaktes JSON, hier zur Lesbarkeit umb
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
| Feld | Bedeutung |
|
| Field | Meaning |
|
||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
| `background` | Muster: `Blank`, `Grid5mm`, `Lined`, `DotGrid` |
|
| `background` | pattern: `Blank`, `Grid5mm`, `Lined`, `DotGrid` |
|
||||||
| `title` | Seitentitel (optional) |
|
| `title` | page title (optional) |
|
||||||
| `size` | Seitengröße `[breite, höhe]` in Seiteneinheiten (10 = 1 mm); fehlt bei DIN A4 hoch (`[2100, 2970]`) |
|
| `size` | page size `[width, height]` in page units (10 = 1 mm); omitted for A4 portrait (`[2100, 2970]`). At most 2 × 2 m, except for the endless page `[100000, 100000]` |
|
||||||
| `pdf_background` | importierte PDF-Seite als Hintergrund (optional): Datei, Seitennummer ab 0, Größe in Punkt |
|
| `pdf_background` | imported PDF page as background (optional): file, page number starting at 0, size in points |
|
||||||
| `strokes` | alle Objekte der Seite, von unten nach oben |
|
| `strokes` | all objects on the page, from bottom to top |
|
||||||
|
|
||||||
### 3.1 Objekte (`strokes`)
|
### 3.1 Objects (`strokes`)
|
||||||
|
|
||||||
Jedes Objekt hat eine `id`, eine `color` (RGBA, linear, Werte 0–1) und `samples`: Punkte mit `x`, `y` (Seiteneinheiten), `p` (Druck 0–1) und `t` (Zeit in Sekunden). Die Dreiecke für die Anzeige werden beim Laden aus den Punkten berechnet und nicht gespeichert.
|
Every object has an `id`, a `color` (RGBA, sRGB, values 0–1) and `samples`: points with `x`, `y` (page units), `p` (pressure 0–1) and `t` (time in seconds). The triangles for display are computed from the points when loading and are not stored.
|
||||||
|
|
||||||
**Tinte**
|
**Ink**
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{ "id": 7, "color": [0.12, 0.12, 0.14, 1.0],
|
{ "id": 7, "color": [0.12, 0.12, 0.14, 1.0],
|
||||||
@@ -115,78 +121,79 @@ Jedes Objekt hat eine `id`, eine `color` (RGBA, linear, Werte 0–1) und `sample
|
|||||||
"tool": "pen", "width": 5.0, "finalized": true }
|
"tool": "pen", "width": 5.0, "finalized": true }
|
||||||
```
|
```
|
||||||
|
|
||||||
- `tool`: `pen`, `highlighter` oder `shape`
|
- `tool`: `pen`, `highlighter` or `shape` (a highlighter snapped to a shape stays `highlighter` and also has `shape`)
|
||||||
- `width`: Strichbreite in Seiteneinheiten (5.0 = 0,5 mm)
|
- `width`: stroke width in page units (5.0 = 0.5 mm)
|
||||||
- `finalized`: Der Strich wurde nach dem Absetzen nachbearbeitet (Glättung, Ecken, Endkappen)
|
- `finalized`: the stroke was post-processed after the pen was lifted (smoothing, corners, end caps)
|
||||||
|
|
||||||
**Formen** haben zusätzlich `shape`, z. B.:
|
**Shapes** additionally have `shape`, e.g.:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
"shape": { "Rectangle": { "corners": [[500, 600], [800, 600], [800, 800], [500, 800]] } }
|
"shape": { "Rectangle": { "corners": [[500, 600], [800, 600], [800, 800], [500, 800]] } }
|
||||||
```
|
```
|
||||||
|
|
||||||
Mögliche Formen: `Line { start, end }`, `Arrow { start, end, double }`, `Circle { center, radius }`, `Ellipse { center, radius_x, radius_y, rotation }`, `Rectangle { corners }`, `Triangle { corners }`, `Rhombus { corners }`, `Polygon { vertices }`, `CoordinateSystem { origin, x_axis_end, y_axis_end, with_arrows, negative_ends? }`, `Octahedron { … }`. Punkte sind `[x, y]`. Beim Achsenkreuz enthält `negative_ends` die Enden der x- und der y-Achse auf der anderen Seite des Ursprungs; ältere Versionen ignorieren das Feld und zeigen ein L-förmiges Koordinatensystem.
|
Possible shapes: `Line { start, end }`, `Arrow { start, end, double }`, `Circle { center, radius }`, `Ellipse { center, radius_x, radius_y, rotation }`, `Rectangle { corners }`, `Triangle { corners }`, `Rhombus { corners }`, `Polygon { vertices }`, `CoordinateSystem { origin, x_axis_end, y_axis_end, with_arrows, negative_ends? }`, `Octahedron { … }`. Points are `[x, y]`. For an axis cross, `negative_ends` contains the ends of the x and y axes on the other side of the origin; older versions ignore the field and show an L-shaped coordinate system.
|
||||||
|
|
||||||
**Bilder** haben `image` (Dateiname in `assets/`); die vier `samples` sind die Ecken oben links, oben rechts, unten rechts, unten links:
|
**Images** have `image` (file name in `assets/`); the four `samples` are the corners top left, top right, bottom right, bottom left:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{ "id": 9, "color": [1, 1, 1, 1], "samples": [ …4 Ecken… ], "width": 0.0, "image": "<sha256>.png" }
|
{ "id": 9, "color": [1, 1, 1, 1], "samples": [ …4 corners… ], "width": 0.0, "image": "<sha256>.png" }
|
||||||
```
|
```
|
||||||
|
|
||||||
**Textfelder** haben `text`; die vier `samples` sind wie bei Bildern die Ecken des Felds:
|
**Text boxes** have `text`; like for images, the four `samples` are the corners of the box:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
"text": { "content": "Überschrift\nzweite Zeile", "size": 42.3, "font": "Sans", "wrap_width": 1500.0 }
|
"text": { "content": "Heading\nsecond line", "size": 42.3, "font": "Sans", "wrap_width": 1500.0 }
|
||||||
```
|
```
|
||||||
|
|
||||||
- `size`: Schriftgröße (Em) in Seiteneinheiten (12 pt ≈ 42,3)
|
- `size`: font size (em) in page units (12 pt ≈ 42.3)
|
||||||
- `font`: `Sans` (Ubuntu Light) oder `Mono` (Hack)
|
- `font`: `Sans` (Ubuntu Light) or `Mono` (Hack)
|
||||||
- `wrap_width`: Umbruchbreite in Seiteneinheiten; die Ecken bilden das Feld dieser Breite (und der Höhe des gesetzten Texts) ab, Drehung und Skalierung stecken in den Ecken
|
- `wrap_width`: wrap width in page units; the corners map the box of this width (and the height of the laid-out text), rotation and scaling are contained in the corners
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Sicherheit beim Speichern
|
## 4. Safe saving
|
||||||
|
|
||||||
### Atomares Schreiben
|
### Atomic writes
|
||||||
1. Der Inhalt wird in `<datei>.tmp.<pid>.<nanosekunden>` geschrieben und mit `fsync` auf den Datenträger gebracht.
|
1. The content is written to `<file>.tmp.<pid>.<nanoseconds>` and flushed to disk with `fsync`.
|
||||||
2. `rename` ersetzt die alte Datei in einem Schritt.
|
2. `rename` replaces the old file in one step.
|
||||||
3. Danach wird auch der Ordner mit `fsync` gesichert.
|
3. Afterwards the folder is synced with `fsync` too.
|
||||||
|
|
||||||
Ein Absturz während des Speicherns hinterlässt deshalb entweder die alte oder die neue Datei, nie eine halbe.
|
A crash while saving therefore leaves either the old or the new file, never a half-written one.
|
||||||
|
|
||||||
### Beschädigte Dateien
|
### Damaged files
|
||||||
- Lässt sich eine Seite nicht lesen, wird sie nach `page_<id>.json.corrupt-<zeitstempel>` verschoben (nicht gelöscht) und die Seite schreibgeschützt angezeigt.
|
- If a page cannot be read, it is moved to `page_<id>.json.corrupt-<timestamp>` (not deleted) and the page is shown read-only.
|
||||||
- Ist `manifest.json` beschädigt oder fehlt, wird `manifest.json.bak` verwendet.
|
- If `manifest.json` is damaged or missing, `manifest.json.bak` is used.
|
||||||
|
|
||||||
### Gelöschte Seiten
|
### Deleted pages
|
||||||
Eine gelöschte Seite verschwindet aus `manifest.json`; ihre Datei `page_<id>.json` bleibt im Ordner liegen. Seitenkennungen werden nie wiederverwendet (`next_page_id`), die Datei kann also mit keiner neuen Seite kollidieren. Wird die Seite in derselben Sitzung wiederhergestellt, schreibt die App sie neu.
|
A deleted page disappears from `manifest.json`; its file `page_<id>.json` stays in the folder. Page IDs are never reused (`next_page_id`), so the file cannot collide with a new page. If the page is restored in the same session, the app writes it again.
|
||||||
|
|
||||||
### Neuere Versionen
|
### Newer versions
|
||||||
Dateien mit einer höheren `format_version` als der unterstützten werden nicht geöffnet – so kann eine ältere App-Version keine Inhalte verlieren, die sie nicht kennt.
|
Files with a higher `format_version` than supported are not opened – this way an older app version cannot lose content it does not know.
|
||||||
|
|
||||||
### Migration
|
### Migration
|
||||||
Beim ersten Speichern einer unversionierten Datei (Version 0) wird vorher eine Kopie `*.v0.bak` angelegt.
|
Before the first save of an unversioned file (version 0), a copy `*.v0.bak` is created.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 5. Versionen
|
## 5. Versions
|
||||||
|
|
||||||
| Version | App | Änderung |
|
| Version | App | Change |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| 0 | – | ohne `format_version` |
|
| 0 | – | without `format_version` |
|
||||||
| 1 | – | `format_version`, Hintergründe im Manifest |
|
| 1 | – | `format_version`, backgrounds in the manifest |
|
||||||
| 2 | – | `tool`, `width`, `finalized` an Strichen; kompaktes JSON |
|
| 2 | – | `tool`, `width`, `finalized` on strokes; compact JSON |
|
||||||
| 3 | 0.3.7 | Formen `Ellipse` und `Arrow` |
|
| 3 | 0.3.7 | shapes `Ellipse` and `Arrow` |
|
||||||
| 4 | 0.5 | Bilder (`image`, Ordner `assets/`) |
|
| 4 | 0.5 | images (`image`, folder `assets/`) |
|
||||||
| 5 | 0.6.1 | importierte PDF-Seiten (`pdf_background`) |
|
| 5 | 0.6.1 | imported PDF pages (`pdf_background`) |
|
||||||
| 6 | 0.7 | Seitentitel (`title` in Seite und Manifest) |
|
| 6 | 0.7 | page titles (`title` in page and manifest) |
|
||||||
| 7 | 0.10 | Textfelder (`text`) |
|
| 7 | 0.10 | text boxes (`text`) |
|
||||||
| 8 | 0.11 | Seitengröße je Seite (`size` in Seite und Manifest) |
|
| 8 | 0.11 | page size per page (`size` in page and manifest) |
|
||||||
|
| 9 | 0.29 | page arrangement per notebook (`layout` in the manifest), endless notebooks |
|
||||||
|
|
||||||
Jede neue Version ändert nur Ergänzungen; ältere Dateien werden ohne Umwandlung gelesen und beim nächsten Speichern mit der aktuellen Versionsnummer geschrieben.
|
Each new version only adds things; older files are read without conversion and written with the current version number on the next save.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 6. Warum JSON
|
## 6. Why JSON
|
||||||
|
|
||||||
Ein Binärformat (z. B. `postcard`) würde Dateien um weitere 20–30 % verkleinern. JSON bleibt trotzdem, weil es sich ansehen, vergleichen und im Notfall von Hand reparieren lässt und das Speichern einer Seite auch bei vielen Strichen deutlich unter einer Millisekunde dauert.
|
A binary format (e.g. `postcard`) would make files another 20–30 % smaller. JSON stays anyway, because it can be inspected, diffed and repaired by hand in an emergency, and saving a page takes well under a millisecond even with many strokes.
|
||||||
@@ -1,18 +1,22 @@
|
|||||||
[Desktop Entry]
|
[Desktop Entry]
|
||||||
Version=1.0
|
Version=1.0
|
||||||
Name=ink-notes
|
Name=ink-notes
|
||||||
GenericName=Notizbuch- & Inking-App
|
GenericName=Note-Taking & Inking App
|
||||||
Comment=Handschriftliche Notizen mit Stift, Touch und Maus; PDFs beschriften
|
GenericName[de]=Notizbuch- & Inking-App
|
||||||
|
Comment=Handwritten notes with pen, touch and mouse; annotate PDFs
|
||||||
|
Comment[de]=Handschriftliche Notizen mit Stift, Touch und Maus; PDFs beschriften
|
||||||
Exec=ink-notes %F
|
Exec=ink-notes %F
|
||||||
Icon=eu.pansi.ink-notes
|
Icon=eu.pansi.ink-notes
|
||||||
Terminal=false
|
Terminal=false
|
||||||
Type=Application
|
Type=Application
|
||||||
Categories=Office;Graphics;Utility;
|
Categories=Office;Graphics;
|
||||||
Keywords=Note;Notiz;Pen;Stift;Ink;Inking;Stylus;Drawing;Zeichnen;PDF;Vector;Text;Annotation;
|
Keywords=Note;Pen;Ink;Inking;Stylus;Drawing;PDF;Vector;Text;Annotation;
|
||||||
StartupWMClass=ink-notes
|
Keywords[de]=Notiz;Stift;Ink;Inking;Stylus;Zeichnen;PDF;Vektor;Text;Annotation;
|
||||||
|
StartupWMClass=eu.pansi.ink-notes
|
||||||
MimeType=application/x-inknotes;
|
MimeType=application/x-inknotes;
|
||||||
Actions=NewWindow;
|
Actions=NewWindow;
|
||||||
|
|
||||||
[Desktop Action NewWindow]
|
[Desktop Action NewWindow]
|
||||||
Name=Neues Fenster
|
Name=New Window
|
||||||
|
Name[de]=Neues Fenster
|
||||||
Exec=ink-notes
|
Exec=ink-notes
|
||||||
@@ -4,22 +4,34 @@
|
|||||||
<metadata_license>CC0-1.0</metadata_license>
|
<metadata_license>CC0-1.0</metadata_license>
|
||||||
<project_license>MIT</project_license>
|
<project_license>MIT</project_license>
|
||||||
<name>ink-notes</name>
|
<name>ink-notes</name>
|
||||||
<summary>Notizbuch-App für Stift, Touch und Maus</summary>
|
<summary>Handwritten notes with pen, touch and mouse</summary>
|
||||||
|
<summary xml:lang="de">Notizbuch-App für Stift, Touch und Maus</summary>
|
||||||
<description>
|
<description>
|
||||||
<p>
|
<p>
|
||||||
ink-notes ist eine Notizbuch-App für Linux, geschrieben in Rust mit wgpu. Handschrift wird als
|
ink-notes is a notebook app for Linux tablets and convertibles. Handwriting is stored as
|
||||||
|
vectors; write with a pen, your finger, a touchpad or a mouse.
|
||||||
|
</p>
|
||||||
|
<p xml:lang="de">
|
||||||
|
ink-notes ist eine Notizbuch-App für Linux-Tablets und Convertibles. Handschrift wird als
|
||||||
Vektoren gespeichert; geschrieben wird mit Stift, Finger, Touchpad oder Maus.
|
Vektoren gespeichert; geschrieben wird mit Stift, Finger, Touchpad oder Maus.
|
||||||
</p>
|
</p>
|
||||||
<p>Funktionen:</p>
|
<p>Features:</p>
|
||||||
|
<p xml:lang="de">Funktionen:</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li>Stift und Textmarker mit Druckstärke, Glättung beim Schreiben und Ecken-Erhaltung</li>
|
<li>Pens and highlighter with pressure, smoothing while writing and sharp corners</li>
|
||||||
<li>Radierer für ganze Striche, Teilstriche oder nur Textmarker; virtuelles Lineal</li>
|
<li xml:lang="de">Stifte und Textmarker mit Druckstärke, Glättung beim Schreiben und Ecken-Erhaltung</li>
|
||||||
<li>Formerkennung (Linien, Pfeile, Kreise, Ellipsen, Rechtecke, Dreiecke, Rauten, Koordinatensysteme)</li>
|
<li>Shape recognition: hold at the end of a stroke to get clean lines, arrows, circles, rectangles, triangles and coordinate systems</li>
|
||||||
<li>Auswählen, Verschieben, Drehen, Skalieren und Umfärben; Rückgängig für alle Änderungen</li>
|
<li xml:lang="de">Formerkennung: am Strichende halten für saubere Linien, Pfeile, Kreise, Rechtecke, Dreiecke und Koordinatensysteme</li>
|
||||||
<li>Textfelder, Bilder und PDF-Import zum Beschriften (Querformat-Folien bekommen Querformat-Seiten)</li>
|
<li>Eraser for whole strokes, partial strokes or highlighter only; virtual ruler</li>
|
||||||
<li>Durchgehendes Scrollen, Zoom von 25 bis 1000 Prozent, Papier- und Musterfarben</li>
|
<li xml:lang="de">Radierer für ganze Striche, Teilstriche oder nur Textmarker; virtuelles Lineal</li>
|
||||||
<li>Mehrere Notizbücher, automatisches Speichern im Hintergrund</li>
|
<li>Select, move, rotate, scale and recolor; undo for every change</li>
|
||||||
<li>Export als PDF (mit durchsuchbarem Text), PNG oder SVG</li>
|
<li xml:lang="de">Auswählen, Verschieben, Drehen, Skalieren und Umfärben; Rückgängig für alle Änderungen</li>
|
||||||
|
<li>Text boxes, images and PDF import to annotate lecture slides and worksheets</li>
|
||||||
|
<li xml:lang="de">Textfelder, Bilder und PDF-Import zum Beschriften von Vorlesungsfolien und Übungsblättern</li>
|
||||||
|
<li>Notebooks in folders, continuous scrolling, automatic saving in the background</li>
|
||||||
|
<li xml:lang="de">Notizbücher in Ordnern, durchgehendes Scrollen, automatisches Speichern im Hintergrund</li>
|
||||||
|
<li>Export as PDF (with searchable text), PNG or SVG</li>
|
||||||
|
<li xml:lang="de">Export als PDF (mit durchsuchbarem Text), PNG oder SVG</li>
|
||||||
</ul>
|
</ul>
|
||||||
</description>
|
</description>
|
||||||
<launchable type="desktop-id">eu.pansi.ink-notes.desktop</launchable>
|
<launchable type="desktop-id">eu.pansi.ink-notes.desktop</launchable>
|
||||||
@@ -29,12 +41,128 @@
|
|||||||
<categories>
|
<categories>
|
||||||
<category>Office</category>
|
<category>Office</category>
|
||||||
<category>Graphics</category>
|
<category>Graphics</category>
|
||||||
<category>Utility</category>
|
|
||||||
</categories>
|
</categories>
|
||||||
|
<keywords>
|
||||||
|
<keyword>notes</keyword>
|
||||||
|
<keyword>handwriting</keyword>
|
||||||
|
<keyword>stylus</keyword>
|
||||||
|
<keyword>pen</keyword>
|
||||||
|
<keyword>PDF</keyword>
|
||||||
|
<keyword>annotate</keyword>
|
||||||
|
</keywords>
|
||||||
|
<supports>
|
||||||
|
<control>pointing</control>
|
||||||
|
<control>touch</control>
|
||||||
|
<control>tablet</control>
|
||||||
|
</supports>
|
||||||
<developer id="eu.pansi">
|
<developer id="eu.pansi">
|
||||||
<name>Harald</name>
|
<name>Harald Pansi</name>
|
||||||
</developer>
|
</developer>
|
||||||
<url type="homepage">https://gitea.pansi.eu/harald/ink-notes</url>
|
<url type="homepage">https://gitea.pansi.eu/harald/ink-notes</url>
|
||||||
<url type="bugtracker">https://gitea.pansi.eu/harald/ink-notes/issues</url>
|
<url type="bugtracker">https://gitea.pansi.eu/harald/ink-notes/issues</url>
|
||||||
|
<url type="vcs-browser">https://gitea.pansi.eu/harald/ink-notes</url>
|
||||||
|
<screenshots>
|
||||||
|
<screenshot type="default">
|
||||||
|
<caption>Notes with highlighter, handwriting and text boxes</caption>
|
||||||
|
<caption xml:lang="de">Notizen mit Textmarker, Handschrift und Textfeldern</caption>
|
||||||
|
<image>https://gitea.pansi.eu/harald/ink-notes/raw/tag/v0.26.1/packaging/screenshots/notes.png</image>
|
||||||
|
</screenshot>
|
||||||
|
<screenshot>
|
||||||
|
<caption>Recognized shapes: coordinate system, triangle, circle, octahedron</caption>
|
||||||
|
<caption xml:lang="de">Erkannte Formen: Koordinatensystem, Dreieck, Kreis, Oktaeder</caption>
|
||||||
|
<image>https://gitea.pansi.eu/harald/ink-notes/raw/tag/v0.26.1/packaging/screenshots/shapes.png</image>
|
||||||
|
</screenshot>
|
||||||
|
<screenshot>
|
||||||
|
<caption>Annotating imported PDF slides</caption>
|
||||||
|
<caption xml:lang="de">Importierte PDF-Folien beschriften</caption>
|
||||||
|
<image>https://gitea.pansi.eu/harald/ink-notes/raw/tag/v0.26.1/packaging/screenshots/pdf.png</image>
|
||||||
|
</screenshot>
|
||||||
|
</screenshots>
|
||||||
|
<branding>
|
||||||
|
<color type="primary" scheme_preference="light">#a8c8f0</color>
|
||||||
|
<color type="primary" scheme_preference="dark">#1f3a5f</color>
|
||||||
|
</branding>
|
||||||
<content_rating type="oars-1.1" />
|
<content_rating type="oars-1.1" />
|
||||||
|
<releases>
|
||||||
|
<release version="0.32.0" date="2026-10-21">
|
||||||
|
<description>
|
||||||
|
<p>The endless canvas starts at the top left and grows to the right and down. New text fields start short and grow with the text. The toolbar buttons are larger again on small screens. On Wayland, the title bar buttons work with a finger.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.31.0" date="2026-10-21">
|
||||||
|
<description>
|
||||||
|
<p>New view-only mode: with 👁 in the toolbar, pen, finger and mouse only scroll and zoom, and nothing can be changed by accident.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.30.2" date="2026-10-20">
|
||||||
|
<description>
|
||||||
|
<p>Ctrl+Plus and Ctrl+Minus zoom only the page again, no longer the whole interface. Text boxes being edited now sit exactly where the text ends up.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.30.1" date="2026-10-20">
|
||||||
|
<description>
|
||||||
|
<p>Snapped highlighter shapes keep the highlighter width. Sharp corners such as the tip of a "1" are drawn round instead of cut off, and strokes no longer jump when the pen lifts. Finger swipes glide more reliably.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.30.0" date="2026-10-19">
|
||||||
|
<description>
|
||||||
|
<p>Faster scrolling through long notebooks and PDFs: a quick finger swipe keeps gliding, and a scrollbar with page numbers jumps through the notebook. The mouse wheel scrolls further per step. New notebooks scroll continuously by default.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.29.1" date="2026-10-19">
|
||||||
|
<description>
|
||||||
|
<p>Moving, rotating and scaling large selections is smooth again and no longer keeps the processor busy. On endless notebooks the mouse wheel scrolls (Ctrl+wheel zooms).</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.29.0" date="2026-10-18">
|
||||||
|
<description>
|
||||||
|
<p>Endless notebooks: one surface without edges to write, pan and zoom in every direction. Choose it when creating a notebook or switch a single-page notebook in the menu; PDF export contains only the written area.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.28.0" date="2026-10-18">
|
||||||
|
<description>
|
||||||
|
<p>Each notebook remembers whether it flips page by page or scrolls continuously. New notebooks start with fixed pages; the layout can be chosen when creating a notebook and changed later in the menu.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.27.1" date="2026-10-18">
|
||||||
|
<description>
|
||||||
|
<p>The pens in the toolbar are shown as pencils in their own colour, so they are easy to tell apart.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.27.0" date="2026-10-18">
|
||||||
|
<description>
|
||||||
|
<p>Pictures keep their proportions when resized. A lock button in the selection tool switches between proportional and free resizing; pictures start locked, other objects free.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.26.2" date="2026-10-13">
|
||||||
|
<description>
|
||||||
|
<p>Smoother scrolling through large imported PDFs: pages no longer stall the display while they are prepared, and pages scrolled past quickly are skipped.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.26.1" date="2026-10-10">
|
||||||
|
<description>
|
||||||
|
<p>Screenshots in the app description for software centers. The app itself is unchanged.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.26.0" date="2026-10-10">
|
||||||
|
<description>
|
||||||
|
<p>Select and move objects with a finger; text and make-space tools also work with a finger. Exports go to the documents folder of the user directories.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.25.0" date="2026-10-09">
|
||||||
|
<description>
|
||||||
|
<p>English user interface; the language follows the system and can be changed in the menu. Holding to snap a shape tolerates a slightly trembling pen.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.24.0" date="2026-10-09">
|
||||||
|
<description>
|
||||||
|
<p>Axis cross from two crossing strokes.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.23.0" date="2026-10-09">
|
||||||
|
<description>
|
||||||
|
<p>The on-screen keyboard of GNOME appears when tapping a text field.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
</releases>
|
||||||
</component>
|
</component>
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,53 @@
|
|||||||
|
# Flatpak manifest for ink-notes (Flathub).
|
||||||
|
#
|
||||||
|
# Build and install locally (from the repository root):
|
||||||
|
# flatpak-builder --user --install --force-clean target/flatpak-build \
|
||||||
|
# packaging/flatpak/eu.pansi.ink-notes.yml
|
||||||
|
#
|
||||||
|
# Regenerate cargo-sources.json after every change to Cargo.lock:
|
||||||
|
# python3 flatpak-cargo-generator.py Cargo.lock -o packaging/flatpak/cargo-sources.json
|
||||||
|
# (flatpak-builder-tools, https://github.com/flatpak/flatpak-builder-tools/tree/master/cargo)
|
||||||
|
#
|
||||||
|
# For the Flathub submission, replace the `type: dir` source with the release tag
|
||||||
|
# (type: git, url, tag, commit).
|
||||||
|
id: eu.pansi.ink-notes
|
||||||
|
runtime: org.freedesktop.Platform
|
||||||
|
runtime-version: '26.08'
|
||||||
|
sdk: org.freedesktop.Sdk
|
||||||
|
sdk-extensions:
|
||||||
|
- org.freedesktop.Sdk.Extension.rust-stable
|
||||||
|
command: ink-notes
|
||||||
|
finish-args:
|
||||||
|
- --socket=wayland
|
||||||
|
- --socket=fallback-x11
|
||||||
|
- --share=ipc
|
||||||
|
- --device=dri
|
||||||
|
# The built-in file picker (inserting images and PDFs) works without a desktop portal and
|
||||||
|
# offers Pictures, Downloads and Desktop; exports (PDF, PNG, SVG) go to the Documents folder.
|
||||||
|
# Dragging from the file manager works from other folders too, via the document portal.
|
||||||
|
- --filesystem=xdg-pictures:ro
|
||||||
|
- --filesystem=xdg-download:ro
|
||||||
|
- --filesystem=xdg-desktop:ro
|
||||||
|
- --filesystem=xdg-documents
|
||||||
|
build-options:
|
||||||
|
append-path: /usr/lib/sdk/rust-stable/bin
|
||||||
|
env:
|
||||||
|
CARGO_HOME: /run/build/ink-notes/cargo
|
||||||
|
modules:
|
||||||
|
- name: ink-notes
|
||||||
|
buildsystem: simple
|
||||||
|
build-commands:
|
||||||
|
- cargo --offline build --release --locked
|
||||||
|
- install -Dm755 target/release/ink-notes /app/bin/ink-notes
|
||||||
|
- install -Dm644 packaging/eu.pansi.ink-notes.desktop /app/share/applications/eu.pansi.ink-notes.desktop
|
||||||
|
- install -Dm644 packaging/eu.pansi.ink-notes.metainfo.xml /app/share/metainfo/eu.pansi.ink-notes.metainfo.xml
|
||||||
|
- install -Dm644 assets/ink-notes.svg /app/share/icons/hicolor/scalable/apps/eu.pansi.ink-notes.svg
|
||||||
|
- install -Dm644 assets/ink-notes.png /app/share/icons/hicolor/256x256/apps/eu.pansi.ink-notes.png
|
||||||
|
sources:
|
||||||
|
- type: dir
|
||||||
|
path: ../..
|
||||||
|
skip:
|
||||||
|
- target
|
||||||
|
- .git
|
||||||
|
- .flatpak-builder
|
||||||
|
- cargo-sources.json
|
||||||
@@ -1,18 +1,22 @@
|
|||||||
[Desktop Entry]
|
[Desktop Entry]
|
||||||
Version=1.0
|
Version=1.0
|
||||||
Name=ink-notes
|
Name=ink-notes
|
||||||
GenericName=Notizbuch- & Inking-App
|
GenericName=Note-Taking & Inking App
|
||||||
Comment=Handschriftliche Notizen mit Stift, Touch und Maus; PDFs beschriften
|
GenericName[de]=Notizbuch- & Inking-App
|
||||||
|
Comment=Handwritten notes with pen, touch and mouse; annotate PDFs
|
||||||
|
Comment[de]=Handschriftliche Notizen mit Stift, Touch und Maus; PDFs beschriften
|
||||||
Exec=ink-notes %F
|
Exec=ink-notes %F
|
||||||
Icon=eu.pansi.ink-notes
|
Icon=eu.pansi.ink-notes
|
||||||
Terminal=false
|
Terminal=false
|
||||||
Type=Application
|
Type=Application
|
||||||
Categories=Office;Graphics;Utility;
|
Categories=Office;Graphics;
|
||||||
Keywords=Note;Notiz;Pen;Stift;Ink;Inking;Stylus;Drawing;Zeichnen;PDF;Vector;Text;Annotation;
|
Keywords=Note;Pen;Ink;Inking;Stylus;Drawing;PDF;Vector;Text;Annotation;
|
||||||
StartupWMClass=ink-notes
|
Keywords[de]=Notiz;Stift;Ink;Inking;Stylus;Zeichnen;PDF;Vektor;Text;Annotation;
|
||||||
|
StartupWMClass=eu.pansi.ink-notes
|
||||||
MimeType=application/x-inknotes;
|
MimeType=application/x-inknotes;
|
||||||
Actions=NewWindow;
|
Actions=NewWindow;
|
||||||
|
|
||||||
[Desktop Action NewWindow]
|
[Desktop Action NewWindow]
|
||||||
Name=Neues Fenster
|
Name=New Window
|
||||||
|
Name[de]=Neues Fenster
|
||||||
Exec=ink-notes
|
Exec=ink-notes
|
||||||
@@ -4,22 +4,34 @@
|
|||||||
<metadata_license>CC0-1.0</metadata_license>
|
<metadata_license>CC0-1.0</metadata_license>
|
||||||
<project_license>MIT</project_license>
|
<project_license>MIT</project_license>
|
||||||
<name>ink-notes</name>
|
<name>ink-notes</name>
|
||||||
<summary>Notizbuch-App für Stift, Touch und Maus</summary>
|
<summary>Handwritten notes with pen, touch and mouse</summary>
|
||||||
|
<summary xml:lang="de">Notizbuch-App für Stift, Touch und Maus</summary>
|
||||||
<description>
|
<description>
|
||||||
<p>
|
<p>
|
||||||
ink-notes ist eine Notizbuch-App für Linux, geschrieben in Rust mit wgpu. Handschrift wird als
|
ink-notes is a notebook app for Linux tablets and convertibles. Handwriting is stored as
|
||||||
|
vectors; write with a pen, your finger, a touchpad or a mouse.
|
||||||
|
</p>
|
||||||
|
<p xml:lang="de">
|
||||||
|
ink-notes ist eine Notizbuch-App für Linux-Tablets und Convertibles. Handschrift wird als
|
||||||
Vektoren gespeichert; geschrieben wird mit Stift, Finger, Touchpad oder Maus.
|
Vektoren gespeichert; geschrieben wird mit Stift, Finger, Touchpad oder Maus.
|
||||||
</p>
|
</p>
|
||||||
<p>Funktionen:</p>
|
<p>Features:</p>
|
||||||
|
<p xml:lang="de">Funktionen:</p>
|
||||||
<ul>
|
<ul>
|
||||||
<li>Stift und Textmarker mit Druckstärke, Glättung beim Schreiben und Ecken-Erhaltung</li>
|
<li>Pens and highlighter with pressure, smoothing while writing and sharp corners</li>
|
||||||
<li>Radierer für ganze Striche, Teilstriche oder nur Textmarker; virtuelles Lineal</li>
|
<li xml:lang="de">Stifte und Textmarker mit Druckstärke, Glättung beim Schreiben und Ecken-Erhaltung</li>
|
||||||
<li>Formerkennung (Linien, Pfeile, Kreise, Ellipsen, Rechtecke, Dreiecke, Rauten, Koordinatensysteme)</li>
|
<li>Shape recognition: hold at the end of a stroke to get clean lines, arrows, circles, rectangles, triangles and coordinate systems</li>
|
||||||
<li>Auswählen, Verschieben, Drehen, Skalieren und Umfärben; Rückgängig für alle Änderungen</li>
|
<li xml:lang="de">Formerkennung: am Strichende halten für saubere Linien, Pfeile, Kreise, Rechtecke, Dreiecke und Koordinatensysteme</li>
|
||||||
<li>Textfelder, Bilder und PDF-Import zum Beschriften (Querformat-Folien bekommen Querformat-Seiten)</li>
|
<li>Eraser for whole strokes, partial strokes or highlighter only; virtual ruler</li>
|
||||||
<li>Durchgehendes Scrollen, Zoom von 25 bis 1000 Prozent, Papier- und Musterfarben</li>
|
<li xml:lang="de">Radierer für ganze Striche, Teilstriche oder nur Textmarker; virtuelles Lineal</li>
|
||||||
<li>Mehrere Notizbücher, automatisches Speichern im Hintergrund</li>
|
<li>Select, move, rotate, scale and recolor; undo for every change</li>
|
||||||
<li>Export als PDF (mit durchsuchbarem Text), PNG oder SVG</li>
|
<li xml:lang="de">Auswählen, Verschieben, Drehen, Skalieren und Umfärben; Rückgängig für alle Änderungen</li>
|
||||||
|
<li>Text boxes, images and PDF import to annotate lecture slides and worksheets</li>
|
||||||
|
<li xml:lang="de">Textfelder, Bilder und PDF-Import zum Beschriften von Vorlesungsfolien und Übungsblättern</li>
|
||||||
|
<li>Notebooks in folders, continuous scrolling, automatic saving in the background</li>
|
||||||
|
<li xml:lang="de">Notizbücher in Ordnern, durchgehendes Scrollen, automatisches Speichern im Hintergrund</li>
|
||||||
|
<li>Export as PDF (with searchable text), PNG or SVG</li>
|
||||||
|
<li xml:lang="de">Export als PDF (mit durchsuchbarem Text), PNG oder SVG</li>
|
||||||
</ul>
|
</ul>
|
||||||
</description>
|
</description>
|
||||||
<launchable type="desktop-id">eu.pansi.ink-notes.desktop</launchable>
|
<launchable type="desktop-id">eu.pansi.ink-notes.desktop</launchable>
|
||||||
@@ -29,12 +41,128 @@
|
|||||||
<categories>
|
<categories>
|
||||||
<category>Office</category>
|
<category>Office</category>
|
||||||
<category>Graphics</category>
|
<category>Graphics</category>
|
||||||
<category>Utility</category>
|
|
||||||
</categories>
|
</categories>
|
||||||
|
<keywords>
|
||||||
|
<keyword>notes</keyword>
|
||||||
|
<keyword>handwriting</keyword>
|
||||||
|
<keyword>stylus</keyword>
|
||||||
|
<keyword>pen</keyword>
|
||||||
|
<keyword>PDF</keyword>
|
||||||
|
<keyword>annotate</keyword>
|
||||||
|
</keywords>
|
||||||
|
<supports>
|
||||||
|
<control>pointing</control>
|
||||||
|
<control>touch</control>
|
||||||
|
<control>tablet</control>
|
||||||
|
</supports>
|
||||||
<developer id="eu.pansi">
|
<developer id="eu.pansi">
|
||||||
<name>Harald</name>
|
<name>Harald Pansi</name>
|
||||||
</developer>
|
</developer>
|
||||||
<url type="homepage">https://gitea.pansi.eu/harald/ink-notes</url>
|
<url type="homepage">https://gitea.pansi.eu/harald/ink-notes</url>
|
||||||
<url type="bugtracker">https://gitea.pansi.eu/harald/ink-notes/issues</url>
|
<url type="bugtracker">https://gitea.pansi.eu/harald/ink-notes/issues</url>
|
||||||
|
<url type="vcs-browser">https://gitea.pansi.eu/harald/ink-notes</url>
|
||||||
|
<screenshots>
|
||||||
|
<screenshot type="default">
|
||||||
|
<caption>Notes with highlighter, handwriting and text boxes</caption>
|
||||||
|
<caption xml:lang="de">Notizen mit Textmarker, Handschrift und Textfeldern</caption>
|
||||||
|
<image>https://gitea.pansi.eu/harald/ink-notes/raw/tag/v0.26.1/packaging/screenshots/notes.png</image>
|
||||||
|
</screenshot>
|
||||||
|
<screenshot>
|
||||||
|
<caption>Recognized shapes: coordinate system, triangle, circle, octahedron</caption>
|
||||||
|
<caption xml:lang="de">Erkannte Formen: Koordinatensystem, Dreieck, Kreis, Oktaeder</caption>
|
||||||
|
<image>https://gitea.pansi.eu/harald/ink-notes/raw/tag/v0.26.1/packaging/screenshots/shapes.png</image>
|
||||||
|
</screenshot>
|
||||||
|
<screenshot>
|
||||||
|
<caption>Annotating imported PDF slides</caption>
|
||||||
|
<caption xml:lang="de">Importierte PDF-Folien beschriften</caption>
|
||||||
|
<image>https://gitea.pansi.eu/harald/ink-notes/raw/tag/v0.26.1/packaging/screenshots/pdf.png</image>
|
||||||
|
</screenshot>
|
||||||
|
</screenshots>
|
||||||
|
<branding>
|
||||||
|
<color type="primary" scheme_preference="light">#a8c8f0</color>
|
||||||
|
<color type="primary" scheme_preference="dark">#1f3a5f</color>
|
||||||
|
</branding>
|
||||||
<content_rating type="oars-1.1" />
|
<content_rating type="oars-1.1" />
|
||||||
|
<releases>
|
||||||
|
<release version="0.32.0" date="2026-10-21">
|
||||||
|
<description>
|
||||||
|
<p>The endless canvas starts at the top left and grows to the right and down. New text fields start short and grow with the text. The toolbar buttons are larger again on small screens. On Wayland, the title bar buttons work with a finger.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.31.0" date="2026-10-21">
|
||||||
|
<description>
|
||||||
|
<p>New view-only mode: with 👁 in the toolbar, pen, finger and mouse only scroll and zoom, and nothing can be changed by accident.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.30.2" date="2026-10-20">
|
||||||
|
<description>
|
||||||
|
<p>Ctrl+Plus and Ctrl+Minus zoom only the page again, no longer the whole interface. Text boxes being edited now sit exactly where the text ends up.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.30.1" date="2026-10-20">
|
||||||
|
<description>
|
||||||
|
<p>Snapped highlighter shapes keep the highlighter width. Sharp corners such as the tip of a "1" are drawn round instead of cut off, and strokes no longer jump when the pen lifts. Finger swipes glide more reliably.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.30.0" date="2026-10-19">
|
||||||
|
<description>
|
||||||
|
<p>Faster scrolling through long notebooks and PDFs: a quick finger swipe keeps gliding, and a scrollbar with page numbers jumps through the notebook. The mouse wheel scrolls further per step. New notebooks scroll continuously by default.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.29.1" date="2026-10-19">
|
||||||
|
<description>
|
||||||
|
<p>Moving, rotating and scaling large selections is smooth again and no longer keeps the processor busy. On endless notebooks the mouse wheel scrolls (Ctrl+wheel zooms).</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.29.0" date="2026-10-18">
|
||||||
|
<description>
|
||||||
|
<p>Endless notebooks: one surface without edges to write, pan and zoom in every direction. Choose it when creating a notebook or switch a single-page notebook in the menu; PDF export contains only the written area.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.28.0" date="2026-10-18">
|
||||||
|
<description>
|
||||||
|
<p>Each notebook remembers whether it flips page by page or scrolls continuously. New notebooks start with fixed pages; the layout can be chosen when creating a notebook and changed later in the menu.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.27.1" date="2026-10-18">
|
||||||
|
<description>
|
||||||
|
<p>The pens in the toolbar are shown as pencils in their own colour, so they are easy to tell apart.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.27.0" date="2026-10-18">
|
||||||
|
<description>
|
||||||
|
<p>Pictures keep their proportions when resized. A lock button in the selection tool switches between proportional and free resizing; pictures start locked, other objects free.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.26.2" date="2026-10-13">
|
||||||
|
<description>
|
||||||
|
<p>Smoother scrolling through large imported PDFs: pages no longer stall the display while they are prepared, and pages scrolled past quickly are skipped.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.26.1" date="2026-10-10">
|
||||||
|
<description>
|
||||||
|
<p>Screenshots in the app description for software centers. The app itself is unchanged.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.26.0" date="2026-10-10">
|
||||||
|
<description>
|
||||||
|
<p>Select and move objects with a finger; text and make-space tools also work with a finger. Exports go to the documents folder of the user directories.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.25.0" date="2026-10-09">
|
||||||
|
<description>
|
||||||
|
<p>English user interface; the language follows the system and can be changed in the menu. Holding to snap a shape tolerates a slightly trembling pen.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.24.0" date="2026-10-09">
|
||||||
|
<description>
|
||||||
|
<p>Axis cross from two crossing strokes.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
<release version="0.23.0" date="2026-10-09">
|
||||||
|
<description>
|
||||||
|
<p>The on-screen keyboard of GNOME appears when tapping a text field.</p>
|
||||||
|
</description>
|
||||||
|
</release>
|
||||||
|
</releases>
|
||||||
</component>
|
</component>
|
||||||
@@ -1,54 +1,73 @@
|
|||||||
## ink-notes {{TAG_NAME}}
|
## ink-notes {{TAG_NAME}}
|
||||||
|
|
||||||
Notizbuch-App für Stift, Touch und Maus unter Linux (getestet mit Zorin OS 18 / Ubuntu 24.04).
|
Notebook app for pen, touch and mouse on Linux (tested on Zorin OS 18 / Ubuntu 24.04).
|
||||||
|
|
||||||
### Highlights:
|
### Highlights:
|
||||||
- **Platz schaffen**: Neues Werkzeug ↕ – aufs Blatt tippen und nach unten ziehen, alles darunter rutscht mit, auch auf den folgenden Seiten (über das Seitenende hinaus geht es auf der nächsten Seite weiter, fehlende Seiten werden angehängt); nach oben ziehen schließt leeren Platz; ein Schritt für Rückgängig
|
- **Feedback round**: The endless canvas starts at the top left and only grows to the right and down; new text fields start short and grow with the text; toolbar buttons are larger again on small screens; on Wayland the title bar buttons (close, minimize, maximize) and moving the window work with a finger
|
||||||
- **Achsenkreuz**: Ein „+“ in einem Zug (mit Halten oder dem Formen-Werkzeug) wird zum Achsenkreuz mit Pfeilspitzen an allen vier Enden; auch im PDF-/Bildexport
|
- **View only**: 👁 in the toolbar hides the tools – pen, finger and mouse only scroll and zoom (the pen glides on like a finger), nothing can be changed by accident; tap 👁 again to write
|
||||||
- **Fehlerbehebung Stift**: Das erste Antippen mit dem Stift trifft jetzt – Knöpfe und Notizbücher reagieren sofort statt erst beim zweiten Tippen; Striche beginnen nicht mehr mit einer Linie von der vorherigen Stiftposition
|
- **Text box fix**: Ctrl+Plus/Minus now only zooms the page, no longer the whole interface as well – that made text jump to another place when leaving a text box
|
||||||
- **Tasten am Stift belegen**: Im ☰-Menü unter Eingabe jede Stifttaste mit Radieren, Auswählen, Textmarker, Stift oder Nichts belegen (gilt, solange die Taste gedrückt ist); Tasten erscheinen nach dem ersten Drücken und leuchten beim Drücken grün
|
- **Writing fixes**: A snapped highlighter keeps its width; tips (e.g. of a "1" or of exponents) are drawn round instead of cut off, and the stroke no longer jumps when the pen lifts. Finger swipes glide more reliably
|
||||||
- **Ordner verschieben**: Ordner lassen sich jetzt wie Notizbücher mit 📂 samt Inhalt in andere Ordner oder auf die oberste Ebene verschieben
|
- **Faster scrolling**: A quick finger swipe keeps gliding; in the continuous view a scrollbar (opposite the toolbar, with the page number while dragging) jumps through long notebooks and PDFs; the mouse wheel scrolls twice as far. New notebooks are continuous; fixed pages are still available in the ☰ menu
|
||||||
- **Ordner für Notizbücher**: Beliebig verschachtelte Ordner (z. B. 3. Semester › Mathe) im Dokumenten-Manager anlegen, umbenennen und löschen, Notizbücher mit 📂 verschieben; neue Notizbücher landen im geöffneten Ordner. Die Notizbuch-Dateien bleiben unverändert (Zuordnung in library.json)
|
- **Selection fix**: Moving, rotating and scaling large selections is smooth again and no longer maxes out the CPU (since 0.27 the selection was copied several times per frame). On the endless canvas the mouse wheel scrolls (Ctrl+wheel zooms)
|
||||||
- **Einfügen per Finger**: Lange (½ s) mit dem Finger aufs Blatt drücken öffnet ein Menü „Einfügen“ – Screenshot, kopierter Text oder kopierte Objekte landen genau an dieser Stelle (wie in Rnote)
|
- **Endless canvas**: New page arrangement "♾ Endless" – a borderless canvas to write, pan and zoom in every direction. Selectable when creating a notebook or in the ☰ menu (for notebooks with one page); the PDF export only contains the used area. New file format version 9: older app versions no longer open notebooks of this version
|
||||||
- **Eigene Farben**: Jede Farbe der Werkzeugleiste (Stifte, Textmarker, Text) lässt sich anpassen – erneut antippen, Vorgabe oder mit 🎨 frei wählen; die Leiste merkt sich die Farben. Farben am Bildschirm wie im PDF-/Bildexport (Schwarz ist schwarz, Textmarker mischt wie im PDF); Karos und Linien im PDF so hell wie am Bildschirm
|
- **Page arrangement per notebook**: Selectable when creating a notebook – "Fixed pages" (default) or "Continuous" – and switchable later in the ☰ menu. Existing notebooks keep their previous setting
|
||||||
- **Beta-Feedback II**: Vier Stifte mit eigener Farbe und Stärke, die sich Änderungen merken; Textmarker wird innerhalb eines Strichs nicht dunkler und ist jetzt auch im PDF-/PNG-/SVG-Export durchsichtig; Seiten lückenlos untereinander mit Trennlinie; neue Seite per ➕ in der Werkzeugleiste; Seite löschen im ☰-Menü (wiederherstellbar); Koordinatensystem ohne Loch am Ursprung
|
- **Pens in their color**: The pens in the toolbar appear as pens in their own color instead of a thin stroke, so they can be told apart at a glance
|
||||||
- **Fehlerbehebungen**: Umbenennen und Löschen in der Notizbuchverwaltung reagieren wieder; Karos, Linien und Punkte werden pro Pixel berechnet und liegen in jedem Zoom gleichmäßig (mindestens ein Pixel breit, kantengeglättet)
|
- **Scale images without distortion**: With the selection tool, a lock below the pen colors switches between uniform (🔒) and free scaling (🔓). Images start locked, strokes and shapes free; on a computer, the Shift key also locks
|
||||||
- **Strichqualität**: Kleine Schleifen wie in „o“, „a“ oder „e“ bleiben rund (der fertige Strich entsteht aus den ungefilterten Stiftpunkten); Strichkanten werden kantengeglättet (4× Multisampling), runde Strichenden sind feiner unterteilt
|
- **Smoother scrolling in large PDFs**: Newly rendered PDF pages no longer pause the display, and pages you scroll past quickly are skipped instead of rendered one after another
|
||||||
- **Musterfarbe**: Karos, Linien und Punkte in hell, mittel, kräftig, blau oder grün (☰-Menü, gilt auch im Export); Punkte des Punktrasters am Bildschirm so groß wie im Export (0,4 mm). README und Dokumentation überarbeitet
|
- **Screenshots for Flathub**: The app description (metainfo) now shows three screenshots; nothing changes in the app itself
|
||||||
- **Beta-Feedback**: Querformat-PDFs (z. B. PowerPoint-Folien) bekommen Querformat-Seiten ohne leeren Streifen (Dateiformat-Version 8); neue Seiten direkt nach der aktuellen einfügen; Auswahlwerkzeug funktioniert mit dem Stift; Zoom bis 1000 % mit schärfer nachgerenderten PDF-Seiten
|
- **Selecting with a finger**: In the selection tool, a finger selects and moves objects (on empty space it keeps scrolling); text and make space work with a finger too
|
||||||
- **Text-Werkzeug**: Mit T ins Blatt tippen und schreiben – normale oder Code-Schrift, 8–36 pt, Zeilenumbruch am Feldrand; Textfelder verschieben, drehen und skalieren wie Bilder; im PDF echter, durchsuchbarer Text; kopierter Text wird mit Strg+V zum Textfeld (Dateiformat-Version 7)
|
- **Flatpak**: Manifest under packaging/flatpak (preparation for Flathub); exports go to the Documents folder from the user directories (e.g. ~/Documents)
|
||||||
- **Durchgehendes Scrollen**: Seiten untereinander mit Mausrad, Finger oder Touchpad scrollen (Strg+Mausrad zoomt); Schreiben im unteren Fünftel der letzten Seite hängt automatisch eine neue an; abschaltbar unter ☰ → Ansicht
|
- **English interface**: ink-notes follows the system language (German or English); switch it in the ☰ menu under "Sprache / Language"
|
||||||
- **Virtuelles Lineal**: Ein- und ausblenden mit L oder über die Werkzeugleiste; verschieben, am Griff drehen (rastet bei 15° ein); Striche entlang einer Kante werden exakt gerade – mit Stift, Textmarker und Formwerkzeug
|
- **Hold to snap**: now tolerates the slight jitter of a resting pen, so shapes also snap in the normal pen mode
|
||||||
- **Teilstrich-Radierer**: Nur den überstrichenen Teil eines Strichs entfernen – ein Radierzug ist ein Undo-Schritt
|
- **Axis cross from two strokes**: Draw a horizontal and a vertical line crossing each other – the second one with hold or the shape tool – and both become an axis cross with arrowheads at all four ends; undo restores the first line
|
||||||
- **Export & Zwischenablage**: Aktuelle Seite als PNG (auch transparent) oder SVG; Strg+C legt die Auswahl zusätzlich als Bild in die Zwischenablage für Chat, Mail oder Office
|
- **On-screen keyboard**: On GNOME/Zorin (Wayland) the on-screen keyboard now appears when tapping a name field – with finger or pen; typing and backspace work. Also, the first finger tap after using the mouse is no longer lost
|
||||||
- **Seitentitel & Inhaltsverzeichnis**: Seiten benennen, Inhaltsansicht in der Seitenübersicht, Titel werden zu PDF-Lesezeichen (Dateiformat-Version 6)
|
- **App icon**: The window identifies itself as eu.pansi.ink-notes – the dock and taskbar show the ink-notes icon instead of a generic one (on X11 also as window icon)
|
||||||
- **PDF importieren & annotieren**: Vorlesungsfolien, Übungsblätter oder Formulare als neues Notizbuch öffnen (☰-Menü oder Drag & Drop), darauf schreiben und markieren; beim Export liegen die Originalseiten verlustfrei als Vektor unter den Notizen (Dateiformat-Version 5: ältere Versionen öffnen solche Notizbücher nicht)
|
- **Make space**: New tool ↕ – tap the page and drag down, everything below moves along, also on the following pages (past the end of a page it continues on the next one, missing pages are appended); dragging up closes empty space; one step for undo
|
||||||
- **Bilder einfügen**: Screenshots per Strg+V, Bilddateien über die eingebaute Dateiauswahl (Strg+I) oder per Drag & Drop; verschieben, drehen, skalieren und darauf schreiben – auch im PDF-Export (Dateiformat-Version 4: ältere Versionen öffnen solche Notizbücher nicht)
|
- **Axis cross**: A "+" in one stroke (with hold or the shape tool) becomes an axis cross with arrowheads at all four ends; also in PDF/image export
|
||||||
- **Dunkelmodus & Papierfarben**: Weiß, Creme, Dunkelgrau oder Schwarz; auf dunklem Papier werden dunkle Stiftfarben automatisch aufgehellt (nur Anzeige – Dateien und PDF-Export bleiben unverändert)
|
- **Pen fix**: The first tap with the pen now registers – buttons and notebooks react immediately instead of on the second tap; strokes no longer start with a line from the previous pen position
|
||||||
- **Nur Textmarker radieren**: Markierungen korrigieren, ohne die Handschrift darunter zu löschen – auch mit Stiftrückseite und Seitentaste
|
- **Assign pen buttons**: In the ☰ menu under input, assign each pen button to erase, select, highlighter, pen or nothing (active while the button is held); buttons appear after the first press and light up green when pressed
|
||||||
- **Einstellbare Druckkurve**: Kennlinie weich bis hart und Mindestdruck mit Vorschau, zum Anpassen an den eigenen Stift
|
- **Move folders**: Folders can now be moved with 📂 including their content into other folders or to the top level, like notebooks
|
||||||
- **Neue Formen**: Ellipsen sowie in einem Zug gezeichnete Pfeile und Doppelpfeile werden erkannt (Dateiformat-Version 3: ältere Versionen öffnen solche Notizbücher nicht)
|
- **Folders for notebooks**: Create, rename and delete nested folders (e.g. Semester 3 › Math) in the document manager and move notebooks with 📂; new notebooks are created in the open folder. The notebook files stay unchanged (assignment in library.json)
|
||||||
- **Stabiler Start**: Kein Absturz mehr, wenn die Grafikkarte nicht nutzbar ist (z. B. fehlende Rechte auf /dev/dri); Software-Renderer als Ausweichlösung und verständliche Fehlermeldung
|
- **Paste with a finger**: Pressing the page with a finger for half a second opens a "Paste" menu – a screenshot, copied text or copied objects land exactly at that spot (like in Rnote)
|
||||||
- **WSL (WSLg)**: Läuft unter WSL automatisch über X11 statt Wayland, da WSLg die Wayland-Verbindung abbricht; übersteuerbar mit `INK_NOTES_DISPLAY=x11|wayland`
|
- **Custom colors**: Every toolbar color (pens, highlighter, text) can be changed – tap it again, pick a preset or any color with 🎨; the toolbar remembers the colors. Colors on screen match the PDF/image export (black is black, the highlighter blends like in the PDF); squares and lines in the PDF are as light as on screen
|
||||||
- **Wichtige Fehlerbehebung**: Nach einem Neustart auf einer späteren Seite konnte Weiterschreiben den bisherigen Inhalt dieser Seite überschreiben (betrifft v0.2.3 – v0.3.2)
|
- **Beta feedback II**: Four pens with their own color and width that remember changes; the highlighter no longer gets darker within one stroke and is now transparent in PDF/PNG/SVG exports too; pages seamlessly below each other with a separator line; new page via ➕ in the toolbar; delete a page in the ☰ menu (restorable); coordinate system without a gap at the origin
|
||||||
- **Neue Werkzeugleiste**: Schmale senkrechte Leiste mit Symbol-Knöpfen, links oder rechts andockbar; selten genutzte Funktionen im ☰-Menü, das Blatt wird daneben zentriert
|
- **Fixes**: Renaming and deleting in the notebook manager respond again; squares, lines and dots are computed per pixel and are even at every zoom level (at least one pixel wide, anti-aliased)
|
||||||
- **Einheitliche Dialoge**: Deckende Fenster ohne doppelte Titel, Seitenauswahl mit Vorschaubildern, größere Bedienelemente in allen Popovern
|
- **Stroke quality**: Small loops as in "o", "a" or "e" stay round (the final stroke is built from the unfiltered pen points); stroke edges are anti-aliased (4× multisampling), round stroke ends are subdivided more finely
|
||||||
- **UI per Stift und Touch bedienbar**: Werkzeugleiste, Popover und Dialoge reagieren jetzt auch auf Stift und Finger, auch bei Display-Skalierung
|
- **Pattern color**: Squares, lines and dots in light, medium, strong, blue or green (☰ menu, also applies to exports); dots of the dot grid on screen are as large as in the export (0.4 mm). README and documentation revised
|
||||||
- **Aktive Stylus-Unterstützung (Lazarite / MPP / AES)**: Stifteingabe über das Tablet-Protokoll von Wayland bzw. X11, mit Druckstärke
|
- **Beta feedback**: Landscape PDFs (e.g. PowerPoint slides) get landscape pages without an empty strip (file format version 8); insert new pages right after the current one; the selection tool works with the pen; zoom up to 1000 % with PDF pages re-rendered more sharply
|
||||||
- **Touchscreen Multi-Touch**: Zoomen mit zwei Fingern, Verschieben mit einem; Zeichnen mit dem Finger zuschaltbar
|
- **Text tool**: Tap the page with T and type – regular or code font, 8–36 pt, line wrapping at the box edge; move, rotate and scale text boxes like images; real, searchable text in the PDF; copied text becomes a text box with Ctrl+V (file format version 7)
|
||||||
- **Zwei-Stufen-Inking-Modell**: Glättung während des Schreibens (1€-Filter), beim Absetzen Nachbearbeitung mit Ecken-Erhaltung
|
- **Continuous scrolling**: Scroll through pages below each other with mouse wheel, finger or touchpad (Ctrl+wheel zooms); writing in the bottom fifth of the last page appends a new one automatically; can be turned off under ☰ → View
|
||||||
- **Geometrie- und Formerkennung**: Geraden, Pfeile & Doppelpfeile, Rechtecke, Kreise, Ellipsen, Dreiecke, Rauten, Vielecke & Koordinatensysteme mit spitzen Pfeilspitzen (Draw-and-Hold); Freiformen bleiben unverändert
|
- **Virtual ruler**: Show and hide with L or via the toolbar; move it, rotate it by the handle (snaps to 15°); strokes along an edge become exactly straight – with pen, highlighter and shape tool
|
||||||
- **Mehrere Notizbücher**: Anlegen, umbenennen, löschen (mit Papierkorb); automatisches Speichern im Hintergrund
|
- **Partial-stroke eraser**: Remove only the part of a stroke you wipe over – one erase stroke is one undo step
|
||||||
- **Datensicherheit**: Versioniertes Dateiformat mit Migration, beschädigte Seiten werden beiseitegelegt statt überschrieben, Schutz vor gleichzeitigem Öffnen, atomares Speichern
|
- **Export & clipboard**: Current page as PNG (also transparent) or SVG; Ctrl+C also puts the selection on the clipboard as an image for chat, email or office apps
|
||||||
- **In-App Updater**: Prüft auf neue Versionen auf Gitea und installiert sie auf Wunsch – nur mit gültiger Minisign-Signatur und über HTTPS
|
- **Page titles & table of contents**: Name pages, table of contents view in the page overview, titles become PDF bookmarks (file format version 6)
|
||||||
- **PDF-Export**: Striche und Formen als Vektoren, für Druck und Weitergabe
|
- **Import & annotate PDFs**: Open lecture slides, exercise sheets or forms as a new notebook (☰ menu or drag & drop), write and highlight on them; on export the original pages lie losslessly as vectors under the notes (file format version 5: older versions do not open such notebooks)
|
||||||
|
- **Insert images**: Screenshots via Ctrl+V, image files via the built-in file picker (Ctrl+I) or drag & drop; move, rotate, scale and write on them – also in the PDF export (file format version 4: older versions do not open such notebooks)
|
||||||
|
- **Dark mode & paper colors**: White, cream, dark gray or black; on dark paper, dark pen colors are brightened automatically (display only – files and PDF export stay unchanged)
|
||||||
|
- **Erase highlighter only**: Correct highlights without deleting the handwriting underneath – also with the pen's eraser end and side button
|
||||||
|
- **Adjustable pressure curve**: Curve from soft to hard and minimum pressure with preview, to match your own pen
|
||||||
|
- **New shapes**: Ellipses as well as arrows and double arrows drawn in one stroke are recognized (file format version 3: older versions do not open such notebooks)
|
||||||
|
- **Stable start**: No more crash when the graphics card cannot be used (e.g. missing permissions on /dev/dri); software renderer as fallback and an understandable error message
|
||||||
|
- **WSL (WSLg)**: Runs via X11 instead of Wayland under WSL automatically, because WSLg drops the Wayland connection; override with `INK_NOTES_DISPLAY=x11|wayland`
|
||||||
|
- **Important fix**: After a restart on a later page, continuing to write could overwrite the previous content of that page (affects v0.2.3 – v0.3.2)
|
||||||
|
- **New toolbar**: Narrow vertical bar with icon buttons, dockable left or right; rarely used functions in the ☰ menu, the page is centered next to it
|
||||||
|
- **Consistent dialogs**: Opaque windows without duplicate titles, page picker with thumbnails, larger controls in all popovers
|
||||||
|
- **UI usable with pen and touch**: Toolbar, popovers and dialogs now also respond to pen and finger, also with display scaling
|
||||||
|
- **Active stylus support (Lazarite / MPP / AES)**: Pen input via the Wayland or X11 tablet protocol, with pressure
|
||||||
|
- **Multi-touch touchscreen**: Zoom with two fingers, pan with one; drawing with a finger can be enabled
|
||||||
|
- **Two-stage inking model**: Smoothing while writing (1€ filter), post-processing with corner preservation when the pen is lifted
|
||||||
|
- **Geometry and shape recognition**: Lines, arrows & double arrows, rectangles, circles, ellipses, triangles, rhombuses, polygons & coordinate systems with sharp arrowheads (draw and hold); freeform strokes stay unchanged
|
||||||
|
- **Multiple notebooks**: Create, rename, delete (with trash); automatic saving in the background
|
||||||
|
- **Data safety**: Versioned file format with migration, damaged pages are set aside instead of overwritten, protection against opening twice, atomic saving
|
||||||
|
- **In-app updater**: Checks Gitea for new versions and installs them on request – only with a valid Minisign signature and over HTTPS
|
||||||
|
- **PDF export**: Strokes and shapes as vectors, for printing and sharing
|
||||||
|
|
||||||
### Installation:
|
### Installation:
|
||||||
- **Zorin OS / Ubuntu / Debian (.deb)**:
|
- **Zorin OS / Ubuntu / Debian (.deb)**:
|
||||||
```bash
|
```bash
|
||||||
sudo dpkg -i ink-notes_{{VERSION}}_amd64.deb
|
sudo dpkg -i ink-notes_{{VERSION}}_amd64.deb
|
||||||
```
|
```
|
||||||
- **AppImage (andere Distributionen mit glibc ≥ 2.39)**:
|
- **AppImage (other distributions with glibc ≥ 2.39)**:
|
||||||
```bash
|
```bash
|
||||||
chmod +x ink-notes_{{VERSION}}_x86_64.AppImage
|
chmod +x ink-notes_{{VERSION}}_x86_64.AppImage
|
||||||
./ink-notes_{{VERSION}}_x86_64.AppImage
|
./ink-notes_{{VERSION}}_x86_64.AppImage
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 184 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 118 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 73 KiB |
+16
-11
@@ -14,6 +14,7 @@ use std::path::{Path, PathBuf};
|
|||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
use crate::storage;
|
use crate::storage;
|
||||||
|
use crate::t;
|
||||||
|
|
||||||
/// Name des Unterordners mit den Bilddateien.
|
/// Name des Unterordners mit den Bilddateien.
|
||||||
pub const ASSETS_DIR: &str = "assets";
|
pub const ASSETS_DIR: &str = "assets";
|
||||||
@@ -40,15 +41,18 @@ pub enum AssetError {
|
|||||||
impl std::fmt::Display for AssetError {
|
impl std::fmt::Display for AssetError {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
AssetError::Decode(msg) => write!(f, "Bild kann nicht gelesen werden: {msg}"),
|
AssetError::Decode(msg) => {
|
||||||
AssetError::TooLarge(bytes) => write!(
|
f.write_str(&t!("Bild kann nicht gelesen werden: {msg}", msg = msg))
|
||||||
f,
|
}
|
||||||
"Bild ist zu groß ({} MB, höchstens {} MB)",
|
AssetError::TooLarge(bytes) => f.write_str(&t!(
|
||||||
bytes / (1024 * 1024),
|
"Bild ist zu groß ({size} MB, höchstens {max} MB)",
|
||||||
MAX_IMPORT_BYTES / (1024 * 1024)
|
size = bytes / (1024 * 1024),
|
||||||
),
|
max = MAX_IMPORT_BYTES / (1024 * 1024)
|
||||||
AssetError::InvalidName(name) => write!(f, "Ungültiger Bildverweis '{name}'"),
|
)),
|
||||||
AssetError::Io(e) => write!(f, "Ein-/Ausgabefehler: {e}"),
|
AssetError::InvalidName(name) => {
|
||||||
|
f.write_str(&t!("Ungültiger Bildverweis '{name}'", name = name))
|
||||||
|
}
|
||||||
|
AssetError::Io(e) => f.write_str(&t!("Ein-/Ausgabefehler: {e}", e = e)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -164,8 +168,9 @@ impl AssetStore {
|
|||||||
height: u32,
|
height: u32,
|
||||||
pixels: Vec<u8>,
|
pixels: Vec<u8>,
|
||||||
) -> Result<ImportedImage, AssetError> {
|
) -> Result<ImportedImage, AssetError> {
|
||||||
let buffer = image::RgbaImage::from_raw(width, height, pixels)
|
let buffer = image::RgbaImage::from_raw(width, height, pixels).ok_or_else(|| {
|
||||||
.ok_or_else(|| AssetError::Decode("Pixeldaten passen nicht zur Bildgröße".into()))?;
|
AssetError::Decode(t!("Pixeldaten passen nicht zur Bildgröße").into())
|
||||||
|
})?;
|
||||||
let mut decoded = image::DynamicImage::ImageRgba8(buffer);
|
let mut decoded = image::DynamicImage::ImageRgba8(buffer);
|
||||||
if width > MAX_IMPORT_DIMENSION || height > MAX_IMPORT_DIMENSION {
|
if width > MAX_IMPORT_DIMENSION || height > MAX_IMPORT_DIMENSION {
|
||||||
decoded = decoded.resize(
|
decoded = decoded.resize(
|
||||||
|
|||||||
+18
-16
@@ -16,6 +16,7 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
|||||||
|
|
||||||
use crate::document::{Notebook, Page, PersistState};
|
use crate::document::{Notebook, Page, PersistState};
|
||||||
use crate::storage::{self, NotebookManifest, PageData, StorageError};
|
use crate::storage::{self, NotebookManifest, PageData, StorageError};
|
||||||
|
use crate::t;
|
||||||
|
|
||||||
/// Abstraktion für die Zeitmessung (für deterministische Tests ohne Thread-Sleep).
|
/// Abstraktion für die Zeitmessung (für deterministische Tests ohne Thread-Sleep).
|
||||||
pub trait Clock: Send + Sync + 'static {
|
pub trait Clock: Send + Sync + 'static {
|
||||||
@@ -69,12 +70,11 @@ pub struct AutosaveError {
|
|||||||
|
|
||||||
impl fmt::Display for AutosaveError {
|
impl fmt::Display for AutosaveError {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
write!(
|
f.write_str(&t!(
|
||||||
f,
|
"Autosave fehlgeschlagen für Seiten {pages}: {messages}",
|
||||||
"Autosave fehlgeschlagen für Seiten {:?}: {}",
|
pages = format!("{:?}", self.failed_page_ids),
|
||||||
self.failed_page_ids,
|
messages = self.messages.join("; ")
|
||||||
self.messages.join("; ")
|
))
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,10 +96,10 @@ pub enum AutosaveStatus {
|
|||||||
impl AutosaveStatus {
|
impl AutosaveStatus {
|
||||||
pub fn display_text(&self) -> &'static str {
|
pub fn display_text(&self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
AutosaveStatus::Saved => "Gespeichert",
|
AutosaveStatus::Saved => t!("Gespeichert"),
|
||||||
AutosaveStatus::Pending => "Ungespeichert",
|
AutosaveStatus::Pending => t!("Ungespeichert"),
|
||||||
AutosaveStatus::Saving => "Speichert...",
|
AutosaveStatus::Saving => t!("Speichert..."),
|
||||||
AutosaveStatus::Error => "Speicherfehler!",
|
AutosaveStatus::Error => t!("Speicherfehler!"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -166,7 +166,7 @@ fn spawn_worker(
|
|||||||
let _ = resp_tx.send(AutosaveResponse::PageSaved {
|
let _ = resp_tx.send(AutosaveResponse::PageSaved {
|
||||||
page_id,
|
page_id,
|
||||||
result: Err((
|
result: Err((
|
||||||
"Worker panic beim Speichern der Seite".to_string(),
|
t!("Worker panic beim Speichern der Seite").to_string(),
|
||||||
Box::new(page_data),
|
Box::new(page_data),
|
||||||
)),
|
)),
|
||||||
});
|
});
|
||||||
@@ -194,7 +194,7 @@ fn spawn_worker(
|
|||||||
Err(_panic) => {
|
Err(_panic) => {
|
||||||
let _ = resp_tx.send(AutosaveResponse::ManifestSaved {
|
let _ = resp_tx.send(AutosaveResponse::ManifestSaved {
|
||||||
result: Err((
|
result: Err((
|
||||||
"Worker panic beim Speichern des Manifests".to_string(),
|
t!("Worker panic beim Speichern des Manifests").to_string(),
|
||||||
Box::new(manifest),
|
Box::new(manifest),
|
||||||
)),
|
)),
|
||||||
});
|
});
|
||||||
@@ -413,7 +413,8 @@ impl AutosaveController {
|
|||||||
Err((err_msg, failed_page)) => {
|
Err((err_msg, failed_page)) => {
|
||||||
eprintln!("[Autosave-Fehler] Seite {page_id} fehlgeschlagen: {err_msg}");
|
eprintln!("[Autosave-Fehler] Seite {page_id} fehlgeschlagen: {err_msg}");
|
||||||
self.status = AutosaveStatus::Error;
|
self.status = AutosaveStatus::Error;
|
||||||
self.last_errors.push(format!("Seite {page_id}: {err_msg}"));
|
self.last_errors
|
||||||
|
.push(t!("Seite {id}: {msg}", id = page_id, msg = err_msg));
|
||||||
|
|
||||||
// Wieder einreihen, wenn nicht bereits eine neuere Version vorliegt
|
// Wieder einreihen, wenn nicht bereits eine neuere Version vorliegt
|
||||||
self.pending_pages.entry(page_id).or_insert(*failed_page);
|
self.pending_pages.entry(page_id).or_insert(*failed_page);
|
||||||
@@ -431,7 +432,7 @@ impl AutosaveController {
|
|||||||
if let Err((err_msg, failed_manifest)) = result {
|
if let Err((err_msg, failed_manifest)) = result {
|
||||||
eprintln!("[Autosave-Fehler] Manifest fehlgeschlagen: {err_msg}");
|
eprintln!("[Autosave-Fehler] Manifest fehlgeschlagen: {err_msg}");
|
||||||
self.status = AutosaveStatus::Error;
|
self.status = AutosaveStatus::Error;
|
||||||
self.last_errors.push(format!("Manifest: {err_msg}"));
|
self.last_errors.push(t!("Manifest: {msg}", msg = err_msg));
|
||||||
if self.pending_manifest.is_none() {
|
if self.pending_manifest.is_none() {
|
||||||
self.pending_manifest = Some(*failed_manifest);
|
self.pending_manifest = Some(*failed_manifest);
|
||||||
}
|
}
|
||||||
@@ -567,7 +568,8 @@ impl AutosaveController {
|
|||||||
}
|
}
|
||||||
Err((e, failed_page)) => {
|
Err((e, failed_page)) => {
|
||||||
self.status = AutosaveStatus::Error;
|
self.status = AutosaveStatus::Error;
|
||||||
self.last_errors.push(format!("Seite {page_id}: {e}"));
|
self.last_errors
|
||||||
|
.push(t!("Seite {id}: {msg}", id = page_id, msg = e));
|
||||||
self.pending_pages.insert(page_id, *failed_page);
|
self.pending_pages.insert(page_id, *failed_page);
|
||||||
let now = self.clock.now();
|
let now = self.clock.now();
|
||||||
let retry = self.retries.entry(page_id).or_insert(PageRetry {
|
let retry = self.retries.entry(page_id).or_insert(PageRetry {
|
||||||
@@ -581,7 +583,7 @@ impl AutosaveController {
|
|||||||
AutosaveResponse::ManifestSaved { result } => {
|
AutosaveResponse::ManifestSaved { result } => {
|
||||||
if let Err((e, failed_manifest)) = result {
|
if let Err((e, failed_manifest)) = result {
|
||||||
self.status = AutosaveStatus::Error;
|
self.status = AutosaveStatus::Error;
|
||||||
self.last_errors.push(format!("Manifest: {e}"));
|
self.last_errors.push(t!("Manifest: {msg}", msg = e));
|
||||||
self.pending_manifest = Some(*failed_manifest);
|
self.pending_manifest = Some(*failed_manifest);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-9
@@ -4,6 +4,7 @@ use serde::{Deserialize, Serialize};
|
|||||||
|
|
||||||
use crate::canvas::InkVertex;
|
use crate::canvas::InkVertex;
|
||||||
use crate::document::PageBackground;
|
use crate::document::PageBackground;
|
||||||
|
use crate::t;
|
||||||
|
|
||||||
/// Farbe von Karos, Linien und Punkten (wird gespeichert und gilt auch für den Export).
|
/// Farbe von Karos, Linien und Punkten (wird gespeichert und gilt auch für den Export).
|
||||||
/// `Light` ist die zurückhaltende Standardfarbe des jeweiligen Papiers.
|
/// `Light` ist die zurückhaltende Standardfarbe des jeweiligen Papiers.
|
||||||
@@ -29,11 +30,11 @@ impl PatternColor {
|
|||||||
|
|
||||||
pub fn label(self) -> &'static str {
|
pub fn label(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
PatternColor::Light => "Hell",
|
PatternColor::Light => t!("Hell"),
|
||||||
PatternColor::Medium => "Mittel",
|
PatternColor::Medium => t!("Mittel"),
|
||||||
PatternColor::Strong => "Kräftig",
|
PatternColor::Strong => t!("Kräftig"),
|
||||||
PatternColor::Blue => "Blau",
|
PatternColor::Blue => t!("Blau"),
|
||||||
PatternColor::Green => "Grün",
|
PatternColor::Green => t!("Grün"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,10 +97,10 @@ impl PaperTheme {
|
|||||||
|
|
||||||
pub fn label(self) -> &'static str {
|
pub fn label(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
PaperTheme::White => "Weiß",
|
PaperTheme::White => t!("Weiß"),
|
||||||
PaperTheme::Cream => "Creme",
|
PaperTheme::Cream => t!("Creme"),
|
||||||
PaperTheme::DarkGray => "Dunkelgrau",
|
PaperTheme::DarkGray => t!("Dunkelgrau"),
|
||||||
PaperTheme::Black => "Schwarz",
|
PaperTheme::Black => t!("Schwarz"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+48
-11
@@ -18,6 +18,7 @@ use crate::background::{
|
|||||||
use crate::document::{Page, PageBackground, PageViewport, Stroke, StylusSample};
|
use crate::document::{Page, PageBackground, PageViewport, Stroke, StylusSample};
|
||||||
use crate::filter::OneEuroFilter;
|
use crate::filter::OneEuroFilter;
|
||||||
use crate::spline::{self, ControlPoint, SplineConfig};
|
use crate::spline::{self, ControlPoint, SplineConfig};
|
||||||
|
use crate::tn;
|
||||||
use crate::viewport::PageStack;
|
use crate::viewport::PageStack;
|
||||||
|
|
||||||
/// 2D-Vertex für Inking-Meshes mit Positions- und Farbattributen (Multi-Color).
|
/// 2D-Vertex für Inking-Meshes mit Positions- und Farbattributen (Multi-Color).
|
||||||
@@ -93,12 +94,13 @@ pub fn spline_vertices_to_ndc(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Verwaltet den GPU-Zustand, Surface, Pipelines und Buffer für das Inking.
|
/// Verwaltet den GPU-Zustand, Surface, Pipelines und Buffer für das Inking.
|
||||||
/// Meldung, wenn kein Grafikadapter das Fenster darstellen kann.
|
/// Meldung, wenn kein Grafikadapter das Fenster darstellen kann (deutsch, anzeigen mit
|
||||||
pub const NO_USABLE_GPU_MESSAGE: &str = "Keine nutzbare Grafikschnittstelle gefunden.\n\
|
/// `i18n::tr`).
|
||||||
|
pub const NO_USABLE_GPU_MESSAGE: &str = tn!("Keine nutzbare Grafikschnittstelle gefunden.\n\
|
||||||
Häufigste Ursache: Der Benutzer darf nicht auf die Grafikkarte zugreifen (/dev/dri).\n\
|
Häufigste Ursache: Der Benutzer darf nicht auf die Grafikkarte zugreifen (/dev/dri).\n\
|
||||||
Prüfen mit `ls -l /dev/dri` und `groups`; ggf. `sudo usermod -aG render,video $USER`\n\
|
Prüfen mit `ls -l /dev/dri` und `groups`; ggf. `sudo usermod -aG render,video $USER`\n\
|
||||||
und neu anmelden. Alternativ einen Software-Renderer installieren (Paket mesa-vulkan-drivers)\n\
|
und neu anmelden. Alternativ einen Software-Renderer installieren (Paket mesa-vulkan-drivers)\n\
|
||||||
oder die Schnittstelle festlegen, z. B. `WGPU_BACKEND=vulkan ink-notes`.";
|
oder die Schnittstelle festlegen, z. B. `WGPU_BACKEND=vulkan ink-notes`.");
|
||||||
|
|
||||||
/// Wählt den Darstellungsmodus: Mailbox (geringste Latenz), sonst Fifo, sonst den ersten
|
/// Wählt den Darstellungsmodus: Mailbox (geringste Latenz), sonst Fifo, sonst den ersten
|
||||||
/// angebotenen. `None`, wenn keiner angeboten wird. `INK_FORCE_FIFO` erzwingt Fifo.
|
/// angebotenen. `None`, wenn keiner angeboten wird. `INK_FORCE_FIFO` erzwingt Fifo.
|
||||||
@@ -305,7 +307,8 @@ impl CanvasState {
|
|||||||
),
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let (adapter, surface_caps, present_mode) = chosen.ok_or(NO_USABLE_GPU_MESSAGE)?;
|
let (adapter, surface_caps, present_mode) =
|
||||||
|
chosen.ok_or(crate::i18n::tr(NO_USABLE_GPU_MESSAGE))?;
|
||||||
|
|
||||||
// 3. Device & Queue erstellen
|
// 3. Device & Queue erstellen
|
||||||
let (device, queue) = adapter
|
let (device, queue) = adapter
|
||||||
@@ -707,14 +710,20 @@ impl CanvasState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn recalculate_viewport(&mut self) {
|
fn recalculate_viewport(&mut self) {
|
||||||
self.viewport = PageViewport::calculate_for(
|
let insets = (self.ui_inset_left, self.ui_inset_right);
|
||||||
self.size.width as f32,
|
let (width, height) = (self.size.width as f32, self.size.height as f32);
|
||||||
self.size.height as f32,
|
self.viewport = if self.page_size == crate::document::ENDLESS_PAGE_SIZE {
|
||||||
|
PageViewport::calculate_endless(width, height, Self::VIEWPORT_MARGIN, insets)
|
||||||
|
} else {
|
||||||
|
PageViewport::calculate_for(
|
||||||
|
width,
|
||||||
|
height,
|
||||||
Self::VIEWPORT_MARGIN,
|
Self::VIEWPORT_MARGIN,
|
||||||
(self.ui_inset_left, self.ui_inset_right),
|
insets,
|
||||||
self.fit_box,
|
self.fit_box,
|
||||||
self.page_size,
|
self.page_size,
|
||||||
);
|
)
|
||||||
|
};
|
||||||
self.update_uniforms();
|
self.update_uniforms();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -733,7 +742,7 @@ impl CanvasState {
|
|||||||
if !self.presentation_warned {
|
if !self.presentation_warned {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"[Grafik] Fenster kann derzeit nicht dargestellt werden (keine Darstellungsmodi). {}",
|
"[Grafik] Fenster kann derzeit nicht dargestellt werden (keine Darstellungsmodi). {}",
|
||||||
NO_USABLE_GPU_MESSAGE
|
crate::i18n::tr(NO_USABLE_GPU_MESSAGE)
|
||||||
);
|
);
|
||||||
self.presentation_warned = true;
|
self.presentation_warned = true;
|
||||||
}
|
}
|
||||||
@@ -834,6 +843,30 @@ impl CanvasState {
|
|||||||
changed
|
changed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Endless page: keeps the view right of and below `limit` (see
|
||||||
|
/// [`crate::document::Page::endless_scroll_limit`]). `true` if the view was corrected.
|
||||||
|
pub fn clamp_endless(&mut self, limit: glam::Vec2) -> bool {
|
||||||
|
let changed = self
|
||||||
|
.camera
|
||||||
|
.clamp_top_left([self.ui_inset_left, 0.0], limit, &self.viewport);
|
||||||
|
if changed {
|
||||||
|
self.update_uniforms();
|
||||||
|
}
|
||||||
|
changed
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Durchgehende Ansicht: Scrollt senkrecht, bis die Fenstermitte auf Höhe `y`
|
||||||
|
/// (Koordinaten der aktuellen Seite) liegt.
|
||||||
|
pub fn scroll_center_to(&mut self, y: f32) {
|
||||||
|
let c = self.camera.screen_to_page_unclamped(
|
||||||
|
self.viewport.page_x + self.viewport.page_width / 2.0,
|
||||||
|
self.size.height as f32 / 2.0,
|
||||||
|
&self.viewport,
|
||||||
|
);
|
||||||
|
self.camera.pan_offset[1] += c.y - y;
|
||||||
|
self.update_uniforms();
|
||||||
|
}
|
||||||
|
|
||||||
/// Durchgehende Ansicht: Die Seite mit der Ecke `origin` (Koordinaten der aktuellen Seite)
|
/// Durchgehende Ansicht: Die Seite mit der Ecke `origin` (Koordinaten der aktuellen Seite)
|
||||||
/// wird zur Bezugsseite, ohne dass sich der Bildausschnitt bewegt. Danach ist die neue
|
/// wird zur Bezugsseite, ohne dass sich der Bildausschnitt bewegt. Danach ist die neue
|
||||||
/// Seite mit [`Self::sync_page`] zu setzen.
|
/// Seite mit [`Self::sync_page`] zu setzen.
|
||||||
@@ -1303,9 +1336,13 @@ impl CanvasState {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Gleiche Tessellierung wie beim Absetzen (runde Kappen und Ecken), damit der Strich
|
||||||
|
// beim Abheben nicht sichtbar springt (Issue #33)
|
||||||
let color = self.current_ink_color;
|
let color = self.current_ink_color;
|
||||||
|
let points = spline::rdp_filter_samples(&self.live_samples, spline::RDP_TOLERANCE_UNITS);
|
||||||
|
let corners = spline::detect_corners(&points, spline::CORNER_ANGLE_THRESHOLD_DEG);
|
||||||
let raw_strip =
|
let raw_strip =
|
||||||
spline::generate_triangle_strip(&self.live_control_points, &self.spline_config);
|
spline::generate_finalized_triangle_strip(&points, &corners, &self.spline_config);
|
||||||
self.live_vertices = raw_strip
|
self.live_vertices = raw_strip
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|v| InkVertex::new(v.position[0], v.position[1], color))
|
.map(|v| InkVertex::new(v.position[0], v.position[1], color))
|
||||||
|
|||||||
+360
-40
@@ -1,10 +1,12 @@
|
|||||||
//! Notizbuch- und Seitenverwaltung mit DIN-A4-Koordinatensystem und Vektor-Stroke-Modell.
|
//! Notizbuch- und Seitenverwaltung mit DIN-A4-Koordinatensystem und Vektor-Stroke-Modell.
|
||||||
|
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
|
|
||||||
use crate::canvas::InkVertex;
|
use crate::canvas::InkVertex;
|
||||||
use crate::history::{HistoryAction, HistoryStack};
|
use crate::history::{HistoryAction, HistoryStack};
|
||||||
pub use crate::spline::{finalize_stroke, finalize_stroke_with_config};
|
pub use crate::spline::{finalize_stroke, finalize_stroke_with_config};
|
||||||
|
use crate::t;
|
||||||
|
|
||||||
/// Standardmaße DIN A4 in Millimetern.
|
/// Standardmaße DIN A4 in Millimetern.
|
||||||
pub const A4_WIDTH_MM: f32 = 210.0;
|
pub const A4_WIDTH_MM: f32 = 210.0;
|
||||||
@@ -19,6 +21,21 @@ pub const PAGE_HEIGHT: f32 = 2970.0;
|
|||||||
pub const A4_SIZE: glam::Vec2 = glam::Vec2::new(PAGE_WIDTH, PAGE_HEIGHT);
|
pub const A4_SIZE: glam::Vec2 = glam::Vec2::new(PAGE_WIDTH, PAGE_HEIGHT);
|
||||||
pub const UNITS_PER_MM: f32 = 10.0;
|
pub const UNITS_PER_MM: f32 = 10.0;
|
||||||
|
|
||||||
|
/// Größe der Seite eines endlosen Notizbuchs (10 × 10 m, Issue #30): praktisch unbegrenzt,
|
||||||
|
/// aber mit festen, positiven Koordinaten – Ansicht, Speichern und Rückgängig funktionieren
|
||||||
|
/// so wie bei jeder anderen Seite.
|
||||||
|
pub const ENDLESS_PAGE_SIZE: glam::Vec2 = glam::Vec2::new(100_000.0, 100_000.0);
|
||||||
|
/// Linke obere Ecke des Startausschnitts (ein DIN-A4-Rahmen in der Mitte der endlosen Seite).
|
||||||
|
pub const ENDLESS_HOME: glam::Vec2 = glam::Vec2::new(
|
||||||
|
(ENDLESS_PAGE_SIZE.x - PAGE_WIDTH) / 2.0,
|
||||||
|
(ENDLESS_PAGE_SIZE.y - PAGE_HEIGHT) / 2.0,
|
||||||
|
);
|
||||||
|
/// Rand um den Inhalt beim Export einer endlosen Seite (10 mm).
|
||||||
|
const ENDLESS_EXPORT_MARGIN: f32 = 100.0;
|
||||||
|
/// Raster, auf das der Exportausschnitt einer endlosen Seite fällt: Vielfaches der Abstände von
|
||||||
|
/// Karos/Punkten (5 mm) und Linien (7 mm), damit das Muster wie am Bildschirm liegt.
|
||||||
|
const ENDLESS_EXPORT_SNAP: f32 = 350.0;
|
||||||
|
|
||||||
/// Ein gefilterter Stylus-Abtastpunkt in DIN-A4-Seitenkoordinaten.
|
/// Ein gefilterter Stylus-Abtastpunkt in DIN-A4-Seitenkoordinaten.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
pub struct StylusSample {
|
pub struct StylusSample {
|
||||||
@@ -197,18 +214,19 @@ pub const IMAGE_UNITS_PER_PIXEL: f32 = UNITS_PER_MM * 25.4 / 96.0;
|
|||||||
|
|
||||||
/// Ecken (oben links, oben rechts, unten rechts, unten links) für ein neu eingefügtes Bild
|
/// Ecken (oben links, oben rechts, unten rechts, unten links) für ein neu eingefügtes Bild
|
||||||
/// von `width` × `height` Pixeln um `center`: Bildschirmgröße bei 96 dpi, höchstens 80 % der
|
/// von `width` × `height` Pixeln um `center`: Bildschirmgröße bei 96 dpi, höchstens 80 % der
|
||||||
/// Seitenbreite und 60 % der Seitenhöhe eines Blatts der Größe `page_size`, und möglichst
|
/// Breite und 60 % der Höhe von `reference` (meist die Seitengröße, auf der endlosen Seite
|
||||||
/// ganz auf dem Blatt.
|
/// DIN A4), und möglichst ganz auf dem Blatt der Größe `page_size`.
|
||||||
pub fn place_image(
|
pub fn place_image(
|
||||||
width: u32,
|
width: u32,
|
||||||
height: u32,
|
height: u32,
|
||||||
center: glam::Vec2,
|
center: glam::Vec2,
|
||||||
page_size: glam::Vec2,
|
page_size: glam::Vec2,
|
||||||
|
reference: glam::Vec2,
|
||||||
) -> [glam::Vec2; 4] {
|
) -> [glam::Vec2; 4] {
|
||||||
let natural =
|
let natural =
|
||||||
glam::Vec2::new(width.max(1) as f32, height.max(1) as f32) * IMAGE_UNITS_PER_PIXEL;
|
glam::Vec2::new(width.max(1) as f32, height.max(1) as f32) * IMAGE_UNITS_PER_PIXEL;
|
||||||
let fit = (page_size.x * 0.8 / natural.x)
|
let fit = (reference.x * 0.8 / natural.x)
|
||||||
.min(page_size.y * 0.6 / natural.y)
|
.min(reference.y * 0.6 / natural.y)
|
||||||
.min(1.0);
|
.min(1.0);
|
||||||
let size = natural * fit;
|
let size = natural * fit;
|
||||||
let half = size / 2.0;
|
let half = size / 2.0;
|
||||||
@@ -596,18 +614,24 @@ impl Stroke {
|
|||||||
|
|
||||||
/// Berechnet die Bounding Box aus den aktuellen Punkten/Vertizes neu.
|
/// Berechnet die Bounding Box aus den aktuellen Punkten/Vertizes neu.
|
||||||
pub fn recompute_aabb(&mut self) {
|
pub fn recompute_aabb(&mut self) {
|
||||||
|
// Ohne Zwischenliste: läuft beim Ziehen einer Auswahl für jeden Strich und jede Bewegung
|
||||||
|
let bounds = |mut pts: Box<dyn Iterator<Item = glam::Vec2> + '_>| {
|
||||||
|
pts.next()
|
||||||
|
.map_or(Aabb::new(glam::Vec2::ZERO, glam::Vec2::ZERO), |first| {
|
||||||
|
pts.fold(Aabb::new(first, first), |mut aabb, p| {
|
||||||
|
aabb.expand_by_point(p);
|
||||||
|
aabb
|
||||||
|
})
|
||||||
|
})
|
||||||
|
};
|
||||||
self.aabb = if !self.points.is_empty() {
|
self.aabb = if !self.points.is_empty() {
|
||||||
let pts: Vec<glam::Vec2> = self.points.iter().map(|s| s.position).collect();
|
bounds(Box::new(self.points.iter().map(|s| s.position)))
|
||||||
Aabb::from_points(&pts)
|
|
||||||
} else if !self.vertices.is_empty() {
|
|
||||||
let pts: Vec<glam::Vec2> = self
|
|
||||||
.vertices
|
|
||||||
.iter()
|
|
||||||
.map(|v| glam::Vec2::new(v.position[0], v.position[1]))
|
|
||||||
.collect();
|
|
||||||
Aabb::from_points(&pts)
|
|
||||||
} else {
|
} else {
|
||||||
Aabb::new(glam::Vec2::ZERO, glam::Vec2::ZERO)
|
bounds(Box::new(
|
||||||
|
self.vertices
|
||||||
|
.iter()
|
||||||
|
.map(|v| glam::Vec2::new(v.position[0], v.position[1])),
|
||||||
|
))
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -773,6 +797,65 @@ impl Page {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Seite eines endlosen Notizbuchs (siehe [`ENDLESS_PAGE_SIZE`]).
|
||||||
|
pub fn is_endless(&self) -> bool {
|
||||||
|
self.size == ENDLESS_PAGE_SIZE
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bezugsgröße für Einfügen und Textumbruch: DIN A4 auf der endlosen Seite, sonst die Seite.
|
||||||
|
pub fn reference_size(&self) -> glam::Vec2 {
|
||||||
|
if self.is_endless() {
|
||||||
|
A4_SIZE
|
||||||
|
} else {
|
||||||
|
self.size
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rechter Rand für ein neues Textfeld bei `x`: auf der endlosen Seite eine A4-Breite
|
||||||
|
/// weiter, sonst der Seitenrand.
|
||||||
|
pub fn text_right_edge(&self, x: f32) -> f32 {
|
||||||
|
if self.is_endless() {
|
||||||
|
x + PAGE_WIDTH
|
||||||
|
} else {
|
||||||
|
self.size.x
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Kopie der Seite als Ausschnitt ab `origin` mit Größe `size`: Alle Objekte werden um
|
||||||
|
/// `-origin` verschoben (für Export und Bilder einer Auswahl).
|
||||||
|
pub fn cropped(&self, origin: glam::Vec2, size: glam::Vec2) -> Page {
|
||||||
|
let mut page = self.clone();
|
||||||
|
for stroke in &mut page.strokes {
|
||||||
|
stroke.translate(-origin);
|
||||||
|
}
|
||||||
|
page.size = size;
|
||||||
|
page.is_dirty = true;
|
||||||
|
page
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Endless page: the view never shows anything left of or above this point – the start
|
||||||
|
/// frame or the content, whichever reaches further, with a 10 mm margin. The canvas
|
||||||
|
/// therefore only grows to the right and down (Issue #30).
|
||||||
|
pub fn endless_scroll_limit(&self) -> glam::Vec2 {
|
||||||
|
let top_left = Self::selection_aabb(&self.strokes)
|
||||||
|
.map_or(ENDLESS_HOME, |content| content.min.min(ENDLESS_HOME));
|
||||||
|
(top_left - ENDLESS_EXPORT_MARGIN).max(glam::Vec2::ZERO)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Exportausschnitt einer endlosen Seite: der Inhalt mit 10 mm Rand (leer: der
|
||||||
|
/// Startausschnitt). Die linke obere Ecke liegt auf dem Musterraster.
|
||||||
|
pub fn endless_export_bounds(&self) -> (glam::Vec2, glam::Vec2) {
|
||||||
|
let Some(content) = Self::selection_aabb(&self.strokes) else {
|
||||||
|
return (ENDLESS_HOME, A4_SIZE);
|
||||||
|
};
|
||||||
|
let max_width = self.strokes.iter().map(|s| s.width).fold(0.0, f32::max);
|
||||||
|
let content = content.expanded(max_width / 2.0 + ENDLESS_EXPORT_MARGIN);
|
||||||
|
let origin = (content.min / ENDLESS_EXPORT_SNAP).floor() * ENDLESS_EXPORT_SNAP;
|
||||||
|
let origin = origin.max(glam::Vec2::ZERO);
|
||||||
|
let end = content.max.min(self.size);
|
||||||
|
(origin, (end - origin).max(glam::Vec2::splat(100.0)))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn is_readonly(&self) -> bool {
|
pub fn is_readonly(&self) -> bool {
|
||||||
self.persist == PersistState::ReadOnlyAfterLoadError
|
self.persist == PersistState::ReadOnlyAfterLoadError
|
||||||
}
|
}
|
||||||
@@ -999,6 +1082,7 @@ impl Page {
|
|||||||
|
|
||||||
/// Liefert Klone der Striche mit den angegebenen IDs.
|
/// Liefert Klone der Striche mit den angegebenen IDs.
|
||||||
pub fn get_strokes(&self, ids: &[u64]) -> Vec<Stroke> {
|
pub fn get_strokes(&self, ids: &[u64]) -> Vec<Stroke> {
|
||||||
|
let ids: HashSet<u64> = ids.iter().copied().collect();
|
||||||
self.strokes
|
self.strokes
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|s| ids.contains(&s.id))
|
.filter(|s| ids.contains(&s.id))
|
||||||
@@ -1006,24 +1090,31 @@ impl Page {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Ersetzt die Striche mit den IDs aus `modified` an ihrer Stelle. Über eine Tabelle
|
||||||
|
/// statt je Strich die ganze Seite zu durchsuchen: Beim Ziehen einer großen Auswahl
|
||||||
|
/// läuft das bei jeder Stiftbewegung.
|
||||||
|
fn replace_strokes(&mut self, modified: &[Stroke]) {
|
||||||
|
let index: HashMap<u64, usize> = self
|
||||||
|
.strokes
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, s)| (s.id, i))
|
||||||
|
.collect();
|
||||||
|
for m in modified {
|
||||||
|
if let Some(&pos) = index.get(&m.id) {
|
||||||
|
self.strokes[pos] = m.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Aktualisiert eine Menge geänderter Striche transaktional im History-Stack.
|
/// Aktualisiert eine Menge geänderter Striche transaktional im History-Stack.
|
||||||
pub fn modify_strokes(&mut self, modified: Vec<Stroke>) {
|
pub fn modify_strokes(&mut self, modified: Vec<Stroke>) {
|
||||||
if modified.is_empty() {
|
if modified.is_empty() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let ids: Vec<u64> = modified.iter().map(|s| s.id).collect();
|
let ids: Vec<u64> = modified.iter().map(|s| s.id).collect();
|
||||||
let before: Vec<Stroke> = self
|
let before = self.get_strokes(&ids);
|
||||||
.strokes
|
self.replace_strokes(&modified);
|
||||||
.iter()
|
|
||||||
.filter(|s| ids.contains(&s.id))
|
|
||||||
.cloned()
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
for m in modified.iter() {
|
|
||||||
if let Some(pos) = self.strokes.iter().position(|s| s.id == m.id) {
|
|
||||||
self.strokes[pos] = m.clone();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self.history.push(HistoryAction::ModifyStrokes {
|
self.history.push(HistoryAction::ModifyStrokes {
|
||||||
before,
|
before,
|
||||||
@@ -1034,9 +1125,33 @@ impl Page {
|
|||||||
|
|
||||||
/// Aktualisiert Striche flüchtig (z. B. während des Ziehens / Dragging), OHNE die History zu verändern.
|
/// Aktualisiert Striche flüchtig (z. B. während des Ziehens / Dragging), OHNE die History zu verändern.
|
||||||
pub fn update_strokes_ephemeral(&mut self, modified: &[Stroke]) {
|
pub fn update_strokes_ephemeral(&mut self, modified: &[Stroke]) {
|
||||||
for m in modified {
|
self.replace_strokes(modified);
|
||||||
if let Some(pos) = self.strokes.iter().position(|s| s.id == m.id) {
|
self.is_dirty = true;
|
||||||
self.strokes[pos] = m.clone();
|
}
|
||||||
|
|
||||||
|
/// Wie [`Self::update_strokes_ephemeral`] für eine Transformation der Ausgangsstriche
|
||||||
|
/// `originals`: setzt die Striche auf der Seite auf ihren Ausgangszustand zurück und wendet
|
||||||
|
/// `transform` an. Verwendet die Puffer der Seitenstriche weiter, statt bei jeder
|
||||||
|
/// Stiftbewegung die ganze Auswahl zweimal zu kopieren.
|
||||||
|
pub fn transform_strokes_ephemeral(
|
||||||
|
&mut self,
|
||||||
|
originals: &[Stroke],
|
||||||
|
transform: impl Fn(&mut Stroke),
|
||||||
|
) {
|
||||||
|
let index: HashMap<u64, usize> = self
|
||||||
|
.strokes
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, s)| (s.id, i))
|
||||||
|
.collect();
|
||||||
|
for original in originals {
|
||||||
|
if let Some(&pos) = index.get(&original.id) {
|
||||||
|
let stroke = &mut self.strokes[pos];
|
||||||
|
// Nur was Verschieben, Drehen und Skalieren verändern
|
||||||
|
stroke.points.clone_from(&original.points);
|
||||||
|
stroke.vertices.clone_from(&original.vertices);
|
||||||
|
stroke.shape.clone_from(&original.shape);
|
||||||
|
transform(stroke);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
self.is_dirty = true;
|
self.is_dirty = true;
|
||||||
@@ -1047,11 +1162,7 @@ impl Page {
|
|||||||
if before.is_empty() || after.is_empty() {
|
if before.is_empty() || after.is_empty() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for m in &after {
|
self.replace_strokes(&after);
|
||||||
if let Some(pos) = self.strokes.iter().position(|s| s.id == m.id) {
|
|
||||||
self.strokes[pos] = m.clone();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.history
|
self.history
|
||||||
.push(HistoryAction::ModifyStrokes { before, after });
|
.push(HistoryAction::ModifyStrokes { before, after });
|
||||||
self.is_dirty = true;
|
self.is_dirty = true;
|
||||||
@@ -1193,6 +1304,61 @@ impl Notebook {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Endloses Notizbuch: eine einzige, praktisch unbegrenzte Seite (Issue #30).
|
||||||
|
pub fn is_endless(&self) -> bool {
|
||||||
|
self.pages.len() == 1 && self.pages[0].is_endless()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Macht aus einem Notizbuch mit einer einzigen Seite (ohne importiertes PDF) ein
|
||||||
|
/// endloses: Die Seite wird zur endlosen Fläche, ihr Inhalt landet im Startausschnitt.
|
||||||
|
/// Der Verlauf der Seite wird geleert (er kennt nur die alten Koordinaten).
|
||||||
|
pub fn make_endless(&mut self) -> bool {
|
||||||
|
if !self.can_make_endless() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let page = &mut self.pages[0];
|
||||||
|
for stroke in &mut page.strokes {
|
||||||
|
stroke.translate(ENDLESS_HOME);
|
||||||
|
}
|
||||||
|
page.size = ENDLESS_PAGE_SIZE;
|
||||||
|
page.history.clear();
|
||||||
|
page.is_dirty = true;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Siehe [`Self::make_endless`].
|
||||||
|
pub fn can_make_endless(&self) -> bool {
|
||||||
|
matches!(self.pages.as_slice(), [page] if page.is_loaded
|
||||||
|
&& !page.is_endless()
|
||||||
|
&& page.pdf_background.is_none())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Siehe [`Self::make_paged`].
|
||||||
|
pub fn can_make_paged(&self) -> bool {
|
||||||
|
if !self.is_endless() || !self.pages[0].is_loaded {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Page::selection_aabb(&self.pages[0].strokes).is_none_or(|content| {
|
||||||
|
content.min.cmpge(ENDLESS_HOME).all() && content.max.cmple(ENDLESS_HOME + A4_SIZE).all()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Macht aus einem endlosen Notizbuch wieder eine DIN-A4-Seite – nur, wenn der Inhalt im
|
||||||
|
/// Startausschnitt liegt (sonst ginge er über den Seitenrand). Leert den Verlauf der Seite.
|
||||||
|
pub fn make_paged(&mut self) -> bool {
|
||||||
|
if !self.can_make_paged() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let page = &mut self.pages[0];
|
||||||
|
for stroke in &mut page.strokes {
|
||||||
|
stroke.translate(-ENDLESS_HOME);
|
||||||
|
}
|
||||||
|
page.size = A4_SIZE;
|
||||||
|
page.history.clear();
|
||||||
|
page.is_dirty = true;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
/// Hängt eine neue Seite mit dem angegebenen Hintergrund und der Größe der aktuellen
|
/// Hängt eine neue Seite mit dem angegebenen Hintergrund und der Größe der aktuellen
|
||||||
/// Seite an.
|
/// Seite an.
|
||||||
pub fn add_page(&mut self, background: PageBackground) -> usize {
|
pub fn add_page(&mut self, background: PageBackground) -> usize {
|
||||||
@@ -1306,10 +1472,10 @@ impl Notebook {
|
|||||||
|
|
||||||
/// Text für das On-Screen-Display (OSD), z. B. "Seite 3 / 12".
|
/// Text für das On-Screen-Display (OSD), z. B. "Seite 3 / 12".
|
||||||
pub fn osd_text(&self) -> String {
|
pub fn osd_text(&self) -> String {
|
||||||
format!(
|
t!(
|
||||||
"Seite {} / {}",
|
"Seite {number} / {count}",
|
||||||
self.current_page_index + 1,
|
number = self.current_page_index + 1,
|
||||||
self.pages.len()
|
count = self.pages.len()
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1400,6 +1566,16 @@ impl Notebook {
|
|||||||
if dy.abs() < 1.0 {
|
if dy.abs() < 1.0 {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
// Endlose Seite: keine weiteren Seiten anlegen, nichts über den Rand schieben
|
||||||
|
let page = &self.pages[page_index];
|
||||||
|
if page.is_endless()
|
||||||
|
&& page
|
||||||
|
.strokes
|
||||||
|
.iter()
|
||||||
|
.any(|s| s.aabb.min.y >= y && s.aabb.max.y + dy > page.size.y)
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
// Seiten als durchgehende Spalte: Lage jeder Seite (auch noch anzulegender)
|
// Seiten als durchgehende Spalte: Lage jeder Seite (auch noch anzulegender)
|
||||||
let last_size = self.pages[run.end - 1].size;
|
let last_size = self.pages[run.end - 1].size;
|
||||||
@@ -1690,6 +1866,32 @@ impl PageViewport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Ansicht der endlosen Seite: Maßstab und Lage wie bei einer DIN-A4-Seite, die am
|
||||||
|
/// Startausschnitt ([`ENDLESS_HOME`]) der endlosen Seite liegt.
|
||||||
|
pub fn calculate_endless(
|
||||||
|
window_width: f32,
|
||||||
|
window_height: f32,
|
||||||
|
margin: f32,
|
||||||
|
insets: (f32, f32),
|
||||||
|
) -> Self {
|
||||||
|
let a4 = Self::calculate_for(
|
||||||
|
window_width,
|
||||||
|
window_height,
|
||||||
|
margin,
|
||||||
|
insets,
|
||||||
|
A4_SIZE,
|
||||||
|
A4_SIZE,
|
||||||
|
);
|
||||||
|
Self {
|
||||||
|
page_x: a4.page_x - ENDLESS_HOME.x * a4.scale,
|
||||||
|
page_y: a4.page_y - ENDLESS_HOME.y * a4.scale,
|
||||||
|
page_width: ENDLESS_PAGE_SIZE.x * a4.scale,
|
||||||
|
page_height: ENDLESS_PAGE_SIZE.y * a4.scale,
|
||||||
|
page_size: ENDLESS_PAGE_SIZE,
|
||||||
|
..a4
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Transformiert einen Fenster-Pixelpunkt in Seitenkoordinaten.
|
/// Transformiert einen Fenster-Pixelpunkt in Seitenkoordinaten.
|
||||||
///
|
///
|
||||||
/// Liefert `None`, falls der Punkt außerhalb der Seite liegt.
|
/// Liefert `None`, falls der Punkt außerhalb der Seite liegt.
|
||||||
@@ -2045,13 +2247,13 @@ mod tests {
|
|||||||
fn test_place_image() {
|
fn test_place_image() {
|
||||||
let center = glam::Vec2::new(PAGE_WIDTH / 2.0, PAGE_HEIGHT / 2.0);
|
let center = glam::Vec2::new(PAGE_WIDTH / 2.0, PAGE_HEIGHT / 2.0);
|
||||||
// Kleines Bild: Bildschirmgröße, zentriert
|
// Kleines Bild: Bildschirmgröße, zentriert
|
||||||
let [tl, tr, br, bl] = place_image(200, 100, center, A4_SIZE);
|
let [tl, tr, br, bl] = place_image(200, 100, center, A4_SIZE, A4_SIZE);
|
||||||
assert!(((tr - tl).length() - 200.0 * IMAGE_UNITS_PER_PIXEL).abs() < 1e-3);
|
assert!(((tr - tl).length() - 200.0 * IMAGE_UNITS_PER_PIXEL).abs() < 1e-3);
|
||||||
assert!(((bl - tl).length() - 100.0 * IMAGE_UNITS_PER_PIXEL).abs() < 1e-3);
|
assert!(((bl - tl).length() - 100.0 * IMAGE_UNITS_PER_PIXEL).abs() < 1e-3);
|
||||||
assert!(((tl + br) / 2.0 - center).length() < 1e-3);
|
assert!(((tl + br) / 2.0 - center).length() < 1e-3);
|
||||||
|
|
||||||
// Großer Screenshot: auf 80 % der Breite verkleinert, Seitenverhältnis bleibt
|
// Großer Screenshot: auf 80 % der Breite verkleinert, Seitenverhältnis bleibt
|
||||||
let [tl, tr, br, _] = place_image(3840, 2160, center, A4_SIZE);
|
let [tl, tr, br, _] = place_image(3840, 2160, center, A4_SIZE, A4_SIZE);
|
||||||
let size = br - tl;
|
let size = br - tl;
|
||||||
assert!((size.x - PAGE_WIDTH * 0.8).abs() < 1e-2);
|
assert!((size.x - PAGE_WIDTH * 0.8).abs() < 1e-2);
|
||||||
assert!((size.x / size.y - 3840.0 / 2160.0).abs() < 1e-3);
|
assert!((size.x / size.y - 3840.0 / 2160.0).abs() < 1e-3);
|
||||||
@@ -2063,6 +2265,7 @@ mod tests {
|
|||||||
400,
|
400,
|
||||||
glam::Vec2::new(-50.0, PAGE_HEIGHT + 50.0),
|
glam::Vec2::new(-50.0, PAGE_HEIGHT + 50.0),
|
||||||
A4_SIZE,
|
A4_SIZE,
|
||||||
|
A4_SIZE,
|
||||||
);
|
);
|
||||||
for c in corners {
|
for c in corners {
|
||||||
assert!(c.x >= -1e-3 && c.x <= PAGE_WIDTH + 1e-3);
|
assert!(c.x >= -1e-3 && c.x <= PAGE_WIDTH + 1e-3);
|
||||||
@@ -2514,6 +2717,13 @@ mod tests {
|
|||||||
// History should not have been updated yet
|
// History should not have been updated yet
|
||||||
assert!(!page.history.can_redo());
|
assert!(!page.history.can_redo());
|
||||||
|
|
||||||
|
// Ziehen über die Ausgangsstriche: jede Bewegung gilt ab dem Ausgangszustand
|
||||||
|
for delta in [glam::Vec2::new(5.0, 0.0), glam::Vec2::new(20.0, 30.0)] {
|
||||||
|
page.transform_strokes_ephemeral(std::slice::from_ref(&s), |st| st.translate(delta));
|
||||||
|
}
|
||||||
|
assert_eq!(page.strokes[0], moved);
|
||||||
|
assert!(!page.history.can_redo());
|
||||||
|
|
||||||
// Transactional commit (mouse release)
|
// Transactional commit (mouse release)
|
||||||
let before = vec![s.clone()];
|
let before = vec![s.clone()];
|
||||||
let after = vec![moved.clone()];
|
let after = vec![moved.clone()];
|
||||||
@@ -2533,4 +2743,114 @@ mod tests {
|
|||||||
glam::Vec2::new(30.0, 40.0)
|
glam::Vec2::new(30.0, 40.0)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn line(id: u64, from: glam::Vec2, to: glam::Vec2) -> Stroke {
|
||||||
|
let sample = |position, timestamp| StylusSample {
|
||||||
|
position,
|
||||||
|
pressure: 0.5,
|
||||||
|
timestamp,
|
||||||
|
};
|
||||||
|
Stroke::new(
|
||||||
|
id,
|
||||||
|
vec![sample(from, 0.0), sample(to, 0.01)],
|
||||||
|
Vec::new(),
|
||||||
|
[0.0, 0.0, 0.0, 1.0],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_endless_notebook_round_trip() {
|
||||||
|
let mut nb = Notebook::new();
|
||||||
|
nb.pages[0].add_stroke(line(
|
||||||
|
1,
|
||||||
|
glam::Vec2::new(100.0, 100.0),
|
||||||
|
glam::Vec2::new(500.0, 300.0),
|
||||||
|
));
|
||||||
|
assert!(!nb.is_endless());
|
||||||
|
assert!(nb.make_endless());
|
||||||
|
assert!(nb.is_endless());
|
||||||
|
// Inhalt liegt im Startausschnitt, der Verlauf ist leer
|
||||||
|
let p = nb.pages[0].strokes[0].points[0].position;
|
||||||
|
assert!((p - (ENDLESS_HOME + glam::Vec2::new(100.0, 100.0))).length() < 1e-3);
|
||||||
|
assert!(!nb.pages[0].history.can_undo());
|
||||||
|
assert!(!nb.make_endless(), "schon endlos");
|
||||||
|
|
||||||
|
// Zurück zu Seiten: Inhalt wieder an der alten Stelle
|
||||||
|
assert!(nb.make_paged());
|
||||||
|
assert_eq!(nb.pages[0].size, A4_SIZE);
|
||||||
|
let p = nb.pages[0].strokes[0].points[0].position;
|
||||||
|
assert!((p - glam::Vec2::new(100.0, 100.0)).length() < 1e-2);
|
||||||
|
|
||||||
|
// Inhalt außerhalb des Startausschnitts: kein Zurück
|
||||||
|
assert!(nb.make_endless());
|
||||||
|
nb.pages[0].add_stroke(line(2, ENDLESS_HOME - 500.0, ENDLESS_HOME - 400.0));
|
||||||
|
assert!(!nb.can_make_paged());
|
||||||
|
assert!(!nb.make_paged());
|
||||||
|
assert!(nb.is_endless());
|
||||||
|
|
||||||
|
// Mehrere Seiten oder PDF-Seite: nicht endlos
|
||||||
|
let mut two = Notebook::new();
|
||||||
|
two.add_page(PageBackground::Blank);
|
||||||
|
assert!(!two.make_endless());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_endless_viewport_shows_home_like_a4() {
|
||||||
|
let a4 = PageViewport::calculate_for(1600.0, 900.0, 20.0, (0.0, 0.0), A4_SIZE, A4_SIZE);
|
||||||
|
let endless = PageViewport::calculate_endless(1600.0, 900.0, 20.0, (0.0, 0.0));
|
||||||
|
assert_eq!(endless.page_size, ENDLESS_PAGE_SIZE);
|
||||||
|
assert!((endless.scale - a4.scale).abs() < 1e-6);
|
||||||
|
// Die Ecke des Startausschnitts liegt dort, wo sonst die A4-Seite beginnt
|
||||||
|
let home = endless
|
||||||
|
.screen_to_page(a4.page_x + 1.0, a4.page_y + 1.0)
|
||||||
|
.unwrap();
|
||||||
|
assert!((home - ENDLESS_HOME - glam::Vec2::splat(1.0 / a4.scale)).length() < 0.05);
|
||||||
|
// Weit neben dem Startausschnitt lässt sich weiter schreiben
|
||||||
|
assert!(endless.screen_to_page(-5000.0, -5000.0).is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_endless_scroll_limit_includes_content_left_of_the_start() {
|
||||||
|
let mut page = Page::new(1, PageBackground::Grid5mm).with_size(ENDLESS_PAGE_SIZE);
|
||||||
|
assert_eq!(
|
||||||
|
page.endless_scroll_limit(),
|
||||||
|
ENDLESS_HOME - ENDLESS_EXPORT_MARGIN
|
||||||
|
);
|
||||||
|
// Content right of and below the start frame does not move the limit
|
||||||
|
page.add_stroke(line(1, ENDLESS_HOME + 500.0, ENDLESS_HOME + 900.0));
|
||||||
|
assert_eq!(
|
||||||
|
page.endless_scroll_limit(),
|
||||||
|
ENDLESS_HOME - ENDLESS_EXPORT_MARGIN
|
||||||
|
);
|
||||||
|
// Older notebooks may have content further up and left: it stays reachable
|
||||||
|
let from = glam::Vec2::new(30_000.0, 40_000.0);
|
||||||
|
page.add_stroke(line(2, from, ENDLESS_HOME));
|
||||||
|
let limit = page.endless_scroll_limit();
|
||||||
|
assert!(limit.cmple(from - ENDLESS_EXPORT_MARGIN).all(), "{limit:?}");
|
||||||
|
assert!(
|
||||||
|
limit.cmpgt(from - 2.0 * ENDLESS_EXPORT_MARGIN).all(),
|
||||||
|
"{limit:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_endless_export_bounds_follow_content() {
|
||||||
|
let mut page = Page::new(1, PageBackground::Grid5mm).with_size(ENDLESS_PAGE_SIZE);
|
||||||
|
// Leer: der Startausschnitt
|
||||||
|
assert_eq!(page.endless_export_bounds(), (ENDLESS_HOME, A4_SIZE));
|
||||||
|
|
||||||
|
let from = glam::Vec2::new(30_123.0, 40_456.0);
|
||||||
|
let to = glam::Vec2::new(36_000.0, 41_000.0);
|
||||||
|
page.add_stroke(line(1, from, to));
|
||||||
|
let (origin, size) = page.endless_export_bounds();
|
||||||
|
// Ecke auf dem Musterraster, Inhalt mit Rand vollständig enthalten
|
||||||
|
assert_eq!(origin % ENDLESS_EXPORT_SNAP, glam::Vec2::ZERO);
|
||||||
|
assert!(origin.cmple(from - ENDLESS_EXPORT_MARGIN).all());
|
||||||
|
assert!((origin + size).cmpge(to + ENDLESS_EXPORT_MARGIN).all());
|
||||||
|
assert!(size.x < 7_000.0 && size.y < 2_000.0, "{size:?}");
|
||||||
|
|
||||||
|
let cropped = page.cropped(origin, size);
|
||||||
|
assert_eq!(cropped.size, size);
|
||||||
|
assert!((cropped.strokes[0].points[0].position - (from - origin)).length() < 1e-2);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+84
-7
@@ -24,6 +24,7 @@ use crate::background::{PatternColor, DOT_SIZE, GRID_5MM_SPACING, LINED_SPACING}
|
|||||||
use crate::document::{
|
use crate::document::{
|
||||||
Notebook, Page, PageBackground, Stroke, A4_HEIGHT_MM, A4_WIDTH_MM, PAGE_HEIGHT, PAGE_WIDTH,
|
Notebook, Page, PageBackground, Stroke, A4_HEIGHT_MM, A4_WIDTH_MM, PAGE_HEIGHT, PAGE_WIDTH,
|
||||||
};
|
};
|
||||||
|
use crate::t;
|
||||||
use ab_glyph::Font as _;
|
use ab_glyph::Font as _;
|
||||||
|
|
||||||
use crate::text::TextFont;
|
use crate::text::TextFont;
|
||||||
@@ -45,7 +46,9 @@ pub fn sanitize_filename_component(title: &str) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Ermittelt das Standard-Dokumentenverzeichnis ($XDG_DOCUMENTS_DIR mit Fallback ~/Documents).
|
/// Ermittelt das Standard-Dokumentenverzeichnis: `$XDG_DOCUMENTS_DIR`, sonst der Eintrag in
|
||||||
|
/// `~/.config/user-dirs.dirs` (z. B. „Dokumente“), sonst `~/Documents`. Im Flatpak ist nur
|
||||||
|
/// dieser Ordner beschreibbar, der Fallback allein träfe bei deutschen Systemen daneben.
|
||||||
pub fn default_documents_dir() -> PathBuf {
|
pub fn default_documents_dir() -> PathBuf {
|
||||||
if let Ok(dir) = std::env::var("XDG_DOCUMENTS_DIR") {
|
if let Ok(dir) = std::env::var("XDG_DOCUMENTS_DIR") {
|
||||||
if !dir.trim().is_empty() {
|
if !dir.trim().is_empty() {
|
||||||
@@ -55,7 +58,16 @@ pub fn default_documents_dir() -> PathBuf {
|
|||||||
|
|
||||||
if let Ok(home) = std::env::var("HOME") {
|
if let Ok(home) = std::env::var("HOME") {
|
||||||
if !home.trim().is_empty() {
|
if !home.trim().is_empty() {
|
||||||
return PathBuf::from(home).join("Documents");
|
let home = PathBuf::from(home);
|
||||||
|
let user_dirs =
|
||||||
|
std::fs::read_to_string(home.join(".config/user-dirs.dirs")).unwrap_or_default();
|
||||||
|
if let Some(dir) =
|
||||||
|
crate::file_picker::parse_user_dir(&user_dirs, "XDG_DOCUMENTS_DIR", &home)
|
||||||
|
.filter(|dir| *dir != home)
|
||||||
|
{
|
||||||
|
return dir;
|
||||||
|
}
|
||||||
|
return home.join("Documents");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,6 +191,28 @@ pub fn export_notebook_to_bytes(
|
|||||||
assets: Option<&AssetStore>,
|
assets: Option<&AssetStore>,
|
||||||
pattern: PatternColor,
|
pattern: PatternColor,
|
||||||
) -> Result<Vec<u8>, Box<dyn Error>> {
|
) -> Result<Vec<u8>, Box<dyn Error>> {
|
||||||
|
// Endlose Seite: nur der beschriebene Ausschnitt wird zur PDF-Seite
|
||||||
|
if notebook.pages.iter().any(|p| p.is_endless()) {
|
||||||
|
let pages = notebook
|
||||||
|
.pages
|
||||||
|
.iter()
|
||||||
|
.map(|p| {
|
||||||
|
if p.is_endless() {
|
||||||
|
let (origin, size) = p.endless_export_bounds();
|
||||||
|
p.cropped(origin, size)
|
||||||
|
} else {
|
||||||
|
p.clone()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let cropped = Notebook::from_pages(
|
||||||
|
pages,
|
||||||
|
notebook.current_page_index,
|
||||||
|
notebook.next_stroke_id,
|
||||||
|
notebook.next_page_id,
|
||||||
|
);
|
||||||
|
return export_notebook_to_bytes(&cropped, strategy, assets, pattern);
|
||||||
|
}
|
||||||
let doc = generate_pdf_document(notebook, strategy, assets, pattern)?;
|
let doc = generate_pdf_document(notebook, strategy, assets, pattern)?;
|
||||||
let bytes = add_alpha_states(fix_text_encoding(doc.save_to_bytes()?, notebook)?, notebook)?;
|
let bytes = add_alpha_states(fix_text_encoding(doc.save_to_bytes()?, notebook)?, notebook)?;
|
||||||
|
|
||||||
@@ -384,15 +418,15 @@ fn generate_pdf_document_with(
|
|||||||
raster_pdf_pages: &std::collections::HashSet<usize>,
|
raster_pdf_pages: &std::collections::HashSet<usize>,
|
||||||
) -> Result<PdfDocumentReference, Box<dyn Error>> {
|
) -> Result<PdfDocumentReference, Box<dyn Error>> {
|
||||||
if notebook.pages.is_empty() {
|
if notebook.pages.is_empty() {
|
||||||
return Err("Notizbuch enthält keine Seiten".into());
|
return Err(t!("Notizbuch enthält keine Seiten").into());
|
||||||
}
|
}
|
||||||
// Nicht geladene Seiten würden sonst stillschweigend als leere Seiten exportiert
|
// Nicht geladene Seiten würden sonst stillschweigend als leere Seiten exportiert
|
||||||
if let Some(page) = notebook.pages.iter().find(|p| {
|
if let Some(page) = notebook.pages.iter().find(|p| {
|
||||||
!p.is_loaded || p.persist == crate::document::PersistState::ReadOnlyAfterLoadError
|
!p.is_loaded || p.persist == crate::document::PersistState::ReadOnlyAfterLoadError
|
||||||
}) {
|
}) {
|
||||||
return Err(format!(
|
return Err(t!(
|
||||||
"Seite {} ist nicht geladen – Export abgebrochen (vorher storage::load_all_pages aufrufen)",
|
"Seite {id} ist nicht geladen – Export abgebrochen (vorher storage::load_all_pages aufrufen)",
|
||||||
page.id
|
id = page.id
|
||||||
)
|
)
|
||||||
.into());
|
.into());
|
||||||
}
|
}
|
||||||
@@ -823,7 +857,7 @@ fn render_pdf_raster(
|
|||||||
let longest_pt = pdf.width_pt.max(pdf.height_pt);
|
let longest_pt = pdf.width_pt.max(pdf.height_pt);
|
||||||
let max_pixels = (longest_pt / 72.0 * PDF_RASTER_DPI).ceil() as u32;
|
let max_pixels = (longest_pt / 72.0 * PDF_RASTER_DPI).ceil() as u32;
|
||||||
let rendered = assets
|
let rendered = assets
|
||||||
.ok_or_else(|| "kein Asset-Ordner".to_string())
|
.ok_or_else(|| t!("kein Asset-Ordner").to_string())
|
||||||
.and_then(|a| a.path_of(&pdf.asset).map_err(|e| e.to_string()))
|
.and_then(|a| a.path_of(&pdf.asset).map_err(|e| e.to_string()))
|
||||||
.and_then(|path| crate::pdf_doc::render_file_page(&path, pdf.page as usize, max_pixels));
|
.and_then(|path| crate::pdf_doc::render_file_page(&path, pdf.page as usize, max_pixels));
|
||||||
let xobject = match rendered {
|
let xobject = match rendered {
|
||||||
@@ -1760,6 +1794,49 @@ mod tests {
|
|||||||
.is_ok());
|
.is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_endless_page_exports_only_the_written_area() {
|
||||||
|
let mut notebook = Notebook::new();
|
||||||
|
assert!(notebook.make_endless());
|
||||||
|
let sample = |x: f32, y: f32| StylusSample {
|
||||||
|
position: glam::Vec2::new(x, y),
|
||||||
|
pressure: 0.5,
|
||||||
|
timestamp: 0.0,
|
||||||
|
};
|
||||||
|
let page = &mut notebook.pages[0];
|
||||||
|
page.add_stroke(Stroke::new(
|
||||||
|
1,
|
||||||
|
vec![sample(20_000.0, 30_000.0), sample(23_000.0, 31_000.0)],
|
||||||
|
vec![
|
||||||
|
InkVertex::new(20_000.0, 30_000.0, [0.0, 0.0, 0.0, 1.0]),
|
||||||
|
InkVertex::new(23_000.0, 31_000.0, [0.0, 0.0, 0.0, 1.0]),
|
||||||
|
InkVertex::new(23_000.0, 31_010.0, [0.0, 0.0, 0.0, 1.0]),
|
||||||
|
],
|
||||||
|
[0.0, 0.0, 0.0, 1.0],
|
||||||
|
));
|
||||||
|
let (_, size) = notebook.pages[0].endless_export_bounds();
|
||||||
|
let bytes = export_notebook_to_bytes(
|
||||||
|
¬ebook,
|
||||||
|
ExportStrategy::FilledPolygon,
|
||||||
|
None,
|
||||||
|
PatternColor::default(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let sizes = crate::pdf_doc::page_sizes(bytes).unwrap();
|
||||||
|
assert_eq!(sizes.len(), 1);
|
||||||
|
// Seiteneinheiten (10 = 1 mm) in Punkt
|
||||||
|
let pt = |units: f32| units / 10.0 / 25.4 * 72.0;
|
||||||
|
assert!(
|
||||||
|
(sizes[0].0 - pt(size.x)).abs() < 1.0,
|
||||||
|
"{sizes:?} statt {size:?}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
(sizes[0].1 - pt(size.y)).abs() < 1.0,
|
||||||
|
"{sizes:?} statt {size:?}"
|
||||||
|
);
|
||||||
|
assert!(sizes[0].0 < pt(4_000.0), "nicht die ganze endlose Seite");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_page_titles_become_pdf_bookmarks() {
|
fn test_page_titles_become_pdf_bookmarks() {
|
||||||
let mut notebook = Notebook::new();
|
let mut notebook = Notebook::new();
|
||||||
|
|||||||
+13
-10
@@ -7,6 +7,7 @@
|
|||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use crate::assets::is_supported_image_path;
|
use crate::assets::is_supported_image_path;
|
||||||
|
use crate::{t, tn};
|
||||||
|
|
||||||
/// Ein Eintrag der Dateiliste.
|
/// Ein Eintrag der Dateiliste.
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -61,8 +62,8 @@ impl FilePicker {
|
|||||||
.map(Path::to_path_buf)
|
.map(Path::to_path_buf)
|
||||||
.or_else(|| {
|
.or_else(|| {
|
||||||
let preferred = match kind {
|
let preferred = match kind {
|
||||||
PickerKind::Image => "🖼 Bilder",
|
PickerKind::Image => tn!("🖼 Bilder"),
|
||||||
PickerKind::Pdf => "⬇ Downloads",
|
PickerKind::Pdf => tn!("⬇ Downloads"),
|
||||||
};
|
};
|
||||||
let all = shortcuts();
|
let all = shortcuts();
|
||||||
all.iter()
|
all.iter()
|
||||||
@@ -90,9 +91,10 @@ impl FilePicker {
|
|||||||
self.error = None;
|
self.error = None;
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
self.error = Some(format!(
|
self.error = Some(t!(
|
||||||
"'{}' kann nicht geöffnet werden: {err}",
|
"'{dir}' kann nicht geöffnet werden: {err}",
|
||||||
dir.display()
|
dir = dir.display(),
|
||||||
|
err = err
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -131,7 +133,8 @@ pub fn list_dir(dir: &Path, kind: PickerKind) -> std::io::Result<Vec<PickerEntry
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Schnellzugriffe: Bilder, Downloads, Schreibtisch und Home-Ordner (soweit vorhanden),
|
/// Schnellzugriffe: Bilder, Downloads, Schreibtisch und Home-Ordner (soweit vorhanden),
|
||||||
/// mit den Namen aus `~/.config/user-dirs.dirs` (z. B. „Bilder“ statt „Pictures“).
|
/// mit den Ordnern aus `~/.config/user-dirs.dirs` (z. B. „Bilder“ statt „Pictures“). Die
|
||||||
|
/// Bezeichnungen sind deutsch, angezeigt werden sie mit `i18n::tr`.
|
||||||
pub fn shortcuts() -> Vec<(&'static str, PathBuf)> {
|
pub fn shortcuts() -> Vec<(&'static str, PathBuf)> {
|
||||||
let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else {
|
let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else {
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
@@ -146,15 +149,15 @@ pub fn shortcuts() -> Vec<(&'static str, PathBuf)> {
|
|||||||
};
|
};
|
||||||
let mut list = Vec::new();
|
let mut list = Vec::new();
|
||||||
if let Some(p) = xdg("XDG_PICTURES_DIR", &["Bilder", "Pictures"]) {
|
if let Some(p) = xdg("XDG_PICTURES_DIR", &["Bilder", "Pictures"]) {
|
||||||
list.push(("🖼 Bilder", p));
|
list.push((tn!("🖼 Bilder"), p));
|
||||||
}
|
}
|
||||||
if let Some(p) = xdg("XDG_DOWNLOAD_DIR", &["Downloads"]) {
|
if let Some(p) = xdg("XDG_DOWNLOAD_DIR", &["Downloads"]) {
|
||||||
list.push(("⬇ Downloads", p));
|
list.push((tn!("⬇ Downloads"), p));
|
||||||
}
|
}
|
||||||
if let Some(p) = xdg("XDG_DESKTOP_DIR", &["Schreibtisch", "Desktop"]) {
|
if let Some(p) = xdg("XDG_DESKTOP_DIR", &["Schreibtisch", "Desktop"]) {
|
||||||
list.push(("🖥 Schreibtisch", p));
|
list.push((tn!("🖥 Schreibtisch"), p));
|
||||||
}
|
}
|
||||||
list.push(("🏠 Persönlicher Ordner", home));
|
list.push((tn!("🏠 Persönlicher Ordner"), home));
|
||||||
list
|
list
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+126
-15
@@ -9,6 +9,7 @@ use std::f32::consts::PI;
|
|||||||
|
|
||||||
use crate::canvas::InkVertex;
|
use crate::canvas::InkVertex;
|
||||||
use crate::document::{Aabb, Stroke, StylusSample};
|
use crate::document::{Aabb, Stroke, StylusSample};
|
||||||
|
use crate::t;
|
||||||
|
|
||||||
/// Arten der geometrischen Primitiven.
|
/// Arten der geometrischen Primitiven.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
@@ -104,26 +105,26 @@ impl RecognizedShape {
|
|||||||
|
|
||||||
pub fn name(&self) -> &'static str {
|
pub fn name(&self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
Self::Line { .. } => "Gerade",
|
Self::Line { .. } => t!("Gerade"),
|
||||||
Self::Circle { .. } => "Kreis",
|
Self::Circle { .. } => t!("Kreis"),
|
||||||
Self::Ellipse { .. } => "Ellipse",
|
Self::Ellipse { .. } => t!("Ellipse"),
|
||||||
Self::Arrow { double: false, .. } => "Pfeil",
|
Self::Arrow { double: false, .. } => t!("Pfeil"),
|
||||||
Self::Arrow { double: true, .. } => "Doppelpfeil",
|
Self::Arrow { double: true, .. } => t!("Doppelpfeil"),
|
||||||
Self::Rectangle { .. } => "Rechteck",
|
Self::Rectangle { .. } => t!("Rechteck"),
|
||||||
Self::CoordinateSystem {
|
Self::CoordinateSystem {
|
||||||
negative_ends: Some(_),
|
negative_ends: Some(_),
|
||||||
..
|
..
|
||||||
} => "Achsenkreuz",
|
} => t!("Achsenkreuz"),
|
||||||
Self::CoordinateSystem { .. } => "Koordinatensystem",
|
Self::CoordinateSystem { .. } => t!("Koordinatensystem"),
|
||||||
Self::Triangle { .. } => "Dreieck",
|
Self::Triangle { .. } => t!("Dreieck"),
|
||||||
Self::Rhombus { .. } => "Raute (Rhombus)",
|
Self::Rhombus { .. } => t!("Raute (Rhombus)"),
|
||||||
Self::Polygon { vertices } => match vertices.len() {
|
Self::Polygon { vertices } => match vertices.len() {
|
||||||
5 => "Fünfeck (Pentagon)",
|
5 => t!("Fünfeck (Pentagon)"),
|
||||||
6 => "Sechseck (Hexagon)",
|
6 => t!("Sechseck (Hexagon)"),
|
||||||
8 => "Achteck (Oktagon)",
|
8 => t!("Achteck (Oktagon)"),
|
||||||
_ => "Polygon",
|
_ => t!("Polygon"),
|
||||||
},
|
},
|
||||||
Self::Octahedron { .. } => "Oktaeder (3D-Kantenmodell)",
|
Self::Octahedron { .. } => t!("Oktaeder (3D-Kantenmodell)"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1499,6 +1500,77 @@ pub fn detect_axis_cross(points: &[Vec2]) -> Option<RecognizedShape> {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Achsenkreuz aus zwei Strichen: eine waagerechte und eine senkrechte Gerade (je höchstens
|
||||||
|
/// 25° schief, Reihenfolge egal), die sich kreuzen und auf beiden Seiten des Schnittpunkts
|
||||||
|
/// deutlich weiterlaufen. Ergebnis wie bei `detect_axis_cross`.
|
||||||
|
pub fn axis_cross_from_lines(a: (Vec2, Vec2), b: (Vec2, Vec2)) -> Option<RecognizedShape> {
|
||||||
|
let max_slope = 25.0_f32.to_radians().tan();
|
||||||
|
let is_horizontal = |(p, q): (Vec2, Vec2)| (q.y - p.y).abs() <= (q.x - p.x).abs() * max_slope;
|
||||||
|
let is_vertical = |(p, q): (Vec2, Vec2)| (q.x - p.x).abs() <= (q.y - p.y).abs() * max_slope;
|
||||||
|
let (horizontal, vertical) = if is_horizontal(a) && is_vertical(b) {
|
||||||
|
(a, b)
|
||||||
|
} else if is_vertical(a) && is_horizontal(b) {
|
||||||
|
(b, a)
|
||||||
|
} else {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
|
||||||
|
let (x_min, x_max) = (
|
||||||
|
horizontal.0.x.min(horizontal.1.x),
|
||||||
|
horizontal.0.x.max(horizontal.1.x),
|
||||||
|
);
|
||||||
|
let (y_min, y_max) = (
|
||||||
|
vertical.0.y.min(vertical.1.y),
|
||||||
|
vertical.0.y.max(vertical.1.y),
|
||||||
|
);
|
||||||
|
let origin = Vec2::new(
|
||||||
|
(vertical.0.x + vertical.1.x) * 0.5,
|
||||||
|
(horizontal.0.y + horizontal.1.y) * 0.5,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Vier Arme: jeder mindestens ein Fünftel seiner Achse, die Achsen nicht winzig
|
||||||
|
let (width, height) = (x_max - x_min, y_max - y_min);
|
||||||
|
let arm_ok = |arm: f32, axis: f32| arm >= axis * 0.2;
|
||||||
|
if width < 30.0
|
||||||
|
|| height < 30.0
|
||||||
|
|| !(arm_ok(origin.x - x_min, width)
|
||||||
|
&& arm_ok(x_max - origin.x, width)
|
||||||
|
&& arm_ok(origin.y - y_min, height)
|
||||||
|
&& arm_ok(y_max - origin.y, height))
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
// x nach rechts, y nach oben (auf dem Blatt: kleineres y)
|
||||||
|
Some(RecognizedShape::CoordinateSystem {
|
||||||
|
origin,
|
||||||
|
x_axis_end: Vec2::new(x_max, origin.y),
|
||||||
|
y_axis_end: Vec2::new(origin.x, y_min),
|
||||||
|
with_arrows: true,
|
||||||
|
negative_ends: Some([Vec2::new(x_min, origin.y), Vec2::new(origin.x, y_max)]),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gerade, die ein Strich darstellt: eine als Gerade eingerastete Form oder ein freihändiger
|
||||||
|
/// Strich, den die Formerkennung als Gerade erkennt. Bilder, Textfelder und Textmarker zählen
|
||||||
|
/// nicht.
|
||||||
|
pub fn stroke_as_line(stroke: &Stroke) -> Option<(Vec2, Vec2)> {
|
||||||
|
if stroke.image.is_some()
|
||||||
|
|| stroke.text.is_some()
|
||||||
|
|| stroke.tool == crate::document::StrokeTool::Highlighter
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let shape = match &stroke.shape {
|
||||||
|
Some(shape) => shape.clone(),
|
||||||
|
None => detect_shape(&stroke.points)?,
|
||||||
|
};
|
||||||
|
match shape {
|
||||||
|
RecognizedShape::Line { start, end } => Some((start, end)),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Führt die automatische Erkennung für einen Strich aus.
|
/// Führt die automatische Erkennung für einen Strich aus.
|
||||||
pub fn detect_shape(points: &[StylusSample]) -> Option<RecognizedShape> {
|
pub fn detect_shape(points: &[StylusSample]) -> Option<RecognizedShape> {
|
||||||
if points.len() < 2 {
|
if points.len() < 2 {
|
||||||
@@ -2674,6 +2746,45 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_axis_cross_from_two_lines() {
|
||||||
|
let horizontal = (Vec2::new(100.0, 305.0), Vec2::new(400.0, 300.0));
|
||||||
|
let vertical = (Vec2::new(252.0, 450.0), Vec2::new(248.0, 150.0));
|
||||||
|
for (a, b) in [(horizontal, vertical), (vertical, horizontal)] {
|
||||||
|
let Some(RecognizedShape::CoordinateSystem {
|
||||||
|
origin,
|
||||||
|
x_axis_end,
|
||||||
|
y_axis_end,
|
||||||
|
with_arrows: true,
|
||||||
|
negative_ends: Some([x_start, y_start]),
|
||||||
|
}) = axis_cross_from_lines(a, b)
|
||||||
|
else {
|
||||||
|
panic!("kein Achsenkreuz");
|
||||||
|
};
|
||||||
|
assert_eq!(origin, Vec2::new(250.0, 302.5));
|
||||||
|
assert_eq!(x_axis_end, Vec2::new(400.0, 302.5));
|
||||||
|
assert_eq!(x_start, Vec2::new(100.0, 302.5));
|
||||||
|
assert_eq!(y_axis_end, Vec2::new(250.0, 150.0));
|
||||||
|
assert_eq!(y_start, Vec2::new(250.0, 450.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_no_axis_cross_from_lines_that_do_not_cross() {
|
||||||
|
let horizontal = (Vec2::new(100.0, 300.0), Vec2::new(400.0, 300.0));
|
||||||
|
// Senkrechte endet über der Waagerechten (L oder T statt Kreuz)
|
||||||
|
let above = (Vec2::new(250.0, 100.0), Vec2::new(250.0, 290.0));
|
||||||
|
assert!(axis_cross_from_lines(horizontal, above).is_none());
|
||||||
|
// Senkrechte schneidet ganz am Rand
|
||||||
|
let at_edge = (Vec2::new(110.0, 150.0), Vec2::new(110.0, 450.0));
|
||||||
|
assert!(axis_cross_from_lines(horizontal, at_edge).is_none());
|
||||||
|
// Zwei Waagerechte oder eine schräge Linie
|
||||||
|
let parallel = (Vec2::new(100.0, 350.0), Vec2::new(400.0, 350.0));
|
||||||
|
assert!(axis_cross_from_lines(horizontal, parallel).is_none());
|
||||||
|
let diagonal = (Vec2::new(150.0, 150.0), Vec2::new(350.0, 450.0));
|
||||||
|
assert!(axis_cross_from_lines(horizontal, diagonal).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_detect_axis_cross_in_one_stroke() {
|
fn test_detect_axis_cross_in_one_stroke() {
|
||||||
let c = Vec2::new(800.0, 900.0);
|
let c = Vec2::new(800.0, 900.0);
|
||||||
|
|||||||
+326
@@ -0,0 +1,326 @@
|
|||||||
|
//! Sprache der Oberfläche: Deutsch oder Englisch.
|
||||||
|
//!
|
||||||
|
//! Die Texte stehen im Quelltext auf Deutsch in `t!("…")`; dieser deutsche Text ist zugleich
|
||||||
|
//! der Schlüssel für die englische Fassung in `en.rs`. Platzhalter heißen `{name}` und werden
|
||||||
|
//! mit `t!("Seite {number}", number = n)` gefüllt (Formatangaben wie `{:.1}` vorher mit
|
||||||
|
//! `format!` anwenden). Texte in Tabellen markiert `tn!("…")`, übersetzt werden sie beim
|
||||||
|
//! Anzeigen mit `tr(…)`. Ein Test prüft, dass jeder markierte Text übersetzt ist.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::fmt::Display;
|
||||||
|
use std::sync::atomic::{AtomicU8, Ordering};
|
||||||
|
use std::sync::OnceLock;
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
mod en;
|
||||||
|
|
||||||
|
/// Sprache der Oberfläche
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum Language {
|
||||||
|
German,
|
||||||
|
English,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Language {
|
||||||
|
pub const ALL: [Language; 2] = [Language::German, Language::English];
|
||||||
|
|
||||||
|
/// Name der Sprache in ihr selbst (für die Auswahl, unabhängig von der aktuellen Sprache)
|
||||||
|
pub fn native_name(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Language::German => "Deutsch",
|
||||||
|
Language::English => "English",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sprache aus den Locale-Variablen (`LC_ALL`, `LC_MESSAGES`, `LANG`, `LANGUAGE`; `C` und
|
||||||
|
/// `POSIX` zählen nicht): Deutsch bei `de…`, sonst Englisch.
|
||||||
|
pub fn from_locale(vars: &[Option<String>]) -> Language {
|
||||||
|
let locale = vars
|
||||||
|
.iter()
|
||||||
|
.flatten()
|
||||||
|
.map(|v| v.trim())
|
||||||
|
.find(|v| !v.is_empty() && *v != "C" && !v.starts_with("C.") && *v != "POSIX");
|
||||||
|
match locale {
|
||||||
|
Some(v) if v.to_ascii_lowercase().starts_with("de") => Language::German,
|
||||||
|
_ => Language::English,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sprache des Systems
|
||||||
|
pub fn system() -> Language {
|
||||||
|
let var = |name| std::env::var(name).ok();
|
||||||
|
Language::from_locale(&[
|
||||||
|
var("LC_ALL"),
|
||||||
|
var("LC_MESSAGES"),
|
||||||
|
var("LANG"),
|
||||||
|
var("LANGUAGE"),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static CURRENT: AtomicU8 = AtomicU8::new(0);
|
||||||
|
|
||||||
|
/// Stellt die Sprache der Oberfläche um (wirkt ab dem nächsten Frame).
|
||||||
|
pub fn set_language(language: Language) {
|
||||||
|
CURRENT.store(language as u8, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Aktuelle Sprache der Oberfläche
|
||||||
|
pub fn language() -> Language {
|
||||||
|
match CURRENT.load(Ordering::Relaxed) {
|
||||||
|
0 => Language::German,
|
||||||
|
_ => Language::English,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn english() -> &'static HashMap<&'static str, &'static str> {
|
||||||
|
static TABLE: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();
|
||||||
|
TABLE.get_or_init(|| en::EN.iter().copied().collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text `german` in der Sprache `language`; fehlt die Übersetzung, bleibt er deutsch.
|
||||||
|
pub fn translate(language: Language, german: &'static str) -> &'static str {
|
||||||
|
match language {
|
||||||
|
Language::German => german,
|
||||||
|
Language::English => english().get(german).copied().unwrap_or(german),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text in der aktuellen Sprache
|
||||||
|
pub fn tr(german: &'static str) -> &'static str {
|
||||||
|
translate(language(), german)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Setzt die Werte für die Platzhalter `{name}` ein.
|
||||||
|
pub fn fill(template: &str, args: &[(&str, &dyn Display)]) -> String {
|
||||||
|
let mut out = String::with_capacity(template.len() + 16);
|
||||||
|
let mut rest = template;
|
||||||
|
while let Some(open) = rest.find('{') {
|
||||||
|
out.push_str(&rest[..open]);
|
||||||
|
let after = &rest[open + 1..];
|
||||||
|
match after.find('}') {
|
||||||
|
Some(close) => {
|
||||||
|
let name = &after[..close];
|
||||||
|
match args.iter().find(|(key, _)| *key == name) {
|
||||||
|
Some((_, value)) => out.push_str(&value.to_string()),
|
||||||
|
None => out.push_str(&rest[open..open + close + 2]),
|
||||||
|
}
|
||||||
|
rest = &after[close + 1..];
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
out.push_str(&rest[open..]);
|
||||||
|
rest = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push_str(rest);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Übersetzt einen deutschen Text: `t!("Abbrechen")` ergibt `&'static str`,
|
||||||
|
/// `t!("Seite {number}", number = n)` einen `String` mit eingesetzten Werten.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! t {
|
||||||
|
($german:literal) => {
|
||||||
|
$crate::i18n::tr($german)
|
||||||
|
};
|
||||||
|
($german:literal, $($name:ident = $value:expr),+ $(,)?) => {
|
||||||
|
$crate::i18n::fill(
|
||||||
|
$crate::i18n::tr($german),
|
||||||
|
&[$((stringify!($name), &$value as &dyn ::std::fmt::Display)),+],
|
||||||
|
)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Markiert einen deutschen Text zum Übersetzen, ohne ihn schon zu übersetzen (für Tabellen;
|
||||||
|
/// angezeigt wird er mit `tr`).
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! tn {
|
||||||
|
($german:literal) => {
|
||||||
|
$german
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// Quelltexte mit übersetzbaren Texten
|
||||||
|
const SOURCES: &[(&str, &str)] = &[
|
||||||
|
("assets.rs", include_str!("assets.rs")),
|
||||||
|
("autosave.rs", include_str!("autosave.rs")),
|
||||||
|
("background.rs", include_str!("background.rs")),
|
||||||
|
("document.rs", include_str!("document.rs")),
|
||||||
|
("export.rs", include_str!("export.rs")),
|
||||||
|
("file_picker.rs", include_str!("file_picker.rs")),
|
||||||
|
("geometry.rs", include_str!("geometry.rs")),
|
||||||
|
("library.rs", include_str!("library.rs")),
|
||||||
|
("main.rs", include_str!("main.rs")),
|
||||||
|
("page_export.rs", include_str!("page_export.rs")),
|
||||||
|
("pdf_doc.rs", include_str!("pdf_doc.rs")),
|
||||||
|
("pdf_merge.rs", include_str!("pdf_merge.rs")),
|
||||||
|
("canvas.rs", include_str!("canvas.rs")),
|
||||||
|
("selection.rs", include_str!("selection.rs")),
|
||||||
|
("settings.rs", include_str!("settings.rs")),
|
||||||
|
("storage.rs", include_str!("storage.rs")),
|
||||||
|
("text.rs", include_str!("text.rs")),
|
||||||
|
("ui.rs", include_str!("ui.rs")),
|
||||||
|
("updater.rs", include_str!("updater.rs")),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Alle Texte in `t!("…")` und `tn!("…")` eines Quelltexts, auch über mehrere Zeilen
|
||||||
|
/// (Escapes wie `\n` aufgelöst)
|
||||||
|
fn marked_texts(src: &str) -> Vec<String> {
|
||||||
|
let chars: Vec<char> = src.chars().collect();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut i = 0;
|
||||||
|
while i < chars.len() {
|
||||||
|
let rest: String = chars[i..chars.len().min(i + 4)].iter().collect();
|
||||||
|
let marker_len = if rest.starts_with("t!(") {
|
||||||
|
3
|
||||||
|
} else if rest.starts_with("tn!(") {
|
||||||
|
4
|
||||||
|
} else {
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
// `t!(` nicht als Ende eines längeren Namens (z. B. `format!(`) zählen
|
||||||
|
if i > 0 && (chars[i - 1].is_alphanumeric() || chars[i - 1] == '_') {
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
i += marker_len;
|
||||||
|
while chars.get(i).is_some_and(|c| c.is_whitespace()) {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
if chars.get(i) != Some(&'"') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
let mut text = String::new();
|
||||||
|
while i < chars.len() && chars[i] != '"' {
|
||||||
|
if chars[i] == '\\' {
|
||||||
|
i += 1;
|
||||||
|
match chars.get(i) {
|
||||||
|
Some('n') => text.push('\n'),
|
||||||
|
// Zeilenfortsetzung: Umbruch und führende Leerzeichen entfallen
|
||||||
|
Some('\n') => {
|
||||||
|
while chars.get(i + 1).is_some_and(|c| c.is_whitespace()) {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(other) => text.push(*other),
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
text.push(chars[i]);
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
out.push(text);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn placeholders(text: &str) -> Vec<&str> {
|
||||||
|
let mut names: Vec<&str> = text
|
||||||
|
.split('{')
|
||||||
|
.skip(1)
|
||||||
|
.filter_map(|part| part.split_once('}').map(|(name, _)| name))
|
||||||
|
.collect();
|
||||||
|
names.sort_unstable();
|
||||||
|
names
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_marked_text_has_an_english_translation() {
|
||||||
|
let table = english();
|
||||||
|
let mut missing: Vec<String> = SOURCES
|
||||||
|
.iter()
|
||||||
|
.flat_map(|(file, src)| {
|
||||||
|
marked_texts(src)
|
||||||
|
.into_iter()
|
||||||
|
.filter(|text| !table.contains_key(text.as_str()))
|
||||||
|
.map(move |text| format!("{file}: {text:?}"))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
missing.sort();
|
||||||
|
missing.dedup();
|
||||||
|
assert!(
|
||||||
|
missing.is_empty(),
|
||||||
|
"Ohne Übersetzung:\n{}",
|
||||||
|
missing.join("\n")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_translation_is_used_and_keeps_its_placeholders() {
|
||||||
|
let used: std::collections::HashSet<String> = SOURCES
|
||||||
|
.iter()
|
||||||
|
.flat_map(|(_, src)| marked_texts(src))
|
||||||
|
.collect();
|
||||||
|
let mut seen = std::collections::HashSet::new();
|
||||||
|
for (german, english) in en::EN {
|
||||||
|
assert!(seen.insert(german), "Doppelt: {german:?}");
|
||||||
|
assert!(used.contains(*german), "Nicht (mehr) verwendet: {german:?}");
|
||||||
|
assert_eq!(
|
||||||
|
placeholders(german),
|
||||||
|
placeholders(english),
|
||||||
|
"Platzhalter verschieden: {german:?} / {english:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn translate_falls_back_to_german() {
|
||||||
|
assert_eq!(translate(Language::German, "Abbrechen"), "Abbrechen");
|
||||||
|
assert_eq!(translate(Language::English, "Abbrechen"), "Cancel");
|
||||||
|
assert_eq!(
|
||||||
|
translate(Language::English, "kein bekannter Text"),
|
||||||
|
"kein bekannter Text"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fill_replaces_named_placeholders() {
|
||||||
|
assert_eq!(
|
||||||
|
fill(
|
||||||
|
"Seite {number} von {count}",
|
||||||
|
&[("number", &3), ("count", &"7")]
|
||||||
|
),
|
||||||
|
"Seite 3 von 7"
|
||||||
|
);
|
||||||
|
assert_eq!(fill("{unbekannt} bleibt", &[]), "{unbekannt} bleibt");
|
||||||
|
assert_eq!(fill("offen {", &[]), "offen {");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn locale_selects_language() {
|
||||||
|
let s = |v: &str| Some(v.to_string());
|
||||||
|
assert_eq!(
|
||||||
|
Language::from_locale(&[None, None, s("de_AT.UTF-8")]),
|
||||||
|
Language::German
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Language::from_locale(&[s("en_US.UTF-8"), None, s("de_DE.UTF-8")]),
|
||||||
|
Language::English
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Language::from_locale(&[s("C"), None, s("de_DE.UTF-8")]),
|
||||||
|
Language::German
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Language::from_locale(&[s("C.UTF-8"), None, s("de_DE.UTF-8")]),
|
||||||
|
Language::German
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Language::from_locale(&[None, None, None]),
|
||||||
|
Language::English
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
Language::from_locale(&[None, None, s("fr_FR.UTF-8")]),
|
||||||
|
Language::English
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+452
@@ -0,0 +1,452 @@
|
|||||||
|
//! Englische Fassung der Oberflächentexte: (deutscher Text im Quelltext, englischer Text).
|
||||||
|
//! Platzhalter `{name}` müssen in beiden Fassungen gleich heißen; der Test in `i18n.rs` meldet
|
||||||
|
//! fehlende, überzählige und abweichende Einträge.
|
||||||
|
|
||||||
|
pub const EN: &[(&str, &str)] = &[
|
||||||
|
("'{dir}' kann nicht geöffnet werden: {err}", "'{dir}' cannot be opened: {err}"),
|
||||||
|
("'{name}' erfolgreich heruntergeladen!", "'{name}' downloaded successfully!"),
|
||||||
|
("'{name}' nicht eingefügt: {err}", "'{name}' not inserted: {err}"),
|
||||||
|
("'{title}' gelöscht", "'{title}' deleted"),
|
||||||
|
("'{title}' importiert ({count} Seiten)", "'{title}' imported ({count} pages)"),
|
||||||
|
("(Empfohlen für dieses System)", "(Recommended for this system)"),
|
||||||
|
("1 Notizbuch", "1 notebook"),
|
||||||
|
("1 Objekt | [R] Drehen [Entf] Löschen", "1 object | [R] Rotate [Del] Delete"),
|
||||||
|
("Abbrechen", "Cancel"),
|
||||||
|
("Abfrage fehlgeschlagen:", "Request failed:"),
|
||||||
|
("Achsenkreuz", "Axis cross"),
|
||||||
|
("Achteck (Oktagon)", "Octagon"),
|
||||||
|
("Aktuelle Version:", "Current version:"),
|
||||||
|
("Alle Striche radieren", "Erase whole strokes"),
|
||||||
|
("Alle", "All"),
|
||||||
|
("Alles gespeichert", "All saved"),
|
||||||
|
("Als leere Seite bearbeiten (Schreibschutz aufheben)", "Edit as blank page (remove write protection)"),
|
||||||
|
("AppImage (Portabel)", "AppImage (portable)"),
|
||||||
|
("Asset-Name darf nicht leer sein.", "Asset name must not be empty."),
|
||||||
|
("Auch per Strg+V aus der Zwischenablage oder durch Ziehen einer Bilddatei ins Fenster", "Also with Ctrl+V from the clipboard or by dragging an image file into the window"),
|
||||||
|
("Auf Seiten mit importiertem PDF lässt sich kein Platz schaffen", "Pages with an imported PDF cannot make space"),
|
||||||
|
("Aus manifest.json.bak wiederherstellen", "Restore from manifest.json.bak"),
|
||||||
|
("Aus: ein Finger verschiebt, zwei Finger zoomen (empfohlen mit Stift).\nAn: ein Finger zeichnet.", "Off: one finger pans, two fingers zoom (recommended with a pen).\nOn: one finger draws."),
|
||||||
|
("Auswahl / Lasso (Select)", "Select / Lasso"),
|
||||||
|
("Auswahl auf Blau umgefärbt", "Selection recolored to blue"),
|
||||||
|
("Auswahl auf Schwarz umgefärbt", "Selection recolored to black"),
|
||||||
|
("Auswahl in der Farbe von Stift {number} umfärben", "Recolor selection with the color of pen {number}"),
|
||||||
|
("Auswahl um 90° gedreht", "Selection rotated by 90°"),
|
||||||
|
("Auswahl umgefärbt", "Selection recolored"),
|
||||||
|
("Auswählen", "Select"),
|
||||||
|
("Auswählen: verschieben, drehen, skalieren, kopieren (V)", "Select: move, rotate, scale, copy (V)"),
|
||||||
|
("Autosave fehlgeschlagen für Seiten {pages}: {messages}", "Autosave failed for pages {pages}: {messages}"),
|
||||||
|
("Beschädigte Seite {id}: {msg}", "Damaged page {id}: {msg}"),
|
||||||
|
("Bild einfügen", "Insert image"),
|
||||||
|
("Bild eingefügt ({width} × {height} px)", "Image inserted ({width} × {height} px)"),
|
||||||
|
("Bild ist zu groß ({size} MB, höchstens {max} MB)", "Image is too large ({size} MB, at most {max} MB)"),
|
||||||
|
("Bild kann nicht gelesen werden: {msg}", "Cannot read image: {msg}"),
|
||||||
|
("Bild mit Papier und Raster (200 dpi)", "Image with paper and pattern (200 dpi)"),
|
||||||
|
("Bild mit transparentem Hintergrund, nur Inhalt", "Image with transparent background, content only"),
|
||||||
|
("Bild nicht eingefügt: {err}", "Image not inserted: {err}"),
|
||||||
|
("Bild, Text oder kopierte Objekte aus der Zwischenablage hier einfügen", "Paste an image, text or copied objects from the clipboard here"),
|
||||||
|
("Blanko", "Blank"),
|
||||||
|
("Blau", "Blue"),
|
||||||
|
("Code", "Code"),
|
||||||
|
("Code-Schrift (feste Zeichenbreite, Tab rückt ein)", "Code font (fixed width, Tab indents)"),
|
||||||
|
("Creme", "Cream"),
|
||||||
|
("Das PDF enthält keine Seiten", "The PDF has no pages"),
|
||||||
|
("Das PDF hat {count} Seiten, höchstens {max} werden unterstützt", "The PDF has {count} pages, at most {max} are supported"),
|
||||||
|
("Das PDF ist verschlüsselt oder passwortgeschützt und kann nicht geöffnet werden", "The PDF is encrypted or password protected and cannot be opened"),
|
||||||
|
("Das PDF wird als neues Notizbuch angelegt, eine Seite je PDF-Seite. Beim Export liegen deine Notizen über den Originalseiten.", "The PDF becomes a new notebook, one page per PDF page. When exporting, your notes lie on top of the original pages."),
|
||||||
|
("Datei existiert nicht", "File does not exist"),
|
||||||
|
("Den Ordner gibt es nicht mehr", "The folder no longer exists"),
|
||||||
|
("Den Ordner „{name}“ gibt es hier schon", "A folder “{name}” already exists here"),
|
||||||
|
("Den Zielordner gibt es nicht mehr", "The target folder no longer exists"),
|
||||||
|
("Der Ordnername ist leer", "The folder name is empty"),
|
||||||
|
("Der Ordnername ist zu lang (höchstens {max} Zeichen)", "The folder name is too long (at most {max} characters)"),
|
||||||
|
("Der übergeordnete Ordner existiert nicht mehr", "The parent folder no longer exists"),
|
||||||
|
("DICKEN-PRESETS", "WIDTH PRESETS"),
|
||||||
|
("Die beschädigte Originaldatei wurde in Quarantäne gesichert:", "The damaged original file was saved to quarantine:"),
|
||||||
|
("Die Datei ist kein lesbares PDF", "The file is not a readable PDF"),
|
||||||
|
("Die einzige Seite eines Notizbuchs kann nicht gelöscht werden", "The only page of a notebook cannot be deleted"),
|
||||||
|
("Die Flatpak-Version wird über die Software-Verwaltung aktualisiert.", "The Flatpak version is updated through the software manager."),
|
||||||
|
("Die heruntergeladene Datei existiert nicht mehr.", "The downloaded file no longer exists."),
|
||||||
|
("die oberste Ebene", "the top level"),
|
||||||
|
("Die Zwischenablage ist leer", "The clipboard is empty"),
|
||||||
|
("Diese Version wird über die Software-Verwaltung aktualisiert (z. B. GNOME Software oder „flatpak update“).", "This version is updated through the software manager (e.g. GNOME Software or “flatpak update”)."),
|
||||||
|
("Dieser Ordner ist leer.", "This folder is empty."),
|
||||||
|
("Dokument '{title}' erstellt", "Document '{title}' created"),
|
||||||
|
("Dokument '{title}' geöffnet", "Document '{title}' opened"),
|
||||||
|
("Dokument in Papierkorb verschoben", "Document moved to the trash"),
|
||||||
|
("DOKUMENT", "DOCUMENT"),
|
||||||
|
("Dokumenten-Manager", "Document manager"),
|
||||||
|
("Doppelpfeil", "Double arrow"),
|
||||||
|
("Download-Verbindungsfehler: {e}", "Download connection error: {e}"),
|
||||||
|
("Dreieck", "Triangle"),
|
||||||
|
("Druckkurve des Stifts", "Pen pressure curve"),
|
||||||
|
("Druckkurve zurücksetzen", "Reset pressure curve"),
|
||||||
|
("Drücke eine Taste am Stift (über dem Bildschirm) – sie erscheint dann hier. Bis dahin radieren alle Tasten.", "Press a button on the pen (above the screen) – it will appear here. Until then all buttons erase."),
|
||||||
|
("Dunkelgrau", "Dark gray"),
|
||||||
|
("Dunkle Stiftfarben aufhellen", "Lighten dark pen colors"),
|
||||||
|
("Eigene Farbe wählen", "Choose a custom color"),
|
||||||
|
("Ein Ordner kann nicht in sich selbst verschoben werden", "A folder cannot be moved into itself"),
|
||||||
|
("Ein-/Ausgabefehler: {e}", "I/O error: {e}"),
|
||||||
|
("Eine Fläche ohne Rand: in alle Richtungen schreiben, verschieben und zoomen. Wechsel nur bei einer einzigen Seite ohne PDF bzw. zurück, solange alles im Startausschnitt liegt.", "One surface without edges: write, pan and zoom in every direction. Switching only works for a single page without a PDF, and back only while everything lies in the starting area."),
|
||||||
|
("Einfügen (Strg+V)", "Paste (Ctrl+V)"),
|
||||||
|
("EINGABE", "INPUT"),
|
||||||
|
("Einstellung nicht gespeichert: {err}", "Setting not saved: {err}"),
|
||||||
|
("Ellipse", "Ellipse"),
|
||||||
|
("Endlos geht nur bei einem Notizbuch mit einer einzigen Seite ohne PDF", "Endless only works for a notebook with a single page without a PDF"),
|
||||||
|
("Entwicklung / Lokal", "Development / local"),
|
||||||
|
("Export fehlgeschlagen: {err}", "Export failed: {err}"),
|
||||||
|
("Farbe {number} – erneut tippen, um sie anzupassen", "Color {number} – tap again to adjust it"),
|
||||||
|
("Farbe {number}", "Color {number}"),
|
||||||
|
("FARBE", "COLOR"),
|
||||||
|
("Fehler beim Beenden", "Error while quitting"),
|
||||||
|
("Fehler beim Erstellen: {err}", "Error while creating: {err}"),
|
||||||
|
("Fehler beim Lesen der Prüfsummendatei: {e}", "Error reading the checksum file: {e}"),
|
||||||
|
("Fehler beim Lesen des Download-Streams: {e}", "Error reading the download stream: {e}"),
|
||||||
|
("Fehler beim Löschen: {err}", "Error while deleting: {err}"),
|
||||||
|
("Fehler beim Schreiben auf die Festplatte: {e}", "Error writing to disk: {e}"),
|
||||||
|
("Fehler beim Umbenennen: {err}", "Error while renaming: {err}"),
|
||||||
|
("Fehler beim Wiederherstellen: {err}", "Error while restoring: {err}"),
|
||||||
|
("Fehler beim Öffnen: {err}", "Error while opening: {err}"),
|
||||||
|
("Fehler: {err}", "Error: {err}"),
|
||||||
|
("Fehlermeldung: {message}", "Error message: {message}"),
|
||||||
|
("Formen (Shape)", "Shapes"),
|
||||||
|
("Formen: Striche werden zu Linien, Rechtecken, Kreisen … (S/F)", "Shapes: strokes become lines, rectangles, circles … (S/F)"),
|
||||||
|
("Fünfeck (Pentagon)", "Pentagon"),
|
||||||
|
("Gerade", "Line"),
|
||||||
|
("Gespeichert in: {path}", "Saved in: {path}"),
|
||||||
|
("Gespeichert", "Saved"),
|
||||||
|
("Gespeichert: {path}", "Saved: {path}"),
|
||||||
|
("Gewechselt zu '{title}'", "Switched to '{title}'"),
|
||||||
|
("Gilt für alle Seiten, auch beim Export", "Applies to all pages, also when exporting"),
|
||||||
|
("Gitea Release-JSON konnte nicht verarbeitet werden: {e}", "Could not process the Gitea release JSON: {e}"),
|
||||||
|
("Gitea Server-URL:", "Gitea server URL:"),
|
||||||
|
("Gitea-Server antwortete mit HTTP {code}: {body}", "Gitea server responded with HTTP {code}: {body}"),
|
||||||
|
("Graphit-Grau", "Graphite gray"),
|
||||||
|
("Größere Schrift (jetzt {size} pt)", "Larger font (now {size} pt)"),
|
||||||
|
("Grün", "Green"),
|
||||||
|
("hart", "hard"),
|
||||||
|
("Hell", "Light"),
|
||||||
|
("Hellgrün", "Light green"),
|
||||||
|
("Heranzoomen (Strg++)", "Zoom in (Ctrl++)"),
|
||||||
|
("Herauszoomen (Strg+-)", "Zoom out (Ctrl+-)"),
|
||||||
|
("HINTERGRUND DIESER SEITE", "BACKGROUND OF THIS PAGE"),
|
||||||
|
("Hinweis: Falls das Repository privat ist, unten ein Personal Access Token eintragen.", "Note: if the repository is private, enter a personal access token below."),
|
||||||
|
("HOME-Umgebungsvariable ist nicht gesetzt.", "HOME environment variable is not set."),
|
||||||
|
("HTTP {code} Weiterleitung ohne Location-Header erhalten", "HTTP {code} redirect without Location header"),
|
||||||
|
("I/O-Fehler: {e}", "I/O error: {e}"),
|
||||||
|
("Im Zielordner gibt es schon einen Ordner „{name}“", "A folder “{name}” already exists in the target folder"),
|
||||||
|
("In dieser Version ist kein Signaturschlüssel für Updates hinterlegt. Bitte das Update manuell installieren.", "This version has no signing key for updates. Please install the update manually."),
|
||||||
|
("In einen anderen Ordner verschieben", "Move to another folder"),
|
||||||
|
("Inhalt nicht lesbar: {e}", "Content not readable: {e}"),
|
||||||
|
("ink-notes ist auf dem neuesten Stand (v{version}).", "ink-notes is up to date (v{version})."),
|
||||||
|
("ink-notes | [{notebook}] {page}{page_title} | [{status}] | {tool} | Hintergrund: {background} | [Ctrl+Z] Undo [Ctrl+Y] Redo [E] Radierer [Ctrl+E/S] PDF-Export", "ink-notes | [{notebook}] {page}{page_title} | [{status}] | {tool} | Background: {background} | [Ctrl+Z] Undo [Ctrl+Y] Redo [E] Eraser [Ctrl+E/S] PDF export"),
|
||||||
|
("Integritätsprüfung fehlgeschlagen für '{asset_name}': Erwartet {expected_hash}, berechnet {actual_hash}. Datei wurde gelöscht.", "Integrity check failed for '{asset_name}': expected {expected_hash}, computed {actual_hash}. The file was deleted."),
|
||||||
|
("Kariert (5mm)", "Grid (5mm)"),
|
||||||
|
("Kariert", "Grid"),
|
||||||
|
("KAROS, LINIEN UND PUNKTE", "GRID, LINES AND DOTS"),
|
||||||
|
("kein Asset-Ordner", "no asset folder"),
|
||||||
|
("Kein Eintrag für '{asset_name}' in SHA256SUMS.txt gefunden. Heruntergeladene Datei wurde gelöscht.", "No entry for '{asset_name}' found in SHA256SUMS.txt. The downloaded file was deleted."),
|
||||||
|
("Kein Release ausgewählt. Download abgelehnt.", "No release selected. Download refused."),
|
||||||
|
("Keine manifest.json vorhanden", "No manifest.json present"),
|
||||||
|
("Keine nutzbare Grafikschnittstelle gefunden.\nHäufigste Ursache: Der Benutzer darf nicht auf die Grafikkarte zugreifen (/dev/dri).\nPrüfen mit `ls -l /dev/dri` und `groups`; ggf. `sudo usermod -aG render,video $USER`\nund neu anmelden. Alternativ einen Software-Renderer installieren (Paket mesa-vulkan-drivers)\noder die Schnittstelle festlegen, z. B. `WGPU_BACKEND=vulkan ink-notes`.", "No usable graphics interface found.\nMost common cause: the user may not access the graphics card (/dev/dri).\nCheck with `ls -l /dev/dri` and `groups`; if needed `sudo usermod -aG render,video $USER`\nand log in again. Alternatively install a software renderer (package mesa-vulkan-drivers)\nor choose the interface, e.g. `WGPU_BACKEND=vulkan ink-notes`."),
|
||||||
|
("Keine Ordner oder Bilder (PNG, JPEG, GIF, WebP, BMP)", "No folders or images (PNG, JPEG, GIF, WebP, BMP)"),
|
||||||
|
("Keine Ordner oder PDF-Dateien", "No folders or PDF files"),
|
||||||
|
("Keine Sicherungskopie (manifest.json.bak) vorhanden", "No backup copy (manifest.json.bak) present"),
|
||||||
|
("Kleinere Schrift (jetzt {size} pt)", "Smaller font (now {size} pt)"),
|
||||||
|
("Klicke auf 'Nach Updates suchen', um die neuesten Releases vom Gitea-Server abzufragen.", "Click 'Check for updates' to query the latest releases from the Gitea server."),
|
||||||
|
("Konnte AppImage nicht atomar ersetzen: {e}. Altes AppImage bleibt unverändert.", "Could not replace the AppImage atomically: {e}. The old AppImage stays unchanged."),
|
||||||
|
("Konnte Backup ({path}) nicht anlegen: {e}. Update abgebrochen, altes AppImage unverändert.", "Could not create backup ({path}): {e}. Update cancelled, old AppImage unchanged."),
|
||||||
|
("Konnte Datei '{path}' zur Prüfsummenberechnung nicht öffnen: {e}", "Could not open file '{path}' to compute its checksum: {e}"),
|
||||||
|
("Konnte nach 100 Versuchen kein eindeutiges Notizbuch-Verzeichnis finden", "Could not find a unique notebook folder after 100 attempts"),
|
||||||
|
("Konnte temporäre Update-Datei nicht schreiben: {e}", "Could not write temporary update file: {e}"),
|
||||||
|
("Konnte Update-Cache-Verzeichnis nicht anlegen ({path}): {e}", "Could not create update cache folder ({path}): {e}"),
|
||||||
|
("Konnte xdg-open nicht ausführen: {e}", "Could not run xdg-open: {e}"),
|
||||||
|
("Konnte Zieldatei '{path}' nicht erstellen: {e}", "Could not create target file '{path}': {e}"),
|
||||||
|
("Konnte {name} nicht dekodieren: {e}.", "Could not decode {name}: {e}."),
|
||||||
|
("Konnte {name} nicht laden: {e}.", "Could not load {name}: {e}."),
|
||||||
|
("Konnte übergeordnetes Verzeichnis des AppImages nicht ermitteln.", "Could not determine the parent folder of the AppImage."),
|
||||||
|
("Koordinatensystem", "Coordinate system"),
|
||||||
|
("Kopieren (Strg+C)", "Copy (Ctrl+C)"),
|
||||||
|
("Korrektur-Rot", "Correction red"),
|
||||||
|
("Kreis", "Circle"),
|
||||||
|
("Kräftig", "Strong"),
|
||||||
|
("Lade '{name}' herunter...", "Downloading '{name}'..."),
|
||||||
|
("Leere Seite direkt nach der aktuellen Seite", "Blank page right after the current page"),
|
||||||
|
("Leichterer Druck zählt als kein Druck (dünnste Linie).\nHilft bei Stiften, die schon beim Schweben Druck melden.", "Lighter pressure counts as no pressure (thinnest line).\nHelps with pens that already report pressure while hovering."),
|
||||||
|
("Leuchtet grün, solange die Taste gedrückt ist", "Lights up green while the button is pressed"),
|
||||||
|
("Liegt bereits hier", "Already here"),
|
||||||
|
("Lineal (L): Fläche ziehen = verschieben, Griff ⟳ = drehen; Striche an einer Kante werden gerade", "Ruler (L): drag the surface = move, handle ⟳ = rotate; strokes along an edge become straight"),
|
||||||
|
("Liniert (7.5mm)", "Lined (7.5mm)"),
|
||||||
|
("Liniert", "Lined"),
|
||||||
|
("Links", "Left"),
|
||||||
|
("Löschen (Entf)", "Delete (Del)"),
|
||||||
|
("Löschen", "Delete"),
|
||||||
|
("Löscht die aktuelle Seite; danach im Menü wiederherstellbar", "Deletes the current page; can be restored from the menu afterwards"),
|
||||||
|
("Manifest aus Backup wiederhergestellt", "Manifest restored from backup"),
|
||||||
|
("Manifest: {msg}", "Manifest: {msg}"),
|
||||||
|
("Manifestdatei nicht gefunden: {path}", "Manifest file not found: {path}"),
|
||||||
|
("Mindestdruck", "Minimum pressure"),
|
||||||
|
("Mit dem Finger zeichnen", "Draw with finger"),
|
||||||
|
("Mittel", "Medium"),
|
||||||
|
("Name …", "Name …"),
|
||||||
|
("Neon-Gelb", "Neon yellow"),
|
||||||
|
("Netzwerk-Transportfehler: {t}", "Network transport error: {t}"),
|
||||||
|
("Neue Seite nach dieser einfügen", "Insert a new page after this one"),
|
||||||
|
("Neue Version verfügbar: {version}", "New version available: {version}"),
|
||||||
|
("Neuen Ordner hier anlegen (z. B. Semester oder Fach)", "Create a new folder here (e.g. semester or subject)"),
|
||||||
|
("Neues Notizbuch in diesem Ordner anlegen und öffnen", "Create a new notebook in this folder and open it"),
|
||||||
|
("Nichts", "Nothing"),
|
||||||
|
("Noch keine Seite hat einen Titel. Gib oben einen Titel für die aktuelle Seite ein.", "No page has a title yet. Enter a title for the current page above."),
|
||||||
|
("Normal", "Normal"),
|
||||||
|
("Normale Schrift", "Normal font"),
|
||||||
|
("Notfall-Export fehlgeschlagen: {err}", "Emergency export failed: {err}"),
|
||||||
|
("Notfall-Export", "Emergency export"),
|
||||||
|
("Notiz-Schwarz", "Note black"),
|
||||||
|
("Notizbuch '{path}' wird bereits von einer anderen Instanz verwendet", "Notebook '{path}' is already used by another instance"),
|
||||||
|
("Notizbuch '{title}' konnte nicht geladen werden – neues Notizbuch angelegt", "Notebook '{title}' could not be loaded – created a new notebook"),
|
||||||
|
("Notizbuch enthält keine Seiten", "Notebook has no pages"),
|
||||||
|
("Notizbuch in Papierkorb verschieben", "Move notebook to the trash"),
|
||||||
|
("Notizbuch ist gesperrt: {msg}", "Notebook is locked: {msg}"),
|
||||||
|
("Notizbuch wiederhergestellt", "Notebook restored"),
|
||||||
|
("Notizbuch wurde mit neuerer Version erstellt (Formatversion {found}, unterstützt wird bis {supported})", "Notebook was created with a newer version (format version {found}, supported up to {supported})"),
|
||||||
|
("Notizbuch", "Notebook"),
|
||||||
|
("Notizbücher verwalten (aktuell: {title})", "Manage notebooks (current: {title})"),
|
||||||
|
("Nur Bilder (PNG, JPEG, GIF, WebP, BMP) und PDFs können eingefügt werden", "Only images (PNG, JPEG, GIF, WebP, BMP) and PDFs can be inserted"),
|
||||||
|
("Nur ansehen – tippen, um wieder zu schreiben", "View only – tap to write again"),
|
||||||
|
("Nur ansehen – 👁 erneut tippen, um zu schreiben", "View only – tap 👁 again to write"),
|
||||||
|
("Nur ansehen: Stift, Finger und Maus verschieben nur das Blatt, nichts wird verändert", "View only: pen, finger and mouse just move the page, nothing gets changed"),
|
||||||
|
("Nur Textmarker radieren – Handschrift darunter bleibt", "Erase highlighter only – handwriting underneath stays"),
|
||||||
|
("Nächste Seite (Bild ab)", "Next page (Page Down)"),
|
||||||
|
("Oktaeder (3D-Kantenmodell)", "Octahedron (3D wireframe)"),
|
||||||
|
("Ordner löschen (die Notizbücher bleiben erhalten)", "Delete folder (the notebooks are kept)"),
|
||||||
|
("Ordner löschen", "Delete folder"),
|
||||||
|
("Ordner nicht gespeichert: {e}", "Folder not saved: {e}"),
|
||||||
|
("Ordner samt Inhalt in einen anderen Ordner verschieben", "Move folder with its contents to another folder"),
|
||||||
|
("Ordner umbenennen", "Rename folder"),
|
||||||
|
("Ordner „{name}“ angelegt", "Folder “{name}” created"),
|
||||||
|
("Ordner „{name}“ gelöscht, sein Inhalt liegt eine Ebene höher", "Folder “{name}” deleted, its contents moved up one level"),
|
||||||
|
("Ordner „{name}“ löschen? Seine Notizbücher und Unterordner rücken eine Ebene nach oben, gelöscht wird kein Notizbuch.", "Delete folder “{name}”? Its notebooks and subfolders move up one level, no notebook is deleted."),
|
||||||
|
("Ordner „{name}“ verschoben in {target}", "Folder “{name}” moved to {target}"),
|
||||||
|
("Ordner: {path}", "Folder: {path}"),
|
||||||
|
("Ordnernamen dürfen kein „/“ enthalten", "Folder names must not contain “/”"),
|
||||||
|
("PAPIERFARBE (NUR ANZEIGE)", "PAPER COLOR (DISPLAY ONLY)"),
|
||||||
|
("Papierkorb-Eintrag '{path}' existiert nicht", "Trash entry '{path}' does not exist"),
|
||||||
|
("Papierkorb-Pfad '{path}' liegt nicht im Papierkorb", "Trash path '{path}' is not in the trash"),
|
||||||
|
("Papierkorb-Verzeichnis existiert nicht", "Trash folder does not exist"),
|
||||||
|
("Pastell-Cyan", "Pastel cyan"),
|
||||||
|
("PDF importieren", "Import PDF"),
|
||||||
|
("PDF kann nicht geöffnet werden", "Cannot open PDF"),
|
||||||
|
("PDF nicht importiert: {err}", "PDF not imported: {err}"),
|
||||||
|
("PDF nicht lesbar: {e}", "PDF not readable: {e}"),
|
||||||
|
("PDF ohne Seite", "PDF without a page"),
|
||||||
|
("PDF-Export läuft…", "PDF export running…"),
|
||||||
|
("PDF-Render-Thread beendet", "PDF render thread stopped"),
|
||||||
|
("Personal Access Token (optional für private Repos):", "Personal access token (optional for private repos):"),
|
||||||
|
("Pfad '{path}' ist ein Symlink und darf nicht gelöscht werden", "Path '{path}' is a symlink and must not be deleted"),
|
||||||
|
("Pfad '{path}' liegt nicht direkt unter Basis-Verzeichnis '{base}'", "Path '{path}' is not directly inside the base folder '{base}'"),
|
||||||
|
("Pfad in Statusleiste anzeigen", "Show path in the status bar"),
|
||||||
|
("Pfeil", "Arrow"),
|
||||||
|
("Pixeldaten passen nicht zur Bildgröße", "Pixel data does not match the image size"),
|
||||||
|
("Platz schaffen", "Make space"),
|
||||||
|
("Platz schaffen: auf das Blatt tippen und nach unten ziehen – alles darunter rutscht mit, auch auf die folgenden Seiten; nach oben schließt leeren Platz", "Make space: tap the page and drag down – everything below moves along, also onto the following pages; dragging up closes empty space"),
|
||||||
|
("Polygon", "Polygon"),
|
||||||
|
("Prüfe Gitea-Releases...", "Checking Gitea releases..."),
|
||||||
|
("Punkte", "Dots"),
|
||||||
|
("Punktraster (5mm)", "Dot grid (5mm)"),
|
||||||
|
("Quell-PDF fehlt", "Source PDF missing"),
|
||||||
|
("Quell-PDF ist verschlüsselt", "Source PDF is encrypted"),
|
||||||
|
("Radieren", "Erase"),
|
||||||
|
("Radierer (E oder rechte Maustaste) – darunter: ganze Striche, Teilstrich oder nur Textmarker", "Eraser (E or right mouse button) – below: whole strokes, partial stroke or highlighter only"),
|
||||||
|
("Radierer (Eraser)", "Eraser"),
|
||||||
|
("Raute (Rhombus)", "Rhombus"),
|
||||||
|
("Rechteck", "Rectangle"),
|
||||||
|
("Rechts", "Right"),
|
||||||
|
("Release enthält keine {name}.", "Release contains no {name}."),
|
||||||
|
("Release- & Update-Center", "Release & update center"),
|
||||||
|
("Rosa", "Pink"),
|
||||||
|
("Rückgängig (Strg+Z)", "Undo (Ctrl+Z)"),
|
||||||
|
("Schließen (Esc)", "Close (Esc)"),
|
||||||
|
("Schriftgröße {size} pt", "Font size {size} pt"),
|
||||||
|
("Schwarz wird Weiß, Dunkelblau wird Hellblau. Gespeichert und als PDF exportiert werden immer die Originalfarben.", "Black becomes white, dark blue becomes light blue. Saving and PDF export always use the original colors."),
|
||||||
|
("Schwarz", "Black"),
|
||||||
|
("Sechseck (Hexagon)", "Hexagon"),
|
||||||
|
("Seite als", "Page as"),
|
||||||
|
("Seite für Seite blättern", "Flip page by page"),
|
||||||
|
("Seite ist schreibgeschützt", "Page is read-only"),
|
||||||
|
("Seite konnte nicht geladen werden", "Page could not be loaded"),
|
||||||
|
("Seite wird exportiert …", "Exporting page …"),
|
||||||
|
("Seite wählen", "Choose page"),
|
||||||
|
("Seite {id} ist nicht geladen – Export abgebrochen (vorher storage::load_all_pages aufrufen)", "Page {id} is not loaded – export cancelled (call storage::load_all_pages first)"),
|
||||||
|
("Seite {id} konnte nicht fehlerfrei geladen werden!", "Page {id} could not be loaded without errors!"),
|
||||||
|
("Seite {id} nicht gefunden", "Page {id} not found"),
|
||||||
|
("Seite {id}: {msg}", "Page {id}: {msg}"),
|
||||||
|
("Seite {number} / {count}", "Page {number} / {count}"),
|
||||||
|
("Seite {number} eingefügt", "Page {number} inserted"),
|
||||||
|
("Seite {number} fehlt im PDF", "Page {number} missing in the PDF"),
|
||||||
|
("Seite {number} fehlt im Quell-PDF", "Page {number} missing in the source PDF"),
|
||||||
|
("Seite {number} gelöscht – im Menü ☰ wiederherstellbar", "Page {number} deleted – can be restored from the ☰ menu"),
|
||||||
|
("Seite {number} mit allem Inhalt löschen?", "Delete page {number} with all its content?"),
|
||||||
|
("Seite {number} wiederhergestellt", "Page {number} restored"),
|
||||||
|
("Seite {number} – {title}", "Page {number} – {title}"),
|
||||||
|
("Seite {number}", "Page {number}"),
|
||||||
|
("Seiten ({count})", "Pages ({count})"),
|
||||||
|
("SEITEN DIESES NOTIZBUCHS", "PAGES OF THIS NOTEBOOK"),
|
||||||
|
("Seiten hängen untereinander, Mausrad und Finger scrollen (Strg+Mausrad zoomt); wer unten auf der letzten Seite schreibt, bekommt automatisch eine neue Seite.", "Pages are stacked, mouse wheel and finger scroll (Ctrl+wheel zooms); writing at the bottom of the last page adds a new page automatically."),
|
||||||
|
("Seiten:", "Pages:"),
|
||||||
|
("Seitenverhältnis frei – tippen zum Sperren", "Aspect ratio free – tap to lock"),
|
||||||
|
("Seitenverhältnis gesperrt – tippen zum Freigeben", "Aspect ratio locked – tap to unlock"),
|
||||||
|
("Serialisierungsfehler: {e}", "Serialization error: {e}"),
|
||||||
|
("Server-Einstellungen gespeichert", "Server settings saved"),
|
||||||
|
("Server:", "Server:"),
|
||||||
|
("Signaturprüfung von {file} fehlgeschlagen: {e}.", "Signature check of {file} failed: {e}."),
|
||||||
|
("Speicherfehler!", "Save error!"),
|
||||||
|
("Speicherfehler: {messages}", "Save error: {messages}"),
|
||||||
|
("Speichert …", "Saving …"),
|
||||||
|
("Speichert...", "Saving..."),
|
||||||
|
("Sprache der Oberfläche", "Interface language"),
|
||||||
|
("Standard-Notizbuch erstellt", "Default notebook created"),
|
||||||
|
("Standard-Notizbuch", "Default notebook"),
|
||||||
|
("STATUS", "STATUS"),
|
||||||
|
("Stift (B/U/R für Farben) – erneut tippen für Farbe & Stärke", "Pen (B/U/R for colors) – tap again for color & width"),
|
||||||
|
("Stift (Pen)", "Pen"),
|
||||||
|
("Stift {number} ({width} mm) – erneut tippen für Farbe & Stärke; Änderungen merkt sich der Stift", "Pen {number} ({width} mm) – tap again for color & width; the pen remembers changes"),
|
||||||
|
("Stift {number} ({width} mm)", "Pen {number} ({width} mm)"),
|
||||||
|
("Stift {number}", "Pen {number}"),
|
||||||
|
("Stift", "Pen"),
|
||||||
|
("STUFENLOSE STÄRKE", "STEPLESS WIDTH"),
|
||||||
|
("Stärke auf {width} setzen", "Set width to {width}"),
|
||||||
|
("System", "System"),
|
||||||
|
("System-Paket (.deb)", "System package (.deb)"),
|
||||||
|
("Tafel-Grün", "Chalkboard green"),
|
||||||
|
("Taste {number}", "Button {number}"),
|
||||||
|
("Tasten am Stift", "Pen buttons"),
|
||||||
|
("Teilstrich radieren – nur den überstrichenen Teil entfernen (Formen ganz)", "Erase partial stroke – remove only the part you wipe over (shapes completely)"),
|
||||||
|
("Text (T)", "Text (T)"),
|
||||||
|
("Text (T): ins Blatt tippen und schreiben, vorhandenen Text antippen zum Ändern; Esc beendet", "Text (T): tap the page and write, tap existing text to edit it; Esc finishes"),
|
||||||
|
("Text eingefügt – mit dem Text-Werkzeug (T) änderbar", "Text pasted – editable with the text tool (T)"),
|
||||||
|
("Textfarbe {number}", "Text color {number}"),
|
||||||
|
("Textmarker (Highlighter)", "Highlighter"),
|
||||||
|
("Textmarker – erneut tippen für Farbe & Stärke", "Highlighter – tap again for color & width"),
|
||||||
|
("Textmarker – Farbe {number}", "Highlighter – color {number}"),
|
||||||
|
("Textmarker", "Highlighter"),
|
||||||
|
("Tipp: Screenshots mit Strg+V einfügen oder Bilddateien ins Fenster ziehen.", "Tip: paste screenshots with Ctrl+V or drag image files into the window."),
|
||||||
|
("Titel umbenennen", "Rename title"),
|
||||||
|
("TITEL VON SEITE {number}", "TITLE OF PAGE {number}"),
|
||||||
|
("Trotzdem beenden", "Quit anyway"),
|
||||||
|
("Trotzdem beenden?", "Quit anyway?"),
|
||||||
|
("Um 90° drehen (R)", "Rotate by 90° (R)"),
|
||||||
|
("Um Datenverlust zu verhindern, ist diese Seite schreibgeschützt.\nWenn Sie diese Seite bearbeiten möchten, können Sie den Schreibschutz aufheben.", "To prevent data loss, this page is read-only.\nIf you want to edit this page, you can remove the write protection."),
|
||||||
|
("Umbenannt in '{title}'", "Renamed to '{title}'"),
|
||||||
|
("Ungespeichert", "Unsaved"),
|
||||||
|
("Ungespeicherte Änderungen konnten nicht gesichert werden:", "Unsaved changes could not be saved:"),
|
||||||
|
("Ungespeicherte Änderungen", "Unsaved changes"),
|
||||||
|
("Ungültige Server-URL '{url}': {e}", "Invalid server URL '{url}': {e}"),
|
||||||
|
("Ungültige URL '{initial_url_str}': {e}", "Invalid URL '{initial_url_str}': {e}"),
|
||||||
|
("Ungültiger AppImage-Dateiname.", "Invalid AppImage file name."),
|
||||||
|
("Ungültiger Asset-Name (enthält unzulässige Pfadkomponenten): '{raw_name}'", "Invalid asset name (contains forbidden path components): '{raw_name}'"),
|
||||||
|
("Ungültiger Bildverweis '{name}'", "Invalid image reference '{name}'"),
|
||||||
|
("Ungültiger Dateiname: '{raw_name}'", "Invalid file name: '{raw_name}'"),
|
||||||
|
("Ungültiger oder versteckter Asset-Name: '{raw_name}'", "Invalid or hidden asset name: '{raw_name}'"),
|
||||||
|
("Ungültiger PDF-Verweis '{key}'", "Invalid PDF reference '{key}'"),
|
||||||
|
("Ungültiger Pfad (Path Traversal): {msg}", "Invalid path (path traversal): {msg}"),
|
||||||
|
("Ungültiger Update-Signaturschlüssel: {e}.", "Invalid update signing key: {e}."),
|
||||||
|
("Ungültiges Manifest: {msg}", "Invalid manifest: {msg}"),
|
||||||
|
("Ungültiges Weiterleitungsziel '{loc}': {e}", "Invalid redirect target '{loc}': {e}"),
|
||||||
|
("Universitäts-Blau", "University blue"),
|
||||||
|
("Unsicheres Protokoll '{scheme}' abgewiesen. Es wird zwingend HTTPS verlangt (z. B. https://gitea.pansi.eu).", "Insecure protocol '{scheme}' rejected. HTTPS is required (e.g. https://gitea.pansi.eu)."),
|
||||||
|
("Unsicheres Protokoll '{scheme}' für '{url}' abgewiesen. Es wird zwingend HTTPS verlangt.", "Insecure protocol '{scheme}' for '{url}' rejected. HTTPS is required."),
|
||||||
|
("Update gestartet / geöffnet", "Update started / opened"),
|
||||||
|
("Update-Fehler: {err}", "Update error: {err}"),
|
||||||
|
("Vektorgrafik, z. B. für Inkscape oder LaTeX", "Vector graphics, e.g. for Inkscape or LaTeX"),
|
||||||
|
("VERFÜGBARE ARTEFAKTE:", "AVAILABLE ARTIFACTS:"),
|
||||||
|
("Vergessen (erscheint beim nächsten Drücken wieder, dann mit Radieren)", "Forget (appears again on the next press, then erasing)"),
|
||||||
|
("Verschoben in {target}", "Moved to {target}"),
|
||||||
|
("Verzeichnis '{path}' enthält kein manifest.json", "Folder '{path}' contains no manifest.json"),
|
||||||
|
("Verzeichnis '{path}' existiert nicht", "Folder '{path}' does not exist"),
|
||||||
|
("Vorherige Seite (Bild auf)", "Previous page (Page Up)"),
|
||||||
|
("Vorlesungsfolien, Übungsblätter oder Formulare als neues Notizbuch öffnen und darauf schreiben", "Open lecture slides, worksheets or forms as a new notebook and write on them"),
|
||||||
|
("weich", "soft"),
|
||||||
|
("Weich: schon leichter Druck ergibt kräftige Linien.\nHart: erst fester Druck ergibt kräftige Linien.", "Soft: even light pressure gives bold lines.\nHard: only firm pressure gives bold lines."),
|
||||||
|
("Weitere Funktionen – Update verfügbar", "More – update available"),
|
||||||
|
("Weitere Funktionen", "More"),
|
||||||
|
("Weitere Funktionen: PDF, Hintergrund, Zoom, Einstellungen", "More: PDF, background, zoom, settings"),
|
||||||
|
("Weiß", "White"),
|
||||||
|
("WERKZEUGLEISTE", "TOOLBAR"),
|
||||||
|
("Wiederherstellung fehlgeschlagen: {err}", "Restore failed: {err}"),
|
||||||
|
("Wiederholen (Strg+Y)", "Redo (Ctrl+Y)"),
|
||||||
|
("Wiederholen", "Retry"),
|
||||||
|
("Worker panic beim Speichern der Seite", "Worker panic while saving the page"),
|
||||||
|
("Worker panic beim Speichern des Manifests", "Worker panic while saving the manifest"),
|
||||||
|
("z. B. Kapitel 2 – Integrale", "e.g. Chapter 2 – Integrals"),
|
||||||
|
("Zielseite fehlt", "Target page missing"),
|
||||||
|
("ZOOM", "ZOOM"),
|
||||||
|
("Zu viele Weiterleitungen (Redirect-Schleife abgebrochen).", "Too many redirects (redirect loop stopped)."),
|
||||||
|
("Zugriffsfehler (I/O). Die Datei existiert, kann aber nicht gelesen werden.\nDie Seite bleibt schreibgeschützt, um ein Überschreiben zu verhindern.", "Access error (I/O). The file exists but cannot be read.\nThe page stays read-only to prevent overwriting it."),
|
||||||
|
("Zurück zu Seiten geht nur, solange alles im Startausschnitt liegt", "Back to pages only works while everything lies in the starting area"),
|
||||||
|
("Zurücksetzen (Strg+0)", "Reset (Ctrl+0)"),
|
||||||
|
("{count} Objekt(e) eingefügt", "{count} object(s) pasted"),
|
||||||
|
("{count} Objekt(e) gelöscht", "{count} object(s) deleted"),
|
||||||
|
("{count} Objekt(e) kopiert – auch als Bild für andere Programme", "{count} object(s) copied – also as an image for other apps"),
|
||||||
|
("{count} Objekt(e) kopiert", "{count} object(s) copied"),
|
||||||
|
("{count} Objekte | [R] Drehen [Entf] Löschen", "{count} objects | [R] Rotate [Del] Delete"),
|
||||||
|
("{count} Seite(n)", "{count} page(s)"),
|
||||||
|
("{e} Download abgelehnt.", "{e} Download refused."),
|
||||||
|
("{file} ist ungültig: {e}.", "{file} is invalid: {e}."),
|
||||||
|
("{mm} mm Platz geschaffen (Rückgängig mit Strg+Z)", "{mm} mm of space made (undo with Ctrl+Z)"),
|
||||||
|
("{mm} mm Platz geschlossen (Rückgängig mit Strg+Z)", "{mm} mm of space closed (undo with Ctrl+Z)"),
|
||||||
|
("{n} Notizbücher", "{n} notebooks"),
|
||||||
|
("{shape_name} ausgerichtet! (Undo mit Strg+Z)", "{shape_name} straightened! (undo with Ctrl+Z)"),
|
||||||
|
("{shape} eingerastet!", "{shape} snapped!"),
|
||||||
|
("{title}_Seite_{number}{suffix}", "{title}_page_{number}{suffix}"),
|
||||||
|
("Änderungen:", "Changes:"),
|
||||||
|
("Übergeordneter Ordner", "Parent folder"),
|
||||||
|
("Übergeordnetes Verzeichnis nicht gefunden", "Parent folder not found"),
|
||||||
|
("„{title}“ verschieben nach:", "Move “{title}” to:"),
|
||||||
|
("↩ Rückgängig", "↩ Undo"),
|
||||||
|
("⏳ Update lädt … {percent} %", "⏳ Downloading update … {percent} %"),
|
||||||
|
("⏷ {mm} mm Platz", "⏷ {mm} mm space"),
|
||||||
|
("♾ Endlos", "♾ Endless"),
|
||||||
|
("⚙ Erweiterte Server-Einstellungen", "⚙ Advanced server settings"),
|
||||||
|
("⚠ Beschädigt", "⚠ Damaged"),
|
||||||
|
("⚠ Datenintegritäts-Warnung", "⚠ Data integrity warning"),
|
||||||
|
("⚠ In anderer Instanz geöffnet (Schreibschutz)", "⚠ Opened in another instance (read-only)"),
|
||||||
|
("⚠ Ungespeicherte Änderungen", "⚠ Unsaved changes"),
|
||||||
|
("⚠\u{fe0f} {name} (Beschädigt - kein Manifest)", "⚠\u{fe0f} {name} (damaged - no manifest)"),
|
||||||
|
("⚠\u{fe0f} {name} (Beschädigt)", "⚠\u{fe0f} {name} (damaged)"),
|
||||||
|
("⚫ Aktiv", "⚫ Active"),
|
||||||
|
("✔ Update bereit", "✔ Update ready"),
|
||||||
|
("➕ Neue Seite einfügen", "➕ Insert new page"),
|
||||||
|
("➕ Notizbuch", "➕ Notebook"),
|
||||||
|
("⟲ Gelöschte Seite {number} wiederherstellen", "⟲ Restore deleted page {number}"),
|
||||||
|
("⬇ Downloads", "⬇ Downloads"),
|
||||||
|
("🌐 Release auf Gitea öffnen", "🌐 Open release on Gitea"),
|
||||||
|
("🏠 Persönlicher Ordner", "🏠 Home folder"),
|
||||||
|
("💾 Einstellungen speichern", "💾 Save settings"),
|
||||||
|
("📁 Ordner", "📁 Folder"),
|
||||||
|
("📂 Im Dateimanager anzeigen", "📂 Show in file manager"),
|
||||||
|
("📂 Ordner öffnen", "📂 Open folder"),
|
||||||
|
("📄 Als PDF exportieren (Strg+E)", "📄 Export as PDF (Ctrl+E)"),
|
||||||
|
("📄 PDF importieren …", "📄 Import PDF …"),
|
||||||
|
("📄 Feste Seiten", "📄 Fixed pages"),
|
||||||
|
("📄 PDF importieren", "📄 Import PDF"),
|
||||||
|
("📋 Einfügen", "📋 Paste"),
|
||||||
|
("📑 Inhalt", "📑 Contents"),
|
||||||
|
("📚 Alle", "📚 All"),
|
||||||
|
("📚 Notizbücher", "📚 Notebooks"),
|
||||||
|
("📚 Oberste Ebene", "📚 Top level"),
|
||||||
|
("📜 Durchgehend", "📜 Continuous"),
|
||||||
|
("📦 Paket mit Software-Center öffnen / installieren", "📦 Open / install package with the software center"),
|
||||||
|
("🔄 Suche nach Updates …", "🔄 Checking for updates …"),
|
||||||
|
("🔄 Updates & Versionen", "🔄 Updates & versions"),
|
||||||
|
("🔄 Backup", "🔄 Backup"),
|
||||||
|
("🔄 Nach Updates suchen", "🔄 Check for updates"),
|
||||||
|
("🖥 Schreibtisch", "🖥 Desktop"),
|
||||||
|
("🖼 Bild aus Datei …", "🖼 Image from file …"),
|
||||||
|
("🖼 Bild einfügen … (Strg+I)", "🖼 Insert image … (Ctrl+I)"),
|
||||||
|
("🖼 Kacheln", "🖼 Tiles"),
|
||||||
|
("🖼 Bild einfügen", "🖼 Insert image"),
|
||||||
|
("🖼 Bilder", "🖼 Pictures"),
|
||||||
|
("🗑 Seite {number} löschen …", "🗑 Delete page {number} …"),
|
||||||
|
("🚀 Update {version} verfügbar", "🚀 Update {version} available"),
|
||||||
|
("🚀 AppImage aktualisieren & ausführen", "🚀 Update AppImage & restart"),
|
||||||
|
("🚀 Updates & Versionen", "🚀 Updates & versions"),
|
||||||
|
];
|
||||||
+94
-27
@@ -45,26 +45,57 @@ pub fn quad_vertices(corners: &[glam::Vec2; 4]) -> [ImageVertex; 6] {
|
|||||||
[tl, tr, bl, bl, tr, br]
|
[tl, tr, bl, bl, tr, br]
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Mipmap-Stufen eines Bildes, jeweils halbe Kantenlänge bis 1 × 1.
|
/// Mipmap-Stufen eines Bildes, jeweils halbe Kantenlänge bis 1 × 1. Für eine gerenderte
|
||||||
pub fn mip_chain(base: &RgbaImage) -> Vec<RgbaImage> {
|
/// PDF-Seite dauert das spürbar (2560 px: einige 10 ms); deshalb erzeugt sie der
|
||||||
let mut levels = vec![base.clone()];
|
/// PDF-Render-Thread und nicht der Haupt-Thread.
|
||||||
let Some(mut current) =
|
pub fn mip_chain(base: RgbaImage) -> Vec<RgbaImage> {
|
||||||
image::RgbaImage::from_raw(base.width, base.height, base.pixels.clone())
|
let mut levels = vec![base];
|
||||||
else {
|
loop {
|
||||||
return levels;
|
let current = &levels[levels.len() - 1];
|
||||||
};
|
if current.width <= 1 && current.height <= 1 {
|
||||||
while current.width() > 1 || current.height() > 1 {
|
break;
|
||||||
let (w, h) = ((current.width() / 2).max(1), (current.height() / 2).max(1));
|
}
|
||||||
current = image::imageops::resize(¤t, w, h, image::imageops::FilterType::Triangle);
|
let next = half_size(current);
|
||||||
levels.push(RgbaImage {
|
levels.push(next);
|
||||||
width: w,
|
|
||||||
height: h,
|
|
||||||
pixels: current.as_raw().clone(),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
levels
|
levels
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Halbiert ein Bild: Mittelwert aus je 2 × 2 Pixeln (bei ungerader Kante entfällt die
|
||||||
|
/// letzte Spalte bzw. Zeile, bei Kantenlänge 1 wird nur in der anderen Richtung gemittelt).
|
||||||
|
fn half_size(image: &RgbaImage) -> RgbaImage {
|
||||||
|
let (w, h) = (image.width as usize, image.height as usize);
|
||||||
|
let (nw, nh) = ((w / 2).max(1), (h / 2).max(1));
|
||||||
|
let mut pixels = vec![0u8; nw * nh * 4];
|
||||||
|
if image.pixels.len() < w * h * 4 {
|
||||||
|
return RgbaImage {
|
||||||
|
width: nw as u32,
|
||||||
|
height: nh as u32,
|
||||||
|
pixels,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
for y in 0..nh {
|
||||||
|
let (y0, y1) = ((2 * y).min(h - 1), (2 * y + 1).min(h - 1));
|
||||||
|
let (row0, row1) = (&image.pixels[y0 * w * 4..], &image.pixels[y1 * w * 4..]);
|
||||||
|
let out = &mut pixels[y * nw * 4..(y + 1) * nw * 4];
|
||||||
|
for x in 0..nw {
|
||||||
|
let (x0, x1) = ((2 * x).min(w - 1) * 4, (2 * x + 1).min(w - 1) * 4);
|
||||||
|
for c in 0..4 {
|
||||||
|
let sum = row0[x0 + c] as u16
|
||||||
|
+ row0[x1 + c] as u16
|
||||||
|
+ row1[x0 + c] as u16
|
||||||
|
+ row1[x1 + c] as u16;
|
||||||
|
out[x * 4 + c] = ((sum + 2) / 4) as u8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RgbaImage {
|
||||||
|
width: nw as u32,
|
||||||
|
height: nh as u32,
|
||||||
|
pixels,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Name der Ersatztextur für Bilder, deren Datei fehlt oder beschädigt ist.
|
/// Name der Ersatztextur für Bilder, deren Datei fehlt oder beschädigt ist.
|
||||||
const MISSING: &str = "";
|
const MISSING: &str = "";
|
||||||
/// Bis zu dieser Grafikspeichermenge bleiben Texturen anderer Seiten erhalten (schnelles
|
/// Bis zu dieser Grafikspeichermenge bleiben Texturen anderer Seiten erhalten (schnelles
|
||||||
@@ -74,6 +105,8 @@ const TEXTURE_CACHE_BYTES: u64 = 384 * 1024 * 1024;
|
|||||||
/// Antwort einer Texturquelle für einen Schlüssel.
|
/// Antwort einer Texturquelle für einen Schlüssel.
|
||||||
pub enum TextureSource {
|
pub enum TextureSource {
|
||||||
Ready(RgbaImage),
|
Ready(RgbaImage),
|
||||||
|
/// Fertige Mipmap-Stufen (siehe [`mip_chain`]), z. B. vom PDF-Render-Thread
|
||||||
|
ReadyMips(Vec<RgbaImage>),
|
||||||
/// Wird gerade erzeugt; später erneut fragen
|
/// Wird gerade erzeugt; später erneut fragen
|
||||||
Pending,
|
Pending,
|
||||||
Failed(String),
|
Failed(String),
|
||||||
@@ -233,10 +266,16 @@ impl ImageLayer {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let (bind_group, bytes) = match load(&key) {
|
let (bind_group, bytes) = match load(&key) {
|
||||||
TextureSource::Ready(image) => (
|
TextureSource::Ready(image) => {
|
||||||
self.upload_texture(device, queue, &key, &image),
|
self.upload_texture(device, queue, &key, mip_chain(image))
|
||||||
image.pixels.len() as u64 * 4 / 3,
|
}
|
||||||
),
|
TextureSource::ReadyMips(levels) if !levels.is_empty() => {
|
||||||
|
self.upload_texture(device, queue, &key, levels)
|
||||||
|
}
|
||||||
|
TextureSource::ReadyMips(_) => {
|
||||||
|
eprintln!("[Bilder] '{key}' kann nicht angezeigt werden: leeres Bild");
|
||||||
|
(self.missing_texture(device, queue), 4)
|
||||||
|
}
|
||||||
// Noch in Arbeit (PDF-Seite wird gerendert): beim nächsten Bild erneut fragen
|
// Noch in Arbeit (PDF-Seite wird gerendert): beim nächsten Bild erneut fragen
|
||||||
TextureSource::Pending => continue,
|
TextureSource::Pending => continue,
|
||||||
TextureSource::Failed(err) => {
|
TextureSource::Failed(err) => {
|
||||||
@@ -342,17 +381,19 @@ impl ImageLayer {
|
|||||||
height: 1,
|
height: 1,
|
||||||
pixels: vec![200, 200, 200, 255],
|
pixels: vec![200, 200, 200, 255],
|
||||||
};
|
};
|
||||||
self.upload_texture(device, queue, MISSING, &gray)
|
self.upload_texture(device, queue, MISSING, vec![gray]).0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Lädt die Mipmap-Stufen hoch (Stufe 0 = volle Größe); liefert die Bind Group und den
|
||||||
|
/// belegten Grafikspeicher.
|
||||||
fn upload_texture(
|
fn upload_texture(
|
||||||
&self,
|
&self,
|
||||||
device: &wgpu::Device,
|
device: &wgpu::Device,
|
||||||
queue: &wgpu::Queue,
|
queue: &wgpu::Queue,
|
||||||
label: &str,
|
label: &str,
|
||||||
image: &RgbaImage,
|
levels: Vec<RgbaImage>,
|
||||||
) -> wgpu::BindGroup {
|
) -> (wgpu::BindGroup, u64) {
|
||||||
let levels = mip_chain(image);
|
let image = &levels[0];
|
||||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||||
label: Some(label),
|
label: Some(label),
|
||||||
size: wgpu::Extent3d {
|
size: wgpu::Extent3d {
|
||||||
@@ -389,8 +430,9 @@ impl ImageLayer {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
let bytes = levels.iter().map(|l| l.pixels.len() as u64).sum();
|
||||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||||
label: Some("Image Texture Bind Group"),
|
label: Some("Image Texture Bind Group"),
|
||||||
layout: &self.texture_layout,
|
layout: &self.texture_layout,
|
||||||
entries: &[
|
entries: &[
|
||||||
@@ -403,7 +445,8 @@ impl ImageLayer {
|
|||||||
resource: wgpu::BindingResource::Sampler(&self.sampler),
|
resource: wgpu::BindingResource::Sampler(&self.sampler),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
})
|
});
|
||||||
|
(bind_group, bytes)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -439,11 +482,35 @@ mod tests {
|
|||||||
height: 3,
|
height: 3,
|
||||||
pixels: vec![128; 8 * 3 * 4],
|
pixels: vec![128; 8 * 3 * 4],
|
||||||
};
|
};
|
||||||
let levels = mip_chain(&base);
|
let levels = mip_chain(base);
|
||||||
let sizes: Vec<(u32, u32)> = levels.iter().map(|l| (l.width, l.height)).collect();
|
let sizes: Vec<(u32, u32)> = levels.iter().map(|l| (l.width, l.height)).collect();
|
||||||
assert_eq!(sizes, vec![(8, 3), (4, 1), (2, 1), (1, 1)]);
|
assert_eq!(sizes, vec![(8, 3), (4, 1), (2, 1), (1, 1)]);
|
||||||
for l in &levels {
|
for l in &levels {
|
||||||
assert_eq!(l.pixels.len(), (l.width * l.height * 4) as usize);
|
assert_eq!(l.pixels.len(), (l.width * l.height * 4) as usize);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_half_size_averages_two_by_two_blocks() {
|
||||||
|
// 3 × 2: links schwarz/weiß übereinander, Mitte grau; die dritte Spalte entfällt
|
||||||
|
let px = |v: u8| [v, v, v, 255];
|
||||||
|
let pixels = [px(0), px(100), px(7), px(255), px(100), px(7)].concat();
|
||||||
|
let base = RgbaImage {
|
||||||
|
width: 3,
|
||||||
|
height: 2,
|
||||||
|
pixels,
|
||||||
|
};
|
||||||
|
let half = half_size(&base);
|
||||||
|
assert_eq!((half.width, half.height), (1, 1));
|
||||||
|
// (0 + 100 + 255 + 100) / 4 = 113,75 → 114
|
||||||
|
assert_eq!(half.pixels, vec![114, 114, 114, 255]);
|
||||||
|
|
||||||
|
// Kantenlänge 1: nur in der anderen Richtung mitteln
|
||||||
|
let column = RgbaImage {
|
||||||
|
width: 1,
|
||||||
|
height: 2,
|
||||||
|
pixels: [px(10), px(20)].concat(),
|
||||||
|
};
|
||||||
|
assert_eq!(half_size(&column).pixels, vec![15, 15, 15, 255]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -10,8 +10,10 @@ pub mod file_picker;
|
|||||||
pub mod filter;
|
pub mod filter;
|
||||||
pub mod geometry;
|
pub mod geometry;
|
||||||
pub mod history;
|
pub mod history;
|
||||||
|
pub mod i18n;
|
||||||
pub mod image_layer;
|
pub mod image_layer;
|
||||||
pub mod library;
|
pub mod library;
|
||||||
|
pub mod osk;
|
||||||
pub mod page_export;
|
pub mod page_export;
|
||||||
pub mod pdf_doc;
|
pub mod pdf_doc;
|
||||||
pub mod pdf_merge;
|
pub mod pdf_merge;
|
||||||
|
|||||||
+21
-13
@@ -14,6 +14,7 @@ use std::path::{Path, PathBuf};
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::storage::{self, StorageError};
|
use crate::storage::{self, StorageError};
|
||||||
|
use crate::t;
|
||||||
|
|
||||||
/// Oberste Ebene.
|
/// Oberste Ebene.
|
||||||
pub const ROOT: &str = "";
|
pub const ROOT: &str = "";
|
||||||
@@ -62,14 +63,15 @@ fn is_within(path: &str, folder: &str) -> bool {
|
|||||||
pub fn validate_name(name: &str) -> Result<String, String> {
|
pub fn validate_name(name: &str) -> Result<String, String> {
|
||||||
let name = name.trim();
|
let name = name.trim();
|
||||||
if name.is_empty() {
|
if name.is_empty() {
|
||||||
return Err("Der Ordnername ist leer".to_string());
|
return Err(t!("Der Ordnername ist leer").to_string());
|
||||||
}
|
}
|
||||||
if name.contains('/') {
|
if name.contains('/') {
|
||||||
return Err("Ordnernamen dürfen kein „/“ enthalten".to_string());
|
return Err(t!("Ordnernamen dürfen kein „/“ enthalten").to_string());
|
||||||
}
|
}
|
||||||
if name.chars().count() > MAX_NAME_CHARS {
|
if name.chars().count() > MAX_NAME_CHARS {
|
||||||
return Err(format!(
|
return Err(t!(
|
||||||
"Der Ordnername ist zu lang (höchstens {MAX_NAME_CHARS} Zeichen)"
|
"Der Ordnername ist zu lang (höchstens {max} Zeichen)",
|
||||||
|
max = MAX_NAME_CHARS
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
Ok(name.to_string())
|
Ok(name.to_string())
|
||||||
@@ -161,11 +163,11 @@ impl Library {
|
|||||||
pub fn create_folder(&mut self, parent: &str, name: &str) -> Result<String, String> {
|
pub fn create_folder(&mut self, parent: &str, name: &str) -> Result<String, String> {
|
||||||
let name = validate_name(name)?;
|
let name = validate_name(name)?;
|
||||||
if !parent.is_empty() && !self.folders.contains(parent) {
|
if !parent.is_empty() && !self.folders.contains(parent) {
|
||||||
return Err("Der übergeordnete Ordner existiert nicht mehr".to_string());
|
return Err(t!("Der übergeordnete Ordner existiert nicht mehr").to_string());
|
||||||
}
|
}
|
||||||
let path = join(parent, &name);
|
let path = join(parent, &name);
|
||||||
if !self.folders.insert(path.clone()) {
|
if !self.folders.insert(path.clone()) {
|
||||||
return Err(format!("Den Ordner „{name}“ gibt es hier schon"));
|
return Err(t!("Den Ordner „{name}“ gibt es hier schon", name = name));
|
||||||
}
|
}
|
||||||
Ok(path)
|
Ok(path)
|
||||||
}
|
}
|
||||||
@@ -175,14 +177,17 @@ impl Library {
|
|||||||
pub fn rename_folder(&mut self, path: &str, new_name: &str) -> Result<String, String> {
|
pub fn rename_folder(&mut self, path: &str, new_name: &str) -> Result<String, String> {
|
||||||
let new_name = validate_name(new_name)?;
|
let new_name = validate_name(new_name)?;
|
||||||
if !self.folders.contains(path) {
|
if !self.folders.contains(path) {
|
||||||
return Err("Den Ordner gibt es nicht mehr".to_string());
|
return Err(t!("Den Ordner gibt es nicht mehr").to_string());
|
||||||
}
|
}
|
||||||
let new_path = join(parent_folder(path), &new_name);
|
let new_path = join(parent_folder(path), &new_name);
|
||||||
if new_path == path {
|
if new_path == path {
|
||||||
return Ok(new_path);
|
return Ok(new_path);
|
||||||
}
|
}
|
||||||
if self.folders.contains(&new_path) {
|
if self.folders.contains(&new_path) {
|
||||||
return Err(format!("Den Ordner „{new_name}“ gibt es hier schon"));
|
return Err(t!(
|
||||||
|
"Den Ordner „{name}“ gibt es hier schon",
|
||||||
|
name = new_name
|
||||||
|
));
|
||||||
}
|
}
|
||||||
self.move_contents(path, &new_path);
|
self.move_contents(path, &new_path);
|
||||||
Ok(new_path)
|
Ok(new_path)
|
||||||
@@ -240,13 +245,13 @@ impl Library {
|
|||||||
/// gibt seinen neuen Pfad zurück. Nicht in sich selbst oder einen eigenen Unterordner.
|
/// gibt seinen neuen Pfad zurück. Nicht in sich selbst oder einen eigenen Unterordner.
|
||||||
pub fn move_folder(&mut self, path: &str, new_parent: &str) -> Result<String, String> {
|
pub fn move_folder(&mut self, path: &str, new_parent: &str) -> Result<String, String> {
|
||||||
if !self.folders.contains(path) {
|
if !self.folders.contains(path) {
|
||||||
return Err("Den Ordner gibt es nicht mehr".to_string());
|
return Err(t!("Den Ordner gibt es nicht mehr").to_string());
|
||||||
}
|
}
|
||||||
if !new_parent.is_empty() && !self.folders.contains(new_parent) {
|
if !new_parent.is_empty() && !self.folders.contains(new_parent) {
|
||||||
return Err("Den Zielordner gibt es nicht mehr".to_string());
|
return Err(t!("Den Zielordner gibt es nicht mehr").to_string());
|
||||||
}
|
}
|
||||||
if is_within(new_parent, path) {
|
if is_within(new_parent, path) {
|
||||||
return Err("Ein Ordner kann nicht in sich selbst verschoben werden".to_string());
|
return Err(t!("Ein Ordner kann nicht in sich selbst verschoben werden").to_string());
|
||||||
}
|
}
|
||||||
let name = folder_name(path);
|
let name = folder_name(path);
|
||||||
let new_path = join(new_parent, name);
|
let new_path = join(new_parent, name);
|
||||||
@@ -254,7 +259,10 @@ impl Library {
|
|||||||
return Ok(new_path);
|
return Ok(new_path);
|
||||||
}
|
}
|
||||||
if self.folders.contains(&new_path) {
|
if self.folders.contains(&new_path) {
|
||||||
return Err(format!("Im Zielordner gibt es schon einen Ordner „{name}“"));
|
return Err(t!(
|
||||||
|
"Im Zielordner gibt es schon einen Ordner „{name}“",
|
||||||
|
name = name
|
||||||
|
));
|
||||||
}
|
}
|
||||||
self.move_contents(path, &new_path);
|
self.move_contents(path, &new_path);
|
||||||
Ok(new_path)
|
Ok(new_path)
|
||||||
@@ -276,7 +284,7 @@ impl Library {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
if !self.folders.contains(folder) {
|
if !self.folders.contains(folder) {
|
||||||
return Err("Den Ordner gibt es nicht mehr".to_string());
|
return Err(t!("Den Ordner gibt es nicht mehr").to_string());
|
||||||
}
|
}
|
||||||
self.notebooks
|
self.notebooks
|
||||||
.insert(notebook_id.to_string(), folder.to_string());
|
.insert(notebook_id.to_string(), folder.to_string());
|
||||||
|
|||||||
+572
-199
File diff suppressed because it is too large.
Load diff
+294
@@ -0,0 +1,294 @@
|
|||||||
|
//! Bildschirmtastatur unter Wayland anfordern.
|
||||||
|
//!
|
||||||
|
//! GNOME (mutter) blendet die Bildschirmtastatur nicht schon beim ersten `enable` eines
|
||||||
|
//! Texteingabefelds (`zwp_text_input_v3`) ein, sondern erst, wenn ein bereits aktives Feld
|
||||||
|
//! `enable` erneut meldet – so macht es GTK beim Antippen. winit meldet `enable` nur einmal,
|
||||||
|
//! sobald egui ein Textfeld fokussiert. Daher schickt ink-notes über ein eigenes
|
||||||
|
//! text-input-Objekt auf derselben Wayland-Verbindung ein weiteres `enable`. Die getippten
|
||||||
|
//! Zeichen kommen weiterhin über winit an.
|
||||||
|
//!
|
||||||
|
//! Die Rücktaste der GNOME-Bildschirmtastatur löscht über `delete_surrounding_text` im zuvor
|
||||||
|
//! gemeldeten Umgebungstext; ohne Umgebungstext passiert nichts, und winit wertet das Löschen
|
||||||
|
//! ohnehin nicht aus. Daher meldet das eigene Objekt einen Platzhalter als Umgebungstext und
|
||||||
|
//! übersetzt die Löschwünsche in Tastendrücke (Rücktaste/Entf) für egui.
|
||||||
|
|
||||||
|
use std::ffi::c_void;
|
||||||
|
|
||||||
|
use wayland_client::{
|
||||||
|
delegate_noop,
|
||||||
|
protocol::{wl_registry, wl_seat},
|
||||||
|
Connection, Dispatch, EventQueue, QueueHandle,
|
||||||
|
};
|
||||||
|
use wayland_protocols::wp::text_input::zv3::client::{
|
||||||
|
zwp_text_input_manager_v3::ZwpTextInputManagerV3,
|
||||||
|
zwp_text_input_v3::{self, ZwpTextInputV3},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Platzhalter-Umgebungstext: ein Zeichen vor der Schreibmarke, damit die Rücktaste der
|
||||||
|
/// Bildschirmtastatur immer etwas zu löschen hat (ein Byte = ein Zeichen)
|
||||||
|
const SURROUNDING_PLACEHOLDER: &str = " ";
|
||||||
|
|
||||||
|
/// Wandelt Texteingaben ohne Vorschau (Preedit) in normale Texteingaben um.
|
||||||
|
///
|
||||||
|
/// Die Bildschirmtastatur schickt jedes Zeichen als fertigen IME-Text, ohne vorher eine Vorschau
|
||||||
|
/// zu melden. egui 0.27 fügt solche Texte nur ein, solange die Schreibmarke dort steht, wo die
|
||||||
|
/// letzte Vorschau begann – also nur das erste Zeichen. `composing` merkt sich über Frames hinweg,
|
||||||
|
/// ob gerade eine Vorschau läuft; deren Abschluss bleibt bei egui.
|
||||||
|
pub fn plain_ime_commits_to_text(events: &mut [egui::Event], composing: &mut bool) {
|
||||||
|
for event in events {
|
||||||
|
match event {
|
||||||
|
egui::Event::CompositionStart => *composing = true,
|
||||||
|
egui::Event::CompositionEnd(text) => {
|
||||||
|
if !*composing && !text.is_empty() && !text.contains(['\n', '\r']) {
|
||||||
|
*event = egui::Event::Text(std::mem::take(text));
|
||||||
|
}
|
||||||
|
*composing = false;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tastendrücke für egui, die `back` Zeichen vor und `forward` Zeichen nach der Schreibmarke
|
||||||
|
/// löschen
|
||||||
|
pub fn deletion_key_events(back: u32, forward: u32) -> Vec<egui::Event> {
|
||||||
|
let presses = std::iter::repeat_n(egui::Key::Backspace, back as usize)
|
||||||
|
.chain(std::iter::repeat_n(egui::Key::Delete, forward as usize));
|
||||||
|
presses
|
||||||
|
.flat_map(|key| {
|
||||||
|
[true, false].map(|pressed| egui::Event::Key {
|
||||||
|
key,
|
||||||
|
physical_key: None,
|
||||||
|
pressed,
|
||||||
|
repeat: false,
|
||||||
|
modifiers: egui::Modifiers::NONE,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Entscheidet, ob die Bildschirmtastatur angefordert wird: sobald ein Textfeld den Fokus
|
||||||
|
/// bekommt und erneut bei jedem Antippen des fokussierten Felds (falls die Tastatur inzwischen
|
||||||
|
/// zugeklappt wurde).
|
||||||
|
pub fn should_request(was_active: bool, active: bool, pressed: bool) -> bool {
|
||||||
|
active && (!was_active || pressed)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct State {
|
||||||
|
seat: Option<wl_seat::WlSeat>,
|
||||||
|
manager: Option<ZwpTextInputManagerV3>,
|
||||||
|
text_input: Option<ZwpTextInputV3>,
|
||||||
|
/// Von der Bildschirmtastatur gewünschtes Löschen (Zeichen vor/nach der Schreibmarke)
|
||||||
|
delete_back: u32,
|
||||||
|
delete_forward: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Eigenes text-input-Objekt, mit dem ink-notes die Bildschirmtastatur anfordert
|
||||||
|
pub struct KeyboardRequester {
|
||||||
|
conn: Connection,
|
||||||
|
queue: EventQueue<State>,
|
||||||
|
state: State,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KeyboardRequester {
|
||||||
|
/// Hängt sich an die Wayland-Verbindung des Fensters.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
/// `wl_display` muss auf die `wl_display` des Fensters zeigen und gültig bleiben, solange
|
||||||
|
/// der `KeyboardRequester` lebt.
|
||||||
|
pub unsafe fn new(wl_display: *mut c_void) -> Self {
|
||||||
|
// Safety: an den Aufrufer weitergereicht
|
||||||
|
let backend =
|
||||||
|
unsafe { wayland_backend::client::Backend::from_foreign_display(wl_display.cast()) };
|
||||||
|
let conn = Connection::from_backend(backend);
|
||||||
|
let queue = conn.new_event_queue();
|
||||||
|
conn.display().get_registry(&queue.handle(), ());
|
||||||
|
let _ = conn.flush();
|
||||||
|
Self {
|
||||||
|
conn,
|
||||||
|
queue,
|
||||||
|
state: State::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verarbeitet eingetroffene Ereignisse; einmal pro Frame aufrufen.
|
||||||
|
pub fn pump(&mut self) {
|
||||||
|
let _ = self.queue.dispatch_pending(&mut self.state);
|
||||||
|
if self.state.text_input.is_none() {
|
||||||
|
if let (Some(manager), Some(seat)) = (&self.state.manager, &self.state.seat) {
|
||||||
|
self.state.text_input =
|
||||||
|
Some(manager.get_text_input(seat, &self.queue.handle(), ()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bittet den Compositor, die Bildschirmtastatur einzublenden. Muss nach dem `enable` von
|
||||||
|
/// winit kommen (also nach `handle_platform_output`).
|
||||||
|
pub fn request(&mut self) {
|
||||||
|
self.pump();
|
||||||
|
if let Some(text_input) = &self.state.text_input {
|
||||||
|
text_input.enable();
|
||||||
|
self.send_surrounding_placeholder();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tastendrücke für das seit dem letzten Aufruf gewünschte Löschen (vor `begin_frame`
|
||||||
|
/// aufrufen und an die egui-Eingabe anhängen)
|
||||||
|
pub fn take_deletions(&mut self) -> Vec<egui::Event> {
|
||||||
|
self.pump();
|
||||||
|
// Den Platzhalter hier nicht neu melden: Die Tastatur löscht bei jeder neuen Meldung
|
||||||
|
// erneut, solange die Rücktaste gedrückt ist – ein kurzes Antippen löschte sonst doppelt.
|
||||||
|
let back = std::mem::take(&mut self.state.delete_back);
|
||||||
|
let forward = std::mem::take(&mut self.state.delete_forward);
|
||||||
|
deletion_key_events(back, forward)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_surrounding_placeholder(&self) {
|
||||||
|
if let Some(text_input) = &self.state.text_input {
|
||||||
|
let len = SURROUNDING_PLACEHOLDER.len() as i32;
|
||||||
|
text_input.set_surrounding_text(SURROUNDING_PLACEHOLDER.to_owned(), len, len);
|
||||||
|
text_input.commit();
|
||||||
|
let _ = self.conn.flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Dispatch<wl_registry::WlRegistry, ()> for State {
|
||||||
|
fn event(
|
||||||
|
state: &mut Self,
|
||||||
|
registry: &wl_registry::WlRegistry,
|
||||||
|
event: wl_registry::Event,
|
||||||
|
_: &(),
|
||||||
|
_: &Connection,
|
||||||
|
qh: &QueueHandle<Self>,
|
||||||
|
) {
|
||||||
|
if let wl_registry::Event::Global {
|
||||||
|
name, interface, ..
|
||||||
|
} = event
|
||||||
|
{
|
||||||
|
match interface.as_str() {
|
||||||
|
"wl_seat" if state.seat.is_none() => {
|
||||||
|
state.seat = Some(registry.bind(name, 1, qh, ()));
|
||||||
|
}
|
||||||
|
"zwp_text_input_manager_v3" if state.manager.is_none() => {
|
||||||
|
state.manager = Some(registry.bind(name, 1, qh, ()));
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
delegate_noop!(State: ignore wl_seat::WlSeat);
|
||||||
|
delegate_noop!(State: ZwpTextInputManagerV3);
|
||||||
|
impl Dispatch<ZwpTextInputV3, ()> for State {
|
||||||
|
fn event(
|
||||||
|
state: &mut Self,
|
||||||
|
_: &ZwpTextInputV3,
|
||||||
|
event: zwp_text_input_v3::Event,
|
||||||
|
_: &(),
|
||||||
|
_: &Connection,
|
||||||
|
_: &QueueHandle<Self>,
|
||||||
|
) {
|
||||||
|
// Getippter Text kommt über winit; hier nur das Löschen
|
||||||
|
if let zwp_text_input_v3::Event::DeleteSurroundingText {
|
||||||
|
before_length,
|
||||||
|
after_length,
|
||||||
|
} = event
|
||||||
|
{
|
||||||
|
state.delete_back += before_length;
|
||||||
|
state.delete_forward += after_length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn requests_when_text_field_gets_focus() {
|
||||||
|
assert!(should_request(false, true, false));
|
||||||
|
assert!(should_request(false, true, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn requests_again_when_focused_field_is_tapped() {
|
||||||
|
assert!(should_request(true, true, true));
|
||||||
|
assert!(!should_request(true, true, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn commits_without_preedit_become_text() {
|
||||||
|
let mut composing = false;
|
||||||
|
let mut events = vec![
|
||||||
|
egui::Event::CompositionEnd("h".into()),
|
||||||
|
egui::Event::CompositionEnd("i".into()),
|
||||||
|
];
|
||||||
|
plain_ime_commits_to_text(&mut events, &mut composing);
|
||||||
|
assert_eq!(
|
||||||
|
events,
|
||||||
|
vec![egui::Event::Text("h".into()), egui::Event::Text("i".into())]
|
||||||
|
);
|
||||||
|
assert!(!composing);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn commits_after_preedit_stay_with_egui() {
|
||||||
|
let mut composing = false;
|
||||||
|
let mut events = vec![
|
||||||
|
egui::Event::CompositionStart,
|
||||||
|
egui::Event::CompositionUpdate("ni".into()),
|
||||||
|
];
|
||||||
|
plain_ime_commits_to_text(&mut events, &mut composing);
|
||||||
|
assert!(composing);
|
||||||
|
// Abschluss erst im nächsten Frame
|
||||||
|
let mut events = vec![egui::Event::CompositionEnd("你".into())];
|
||||||
|
plain_ime_commits_to_text(&mut events, &mut composing);
|
||||||
|
assert_eq!(events, vec![egui::Event::CompositionEnd("你".into())]);
|
||||||
|
assert!(!composing);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn line_breaks_and_empty_commits_are_left_alone() {
|
||||||
|
let mut composing = false;
|
||||||
|
let mut events = vec![
|
||||||
|
egui::Event::CompositionEnd("\n".into()),
|
||||||
|
egui::Event::CompositionEnd(String::new()),
|
||||||
|
];
|
||||||
|
let before = events.clone();
|
||||||
|
plain_ime_commits_to_text(&mut events, &mut composing);
|
||||||
|
assert_eq!(events, before);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn deletions_become_key_presses() {
|
||||||
|
let events = deletion_key_events(2, 1);
|
||||||
|
let keys: Vec<_> = events
|
||||||
|
.iter()
|
||||||
|
.map(|e| match e {
|
||||||
|
egui::Event::Key { key, pressed, .. } => (*key, *pressed),
|
||||||
|
other => panic!("unerwartet: {other:?}"),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
keys,
|
||||||
|
vec![
|
||||||
|
(egui::Key::Backspace, true),
|
||||||
|
(egui::Key::Backspace, false),
|
||||||
|
(egui::Key::Backspace, true),
|
||||||
|
(egui::Key::Backspace, false),
|
||||||
|
(egui::Key::Delete, true),
|
||||||
|
(egui::Key::Delete, false),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert!(deletion_key_events(0, 0).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_request_without_focused_text_field() {
|
||||||
|
assert!(!should_request(false, false, true));
|
||||||
|
assert!(!should_request(true, false, true));
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
-30
@@ -13,8 +13,9 @@ use hayro::{PixmapSettings, RenderCache, RenderSettings};
|
|||||||
|
|
||||||
use crate::assets::{AssetStore, RgbaImage};
|
use crate::assets::{AssetStore, RgbaImage};
|
||||||
use crate::background::PatternColor;
|
use crate::background::PatternColor;
|
||||||
use crate::document::{Aabb, Notebook, Page, PageBackground, A4_WIDTH_MM, PAGE_WIDTH};
|
use crate::document::{Aabb, Notebook, Page, PageBackground};
|
||||||
use crate::export::{export_notebook_to_bytes, ExportStrategy};
|
use crate::export::{export_notebook_to_bytes, ExportStrategy};
|
||||||
|
use crate::t;
|
||||||
|
|
||||||
/// Auflösung des PNG-Exports einer Seite.
|
/// Auflösung des PNG-Exports einer Seite.
|
||||||
pub const PAGE_PNG_DPI: f32 = 200.0;
|
pub const PAGE_PNG_DPI: f32 = 200.0;
|
||||||
@@ -50,8 +51,8 @@ fn content_only(page: &Page) -> Page {
|
|||||||
|
|
||||||
/// Rastert die erste Seite eines PDFs mit `dpi`; Farben ohne Vormultiplikation.
|
/// Rastert die erste Seite eines PDFs mit `dpi`; Farben ohne Vormultiplikation.
|
||||||
fn rasterize(pdf_bytes: Vec<u8>, dpi: f32, transparent: bool) -> Result<RgbaImage, Box<dyn Error>> {
|
fn rasterize(pdf_bytes: Vec<u8>, dpi: f32, transparent: bool) -> Result<RgbaImage, Box<dyn Error>> {
|
||||||
let pdf = Pdf::new(pdf_bytes).map_err(|e| format!("PDF nicht lesbar: {e:?}"))?;
|
let pdf = Pdf::new(pdf_bytes).map_err(|e| t!("PDF nicht lesbar: {e}", e = format!("{e:?}")))?;
|
||||||
let page = pdf.pages().first().ok_or("PDF ohne Seite")?;
|
let page = pdf.pages().first().ok_or(t!("PDF ohne Seite"))?;
|
||||||
let scale = dpi / 72.0;
|
let scale = dpi / 72.0;
|
||||||
let pixmap = hayro::render(
|
let pixmap = hayro::render(
|
||||||
page,
|
page,
|
||||||
@@ -84,7 +85,7 @@ fn rasterize(pdf_bytes: Vec<u8>, dpi: f32, transparent: bool) -> Result<RgbaImag
|
|||||||
/// Kodiert ein Bild als PNG.
|
/// Kodiert ein Bild als PNG.
|
||||||
pub fn encode_png(image: &RgbaImage) -> Result<Vec<u8>, Box<dyn Error>> {
|
pub fn encode_png(image: &RgbaImage) -> Result<Vec<u8>, Box<dyn Error>> {
|
||||||
let buffer = image::RgbaImage::from_raw(image.width, image.height, image.pixels.clone())
|
let buffer = image::RgbaImage::from_raw(image.width, image.height, image.pixels.clone())
|
||||||
.ok_or("Pixeldaten passen nicht zur Bildgröße")?;
|
.ok_or(t!("Pixeldaten passen nicht zur Bildgröße"))?;
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
image::DynamicImage::ImageRgba8(buffer)
|
image::DynamicImage::ImageRgba8(buffer)
|
||||||
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)?;
|
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)?;
|
||||||
@@ -118,8 +119,8 @@ pub fn page_svg(
|
|||||||
pattern: PatternColor,
|
pattern: PatternColor,
|
||||||
) -> Result<String, Box<dyn Error>> {
|
) -> Result<String, Box<dyn Error>> {
|
||||||
let pdf = Pdf::new(single_page_pdf(page, assets, pattern)?)
|
let pdf = Pdf::new(single_page_pdf(page, assets, pattern)?)
|
||||||
.map_err(|e| format!("PDF nicht lesbar: {e:?}"))?;
|
.map_err(|e| t!("PDF nicht lesbar: {e}", e = format!("{e:?}")))?;
|
||||||
let pdf_page = pdf.pages().first().ok_or("PDF ohne Seite")?;
|
let pdf_page = pdf.pages().first().ok_or(t!("PDF ohne Seite"))?;
|
||||||
Ok(hayro_svg::convert(
|
Ok(hayro_svg::convert(
|
||||||
pdf_page,
|
pdf_page,
|
||||||
&hayro_svg::RenderCache::new(),
|
&hayro_svg::RenderCache::new(),
|
||||||
@@ -144,38 +145,24 @@ pub fn selection_image(
|
|||||||
};
|
};
|
||||||
let max_width = selected.strokes.iter().map(|s| s.width).fold(0.0, f32::max);
|
let max_width = selected.strokes.iter().map(|s| s.width).fold(0.0, f32::max);
|
||||||
let bounds: Aabb = bounds.expanded(max_width / 2.0 + 4.0);
|
let bounds: Aabb = bounds.expanded(max_width / 2.0 + 4.0);
|
||||||
|
let size = bounds.max - bounds.min;
|
||||||
let full = rasterize(
|
if size.min_element() < 1.0 {
|
||||||
single_page_pdf(&selected, assets, PatternColor::default())?,
|
return Ok(None);
|
||||||
|
}
|
||||||
|
// Nur den Ausschnitt rastern (auf der endlosen Seite wäre die ganze Seite riesig)
|
||||||
|
let cropped = selected.cropped(bounds.min, size);
|
||||||
|
let image = rasterize(
|
||||||
|
single_page_pdf(&cropped, assets, PatternColor::default())?,
|
||||||
SELECTION_PNG_DPI,
|
SELECTION_PNG_DPI,
|
||||||
true,
|
true,
|
||||||
)?;
|
)?;
|
||||||
// Seiteneinheiten → Pixel
|
Ok(Some(image))
|
||||||
let px_per_unit = SELECTION_PNG_DPI / 25.4 * A4_WIDTH_MM / PAGE_WIDTH;
|
|
||||||
let x0 = ((bounds.min.x * px_per_unit).floor().max(0.0) as u32).min(full.width);
|
|
||||||
let y0 = ((bounds.min.y * px_per_unit).floor().max(0.0) as u32).min(full.height);
|
|
||||||
let x1 = ((bounds.max.x * px_per_unit).ceil().max(0.0) as u32).min(full.width);
|
|
||||||
let y1 = ((bounds.max.y * px_per_unit).ceil().max(0.0) as u32).min(full.height);
|
|
||||||
if x1 <= x0 || y1 <= y0 {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
let (w, h) = (x1 - x0, y1 - y0);
|
|
||||||
let mut pixels = Vec::with_capacity((w * h * 4) as usize);
|
|
||||||
for y in y0..y1 {
|
|
||||||
let start = ((y * full.width + x0) * 4) as usize;
|
|
||||||
pixels.extend_from_slice(&full.pixels[start..start + (w * 4) as usize]);
|
|
||||||
}
|
|
||||||
Ok(Some(RgbaImage {
|
|
||||||
width: w,
|
|
||||||
height: h,
|
|
||||||
pixels,
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::document::{Stroke, StylusSample, PAGE_HEIGHT};
|
use crate::document::{Stroke, StylusSample, A4_WIDTH_MM, PAGE_HEIGHT, PAGE_WIDTH};
|
||||||
|
|
||||||
fn page_with_line() -> Page {
|
fn page_with_line() -> Page {
|
||||||
let mut page = Page::new(1, PageBackground::Grid5mm);
|
let mut page = Page::new(1, PageBackground::Grid5mm);
|
||||||
|
|||||||
+250
-38
@@ -1,11 +1,13 @@
|
|||||||
//! Lesen und Rendern importierter PDF-Dateien mit `hayro` (reines Rust, nur CPU).
|
//! Lesen und Rendern importierter PDF-Dateien mit `hayro` (reines Rust, nur CPU).
|
||||||
//!
|
//!
|
||||||
//! Das Rendern einer Seite kann einige hundert Millisekunden dauern; [`PdfRenderService`]
|
//! Das Rendern einer Seite kann einige hundert Millisekunden dauern; [`PdfRenderService`]
|
||||||
//! erledigt es deshalb in einem Hintergrund-Thread und meldet fertige Seiten zurück.
|
//! erledigt es deshalb in einem Hintergrund-Thread, samt Mipmaps für die Anzeige, und meldet
|
||||||
|
//! fertige Seiten zurück.
|
||||||
|
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::mpsc::{self, Receiver, Sender};
|
use std::sync::mpsc::{self, Receiver};
|
||||||
|
use std::sync::{Arc, Condvar, Mutex};
|
||||||
|
|
||||||
use hayro::hayro_interpret::InterpreterSettings;
|
use hayro::hayro_interpret::InterpreterSettings;
|
||||||
use hayro::hayro_syntax::{LoadPdfError, Pdf};
|
use hayro::hayro_syntax::{LoadPdfError, Pdf};
|
||||||
@@ -13,6 +15,7 @@ use hayro::vello_cpu::color::palette::css::WHITE;
|
|||||||
use hayro::{PixmapSettings, RenderCache, RenderSettings};
|
use hayro::{PixmapSettings, RenderCache, RenderSettings};
|
||||||
|
|
||||||
use crate::assets::RgbaImage;
|
use crate::assets::RgbaImage;
|
||||||
|
use crate::t;
|
||||||
|
|
||||||
/// Längste Kante einer gerenderten Seite für die Anzeige in Pixeln (A4 ≈ 220 dpi).
|
/// Längste Kante einer gerenderten Seite für die Anzeige in Pixeln (A4 ≈ 220 dpi).
|
||||||
pub const DISPLAY_RENDER_PIXELS: u32 = 2560;
|
pub const DISPLAY_RENDER_PIXELS: u32 = 2560;
|
||||||
@@ -38,12 +41,13 @@ pub fn page_sizes(bytes: Vec<u8>) -> Result<Vec<(f32, f32)>, String> {
|
|||||||
let pdf = open(bytes)?;
|
let pdf = open(bytes)?;
|
||||||
let sizes: Vec<(f32, f32)> = pdf.pages().iter().map(|p| p.render_dimensions()).collect();
|
let sizes: Vec<(f32, f32)> = pdf.pages().iter().map(|p| p.render_dimensions()).collect();
|
||||||
if sizes.is_empty() {
|
if sizes.is_empty() {
|
||||||
return Err("Das PDF enthält keine Seiten".into());
|
return Err(t!("Das PDF enthält keine Seiten").into());
|
||||||
}
|
}
|
||||||
if sizes.len() > MAX_IMPORT_PAGES {
|
if sizes.len() > MAX_IMPORT_PAGES {
|
||||||
return Err(format!(
|
return Err(t!(
|
||||||
"Das PDF hat {} Seiten, höchstens {MAX_IMPORT_PAGES} werden unterstützt",
|
"Das PDF hat {count} Seiten, höchstens {max} werden unterstützt",
|
||||||
sizes.len()
|
count = sizes.len(),
|
||||||
|
max = MAX_IMPORT_PAGES
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
Ok(sizes)
|
Ok(sizes)
|
||||||
@@ -52,10 +56,10 @@ pub fn page_sizes(bytes: Vec<u8>) -> Result<Vec<(f32, f32)>, String> {
|
|||||||
fn open(bytes: Vec<u8>) -> Result<Pdf, String> {
|
fn open(bytes: Vec<u8>) -> Result<Pdf, String> {
|
||||||
Pdf::new(bytes).map_err(|e| match e {
|
Pdf::new(bytes).map_err(|e| match e {
|
||||||
LoadPdfError::Decryption(_) => {
|
LoadPdfError::Decryption(_) => {
|
||||||
"Das PDF ist verschlüsselt oder passwortgeschützt und kann nicht geöffnet werden"
|
t!("Das PDF ist verschlüsselt oder passwortgeschützt und kann nicht geöffnet werden")
|
||||||
.to_string()
|
.to_string()
|
||||||
}
|
}
|
||||||
LoadPdfError::Invalid => "Die Datei ist kein lesbares PDF".to_string(),
|
LoadPdfError::Invalid => t!("Die Datei ist kein lesbares PDF").to_string(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,7 +69,7 @@ pub fn render_page(pdf: &Pdf, index: usize, max_pixels: u32) -> Result<RgbaImage
|
|||||||
let page = pdf
|
let page = pdf
|
||||||
.pages()
|
.pages()
|
||||||
.get(index)
|
.get(index)
|
||||||
.ok_or_else(|| format!("Seite {} fehlt im PDF", index + 1))?;
|
.ok_or_else(|| t!("Seite {number} fehlt im PDF", number = index + 1))?;
|
||||||
let (w, h) = page.render_dimensions();
|
let (w, h) = page.render_dimensions();
|
||||||
let scale = (max_pixels as f32 / w.max(h).max(1.0)).min(16.0);
|
let scale = (max_pixels as f32 / w.max(h).max(1.0)).min(16.0);
|
||||||
let pixmap = hayro::render(
|
let pixmap = hayro::render(
|
||||||
@@ -102,30 +106,107 @@ struct RenderRequest {
|
|||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
page: usize,
|
page: usize,
|
||||||
max_pixels: u32,
|
max_pixels: u32,
|
||||||
|
/// Wichtigkeit: kleiner zuerst (Reihenfolge der Anfragen im aktuellen Bild)
|
||||||
|
rank: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Ergebnis eines Render-Auftrags.
|
/// Wichtigkeit einer vorab gerenderten Seite: nach allen sichtbaren.
|
||||||
pub type RenderResult = Result<RgbaImage, String>;
|
const PREFETCH_RANK: usize = usize::MAX;
|
||||||
|
|
||||||
|
/// Warteschlange der noch nicht begonnenen Render-Aufträge, geteilt mit dem Render-Thread.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct RenderQueue {
|
||||||
|
requests: Vec<RenderRequest>,
|
||||||
|
shutdown: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RenderQueue {
|
||||||
|
/// Fügt einen Auftrag hinzu oder macht einen wartenden wichtiger.
|
||||||
|
fn push(&mut self, request: RenderRequest) {
|
||||||
|
match self.requests.iter_mut().find(|r| r.key == request.key) {
|
||||||
|
Some(queued) => queued.rank = queued.rank.min(request.rank),
|
||||||
|
None => self.requests.push(request),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Nimmt den wichtigsten Auftrag heraus.
|
||||||
|
fn pop(&mut self) -> Option<RenderRequest> {
|
||||||
|
let (index, _) = self
|
||||||
|
.requests
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.min_by_key(|(_, r)| r.rank)?;
|
||||||
|
Some(self.requests.swap_remove(index))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verwirft Aufträge, für die `rank_of` keinen Rang mehr liefert, und ordnet die übrigen
|
||||||
|
/// neu. Liefert die Schlüssel der verworfenen.
|
||||||
|
fn retain(&mut self, rank_of: impl Fn(&str) -> Option<usize>) -> Vec<String> {
|
||||||
|
let mut dropped = Vec::new();
|
||||||
|
self.requests.retain_mut(|r| match rank_of(&r.key) {
|
||||||
|
Some(rank) => {
|
||||||
|
r.rank = rank;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
dropped.push(r.key.clone());
|
||||||
|
false
|
||||||
|
}
|
||||||
|
});
|
||||||
|
dropped
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type SharedQueue = Arc<(Mutex<RenderQueue>, Condvar)>;
|
||||||
|
|
||||||
|
/// Ergebnis eines Render-Auftrags: die Mipmap-Stufen der Seite (siehe
|
||||||
|
/// [`crate::image_layer::mip_chain`]), Stufe 0 in voller Größe.
|
||||||
|
pub type RenderResult = Result<Vec<RgbaImage>, String>;
|
||||||
|
|
||||||
/// Rendert PDF-Seiten im Hintergrund. Fertige Seiten holt der Event-Loop mit
|
/// Rendert PDF-Seiten im Hintergrund. Fertige Seiten holt der Event-Loop mit
|
||||||
/// [`PdfRenderService::take`] ab; `on_ready` weckt ihn dafür auf.
|
/// [`PdfRenderService::take`] ab; `on_ready` weckt ihn dafür auf.
|
||||||
|
///
|
||||||
|
/// Je Bild meldet der Event-Loop zwischen [`Self::begin_frame`] und [`Self::end_frame`] mit
|
||||||
|
/// `take` alle Seiten an, die er gerade braucht (die wichtigste zuerst). Gerendert wird die
|
||||||
|
/// wichtigste wartende Seite zuerst; Seiten, die beim schnellen Scrollen schon wieder aus dem
|
||||||
|
/// Bild sind, verwirft `end_frame`, bevor der Render-Thread sie beginnt.
|
||||||
pub struct PdfRenderService {
|
pub struct PdfRenderService {
|
||||||
requests: Sender<RenderRequest>,
|
queue: SharedQueue,
|
||||||
|
worker: std::thread::JoinHandle<()>,
|
||||||
results: Receiver<(String, RenderResult)>,
|
results: Receiver<(String, RenderResult)>,
|
||||||
|
/// Wartende oder gerade gerenderte Seiten
|
||||||
pending: HashSet<String>,
|
pending: HashSet<String>,
|
||||||
ready: HashMap<String, RenderResult>,
|
ready: HashMap<String, RenderResult>,
|
||||||
|
/// Im aktuellen Bild angeforderte Seiten in ihrer Reihenfolge
|
||||||
|
wanted: Vec<String>,
|
||||||
|
/// Zuletzt vorab angeforderte Seite (bleibt erhalten, bis sie abgeholt wird)
|
||||||
|
prefetched: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PdfRenderService {
|
impl PdfRenderService {
|
||||||
pub fn new(on_ready: impl Fn() + Send + 'static) -> Self {
|
pub fn new(on_ready: impl Fn() + Send + 'static) -> Self {
|
||||||
let (req_tx, req_rx) = mpsc::channel::<RenderRequest>();
|
let queue: SharedQueue = Arc::default();
|
||||||
let (res_tx, res_rx) = mpsc::channel();
|
let (res_tx, res_rx) = mpsc::channel();
|
||||||
std::thread::Builder::new()
|
let worker_queue = Arc::clone(&queue);
|
||||||
|
let worker = std::thread::Builder::new()
|
||||||
.name("pdf-render".into())
|
.name("pdf-render".into())
|
||||||
.spawn(move || {
|
.spawn(move || {
|
||||||
// Zuletzt geöffnetes PDF behalten: Blättern rendert meist dieselbe Datei
|
// Zuletzt geöffnetes PDF behalten: Blättern rendert meist dieselbe Datei
|
||||||
let mut open_pdf: Option<(PathBuf, Pdf)> = None;
|
let mut open_pdf: Option<(PathBuf, Pdf)> = None;
|
||||||
while let Ok(request) = req_rx.recv() {
|
loop {
|
||||||
|
let request = {
|
||||||
|
let (lock, ready) = &*worker_queue;
|
||||||
|
let mut queue = lock.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
loop {
|
||||||
|
if queue.shutdown {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Some(request) = queue.pop() {
|
||||||
|
break request;
|
||||||
|
}
|
||||||
|
queue = ready.wait(queue).unwrap_or_else(|e| e.into_inner());
|
||||||
|
}
|
||||||
|
};
|
||||||
if open_pdf.as_ref().map(|(p, _)| p) != Some(&request.path) {
|
if open_pdf.as_ref().map(|(p, _)| p) != Some(&request.path) {
|
||||||
open_pdf = std::fs::read(&request.path)
|
open_pdf = std::fs::read(&request.path)
|
||||||
.map_err(|e| e.to_string())
|
.map_err(|e| e.to_string())
|
||||||
@@ -135,36 +216,64 @@ impl PdfRenderService {
|
|||||||
.map(|pdf| (request.path.clone(), pdf));
|
.map(|pdf| (request.path.clone(), pdf));
|
||||||
}
|
}
|
||||||
let result = match &open_pdf {
|
let result = match &open_pdf {
|
||||||
Some((_, pdf)) => render_page(pdf, request.page, request.max_pixels),
|
// Mipmaps hier statt im Haupt-Thread: sonst stockt das Scrollen bei
|
||||||
None => Err("PDF kann nicht geöffnet werden".into()),
|
// jeder neu gerenderten Seite (Issue #28)
|
||||||
|
Some((_, pdf)) => render_page(pdf, request.page, request.max_pixels)
|
||||||
|
.map(crate::image_layer::mip_chain),
|
||||||
|
None => Err(t!("PDF kann nicht geöffnet werden").into()),
|
||||||
};
|
};
|
||||||
if res_tx.send((request.key, result)).is_err() {
|
if res_tx.send((request.key, result)).is_err() {
|
||||||
break;
|
return;
|
||||||
}
|
}
|
||||||
on_ready();
|
on_ready();
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.expect("PDF-Render-Thread konnte nicht gestartet werden");
|
.expect("PDF-Render-Thread konnte nicht gestartet werden");
|
||||||
Self {
|
Self {
|
||||||
requests: req_tx,
|
queue,
|
||||||
|
worker,
|
||||||
results: res_rx,
|
results: res_rx,
|
||||||
pending: HashSet::new(),
|
pending: HashSet::new(),
|
||||||
ready: HashMap::new(),
|
ready: HashMap::new(),
|
||||||
|
wanted: Vec::new(),
|
||||||
|
prefetched: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Beginnt die Anfragen eines neuen Bildes (siehe [`Self::end_frame`]).
|
||||||
|
pub fn begin_frame(&mut self) {
|
||||||
|
self.wanted.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verwirft wartende Aufträge und fertige Ergebnisse für Seiten, die in diesem Bild nicht
|
||||||
|
/// mehr angefordert wurden (außer der vorab angeforderten), und ordnet die übrigen nach
|
||||||
|
/// der Reihenfolge der Anfragen.
|
||||||
|
pub fn end_frame(&mut self) {
|
||||||
|
let rank_of = |key: &str| {
|
||||||
|
self.wanted
|
||||||
|
.iter()
|
||||||
|
.position(|k| k == key)
|
||||||
|
.or_else(|| (self.prefetched.as_deref() == Some(key)).then_some(PREFETCH_RANK))
|
||||||
|
};
|
||||||
|
let dropped = {
|
||||||
|
let mut queue = self.queue.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
queue.retain(rank_of)
|
||||||
|
};
|
||||||
|
for key in dropped {
|
||||||
|
self.pending.remove(&key);
|
||||||
|
}
|
||||||
|
self.ready.retain(|key, _| rank_of(key).is_some());
|
||||||
|
}
|
||||||
|
|
||||||
/// Rendert eine Seite vorab (z. B. die nächste), ohne auf das Ergebnis zu warten;
|
/// Rendert eine Seite vorab (z. B. die nächste), ohne auf das Ergebnis zu warten;
|
||||||
/// [`Self::take`] liefert es später sofort.
|
/// [`Self::take`] liefert es später sofort.
|
||||||
pub fn prefetch(&mut self, key: &str, path: PathBuf, page: usize) {
|
pub fn prefetch(&mut self, key: &str, path: PathBuf, page: usize) {
|
||||||
self.collect();
|
self.collect();
|
||||||
if self.ready.contains_key(key) || self.pending.contains(key) {
|
self.prefetched = Some(key.to_string());
|
||||||
|
if self.ready.contains_key(key) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Vorab gerenderte Seiten nicht unbegrenzt aufheben
|
self.request(key, path, page, DISPLAY_RENDER_PIXELS, PREFETCH_RANK);
|
||||||
if self.ready.len() >= 2 {
|
|
||||||
self.ready.clear();
|
|
||||||
}
|
|
||||||
self.request(key, path, page, DISPLAY_RENDER_PIXELS);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn collect(&mut self) {
|
fn collect(&mut self) {
|
||||||
@@ -174,21 +283,37 @@ impl PdfRenderService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Erteilt den Auftrag, falls noch keiner läuft. `false`, wenn der Thread beendet ist.
|
/// Erteilt den Auftrag bzw. macht einen wartenden wichtiger. `false`, wenn der
|
||||||
fn request(&mut self, key: &str, path: PathBuf, page: usize, max_pixels: u32) -> bool {
|
/// Render-Thread beendet ist.
|
||||||
if !self.pending.insert(key.to_string()) {
|
fn request(
|
||||||
|
&mut self,
|
||||||
|
key: &str,
|
||||||
|
path: PathBuf,
|
||||||
|
page: usize,
|
||||||
|
max_pixels: u32,
|
||||||
|
rank: usize,
|
||||||
|
) -> bool {
|
||||||
|
if self.worker.is_finished() {
|
||||||
|
self.pending.remove(key);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let (lock, ready) = &*self.queue;
|
||||||
|
let mut queue = lock.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
// Steht ein angefragter Auftrag nicht mehr in der Warteschlange, rendert ihn der
|
||||||
|
// Thread gerade: nicht doppelt erteilen
|
||||||
|
let waiting = queue.requests.iter().any(|r| r.key == key);
|
||||||
|
if self.pending.contains(key) && !waiting {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
let request = RenderRequest {
|
self.pending.insert(key.to_string());
|
||||||
|
queue.push(RenderRequest {
|
||||||
key: key.to_string(),
|
key: key.to_string(),
|
||||||
path,
|
path,
|
||||||
page,
|
page,
|
||||||
max_pixels,
|
max_pixels,
|
||||||
};
|
rank,
|
||||||
if self.requests.send(request).is_err() {
|
});
|
||||||
self.pending.remove(key);
|
ready.notify_one();
|
||||||
return false;
|
|
||||||
}
|
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -202,16 +327,29 @@ impl PdfRenderService {
|
|||||||
max_pixels: u32,
|
max_pixels: u32,
|
||||||
) -> Option<RenderResult> {
|
) -> Option<RenderResult> {
|
||||||
self.collect();
|
self.collect();
|
||||||
|
if self.prefetched.as_deref() == Some(key) {
|
||||||
|
self.prefetched = None;
|
||||||
|
}
|
||||||
if let Some(result) = self.ready.remove(key) {
|
if let Some(result) = self.ready.remove(key) {
|
||||||
return Some(result);
|
return Some(result);
|
||||||
}
|
}
|
||||||
if !self.request(key, path, page, max_pixels) {
|
let rank = self.wanted.len();
|
||||||
return Some(Err("PDF-Render-Thread beendet".into()));
|
self.wanted.push(key.to_string());
|
||||||
|
if !self.request(key, path, page, max_pixels, rank) {
|
||||||
|
return Some(Err(t!("PDF-Render-Thread beendet").into()));
|
||||||
}
|
}
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Drop for PdfRenderService {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let (lock, ready) = &*self.queue;
|
||||||
|
lock.lock().unwrap_or_else(|e| e.into_inner()).shutdown = true;
|
||||||
|
ready.notify_all();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub(crate) mod tests {
|
pub(crate) mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -301,8 +439,12 @@ pub(crate) mod tests {
|
|||||||
wake_rx
|
wake_rx
|
||||||
.recv_timeout(std::time::Duration::from_secs(20))
|
.recv_timeout(std::time::Duration::from_secs(20))
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let image = service.take("a#0", path.clone(), 0, px).unwrap().unwrap();
|
let levels = service.take("a#0", path.clone(), 0, px).unwrap().unwrap();
|
||||||
assert_eq!(image.width, DISPLAY_RENDER_PIXELS);
|
assert_eq!(levels[0].width, DISPLAY_RENDER_PIXELS);
|
||||||
|
assert_eq!(
|
||||||
|
(levels.last().unwrap().width, levels.last().unwrap().height),
|
||||||
|
(1, 1)
|
||||||
|
);
|
||||||
|
|
||||||
// Vorab rendern: danach sofort verfügbar
|
// Vorab rendern: danach sofort verfügbar
|
||||||
service.prefetch("a#0", path.clone(), 0);
|
service.prefetch("a#0", path.clone(), 0);
|
||||||
@@ -312,6 +454,76 @@ pub(crate) mod tests {
|
|||||||
assert!(service.take("a#0", path, 0, px).unwrap().is_ok());
|
assert!(service.take("a#0", path, 0, px).unwrap().is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn request(key: &str, rank: usize) -> RenderRequest {
|
||||||
|
RenderRequest {
|
||||||
|
key: key.into(),
|
||||||
|
path: PathBuf::new(),
|
||||||
|
page: 0,
|
||||||
|
max_pixels: 1,
|
||||||
|
rank,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_render_queue_priorities_and_stale_requests() {
|
||||||
|
let mut queue = RenderQueue::default();
|
||||||
|
queue.push(request("a", 2));
|
||||||
|
queue.push(request("b", 0));
|
||||||
|
queue.push(request("c", 1));
|
||||||
|
// Erneute Anfrage macht einen wartenden Auftrag wichtiger, ohne ihn zu verdoppeln
|
||||||
|
queue.push(request("a", 0));
|
||||||
|
assert_eq!(queue.requests.len(), 3);
|
||||||
|
assert_eq!(queue.pop().map(|r| r.key), Some("a".into()));
|
||||||
|
|
||||||
|
// Nach dem Scrollen wird nur noch „c“ gebraucht: „b“ fällt weg
|
||||||
|
let dropped = queue.retain(|key| (key == "c").then_some(0));
|
||||||
|
assert_eq!(dropped, vec!["b".to_string()]);
|
||||||
|
assert_eq!(queue.pop().map(|r| r.key), Some("c".into()));
|
||||||
|
assert!(queue.pop().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_end_frame_drops_unwanted_results_but_keeps_prefetch() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join("a.pdf");
|
||||||
|
std::fs::write(&path, sample_pdf(&[(400.0, 300.0, 0), (400.0, 300.0, 0)])).unwrap();
|
||||||
|
let (wake_tx, wake_rx) = mpsc::channel();
|
||||||
|
let mut service = PdfRenderService::new(move || {
|
||||||
|
let _ = wake_tx.send(());
|
||||||
|
});
|
||||||
|
let px = DISPLAY_RENDER_PIXELS;
|
||||||
|
let wait = || {
|
||||||
|
wake_rx
|
||||||
|
.recv_timeout(std::time::Duration::from_secs(20))
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
|
||||||
|
// Bild 1 braucht Seite 1; vorab gerendert wird Seite 2
|
||||||
|
service.begin_frame();
|
||||||
|
assert!(service.take("a#0", path.clone(), 0, px).is_none());
|
||||||
|
service.prefetch("a#1", path.clone(), 1);
|
||||||
|
service.end_frame();
|
||||||
|
wait();
|
||||||
|
wait();
|
||||||
|
|
||||||
|
// Bild 2 braucht keine Seite mehr (weggescrollt): Seite 1 wird verworfen,
|
||||||
|
// die vorab gerenderte Seite 2 bleibt
|
||||||
|
service.begin_frame();
|
||||||
|
service.collect();
|
||||||
|
service.end_frame();
|
||||||
|
assert!(!service.ready.contains_key("a#0"));
|
||||||
|
assert!(service.ready.contains_key("a#1"));
|
||||||
|
assert!(service.pending.is_empty());
|
||||||
|
|
||||||
|
service.begin_frame();
|
||||||
|
assert!(service.take("a#1", path.clone(), 1, px).unwrap().is_ok());
|
||||||
|
// Seite 1 wird bei Bedarf neu gerendert
|
||||||
|
assert!(service.take("a#0", path.clone(), 0, px).is_none());
|
||||||
|
service.end_frame();
|
||||||
|
wait();
|
||||||
|
assert!(service.take("a#0", path, 0, px).unwrap().is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_parse_page_key() {
|
fn test_parse_page_key() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
|||||||
+12
-5
@@ -9,6 +9,8 @@ use std::collections::{BTreeMap, HashMap};
|
|||||||
|
|
||||||
use printpdf::lopdf::{Dictionary, Document, Object, ObjectId, Stream};
|
use printpdf::lopdf::{Dictionary, Document, Object, ObjectId, Stream};
|
||||||
|
|
||||||
|
use crate::t;
|
||||||
|
|
||||||
/// Eine Zielseite, unter die eine Seite eines Quell-PDFs gelegt wird.
|
/// Eine Zielseite, unter die eine Seite eines Quell-PDFs gelegt wird.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub struct Underlay {
|
pub struct Underlay {
|
||||||
@@ -137,7 +139,7 @@ fn page_as_form(
|
|||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
let data = stream
|
let data = stream
|
||||||
.decompressed_content()
|
.decompressed_content()
|
||||||
.map_err(|e| format!("Inhalt nicht lesbar: {e}"))?;
|
.map_err(|e| t!("Inhalt nicht lesbar: {e}", e = e))?;
|
||||||
content.extend_from_slice(&data);
|
content.extend_from_slice(&data);
|
||||||
content.push(b'\n');
|
content.push(b'\n');
|
||||||
}
|
}
|
||||||
@@ -183,10 +185,10 @@ pub fn apply_underlays(
|
|||||||
let result = (|| {
|
let result = (|| {
|
||||||
let bytes = sources
|
let bytes = sources
|
||||||
.get(&underlay.source)
|
.get(&underlay.source)
|
||||||
.ok_or_else(|| "Quell-PDF fehlt".to_string())?;
|
.ok_or_else(|| t!("Quell-PDF fehlt").to_string())?;
|
||||||
let mut source = Document::load_mem(bytes).map_err(|e| e.to_string())?;
|
let mut source = Document::load_mem(bytes).map_err(|e| e.to_string())?;
|
||||||
if source.is_encrypted() {
|
if source.is_encrypted() {
|
||||||
return Err("Quell-PDF ist verschlüsselt".to_string());
|
return Err(t!("Quell-PDF ist verschlüsselt").to_string());
|
||||||
}
|
}
|
||||||
source.renumber_objects_with(target.max_id + 1);
|
source.renumber_objects_with(target.max_id + 1);
|
||||||
let pages = source.get_pages();
|
let pages = source.get_pages();
|
||||||
@@ -206,10 +208,15 @@ pub fn apply_underlays(
|
|||||||
.map_err(Clone::clone)?;
|
.map_err(Clone::clone)?;
|
||||||
let source_page = *pages
|
let source_page = *pages
|
||||||
.get(&(underlay.source_page as u32 + 1))
|
.get(&(underlay.source_page as u32 + 1))
|
||||||
.ok_or_else(|| format!("Seite {} fehlt im Quell-PDF", underlay.source_page + 1))?;
|
.ok_or_else(|| {
|
||||||
|
t!(
|
||||||
|
"Seite {number} fehlt im Quell-PDF",
|
||||||
|
number = underlay.source_page + 1
|
||||||
|
)
|
||||||
|
})?;
|
||||||
let target_page = *target_pages
|
let target_page = *target_pages
|
||||||
.get(underlay.target_page)
|
.get(underlay.target_page)
|
||||||
.ok_or_else(|| "Zielseite fehlt".to_string())?;
|
.ok_or_else(|| t!("Zielseite fehlt").to_string())?;
|
||||||
let (form, matrix) = page_as_form(&target, source_page, underlay.rect)?;
|
let (form, matrix) = page_as_form(&target, source_page, underlay.rect)?;
|
||||||
let form_id = target.add_object(Object::Stream(form));
|
let form_id = target.add_object(Object::Stream(form));
|
||||||
let name = format!("InkPdf{}", form_id.0);
|
let name = format!("InkPdf{}", form_id.0);
|
||||||
|
|||||||
+138
-10
@@ -7,6 +7,7 @@ use std::f32::consts::FRAC_PI_2;
|
|||||||
|
|
||||||
use crate::canvas::CanvasState;
|
use crate::canvas::CanvasState;
|
||||||
use crate::document::{Aabb, Page, Stroke};
|
use crate::document::{Aabb, Page, Stroke};
|
||||||
|
use crate::t;
|
||||||
|
|
||||||
/// Status des aktiven Ziehvorgangs (Drag-Operation) mit der Maus oder dem Stylus.
|
/// Status des aktiven Ziehvorgangs (Drag-Operation) mit der Maus oder dem Stylus.
|
||||||
#[derive(Debug, Clone, PartialEq, Default)]
|
#[derive(Debug, Clone, PartialEq, Default)]
|
||||||
@@ -35,9 +36,34 @@ pub enum DragMode {
|
|||||||
start_pos_page: Vec2,
|
start_pos_page: Vec2,
|
||||||
initial_box_size: Vec2,
|
initial_box_size: Vec2,
|
||||||
initial_strokes: Vec<Stroke>,
|
initial_strokes: Vec<Stroke>,
|
||||||
|
/// Seitenverhältnis beibehalten (Schloss der Auswahl oder Shift gedrückt)
|
||||||
|
keep_aspect: bool,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Skalierungsfaktoren, wenn der Eckgriff von `start` (relativ zur festen Ecke `fixed`)
|
||||||
|
/// nach `current` gezogen wird. Mit `keep_aspect` wird gleichmäßig skaliert: der Faktor ist
|
||||||
|
/// die Projektion der Zugposition auf die Diagonale, damit das Seitenverhältnis bleibt.
|
||||||
|
pub fn scale_factors(fixed: Vec2, start: Vec2, current: Vec2, keep_aspect: bool) -> Vec2 {
|
||||||
|
let orig = start - fixed;
|
||||||
|
let new = current - fixed;
|
||||||
|
if keep_aspect {
|
||||||
|
let len_sq = orig.length_squared();
|
||||||
|
if len_sq <= 1.0 {
|
||||||
|
return Vec2::ONE;
|
||||||
|
}
|
||||||
|
return Vec2::splat((new.dot(orig) / len_sq).clamp(0.05, 20.0));
|
||||||
|
}
|
||||||
|
let factor = |n: f32, o: f32| {
|
||||||
|
if o.abs() > 1.0 {
|
||||||
|
(n / o).clamp(0.05, 20.0)
|
||||||
|
} else {
|
||||||
|
1.0
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Vec2::new(factor(new.x, orig.x), factor(new.y, orig.y))
|
||||||
|
}
|
||||||
|
|
||||||
/// Ergebnis eines Hit-Tests auf Auswahl-Griffe (Handles).
|
/// Ergebnis eines Hit-Tests auf Auswahl-Griffe (Handles).
|
||||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||||
pub enum SelectionHandleHit {
|
pub enum SelectionHandleHit {
|
||||||
@@ -62,7 +88,13 @@ pub enum SelectionHandleHit {
|
|||||||
pub struct SelectionState {
|
pub struct SelectionState {
|
||||||
pub selected_ids: Vec<u64>,
|
pub selected_ids: Vec<u64>,
|
||||||
pub drag_mode: DragMode,
|
pub drag_mode: DragMode,
|
||||||
|
/// Letzte Zugposition, die noch nicht angewendet ist: Der Stift meldet sich öfter, als
|
||||||
|
/// gezeichnet wird; angewendet wird einmal je Bild (siehe `flush_selection_drag`).
|
||||||
|
pub pending_drag: Option<Vec2>,
|
||||||
pub clipboard: Vec<Stroke>,
|
pub clipboard: Vec<Stroke>,
|
||||||
|
/// Von Hand umgeschaltetes Seitenverhältnis-Schloss und die Auswahl (IDs), für die es
|
||||||
|
/// gilt. Ändert sich die Auswahl, gilt wieder die Vorgabe (siehe [`Self::keeps_aspect`]).
|
||||||
|
aspect_lock: Option<(Vec<u64>, bool)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SelectionState {
|
impl SelectionState {
|
||||||
@@ -70,10 +102,31 @@ impl SelectionState {
|
|||||||
Self {
|
Self {
|
||||||
selected_ids: Vec::new(),
|
selected_ids: Vec::new(),
|
||||||
drag_mode: DragMode::None,
|
drag_mode: DragMode::None,
|
||||||
|
pending_drag: None,
|
||||||
clipboard: Vec::new(),
|
clipboard: Vec::new(),
|
||||||
|
aspect_lock: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Ob Skalieren an den Eckgriffen das Seitenverhältnis der Auswahl beibehält. Vorgabe:
|
||||||
|
/// ja, sobald ein Bild ausgewählt ist (Issue #29); per Knopf für diese Auswahl umschaltbar.
|
||||||
|
pub fn keeps_aspect(&self, page: &Page) -> bool {
|
||||||
|
match &self.aspect_lock {
|
||||||
|
Some((ids, locked)) if *ids == self.selected_ids => *locked,
|
||||||
|
// Läuft bei jedem Bild: erst die (wenigen) Bilder suchen, ohne Striche zu kopieren
|
||||||
|
_ => page
|
||||||
|
.strokes
|
||||||
|
.iter()
|
||||||
|
.any(|s| s.is_image() && self.selected_ids.contains(&s.id)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Schaltet das Seitenverhältnis-Schloss der aktuellen Auswahl um.
|
||||||
|
pub fn toggle_aspect_lock(&mut self, page: &Page) {
|
||||||
|
let locked = !self.keeps_aspect(page);
|
||||||
|
self.aspect_lock = Some((self.selected_ids.clone(), locked));
|
||||||
|
}
|
||||||
|
|
||||||
/// Prüft, ob aktuell Objekte ausgewählt sind.
|
/// Prüft, ob aktuell Objekte ausgewählt sind.
|
||||||
pub fn is_empty(&self) -> bool {
|
pub fn is_empty(&self) -> bool {
|
||||||
self.selected_ids.is_empty()
|
self.selected_ids.is_empty()
|
||||||
@@ -111,8 +164,13 @@ impl SelectionState {
|
|||||||
|
|
||||||
/// Berechnet die gemeinsame AABB aller ausgewählten Objekte.
|
/// Berechnet die gemeinsame AABB aller ausgewählten Objekte.
|
||||||
pub fn get_selection_aabb(&self, page: &Page) -> Option<Aabb> {
|
pub fn get_selection_aabb(&self, page: &Page) -> Option<Aabb> {
|
||||||
let strokes = page.get_strokes(&self.selected_ids);
|
// Läuft bei jedem Bild: ohne die ausgewählten Striche zu kopieren
|
||||||
Page::selection_aabb(&strokes)
|
let ids: std::collections::HashSet<u64> = self.selected_ids.iter().copied().collect();
|
||||||
|
page.strokes
|
||||||
|
.iter()
|
||||||
|
.filter(|s| ids.contains(&s.id))
|
||||||
|
.map(|s| s.aabb)
|
||||||
|
.reduce(|a, b| a.union(&b))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Führt Hit-Testing auf die Auswahlgriffe (Drehen, Ecken, Körper) in Bildschirmkoordinaten
|
/// Führt Hit-Testing auf die Auswahlgriffe (Drehen, Ecken, Körper) in Bildschirmkoordinaten
|
||||||
@@ -404,15 +462,14 @@ pub fn render_selection_overlay(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Kleines Info-Badge an der Unterkante (z. B. "2 Objekte | [R] Drehen [Entf] Löschen")
|
// Kleines Info-Badge an der Unterkante (z. B. "2 Objekte | [R] Drehen [Entf] Löschen")
|
||||||
let badge_text = format!(
|
let badge_text = if selection.count() == 1 {
|
||||||
"{} {} | [R] Drehen [Entf] Löschen",
|
t!("1 Objekt | [R] Drehen [Entf] Löschen").to_string()
|
||||||
selection.count(),
|
|
||||||
if selection.count() == 1 {
|
|
||||||
"Objekt"
|
|
||||||
} else {
|
} else {
|
||||||
"Objekte"
|
t!(
|
||||||
}
|
"{count} Objekte | [R] Drehen [Entf] Löschen",
|
||||||
);
|
count = selection.count()
|
||||||
|
)
|
||||||
|
};
|
||||||
let badge_pos = egui::pos2(rect.center().x, rect.max.y + 16.0);
|
let badge_pos = egui::pos2(rect.center().x, rect.max.y + 16.0);
|
||||||
painter.text(
|
painter.text(
|
||||||
badge_pos,
|
badge_pos,
|
||||||
@@ -523,6 +580,77 @@ mod tests {
|
|||||||
assert!((orig_pos.x - restored_pos.x).abs() < 1e-4);
|
assert!((orig_pos.x - restored_pos.x).abs() < 1e-4);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_scale_factors_free_and_keep_aspect() {
|
||||||
|
let fixed = Vec2::new(0.0, 0.0);
|
||||||
|
let start = Vec2::new(200.0, 100.0);
|
||||||
|
// Frei: Breite und Höhe unabhängig
|
||||||
|
let free = scale_factors(fixed, start, Vec2::new(400.0, 100.0), false);
|
||||||
|
assert_eq!(free, Vec2::new(2.0, 1.0));
|
||||||
|
// Seitenverhältnis fest: gleicher Faktor in beiden Richtungen
|
||||||
|
let locked = scale_factors(fixed, start, Vec2::new(400.0, 100.0), true);
|
||||||
|
assert!((locked.x - locked.y).abs() < 1e-6);
|
||||||
|
assert!((locked.x - 1.8).abs() < 1e-4);
|
||||||
|
// Entlang der Diagonale genau verdoppelt
|
||||||
|
let diag = scale_factors(fixed, start, Vec2::new(400.0, 200.0), true);
|
||||||
|
assert!((diag - Vec2::splat(2.0)).length() < 1e-5);
|
||||||
|
// Über die feste Ecke hinaus: kein Spiegeln
|
||||||
|
let past = scale_factors(fixed, start, Vec2::new(-50.0, -50.0), true);
|
||||||
|
assert_eq!(past, Vec2::splat(0.05));
|
||||||
|
// Senkrechte Linie (Breite 0): frei bleibt x unverändert, fest skaliert beides
|
||||||
|
let line = Vec2::new(0.0, 100.0);
|
||||||
|
assert_eq!(
|
||||||
|
scale_factors(fixed, line, Vec2::new(30.0, 200.0), false),
|
||||||
|
Vec2::new(1.0, 2.0)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
scale_factors(fixed, line, Vec2::new(30.0, 200.0), true),
|
||||||
|
Vec2::splat(2.0)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_aspect_lock_defaults_to_images_and_toggles_per_selection() {
|
||||||
|
let mut page = Page::new(1, PageBackground::Blank);
|
||||||
|
let corners = [
|
||||||
|
Vec2::new(0.0, 0.0),
|
||||||
|
Vec2::new(100.0, 0.0),
|
||||||
|
Vec2::new(100.0, 50.0),
|
||||||
|
Vec2::new(0.0, 50.0),
|
||||||
|
];
|
||||||
|
page.add_stroke(Stroke::new_image(1, "a.png".into(), corners));
|
||||||
|
page.add_stroke(make_test_stroke(2, 200.0, 200.0, [0.1, 0.1, 0.1, 1.0]));
|
||||||
|
let mut sel = SelectionState::new();
|
||||||
|
|
||||||
|
// Vorgabe: Bilder gesperrt, Striche frei
|
||||||
|
sel.select_single(1);
|
||||||
|
assert!(sel.keeps_aspect(&page));
|
||||||
|
sel.select_single(2);
|
||||||
|
assert!(!sel.keeps_aspect(&page));
|
||||||
|
|
||||||
|
// Umschalten gilt für diese Auswahl
|
||||||
|
sel.toggle_aspect_lock(&page);
|
||||||
|
assert!(sel.keeps_aspect(&page));
|
||||||
|
sel.select_single(1);
|
||||||
|
sel.toggle_aspect_lock(&page);
|
||||||
|
assert!(!sel.keeps_aspect(&page));
|
||||||
|
sel.toggle_aspect_lock(&page);
|
||||||
|
assert!(sel.keeps_aspect(&page));
|
||||||
|
sel.toggle_aspect_lock(&page);
|
||||||
|
|
||||||
|
// Neue Auswahl: wieder die Vorgabe
|
||||||
|
sel.select_multiple(vec![1, 2]);
|
||||||
|
assert!(sel.keeps_aspect(&page));
|
||||||
|
sel.select_single(1);
|
||||||
|
assert!(
|
||||||
|
!sel.keeps_aspect(&page),
|
||||||
|
"gleiche Auswahl behält das Umschalten"
|
||||||
|
);
|
||||||
|
sel.clear();
|
||||||
|
sel.select_single(1);
|
||||||
|
assert!(!sel.keeps_aspect(&page));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_recolor_ignores_images() {
|
fn test_recolor_ignores_images() {
|
||||||
let mut page = Page::new(1, PageBackground::Blank);
|
let mut page = Page::new(1, PageBackground::Blank);
|
||||||
|
|||||||
+13
-6
@@ -7,7 +7,9 @@ use std::path::{Path, PathBuf};
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::background::{PaperTheme, PatternColor};
|
use crate::background::{PaperTheme, PatternColor};
|
||||||
|
use crate::i18n::Language;
|
||||||
use crate::storage::{self, StorageError};
|
use crate::storage::{self, StorageError};
|
||||||
|
use crate::t;
|
||||||
|
|
||||||
/// Fensterseite, an der die Werkzeugleiste angedockt ist.
|
/// Fensterseite, an der die Werkzeugleiste angedockt ist.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||||
@@ -177,11 +179,11 @@ impl StylusAction {
|
|||||||
|
|
||||||
pub fn label(self) -> &'static str {
|
pub fn label(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
StylusAction::Erase => "Radieren",
|
StylusAction::Erase => t!("Radieren"),
|
||||||
StylusAction::Select => "Auswählen",
|
StylusAction::Select => t!("Auswählen"),
|
||||||
StylusAction::Highlighter => "Textmarker",
|
StylusAction::Highlighter => t!("Textmarker"),
|
||||||
StylusAction::Pen => "Stift",
|
StylusAction::Pen => t!("Stift"),
|
||||||
StylusAction::Nothing => "Nichts",
|
StylusAction::Nothing => t!("Nichts"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -210,7 +212,8 @@ pub struct UiSettings {
|
|||||||
pub pattern_color: PatternColor,
|
pub pattern_color: PatternColor,
|
||||||
/// Druckkennlinie des Stifts
|
/// Druckkennlinie des Stifts
|
||||||
pub pressure_curve: PressureCurve,
|
pub pressure_curve: PressureCurve,
|
||||||
/// Seiten durchgehend untereinander anzeigen (sonst einzeln blättern)
|
/// Frühere globale Einstellung „Seiten durchgehend scrollen“: gilt nur noch für Notizbücher
|
||||||
|
/// ohne eigene Anordnung im Manifest (vor 0.28 angelegt), wird nicht mehr geändert
|
||||||
pub continuous_scroll: bool,
|
pub continuous_scroll: bool,
|
||||||
/// Stifte der Werkzeugleiste und der gewählte davon
|
/// Stifte der Werkzeugleiste und der gewählte davon
|
||||||
pub pen_presets: [PenPreset; PEN_PRESET_COUNT],
|
pub pen_presets: [PenPreset; PEN_PRESET_COUNT],
|
||||||
@@ -222,6 +225,8 @@ pub struct UiSettings {
|
|||||||
pub active_text_color: usize,
|
pub active_text_color: usize,
|
||||||
/// Tasten am Stift in der Reihenfolge, in der sie zuerst gedrückt wurden
|
/// Tasten am Stift in der Reihenfolge, in der sie zuerst gedrückt wurden
|
||||||
pub stylus_buttons: Vec<StylusButton>,
|
pub stylus_buttons: Vec<StylusButton>,
|
||||||
|
/// Sprache der Oberfläche; ohne Angabe die des Systems
|
||||||
|
pub language: Option<Language>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for UiSettings {
|
impl Default for UiSettings {
|
||||||
@@ -240,6 +245,7 @@ impl Default for UiSettings {
|
|||||||
text_colors: DEFAULT_TEXT_COLORS,
|
text_colors: DEFAULT_TEXT_COLORS,
|
||||||
active_text_color: 0,
|
active_text_color: 0,
|
||||||
stylus_buttons: Vec::new(),
|
stylus_buttons: Vec::new(),
|
||||||
|
language: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -338,6 +344,7 @@ mod tests {
|
|||||||
action: StylusAction::Nothing,
|
action: StylusAction::Nothing,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
language: Some(Language::English),
|
||||||
};
|
};
|
||||||
settings.save_to(&path).unwrap();
|
settings.save_to(&path).unwrap();
|
||||||
assert_eq!(UiSettings::load_from(&path), settings);
|
assert_eq!(UiSettings::load_from(&path), settings);
|
||||||
|
|||||||
+63
-2
@@ -601,6 +601,7 @@ pub fn generate_finalized_triangle_strip(
|
|||||||
|
|
||||||
// Runde Kappen fein genug unterteilt, dass sie auch stark vergrößert rund wirken
|
// Runde Kappen fein genug unterteilt, dass sie auch stark vergrößert rund wirken
|
||||||
const CAP_STEPS: usize = 10;
|
const CAP_STEPS: usize = 10;
|
||||||
|
const CORNER_STEPS: usize = 24;
|
||||||
let mut vertices = Vec::new();
|
let mut vertices = Vec::new();
|
||||||
|
|
||||||
// 3. Runde Start-Kappe vor dem ersten Run
|
// 3. Runde Start-Kappe vor dem ersten Run
|
||||||
@@ -622,12 +623,22 @@ pub fn generate_finalized_triangle_strip(
|
|||||||
// 4. Runs und Ecken-Übergänge verbinden
|
// 4. Runs und Ecken-Übergänge verbinden
|
||||||
for (run_idx, run) in runs.iter().enumerate() {
|
for (run_idx, run) in runs.iter().enumerate() {
|
||||||
if run_idx > 0 {
|
if run_idx > 0 {
|
||||||
// Ecken-Verbindung: Nahtlose C0-Verbindung am Knick
|
// Runde Ecken-Verbindung: Ein voller Kreis um den Knick füllt die Außenseite, sonst
|
||||||
|
// enden beide Abschnitte stumpf und die Spitze (etwa einer „1“) wirkt abgeschnitten.
|
||||||
|
// Alle Dreiecke liegen im Kreis, auch die Übergänge zum vorigen und nächsten Run.
|
||||||
let s_corner = &run[0];
|
let s_corner = &run[0];
|
||||||
let p_c = s_corner.position;
|
let p_c = s_corner.position;
|
||||||
let pr_c = s_corner.pressure;
|
let pr_c = s_corner.pressure;
|
||||||
|
let r = s_corner.radius;
|
||||||
|
let prev_right = runs[run_idx - 1].last().map_or(s_corner.right, |s| s.right);
|
||||||
|
let d = prev_right - p_c;
|
||||||
|
let a0 = d.y.atan2(d.x);
|
||||||
|
for k in 0..=CORNER_STEPS {
|
||||||
|
let a = a0 + (k as f32 / CORNER_STEPS as f32) * std::f32::consts::TAU;
|
||||||
|
let rim = p_c + glam::Vec2::new(a.cos(), a.sin()) * r;
|
||||||
vertices.push(Vertex::new(p_c.x, p_c.y, pr_c, 0.0));
|
vertices.push(Vertex::new(p_c.x, p_c.y, pr_c, 0.0));
|
||||||
vertices.push(Vertex::new(p_c.x, p_c.y, pr_c, 0.0));
|
vertices.push(Vertex::new(rim.x, rim.y, pr_c, 1.0));
|
||||||
|
}
|
||||||
vertices.push(Vertex::new(s_corner.left.x, s_corner.left.y, pr_c, -1.0));
|
vertices.push(Vertex::new(s_corner.left.x, s_corner.left.y, pr_c, -1.0));
|
||||||
vertices.push(Vertex::new(s_corner.right.x, s_corner.right.y, pr_c, 1.0));
|
vertices.push(Vertex::new(s_corner.right.x, s_corner.right.y, pr_c, 1.0));
|
||||||
}
|
}
|
||||||
@@ -900,6 +911,56 @@ mod tests {
|
|||||||
assert!((corner_pt.position.y - 0.0).abs() < 1e-3);
|
assert!((corner_pt.position.y - 0.0).abs() < 1e-3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Liegt `p` in einem der Dreiecke des Triangle-Strips?
|
||||||
|
fn strip_covers(vertices: &[InkVertex], p: glam::Vec2) -> bool {
|
||||||
|
let pos = |v: &InkVertex| glam::Vec2::new(v.position[0], v.position[1]);
|
||||||
|
let cross = |a: glam::Vec2, b: glam::Vec2, c: glam::Vec2| (b - a).perp_dot(c - a);
|
||||||
|
vertices.windows(3).any(|t| {
|
||||||
|
let (a, b, c) = (pos(&t[0]), pos(&t[1]), pos(&t[2]));
|
||||||
|
let (d1, d2, d3) = (cross(a, b, p), cross(b, c, p), cross(c, a, p));
|
||||||
|
let neg = d1 < 0.0 || d2 < 0.0 || d3 < 0.0;
|
||||||
|
let pos = d1 > 0.0 || d2 > 0.0 || d3 > 0.0;
|
||||||
|
!(neg && pos)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_sharp_corner_tip_is_not_cut_off() {
|
||||||
|
// „1“: schräg hinauf bis (100, 0), dann senkrecht hinunter (Issue #33)
|
||||||
|
let mut raw = Vec::new();
|
||||||
|
for i in 0..=20 {
|
||||||
|
let u = i as f32 / 20.0;
|
||||||
|
raw.push(StylusSample {
|
||||||
|
position: glam::Vec2::new(60.0 + 40.0 * u, 80.0 - 80.0 * u),
|
||||||
|
pressure: 0.5,
|
||||||
|
timestamp: i as f64 * 0.01,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for i in 1..=30 {
|
||||||
|
raw.push(StylusSample {
|
||||||
|
position: glam::Vec2::new(100.0, i as f32 * 5.0),
|
||||||
|
pressure: 0.5,
|
||||||
|
timestamp: (20 + i) as f64 * 0.01,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let config = SplineConfig::from_width_units(10.0);
|
||||||
|
let stroke = finalize_stroke_with_config(1, &raw, [0.0; 4], &config);
|
||||||
|
assert_eq!(
|
||||||
|
detect_corners(&stroke.points, CORNER_ANGLE_THRESHOLD_DEG).len(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
// Die Spitze reicht rund um den Knick so weit wie die Strichbreite
|
||||||
|
let r = calculate_radius(0.5, config.min_radius, config.max_radius) * 0.95;
|
||||||
|
for deg in [-150.0_f32, -120.0, -90.0, -60.0, -30.0, 0.0] {
|
||||||
|
let a = deg.to_radians();
|
||||||
|
let p = glam::Vec2::new(100.0, 0.0) + glam::Vec2::new(a.cos(), a.sin()) * r;
|
||||||
|
assert!(
|
||||||
|
strip_covers(&stroke.vertices, p),
|
||||||
|
"Spitze bei {deg}° abgeschnitten"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_small_loops_stay_round() {
|
fn test_small_loops_stay_round() {
|
||||||
// Kleines „o“ (Radius 0,8 mm) in 0,1 s mit 200 Hz, mit Vorschub wie im Wort
|
// Kleines „o“ (Radius 0,8 mm) in 0,1 s mit 200 Hz, mit Vorschub wie im Wort
|
||||||
|
|||||||
+127
-49
@@ -15,6 +15,7 @@ use crate::document::{
|
|||||||
};
|
};
|
||||||
use crate::filter::OneEuroFilter;
|
use crate::filter::OneEuroFilter;
|
||||||
use crate::spline::{self, ControlPoint, SplineConfig};
|
use crate::spline::{self, ControlPoint, SplineConfig};
|
||||||
|
use crate::t;
|
||||||
|
|
||||||
/// Serialisierbarer Stylus-Abtastpunkt in DIN-A4-Koordinaten.
|
/// Serialisierbarer Stylus-Abtastpunkt in DIN-A4-Koordinaten.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||||
@@ -167,7 +168,9 @@ impl StrokeData {
|
|||||||
/// - Version 6: Seitentitel (`title` in Seite und Manifest).
|
/// - Version 6: Seitentitel (`title` in Seite und Manifest).
|
||||||
/// - Version 7: Textfelder (`text` am Strich).
|
/// - Version 7: Textfelder (`text` am Strich).
|
||||||
/// - Version 8: Seitengröße je Seite (`size` in Seite und Manifest), Querformat für Folien.
|
/// - Version 8: Seitengröße je Seite (`size` in Seite und Manifest), Querformat für Folien.
|
||||||
pub const CURRENT_FORMAT_VERSION: u32 = 8;
|
/// - Version 9: endlose Notizbücher (`layout: "Endless"` im Manifest, eine Seite mit
|
||||||
|
/// `document::ENDLESS_PAGE_SIZE`). Ältere Versionen würden sie als riesige Seite öffnen.
|
||||||
|
pub const CURRENT_FORMAT_VERSION: u32 = 9;
|
||||||
|
|
||||||
/// Standardwert für ältere Dateien ohne explizite Formatversion (Legacy v0).
|
/// Standardwert für ältere Dateien ohne explizite Formatversion (Legacy v0).
|
||||||
pub fn legacy_format_version() -> u32 {
|
pub fn legacy_format_version() -> u32 {
|
||||||
@@ -199,8 +202,12 @@ fn stored_size(size: glam::Vec2) -> Option<[f32; 2]> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Seitengröße aus einer (evtl. von Hand bearbeiteten) Datei; unbrauchbare Werte ergeben A4.
|
/// Seitengröße aus einer (evtl. von Hand bearbeiteten) Datei; unbrauchbare Werte ergeben A4.
|
||||||
|
/// Höchstens 2 × 2 m – außer der endlosen Seite.
|
||||||
pub fn page_size_from(stored: Option<[f32; 2]>) -> glam::Vec2 {
|
pub fn page_size_from(stored: Option<[f32; 2]>) -> glam::Vec2 {
|
||||||
match stored {
|
match stored {
|
||||||
|
Some(size) if glam::Vec2::from(size) == crate::document::ENDLESS_PAGE_SIZE => {
|
||||||
|
crate::document::ENDLESS_PAGE_SIZE
|
||||||
|
}
|
||||||
Some([w, h]) if w.is_finite() && h.is_finite() && w >= 100.0 && h >= 100.0 => {
|
Some([w, h]) if w.is_finite() && h.is_finite() && w >= 100.0 && h >= 100.0 => {
|
||||||
glam::Vec2::new(w.min(20_000.0), h.min(20_000.0))
|
glam::Vec2::new(w.min(20_000.0), h.min(20_000.0))
|
||||||
}
|
}
|
||||||
@@ -279,9 +286,34 @@ pub struct NotebookManifest {
|
|||||||
pub page_ids: Vec<u64>,
|
pub page_ids: Vec<u64>,
|
||||||
pub next_stroke_id: u64,
|
pub next_stroke_id: u64,
|
||||||
pub next_page_id: u64,
|
pub next_page_id: u64,
|
||||||
|
/// Anordnung der Seiten. Fehlt bei Notizbüchern von vor 0.28; dann gilt die frühere
|
||||||
|
/// globale Einstellung `continuous_scroll` aus `ui.json` (siehe [`Self::layout_or`]).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub layout: Option<NotebookLayout>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Anordnung der Seiten eines Notizbuchs (Issue #30).
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||||
|
pub enum NotebookLayout {
|
||||||
|
/// Feste Seiten: Seite für Seite blättern
|
||||||
|
#[default]
|
||||||
|
Paged,
|
||||||
|
/// Seiten hängen untereinander und werden durchgehend gescrollt
|
||||||
|
Continuous,
|
||||||
|
/// Eine einzige, praktisch unbegrenzte Fläche (siehe `document::ENDLESS_PAGE_SIZE`)
|
||||||
|
Endless,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NotebookManifest {
|
impl NotebookManifest {
|
||||||
|
/// Anordnung des Notizbuchs; ohne eigene Angabe die frühere globale Einstellung.
|
||||||
|
pub fn layout_or(&self, legacy_continuous: bool) -> NotebookLayout {
|
||||||
|
self.layout.unwrap_or(if legacy_continuous {
|
||||||
|
NotebookLayout::Continuous
|
||||||
|
} else {
|
||||||
|
NotebookLayout::Paged
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
|
pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
|
||||||
let now = std::time::SystemTime::now()
|
let now = std::time::SystemTime::now()
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
@@ -298,6 +330,7 @@ impl NotebookManifest {
|
|||||||
page_ids: vec![1],
|
page_ids: vec![1],
|
||||||
next_stroke_id: 1,
|
next_stroke_id: 1,
|
||||||
next_page_id: 2,
|
next_page_id: 2,
|
||||||
|
layout: Some(NotebookLayout::Continuous),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -371,19 +404,30 @@ pub enum StorageError {
|
|||||||
impl fmt::Display for StorageError {
|
impl fmt::Display for StorageError {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
match self {
|
match self {
|
||||||
StorageError::Io(e) => write!(f, "I/O-Fehler: {e}"),
|
StorageError::Io(e) => f.write_str(&t!("I/O-Fehler: {e}", e = e)),
|
||||||
StorageError::Serialization(e) => write!(f, "Serialisierungsfehler: {e}"),
|
StorageError::Serialization(e) => {
|
||||||
StorageError::InvalidManifest(msg) => write!(f, "Ungültiges Manifest: {msg}"),
|
f.write_str(&t!("Serialisierungsfehler: {e}", e = e))
|
||||||
StorageError::CorruptedPage(id, msg) => {
|
}
|
||||||
write!(f, "Beschädigte Seite {id}: {msg}")
|
StorageError::InvalidManifest(msg) => {
|
||||||
|
f.write_str(&t!("Ungültiges Manifest: {msg}", msg = msg))
|
||||||
|
}
|
||||||
|
StorageError::CorruptedPage(id, msg) => {
|
||||||
|
f.write_str(&t!("Beschädigte Seite {id}: {msg}", id = id, msg = msg))
|
||||||
|
}
|
||||||
|
StorageError::PageNotFound(id) => {
|
||||||
|
f.write_str(&t!("Seite {id} nicht gefunden", id = id))
|
||||||
|
}
|
||||||
|
StorageError::UnsupportedVersion { found, supported } => f.write_str(&t!(
|
||||||
|
"Notizbuch wurde mit neuerer Version erstellt (Formatversion {found}, unterstützt wird bis {supported})",
|
||||||
|
found = found,
|
||||||
|
supported = supported
|
||||||
|
)),
|
||||||
|
StorageError::AlreadyLocked(msg) => {
|
||||||
|
f.write_str(&t!("Notizbuch ist gesperrt: {msg}", msg = msg))
|
||||||
|
}
|
||||||
|
StorageError::PathTraversal(msg) => {
|
||||||
|
f.write_str(&t!("Ungültiger Pfad (Path Traversal): {msg}", msg = msg))
|
||||||
}
|
}
|
||||||
StorageError::PageNotFound(id) => write!(f, "Seite {id} nicht gefunden"),
|
|
||||||
StorageError::UnsupportedVersion { found, supported } => write!(
|
|
||||||
f,
|
|
||||||
"Notizbuch wurde mit neuerer Version erstellt (Formatversion {found}, unterstützt wird bis {supported})"
|
|
||||||
),
|
|
||||||
StorageError::AlreadyLocked(msg) => write!(f, "Notizbuch ist gesperrt: {msg}"),
|
|
||||||
StorageError::PathTraversal(msg) => write!(f, "Ungültiger Pfad (Path Traversal): {msg}"),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -490,7 +534,7 @@ pub fn atomic_write_file(path: &Path, content: &[u8]) -> Result<(), io::Error> {
|
|||||||
let dir = path.parent().ok_or_else(|| {
|
let dir = path.parent().ok_or_else(|| {
|
||||||
io::Error::new(
|
io::Error::new(
|
||||||
io::ErrorKind::NotFound,
|
io::ErrorKind::NotFound,
|
||||||
"Übergeordnetes Verzeichnis nicht gefunden",
|
t!("Übergeordnetes Verzeichnis nicht gefunden"),
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
create_secure_dir_all(dir)?;
|
create_secure_dir_all(dir)?;
|
||||||
@@ -595,9 +639,9 @@ pub fn load_manifest(notebook_dir: &Path) -> Result<NotebookManifest, StorageErr
|
|||||||
eprintln!("[Storage-Warnung] manifest.json fehlt, lade aus manifest.json.bak");
|
eprintln!("[Storage-Warnung] manifest.json fehlt, lade aus manifest.json.bak");
|
||||||
return load_manifest_from_file(&bak_path);
|
return load_manifest_from_file(&bak_path);
|
||||||
}
|
}
|
||||||
return Err(StorageError::InvalidManifest(format!(
|
return Err(StorageError::InvalidManifest(t!(
|
||||||
"Manifestdatei nicht gefunden: {}",
|
"Manifestdatei nicht gefunden: {path}",
|
||||||
path.display()
|
path = path.display()
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -625,7 +669,7 @@ pub fn quarantine_corrupted_page(notebook_dir: &Path, page_id: u64) -> Result<Pa
|
|||||||
if !source_path.exists() {
|
if !source_path.exists() {
|
||||||
return Err(io::Error::new(
|
return Err(io::Error::new(
|
||||||
io::ErrorKind::NotFound,
|
io::ErrorKind::NotFound,
|
||||||
"Datei existiert nicht",
|
t!("Datei existiert nicht"),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let ts = std::time::SystemTime::now()
|
let ts = std::time::SystemTime::now()
|
||||||
@@ -764,7 +808,7 @@ pub fn load_notebook(notebook_dir: &Path) -> Result<(Notebook, NotebookManifest)
|
|||||||
first_id,
|
first_id,
|
||||||
PageLoadWarning {
|
PageLoadWarning {
|
||||||
page_id: first_id,
|
page_id: first_id,
|
||||||
message: format!("I/O-Fehler: {e}"),
|
message: t!("I/O-Fehler: {e}", e = e),
|
||||||
quarantine_path: None,
|
quarantine_path: None,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -876,7 +920,7 @@ pub fn ensure_page_loaded(
|
|||||||
page_id,
|
page_id,
|
||||||
PageLoadWarning {
|
PageLoadWarning {
|
||||||
page_id,
|
page_id,
|
||||||
message: format!("I/O-Fehler: {err_str}"),
|
message: t!("I/O-Fehler: {e}", e = err_str),
|
||||||
quarantine_path: None,
|
quarantine_path: None,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -970,9 +1014,9 @@ impl NotebookLock {
|
|||||||
Err(e) => {
|
Err(e) => {
|
||||||
let kind = e.kind();
|
let kind = e.kind();
|
||||||
if kind == io::ErrorKind::WouldBlock || e.raw_os_error() == Some(11) {
|
if kind == io::ErrorKind::WouldBlock || e.raw_os_error() == Some(11) {
|
||||||
Err(StorageError::AlreadyLocked(format!(
|
Err(StorageError::AlreadyLocked(t!(
|
||||||
"Notizbuch '{}' wird bereits von einer anderen Instanz verwendet",
|
"Notizbuch '{path}' wird bereits von einer anderen Instanz verwendet",
|
||||||
notebook_dir.display()
|
path = notebook_dir.display()
|
||||||
)))
|
)))
|
||||||
} else {
|
} else {
|
||||||
Err(StorageError::Io(e))
|
Err(StorageError::Io(e))
|
||||||
@@ -1058,7 +1102,7 @@ pub fn list_notebooks(base_dir: &Path) -> Vec<NotebookSummary> {
|
|||||||
|
|
||||||
list.push(NotebookSummary {
|
list.push(NotebookSummary {
|
||||||
id: dir_name.to_string(),
|
id: dir_name.to_string(),
|
||||||
title: format!("⚠️ {dir_name} (Beschädigt)"),
|
title: t!("⚠️ {name} (Beschädigt)", name = dir_name),
|
||||||
page_count: 0,
|
page_count: 0,
|
||||||
modified_at,
|
modified_at,
|
||||||
status: NotebookStatus::Damaged,
|
status: NotebookStatus::Damaged,
|
||||||
@@ -1077,11 +1121,11 @@ pub fn list_notebooks(base_dir: &Path) -> Vec<NotebookSummary> {
|
|||||||
|
|
||||||
list.push(NotebookSummary {
|
list.push(NotebookSummary {
|
||||||
id: dir_name.to_string(),
|
id: dir_name.to_string(),
|
||||||
title: format!("⚠️ {dir_name} (Beschädigt - kein Manifest)"),
|
title: t!("⚠️ {name} (Beschädigt - kein Manifest)", name = dir_name),
|
||||||
page_count: 0,
|
page_count: 0,
|
||||||
modified_at,
|
modified_at,
|
||||||
status: NotebookStatus::Damaged,
|
status: NotebookStatus::Damaged,
|
||||||
error: Some("Keine manifest.json vorhanden".to_string()),
|
error: Some(t!("Keine manifest.json vorhanden").to_string()),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1135,7 +1179,7 @@ pub fn create_new_notebook(
|
|||||||
if counter > 100 {
|
if counter > 100 {
|
||||||
return Err(StorageError::Io(io::Error::new(
|
return Err(StorageError::Io(io::Error::new(
|
||||||
io::ErrorKind::AlreadyExists,
|
io::ErrorKind::AlreadyExists,
|
||||||
"Konnte nach 100 Versuchen kein eindeutiges Notizbuch-Verzeichnis finden",
|
t!("Konnte nach 100 Versuchen kein eindeutiges Notizbuch-Verzeichnis finden"),
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1214,18 +1258,18 @@ pub fn rename_notebook(
|
|||||||
/// Prüft, dass der Pfad direkt unter `base_dir` liegt, kein Symlink ist und `manifest.json` enthält.
|
/// Prüft, dass der Pfad direkt unter `base_dir` liegt, kein Symlink ist und `manifest.json` enthält.
|
||||||
pub fn delete_notebook(notebook_dir: &Path, base_dir: &Path) -> Result<PathBuf, StorageError> {
|
pub fn delete_notebook(notebook_dir: &Path, base_dir: &Path) -> Result<PathBuf, StorageError> {
|
||||||
if !notebook_dir.exists() {
|
if !notebook_dir.exists() {
|
||||||
return Err(StorageError::InvalidManifest(format!(
|
return Err(StorageError::InvalidManifest(t!(
|
||||||
"Verzeichnis '{}' existiert nicht",
|
"Verzeichnis '{path}' existiert nicht",
|
||||||
notebook_dir.display()
|
path = notebook_dir.display()
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prüfen auf Symlink
|
// Prüfen auf Symlink
|
||||||
let symlink_meta = fs::symlink_metadata(notebook_dir).map_err(StorageError::Io)?;
|
let symlink_meta = fs::symlink_metadata(notebook_dir).map_err(StorageError::Io)?;
|
||||||
if symlink_meta.file_type().is_symlink() {
|
if symlink_meta.file_type().is_symlink() {
|
||||||
return Err(StorageError::InvalidManifest(format!(
|
return Err(StorageError::InvalidManifest(t!(
|
||||||
"Pfad '{}' ist ein Symlink und darf nicht gelöscht werden",
|
"Pfad '{path}' ist ein Symlink und darf nicht gelöscht werden",
|
||||||
notebook_dir.display()
|
path = notebook_dir.display()
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1234,18 +1278,18 @@ pub fn delete_notebook(notebook_dir: &Path, base_dir: &Path) -> Result<PathBuf,
|
|||||||
|
|
||||||
// Prüfen, dass der Pfad direkt unter base_dir liegt
|
// Prüfen, dass der Pfad direkt unter base_dir liegt
|
||||||
if canon_target.parent() != Some(&canon_base) {
|
if canon_target.parent() != Some(&canon_base) {
|
||||||
return Err(StorageError::PathTraversal(format!(
|
return Err(StorageError::PathTraversal(t!(
|
||||||
"Pfad '{}' liegt nicht direkt unter Basis-Verzeichnis '{}'",
|
"Pfad '{path}' liegt nicht direkt unter Basis-Verzeichnis '{base}'",
|
||||||
notebook_dir.display(),
|
path = notebook_dir.display(),
|
||||||
base_dir.display()
|
base = base_dir.display()
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prüfen, dass manifest.json vorhanden ist
|
// Prüfen, dass manifest.json vorhanden ist
|
||||||
if !canon_target.join("manifest.json").exists() {
|
if !canon_target.join("manifest.json").exists() {
|
||||||
return Err(StorageError::InvalidManifest(format!(
|
return Err(StorageError::InvalidManifest(t!(
|
||||||
"Verzeichnis '{}' enthält kein manifest.json",
|
"Verzeichnis '{path}' enthält kein manifest.json",
|
||||||
notebook_dir.display()
|
path = notebook_dir.display()
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1276,9 +1320,9 @@ pub fn restore_notebook_from_trash(
|
|||||||
if !trash_target.exists() {
|
if !trash_target.exists() {
|
||||||
return Err(StorageError::Io(io::Error::new(
|
return Err(StorageError::Io(io::Error::new(
|
||||||
io::ErrorKind::NotFound,
|
io::ErrorKind::NotFound,
|
||||||
format!(
|
t!(
|
||||||
"Papierkorb-Eintrag '{}' existiert nicht",
|
"Papierkorb-Eintrag '{path}' existiert nicht",
|
||||||
trash_target.display()
|
path = trash_target.display()
|
||||||
),
|
),
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
@@ -1289,7 +1333,7 @@ pub fn restore_notebook_from_trash(
|
|||||||
let expected_trash_dir = canon_base.join(".trash");
|
let expected_trash_dir = canon_base.join(".trash");
|
||||||
if !expected_trash_dir.exists() {
|
if !expected_trash_dir.exists() {
|
||||||
return Err(StorageError::InvalidManifest(
|
return Err(StorageError::InvalidManifest(
|
||||||
"Papierkorb-Verzeichnis existiert nicht".to_string(),
|
t!("Papierkorb-Verzeichnis existiert nicht").to_string(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let canon_trash_base = expected_trash_dir
|
let canon_trash_base = expected_trash_dir
|
||||||
@@ -1297,9 +1341,9 @@ pub fn restore_notebook_from_trash(
|
|||||||
.map_err(StorageError::Io)?;
|
.map_err(StorageError::Io)?;
|
||||||
|
|
||||||
if canon_trash.parent() != Some(&canon_trash_base) {
|
if canon_trash.parent() != Some(&canon_trash_base) {
|
||||||
return Err(StorageError::PathTraversal(format!(
|
return Err(StorageError::PathTraversal(t!(
|
||||||
"Papierkorb-Pfad '{}' liegt nicht im Papierkorb",
|
"Papierkorb-Pfad '{path}' liegt nicht im Papierkorb",
|
||||||
trash_target.display()
|
path = trash_target.display()
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1344,7 +1388,7 @@ pub fn restore_manifest_from_backup(notebook_dir: &Path) -> Result<(), StorageEr
|
|||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
Err(StorageError::InvalidManifest(
|
Err(StorageError::InvalidManifest(
|
||||||
"Keine Sicherungskopie (manifest.json.bak) vorhanden".to_string(),
|
t!("Keine Sicherungskopie (manifest.json.bak) vorhanden").to_string(),
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1387,7 +1431,7 @@ pub fn load_all_pages(notebook_dir: &Path, notebook: &mut Notebook) -> Result<()
|
|||||||
if page.persist == crate::document::PersistState::ReadOnlyAfterLoadError {
|
if page.persist == crate::document::PersistState::ReadOnlyAfterLoadError {
|
||||||
return Err(StorageError::CorruptedPage(
|
return Err(StorageError::CorruptedPage(
|
||||||
page.id,
|
page.id,
|
||||||
"Seite konnte nicht geladen werden".to_string(),
|
t!("Seite konnte nicht geladen werden").to_string(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if !page.is_loaded {
|
if !page.is_loaded {
|
||||||
@@ -1592,6 +1636,40 @@ mod tests {
|
|||||||
assert!(shutdown_res.is_ok());
|
assert!(shutdown_res.is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_notebook_layout_is_saved_and_old_manifests_fall_back() {
|
||||||
|
let temp_dir = tempfile::tempdir().unwrap();
|
||||||
|
let (_nb, mut manifest, dir) = create_new_notebook(temp_dir.path(), "Layout").unwrap();
|
||||||
|
// Neue Notizbücher: durchgehend, unabhängig von der früheren globalen Einstellung
|
||||||
|
assert_eq!(manifest.layout, Some(NotebookLayout::Continuous));
|
||||||
|
assert_eq!(manifest.layout_or(false), NotebookLayout::Continuous);
|
||||||
|
|
||||||
|
manifest.layout = Some(NotebookLayout::Paged);
|
||||||
|
save_manifest(&dir, &manifest).unwrap();
|
||||||
|
let (_nb, loaded) = load_notebook(&dir).unwrap();
|
||||||
|
assert_eq!(loaded.layout, Some(NotebookLayout::Paged));
|
||||||
|
|
||||||
|
// Manifest von vor 0.28 ohne `layout`: es gilt die globale Einstellung
|
||||||
|
let mut json: serde_json::Value =
|
||||||
|
serde_json::from_str(&fs::read_to_string(dir.join("manifest.json")).unwrap()).unwrap();
|
||||||
|
json.as_object_mut().unwrap().remove("layout");
|
||||||
|
let old: NotebookManifest = serde_json::from_value(json).unwrap();
|
||||||
|
assert_eq!(old.layout, None);
|
||||||
|
assert_eq!(old.layout_or(true), NotebookLayout::Continuous);
|
||||||
|
assert_eq!(old.layout_or(false), NotebookLayout::Paged);
|
||||||
|
// … und schreibt beim Speichern auch keins dazu
|
||||||
|
assert!(!serde_json::to_string(&old).unwrap().contains("\"layout\""));
|
||||||
|
|
||||||
|
// Endlos: die endlose Seite übersteht Speichern und Laden
|
||||||
|
let (mut nb, mut manifest, dir) = create_new_notebook(temp_dir.path(), "Endlos").unwrap();
|
||||||
|
assert!(nb.make_endless());
|
||||||
|
manifest.layout = Some(NotebookLayout::Endless);
|
||||||
|
save_notebook(&dir, &nb, &mut manifest).unwrap();
|
||||||
|
let (loaded_nb, loaded) = load_notebook(&dir).unwrap();
|
||||||
|
assert_eq!(loaded.layout, Some(NotebookLayout::Endless));
|
||||||
|
assert!(loaded_nb.is_endless());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_notebook_management() {
|
fn test_notebook_management() {
|
||||||
let temp_dir = tempfile::tempdir().expect("Konnte temporäres Verzeichnis nicht anlegen");
|
let temp_dir = tempfile::tempdir().expect("Konnte temporäres Verzeichnis nicht anlegen");
|
||||||
|
|||||||
+31
-2
@@ -10,6 +10,8 @@
|
|||||||
|
|
||||||
use std::sync::OnceLock;
|
use std::sync::OnceLock;
|
||||||
|
|
||||||
|
use crate::t;
|
||||||
|
|
||||||
use ab_glyph::{Font, FontRef, GlyphId, PxScale};
|
use ab_glyph::{Font, FontRef, GlyphId, PxScale};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
@@ -29,8 +31,8 @@ pub enum TextFont {
|
|||||||
impl TextFont {
|
impl TextFont {
|
||||||
pub fn label(self) -> &'static str {
|
pub fn label(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
TextFont::Sans => "Normal",
|
TextFont::Sans => t!("Normal"),
|
||||||
TextFont::Mono => "Code",
|
TextFont::Mono => t!("Code"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,6 +151,20 @@ impl TextBox {
|
|||||||
glam::Vec2::new(self.wrap_width.max(self.size), self.layout().height())
|
glam::Vec2::new(self.wrap_width.max(self.size), self.layout().height())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Width of the field while it is being edited: as wide as the longest line plus room for
|
||||||
|
/// the next character, at most the wrap width, so a new field starts short (Issue #34).
|
||||||
|
pub fn edit_width(&self) -> f32 {
|
||||||
|
let widest = self
|
||||||
|
.layout()
|
||||||
|
.lines
|
||||||
|
.iter()
|
||||||
|
.map(|line| line.width)
|
||||||
|
.fold(0.0, f32::max);
|
||||||
|
(widest + self.size)
|
||||||
|
.max(3.0 * self.size)
|
||||||
|
.min(self.wrap_width.max(self.size))
|
||||||
|
}
|
||||||
|
|
||||||
/// Setzt den Text mit Zeilenumbruch an Leerzeichen; zu lange Wörter werden zeichenweise
|
/// Setzt den Text mit Zeilenumbruch an Leerzeichen; zu lange Wörter werden zeichenweise
|
||||||
/// umbrochen, Zeilenumbrüche im Text bleiben erhalten.
|
/// umbrochen, Zeilenumbrüche im Text bleiben erhalten.
|
||||||
pub fn layout(&self) -> TextLayout {
|
pub fn layout(&self) -> TextLayout {
|
||||||
@@ -407,6 +423,19 @@ mod tests {
|
|||||||
TextBox::new(content.to_string(), 50.0, TextFont::Sans, wrap_width)
|
TextBox::new(content.to_string(), 50.0, TextFont::Sans, wrap_width)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_edit_width_grows_with_the_text() {
|
||||||
|
let empty = sample("", 1500.0);
|
||||||
|
assert!((empty.edit_width() - 150.0).abs() < 1e-3);
|
||||||
|
let short = sample("Hallo", 1500.0);
|
||||||
|
let longer = sample("Hallo Welt, wie geht es", 1500.0);
|
||||||
|
assert!(short.edit_width() < longer.edit_width());
|
||||||
|
assert!(longer.edit_width() < 1500.0);
|
||||||
|
// Long text wraps at the page edge and fills the full width
|
||||||
|
let long = sample(&"Wort ".repeat(100), 1500.0);
|
||||||
|
assert!((long.edit_width() - 1500.0).abs() < 1e-3);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_fonts_load() {
|
fn test_fonts_load() {
|
||||||
for font in [TextFont::Sans, TextFont::Mono] {
|
for font in [TextFont::Sans, TextFont::Mono] {
|
||||||
|
|||||||
+154
-72
@@ -23,6 +23,8 @@ use std::time::{Duration, Instant};
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
use crate::t;
|
||||||
|
|
||||||
/// Konfiguration für den Gitea-Update-Server.
|
/// Konfiguration für den Gitea-Update-Server.
|
||||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct UpdaterConfig {
|
pub struct UpdaterConfig {
|
||||||
@@ -59,13 +61,18 @@ impl Default for UpdaterConfig {
|
|||||||
impl UpdaterConfig {
|
impl UpdaterConfig {
|
||||||
/// Validiert die Server-URL auf Protokollsicherheit (erzwingt HTTPS).
|
/// Validiert die Server-URL auf Protokollsicherheit (erzwingt HTTPS).
|
||||||
pub fn validate_url(&self) -> Result<url::Url, String> {
|
pub fn validate_url(&self) -> Result<url::Url, String> {
|
||||||
let parsed = url::Url::parse(&self.server_url)
|
let parsed = url::Url::parse(&self.server_url).map_err(|e| {
|
||||||
.map_err(|e| format!("Ungültige Server-URL '{}': {e}", self.server_url))?;
|
t!(
|
||||||
|
"Ungültige Server-URL '{url}': {e}",
|
||||||
|
url = self.server_url,
|
||||||
|
e = e
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
if parsed.scheme() != "https" && !self.allow_insecure_http {
|
if parsed.scheme() != "https" && !self.allow_insecure_http {
|
||||||
return Err(format!(
|
return Err(t!(
|
||||||
"Unsicheres Protokoll '{}' abgewiesen. Es wird zwingend HTTPS verlangt (z. B. https://gitea.pansi.eu).",
|
"Unsicheres Protokoll '{scheme}' abgewiesen. Es wird zwingend HTTPS verlangt (z. B. https://gitea.pansi.eu).",
|
||||||
parsed.scheme()
|
scheme = parsed.scheme()
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
Ok(parsed)
|
Ok(parsed)
|
||||||
@@ -111,11 +118,20 @@ pub enum RuntimeEnvironment {
|
|||||||
DebPackage { binary_path: PathBuf },
|
DebPackage { binary_path: PathBuf },
|
||||||
/// Aus Quellcode / Entwicklungs-Binary (z.B. target/debug oder target/release)
|
/// Aus Quellcode / Entwicklungs-Binary (z.B. target/debug oder target/release)
|
||||||
PortableOrDev { binary_path: PathBuf },
|
PortableOrDev { binary_path: PathBuf },
|
||||||
|
/// Als Flatpak installiert: Updates kommen über die Software-Verwaltung, ink-notes lädt
|
||||||
|
/// selbst nichts herunter (Vorgabe von Flathub)
|
||||||
|
Flatpak,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RuntimeEnvironment {
|
impl RuntimeEnvironment {
|
||||||
/// Erkennt die aktuelle Laufzeitumgebung anhand der Umgebung und des Binärpfads.
|
/// Erkennt die aktuelle Laufzeitumgebung anhand der Umgebung und des Binärpfads.
|
||||||
pub fn detect() -> Self {
|
pub fn detect() -> Self {
|
||||||
|
if is_flatpak(
|
||||||
|
std::env::var("FLATPAK_ID").ok().as_deref(),
|
||||||
|
Path::new("/.flatpak-info").exists(),
|
||||||
|
) {
|
||||||
|
return RuntimeEnvironment::Flatpak;
|
||||||
|
}
|
||||||
let appimage_var = std::env::var("APPIMAGE").ok();
|
let appimage_var = std::env::var("APPIMAGE").ok();
|
||||||
let current_exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("ink-notes"));
|
let current_exe = std::env::current_exe().unwrap_or_else(|_| PathBuf::from("ink-notes"));
|
||||||
Self::detect_from(appimage_var.as_deref(), ¤t_exe)
|
Self::detect_from(appimage_var.as_deref(), ¤t_exe)
|
||||||
@@ -146,33 +162,47 @@ impl RuntimeEnvironment {
|
|||||||
|
|
||||||
pub fn display_name(&self) -> &'static str {
|
pub fn display_name(&self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
RuntimeEnvironment::AppImage { .. } => "AppImage (Portabel)",
|
RuntimeEnvironment::AppImage { .. } => t!("AppImage (Portabel)"),
|
||||||
RuntimeEnvironment::DebPackage { .. } => "System-Paket (.deb)",
|
RuntimeEnvironment::DebPackage { .. } => t!("System-Paket (.deb)"),
|
||||||
RuntimeEnvironment::PortableOrDev { .. } => "Entwicklung / Lokal",
|
RuntimeEnvironment::PortableOrDev { .. } => t!("Entwicklung / Lokal"),
|
||||||
|
RuntimeEnvironment::Flatpak => "Flatpak",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Ob ink-notes selbst nach Updates suchen und sie installieren darf
|
||||||
|
pub fn self_update_allowed(&self) -> bool {
|
||||||
|
!matches!(self, RuntimeEnvironment::Flatpak)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Läuft ink-notes in einer Flatpak-Sandbox (`FLATPAK_ID` gesetzt oder `/.flatpak-info`
|
||||||
|
/// vorhanden)?
|
||||||
|
pub fn is_flatpak(flatpak_id: Option<&str>, info_file_exists: bool) -> bool {
|
||||||
|
flatpak_id.is_some_and(|id| !id.trim().is_empty()) || info_file_exists
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Bereinigt und validiert einen Asset-Dateinamen gegen Path Traversal Angriffe.
|
/// Bereinigt und validiert einen Asset-Dateinamen gegen Path Traversal Angriffe.
|
||||||
pub fn sanitize_asset_name(raw_name: &str) -> Result<String, String> {
|
pub fn sanitize_asset_name(raw_name: &str) -> Result<String, String> {
|
||||||
let trimmed = raw_name.trim();
|
let trimmed = raw_name.trim();
|
||||||
if trimmed.is_empty() {
|
if trimmed.is_empty() {
|
||||||
return Err("Asset-Name darf nicht leer sein.".to_string());
|
return Err(t!("Asset-Name darf nicht leer sein.").to_string());
|
||||||
}
|
}
|
||||||
if trimmed.contains('/') || trimmed.contains('\\') || trimmed.contains("..") {
|
if trimmed.contains('/') || trimmed.contains('\\') || trimmed.contains("..") {
|
||||||
return Err(format!(
|
return Err(t!(
|
||||||
"Ungültiger Asset-Name (enthält unzulässige Pfadkomponenten): '{raw_name}'"
|
"Ungültiger Asset-Name (enthält unzulässige Pfadkomponenten): '{raw_name}'",
|
||||||
|
raw_name = raw_name
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let path = Path::new(trimmed);
|
let path = Path::new(trimmed);
|
||||||
let file_name = path
|
let file_name = path
|
||||||
.file_name()
|
.file_name()
|
||||||
.and_then(|n| n.to_str())
|
.and_then(|n| n.to_str())
|
||||||
.ok_or_else(|| format!("Ungültiger Dateiname: '{raw_name}'"))?;
|
.ok_or_else(|| t!("Ungültiger Dateiname: '{raw_name}'", raw_name = raw_name))?;
|
||||||
|
|
||||||
if file_name != trimmed || file_name.starts_with('.') {
|
if file_name != trimmed || file_name.starts_with('.') {
|
||||||
return Err(format!(
|
return Err(t!(
|
||||||
"Ungültiger oder versteckter Asset-Name: '{raw_name}'"
|
"Ungültiger oder versteckter Asset-Name: '{raw_name}'",
|
||||||
|
raw_name = raw_name
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
Ok(file_name.to_string())
|
Ok(file_name.to_string())
|
||||||
@@ -193,9 +223,10 @@ pub fn get_updates_cache_dir() -> Result<PathBuf, String> {
|
|||||||
|
|
||||||
let dir = base.join("ink-notes").join("updates");
|
let dir = base.join("ink-notes").join("updates");
|
||||||
std::fs::create_dir_all(&dir).map_err(|e| {
|
std::fs::create_dir_all(&dir).map_err(|e| {
|
||||||
format!(
|
t!(
|
||||||
"Konnte Update-Cache-Verzeichnis nicht anlegen ({}): {e}",
|
"Konnte Update-Cache-Verzeichnis nicht anlegen ({path}): {e}",
|
||||||
dir.display()
|
path = dir.display(),
|
||||||
|
e = e
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
@@ -210,7 +241,7 @@ pub fn get_updates_cache_dir() -> Result<PathBuf, String> {
|
|||||||
|
|
||||||
fn default_user_cache_dir() -> Result<PathBuf, String> {
|
fn default_user_cache_dir() -> Result<PathBuf, String> {
|
||||||
let home = std::env::var("HOME")
|
let home = std::env::var("HOME")
|
||||||
.map_err(|_| "HOME-Umgebungsvariable ist nicht gesetzt.".to_string())?;
|
.map_err(|_| t!("HOME-Umgebungsvariable ist nicht gesetzt.").to_string())?;
|
||||||
Ok(PathBuf::from(home).join(".cache"))
|
Ok(PathBuf::from(home).join(".cache"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -251,9 +282,10 @@ pub fn is_newer_version(remote_tag: &str, current_tag: &str, include_prereleases
|
|||||||
/// Berechnet den hex-kodierten SHA-256 Hash einer Datei.
|
/// Berechnet den hex-kodierten SHA-256 Hash einer Datei.
|
||||||
pub fn compute_sha256(path: &Path) -> Result<String, String> {
|
pub fn compute_sha256(path: &Path) -> Result<String, String> {
|
||||||
let mut file = std::fs::File::open(path).map_err(|e| {
|
let mut file = std::fs::File::open(path).map_err(|e| {
|
||||||
format!(
|
t!(
|
||||||
"Konnte Datei '{}' zur Prüfsummenberechnung nicht öffnen: {e}",
|
"Konnte Datei '{path}' zur Prüfsummenberechnung nicht öffnen: {e}",
|
||||||
path.display()
|
path = path.display(),
|
||||||
|
e = e
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
let mut hasher = Sha256::new();
|
let mut hasher = Sha256::new();
|
||||||
@@ -261,7 +293,7 @@ pub fn compute_sha256(path: &Path) -> Result<String, String> {
|
|||||||
loop {
|
loop {
|
||||||
let n = file
|
let n = file
|
||||||
.read(&mut buffer)
|
.read(&mut buffer)
|
||||||
.map_err(|e| format!("Fehler beim Lesen der Prüfsummendatei: {e}"))?;
|
.map_err(|e| t!("Fehler beim Lesen der Prüfsummendatei: {e}", e = e))?;
|
||||||
if n == 0 {
|
if n == 0 {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -300,15 +332,13 @@ pub fn verify_checksum(
|
|||||||
let checksums = parse_checksums(checksums_content);
|
let checksums = parse_checksums(checksums_content);
|
||||||
let expected_hash = checksums.get(asset_name).ok_or_else(|| {
|
let expected_hash = checksums.get(asset_name).ok_or_else(|| {
|
||||||
let _ = std::fs::remove_file(downloaded_path);
|
let _ = std::fs::remove_file(downloaded_path);
|
||||||
format!("Kein Eintrag für '{asset_name}' in SHA256SUMS.txt gefunden. Heruntergeladene Datei wurde gelöscht.")
|
t!("Kein Eintrag für '{asset_name}' in SHA256SUMS.txt gefunden. Heruntergeladene Datei wurde gelöscht.", asset_name = asset_name)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let actual_hash = compute_sha256(downloaded_path)?;
|
let actual_hash = compute_sha256(downloaded_path)?;
|
||||||
if !actual_hash.eq_ignore_ascii_case(expected_hash) {
|
if !actual_hash.eq_ignore_ascii_case(expected_hash) {
|
||||||
let _ = std::fs::remove_file(downloaded_path);
|
let _ = std::fs::remove_file(downloaded_path);
|
||||||
return Err(format!(
|
return Err(t!("Integritätsprüfung fehlgeschlagen für '{asset_name}': Erwartet {expected_hash}, berechnet {actual_hash}. Datei wurde gelöscht.", asset_name = asset_name, expected_hash = expected_hash, actual_hash = actual_hash));
|
||||||
"Integritätsprüfung fehlgeschlagen für '{asset_name}': Erwartet {expected_hash}, berechnet {actual_hash}. Datei wurde gelöscht."
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -334,15 +364,26 @@ pub fn verify_checksums_signature(
|
|||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
let key = public_key_b64.trim();
|
let key = public_key_b64.trim();
|
||||||
if key.is_empty() {
|
if key.is_empty() {
|
||||||
return Err("In dieser Version ist kein Signaturschlüssel für Updates hinterlegt. Bitte das Update manuell installieren.".to_string());
|
return Err(t!("In dieser Version ist kein Signaturschlüssel für Updates hinterlegt. Bitte das Update manuell installieren.").to_string());
|
||||||
}
|
}
|
||||||
let public_key = minisign_verify::PublicKey::from_base64(key)
|
let public_key = minisign_verify::PublicKey::from_base64(key)
|
||||||
.map_err(|e| format!("Ungültiger Update-Signaturschlüssel: {e}."))?;
|
.map_err(|e| t!("Ungültiger Update-Signaturschlüssel: {e}.", e = e))?;
|
||||||
let signature = minisign_verify::Signature::decode(signature_text)
|
let signature = minisign_verify::Signature::decode(signature_text).map_err(|e| {
|
||||||
.map_err(|e| format!("{CHECKSUMS_SIGNATURE_ASSET_NAME} ist ungültig: {e}."))?;
|
t!(
|
||||||
|
"{file} ist ungültig: {e}.",
|
||||||
|
file = CHECKSUMS_SIGNATURE_ASSET_NAME,
|
||||||
|
e = e
|
||||||
|
)
|
||||||
|
})?;
|
||||||
public_key
|
public_key
|
||||||
.verify(checksums, &signature, false)
|
.verify(checksums, &signature, false)
|
||||||
.map_err(|e| format!("Signaturprüfung von {CHECKSUMS_ASSET_NAME} fehlgeschlagen: {e}."))
|
.map_err(|e| {
|
||||||
|
t!(
|
||||||
|
"Signaturprüfung von {file} fehlgeschlagen: {e}.",
|
||||||
|
file = CHECKSUMS_ASSET_NAME,
|
||||||
|
e = e
|
||||||
|
)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Lädt einen Text-Asset des Releases über den abgesicherten HTTP-Client.
|
/// Lädt einen Text-Asset des Releases über den abgesicherten HTTP-Client.
|
||||||
@@ -356,7 +397,7 @@ fn fetch_release_text(
|
|||||||
.assets
|
.assets
|
||||||
.iter()
|
.iter()
|
||||||
.find(|a| a.name == name)
|
.find(|a| a.name == name)
|
||||||
.ok_or_else(|| format!("Release enthält keine {name}."))?;
|
.ok_or_else(|| t!("Release enthält keine {name}.", name = name))?;
|
||||||
http_get_with_auth_guard(
|
http_get_with_auth_guard(
|
||||||
agent,
|
agent,
|
||||||
&asset.browser_download_url,
|
&asset.browser_download_url,
|
||||||
@@ -364,9 +405,9 @@ fn fetch_release_text(
|
|||||||
5,
|
5,
|
||||||
config.allow_insecure_http,
|
config.allow_insecure_http,
|
||||||
)
|
)
|
||||||
.map_err(|e| format!("Konnte {name} nicht laden: {e}."))?
|
.map_err(|e| t!("Konnte {name} nicht laden: {e}.", name = name, e = e))?
|
||||||
.into_string()
|
.into_string()
|
||||||
.map_err(|e| format!("Konnte {name} nicht dekodieren: {e}."))
|
.map_err(|e| t!("Konnte {name} nicht dekodieren: {e}.", name = name, e = e))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Lädt `SHA256SUMS.txt` samt Minisign-Signatur und gibt den Inhalt nur bei gültiger
|
/// Lädt `SHA256SUMS.txt` samt Minisign-Signatur und gibt den Inhalt nur bei gültiger
|
||||||
@@ -429,9 +470,7 @@ fn ensure_secure_scheme(url: &url::Url, allow_insecure_http: bool) -> Result<(),
|
|||||||
match url.scheme() {
|
match url.scheme() {
|
||||||
"https" => Ok(()),
|
"https" => Ok(()),
|
||||||
"http" if allow_insecure_http => Ok(()),
|
"http" if allow_insecure_http => Ok(()),
|
||||||
scheme => Err(format!(
|
scheme => Err(t!("Unsicheres Protokoll '{scheme}' für '{url}' abgewiesen. Es wird zwingend HTTPS verlangt.", scheme = scheme, url = url)),
|
||||||
"Unsicheres Protokoll '{scheme}' für '{url}' abgewiesen. Es wird zwingend HTTPS verlangt."
|
|
||||||
)),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -453,8 +492,13 @@ fn http_get_with_auth_guard(
|
|||||||
max_redirects: usize,
|
max_redirects: usize,
|
||||||
allow_insecure_http: bool,
|
allow_insecure_http: bool,
|
||||||
) -> Result<ureq::Response, String> {
|
) -> Result<ureq::Response, String> {
|
||||||
let mut current_url = url::Url::parse(initial_url_str)
|
let mut current_url = url::Url::parse(initial_url_str).map_err(|e| {
|
||||||
.map_err(|e| format!("Ungültige URL '{initial_url_str}': {e}"))?;
|
t!(
|
||||||
|
"Ungültige URL '{initial_url_str}': {e}",
|
||||||
|
initial_url_str = initial_url_str,
|
||||||
|
e = e
|
||||||
|
)
|
||||||
|
})?;
|
||||||
let initial_origin = current_url.origin().ascii_serialization();
|
let initial_origin = current_url.origin().ascii_serialization();
|
||||||
|
|
||||||
for _ in 0..=max_redirects {
|
for _ in 0..=max_redirects {
|
||||||
@@ -476,24 +520,35 @@ fn http_get_with_auth_guard(
|
|||||||
Ok(resp) => return Ok(resp),
|
Ok(resp) => return Ok(resp),
|
||||||
Err(ureq::Error::Status(code, resp)) if (301..=308).contains(&code) => {
|
Err(ureq::Error::Status(code, resp)) if (301..=308).contains(&code) => {
|
||||||
let loc = resp.header("Location").ok_or_else(|| {
|
let loc = resp.header("Location").ok_or_else(|| {
|
||||||
format!("HTTP {code} Weiterleitung ohne Location-Header erhalten")
|
t!(
|
||||||
|
"HTTP {code} Weiterleitung ohne Location-Header erhalten",
|
||||||
|
code = code
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
current_url = current_url.join(loc).map_err(|e| {
|
||||||
|
t!(
|
||||||
|
"Ungültiges Weiterleitungsziel '{loc}': {e}",
|
||||||
|
loc = loc,
|
||||||
|
e = e
|
||||||
|
)
|
||||||
})?;
|
})?;
|
||||||
current_url = current_url
|
|
||||||
.join(loc)
|
|
||||||
.map_err(|e| format!("Ungültiges Weiterleitungsziel '{loc}': {e}"))?;
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
Err(ureq::Error::Status(code, resp)) => {
|
Err(ureq::Error::Status(code, resp)) => {
|
||||||
let body = resp.into_string().unwrap_or_default();
|
let body = resp.into_string().unwrap_or_default();
|
||||||
return Err(format!("Gitea-Server antwortete mit HTTP {code}: {body}"));
|
return Err(t!(
|
||||||
|
"Gitea-Server antwortete mit HTTP {code}: {body}",
|
||||||
|
code = code,
|
||||||
|
body = body
|
||||||
|
));
|
||||||
}
|
}
|
||||||
Err(ureq::Error::Transport(t)) => {
|
Err(ureq::Error::Transport(t)) => {
|
||||||
return Err(format!("Netzwerk-Transportfehler: {t}"));
|
return Err(t!("Netzwerk-Transportfehler: {t}", t = t));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Err("Zu viele Weiterleitungen (Redirect-Schleife abgebrochen).".to_string())
|
Err(t!("Zu viele Weiterleitungen (Redirect-Schleife abgebrochen).").to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Asynchroner Controller für Update-Prüfung und Asset-Download.
|
/// Asynchroner Controller für Update-Prüfung und Asset-Download.
|
||||||
@@ -544,6 +599,9 @@ impl UpdaterController {
|
|||||||
|
|
||||||
/// Fragt im Hintergrund die Gitea-API ab.
|
/// Fragt im Hintergrund die Gitea-API ab.
|
||||||
pub fn check_for_updates(&mut self) {
|
pub fn check_for_updates(&mut self) {
|
||||||
|
if !self.runtime.self_update_allowed() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
if matches!(
|
if matches!(
|
||||||
self.status,
|
self.status,
|
||||||
UpdaterStatus::Checking | UpdaterStatus::Downloading { .. }
|
UpdaterStatus::Checking | UpdaterStatus::Downloading { .. }
|
||||||
@@ -592,8 +650,9 @@ impl UpdaterController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let _ = tx.send(UpdaterEvent::CheckError(format!(
|
let _ = tx.send(UpdaterEvent::CheckError(t!(
|
||||||
"Gitea Release-JSON konnte nicht verarbeitet werden: {e}"
|
"Gitea Release-JSON konnte nicht verarbeitet werden: {e}",
|
||||||
|
e = e
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -649,15 +708,16 @@ impl UpdaterController {
|
|||||||
) {
|
) {
|
||||||
Ok(text) => text,
|
Ok(text) => text,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let _ = tx.send(UpdaterEvent::DownloadError(format!(
|
let _ = tx.send(UpdaterEvent::DownloadError(t!(
|
||||||
"{e} Download abgelehnt."
|
"{e} Download abgelehnt.",
|
||||||
|
e = e
|
||||||
)));
|
)));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
None => {
|
None => {
|
||||||
let _ = tx.send(UpdaterEvent::DownloadError(
|
let _ = tx.send(UpdaterEvent::DownloadError(
|
||||||
"Kein Release ausgewählt. Download abgelehnt.".to_string(),
|
t!("Kein Release ausgewählt. Download abgelehnt.").to_string(),
|
||||||
));
|
));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -673,8 +733,9 @@ impl UpdaterController {
|
|||||||
) {
|
) {
|
||||||
Ok(r) => r,
|
Ok(r) => r,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let _ = tx.send(UpdaterEvent::DownloadError(format!(
|
let _ = tx.send(UpdaterEvent::DownloadError(t!(
|
||||||
"Download-Verbindungsfehler: {e}"
|
"Download-Verbindungsfehler: {e}",
|
||||||
|
e = e
|
||||||
)));
|
)));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -686,9 +747,10 @@ impl UpdaterController {
|
|||||||
let mut file = match std::fs::File::create(&target_file) {
|
let mut file = match std::fs::File::create(&target_file) {
|
||||||
Ok(f) => f,
|
Ok(f) => f,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let _ = tx.send(UpdaterEvent::DownloadError(format!(
|
let _ = tx.send(UpdaterEvent::DownloadError(t!(
|
||||||
"Konnte Zieldatei '{}' nicht erstellen: {e}",
|
"Konnte Zieldatei '{path}' nicht erstellen: {e}",
|
||||||
target_file.display()
|
path = target_file.display(),
|
||||||
|
e = e
|
||||||
)));
|
)));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -705,8 +767,9 @@ impl UpdaterController {
|
|||||||
Ok(count) => count,
|
Ok(count) => count,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let _ = std::fs::remove_file(&target_file);
|
let _ = std::fs::remove_file(&target_file);
|
||||||
let _ = tx.send(UpdaterEvent::DownloadError(format!(
|
let _ = tx.send(UpdaterEvent::DownloadError(t!(
|
||||||
"Fehler beim Lesen des Download-Streams: {e}"
|
"Fehler beim Lesen des Download-Streams: {e}",
|
||||||
|
e = e
|
||||||
)));
|
)));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -714,8 +777,9 @@ impl UpdaterController {
|
|||||||
|
|
||||||
if let Err(e) = file.write_all(&buffer[..n]) {
|
if let Err(e) = file.write_all(&buffer[..n]) {
|
||||||
let _ = std::fs::remove_file(&target_file);
|
let _ = std::fs::remove_file(&target_file);
|
||||||
let _ = tx.send(UpdaterEvent::DownloadError(format!(
|
let _ = tx.send(UpdaterEvent::DownloadError(t!(
|
||||||
"Fehler beim Schreiben auf die Festplatte: {e}"
|
"Fehler beim Schreiben auf die Festplatte: {e}",
|
||||||
|
e = e
|
||||||
)));
|
)));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -776,18 +840,19 @@ impl UpdaterController {
|
|||||||
/// Startet die sichere Installation des heruntergeladenen Pakets oder öffnet es im System.
|
/// Startet die sichere Installation des heruntergeladenen Pakets oder öffnet es im System.
|
||||||
pub fn install_or_open(&self, file_path: &Path) -> Result<(), String> {
|
pub fn install_or_open(&self, file_path: &Path) -> Result<(), String> {
|
||||||
if !file_path.exists() {
|
if !file_path.exists() {
|
||||||
return Err("Die heruntergeladene Datei existiert nicht mehr.".to_string());
|
return Err(t!("Die heruntergeladene Datei existiert nicht mehr.").to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
match &self.runtime {
|
match &self.runtime {
|
||||||
RuntimeEnvironment::AppImage { appimage_path } => {
|
RuntimeEnvironment::AppImage { appimage_path } => {
|
||||||
let parent_dir = appimage_path.parent().ok_or_else(|| {
|
let parent_dir = appimage_path.parent().ok_or_else(|| {
|
||||||
"Konnte übergeordnetes Verzeichnis des AppImages nicht ermitteln.".to_string()
|
t!("Konnte übergeordnetes Verzeichnis des AppImages nicht ermitteln.")
|
||||||
|
.to_string()
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let file_name = appimage_path
|
let file_name = appimage_path
|
||||||
.file_name()
|
.file_name()
|
||||||
.ok_or_else(|| "Ungültiger AppImage-Dateiname.".to_string())?
|
.ok_or_else(|| t!("Ungültiger AppImage-Dateiname.").to_string())?
|
||||||
.to_string_lossy();
|
.to_string_lossy();
|
||||||
|
|
||||||
let temp_new_file =
|
let temp_new_file =
|
||||||
@@ -797,8 +862,9 @@ impl UpdaterController {
|
|||||||
// 1. Neue Datei im SELBEN Verzeichnis anlegen (garantiert atomares rename)
|
// 1. Neue Datei im SELBEN Verzeichnis anlegen (garantiert atomares rename)
|
||||||
if let Err(e) = std::fs::copy(file_path, &temp_new_file) {
|
if let Err(e) = std::fs::copy(file_path, &temp_new_file) {
|
||||||
let _ = std::fs::remove_file(&temp_new_file);
|
let _ = std::fs::remove_file(&temp_new_file);
|
||||||
return Err(format!(
|
return Err(t!(
|
||||||
"Konnte temporäre Update-Datei nicht schreiben: {e}"
|
"Konnte temporäre Update-Datei nicht schreiben: {e}",
|
||||||
|
e = e
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -816,18 +882,17 @@ impl UpdaterController {
|
|||||||
// 3. Backup des alten AppImages anlegen – Fehler NIEMALS ignorieren!
|
// 3. Backup des alten AppImages anlegen – Fehler NIEMALS ignorieren!
|
||||||
if let Err(e) = std::fs::copy(appimage_path, &backup_file) {
|
if let Err(e) = std::fs::copy(appimage_path, &backup_file) {
|
||||||
let _ = std::fs::remove_file(&temp_new_file);
|
let _ = std::fs::remove_file(&temp_new_file);
|
||||||
return Err(format!(
|
return Err(t!(
|
||||||
"Konnte Backup ({}) nicht anlegen: {e}. Update abgebrochen, altes AppImage unverändert.",
|
"Konnte Backup ({path}) nicht anlegen: {e}. Update abgebrochen, altes AppImage unverändert.",
|
||||||
backup_file.display()
|
path = backup_file.display(),
|
||||||
|
e = e
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Atomar ersetzen via rename
|
// 4. Atomar ersetzen via rename
|
||||||
if let Err(e) = std::fs::rename(&temp_new_file, appimage_path) {
|
if let Err(e) = std::fs::rename(&temp_new_file, appimage_path) {
|
||||||
let _ = std::fs::remove_file(&temp_new_file);
|
let _ = std::fs::remove_file(&temp_new_file);
|
||||||
return Err(format!(
|
return Err(t!("Konnte AppImage nicht atomar ersetzen: {e}. Altes AppImage bleibt unverändert.", e = e));
|
||||||
"Konnte AppImage nicht atomar ersetzen: {e}. Altes AppImage bleibt unverändert."
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Heruntergeladene Cache-Datei aufräumen
|
// Heruntergeladene Cache-Datei aufräumen
|
||||||
@@ -837,7 +902,7 @@ impl UpdaterController {
|
|||||||
RuntimeEnvironment::DebPackage { .. } => {
|
RuntimeEnvironment::DebPackage { .. } => {
|
||||||
match Command::new("xdg-open").arg(file_path).spawn() {
|
match Command::new("xdg-open").arg(file_path).spawn() {
|
||||||
Ok(_) => Ok(()),
|
Ok(_) => Ok(()),
|
||||||
Err(e) => Err(format!("Konnte xdg-open nicht ausführen: {e}")),
|
Err(e) => Err(t!("Konnte xdg-open nicht ausführen: {e}", e = e)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
RuntimeEnvironment::PortableOrDev { .. } => {
|
RuntimeEnvironment::PortableOrDev { .. } => {
|
||||||
@@ -846,6 +911,10 @@ impl UpdaterController {
|
|||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
RuntimeEnvironment::Flatpak => Err(t!(
|
||||||
|
"Die Flatpak-Version wird über die Software-Verwaltung aktualisiert."
|
||||||
|
)
|
||||||
|
.to_string()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1033,6 +1102,19 @@ dcdeb7ac87d9e6cb8022e5a71bc7f2c56d779b4fce4efdd5bae5be3b0214884a ink-notes_0.1.
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_flatpak_detection_disables_self_update() {
|
||||||
|
assert!(is_flatpak(Some("eu.pansi.ink-notes"), false));
|
||||||
|
assert!(is_flatpak(None, true));
|
||||||
|
assert!(!is_flatpak(Some(" "), false));
|
||||||
|
assert!(!is_flatpak(None, false));
|
||||||
|
assert!(!RuntimeEnvironment::Flatpak.self_update_allowed());
|
||||||
|
assert!(
|
||||||
|
RuntimeEnvironment::detect_from(None, Path::new("/usr/bin/ink-notes"))
|
||||||
|
.self_update_allowed()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_https_enforcement() {
|
fn test_https_enforcement() {
|
||||||
let config = UpdaterConfig {
|
let config = UpdaterConfig {
|
||||||
|
|||||||
+194
@@ -157,6 +157,24 @@ impl ViewportState {
|
|||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Endless page: shifts the view so that the screen point `corner` (top left of the free
|
||||||
|
/// area) shows nothing left of or above `limit`. `true` if the view was corrected.
|
||||||
|
pub fn clamp_top_left(
|
||||||
|
&mut self,
|
||||||
|
corner: [f32; 2],
|
||||||
|
limit: Vec2,
|
||||||
|
page_viewport: &PageViewport,
|
||||||
|
) -> bool {
|
||||||
|
let c = self.screen_to_page_unclamped(corner[0], corner[1], page_viewport);
|
||||||
|
let clamped = c.max(limit);
|
||||||
|
if (clamped - c).length() < 1e-3 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
self.pan_offset[0] += c.x - clamped.x;
|
||||||
|
self.pan_offset[1] += c.y - clamped.y;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
/// Passt den Pan-Offset um eine Bildschirmverschiebung (in Fensterpixeln) an.
|
/// Passt den Pan-Offset um eine Bildschirmverschiebung (in Fensterpixeln) an.
|
||||||
pub fn pan_by_screen_delta(
|
pub fn pan_by_screen_delta(
|
||||||
&mut self,
|
&mut self,
|
||||||
@@ -305,6 +323,102 @@ impl ViewportState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Schwung beim Scrollen mit dem Finger (Issue #28): Nach dem Abheben gleitet der
|
||||||
|
/// Ausschnitt mit der zuletzt gewischten Geschwindigkeit weiter und bremst langsam ab.
|
||||||
|
/// Geschwindigkeiten in Bildschirmpixeln je Sekunde.
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct Fling {
|
||||||
|
velocity: Vec2,
|
||||||
|
/// Fingerweg (aufsummiert) der letzten [`Self::WINDOW`] mit Zeitpunkt
|
||||||
|
trail: std::collections::VecDeque<(std::time::Instant, Vec2)>,
|
||||||
|
/// Zeit der letzten Fingerbewegung bzw. des letzten Gleitschritts
|
||||||
|
last: Option<std::time::Instant>,
|
||||||
|
active: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Fling {
|
||||||
|
/// Abbremsen je Sekunde (Anteil der Geschwindigkeit, der nach 1 s bleibt: e^-FRICTION)
|
||||||
|
const FRICTION: f32 = 2.5;
|
||||||
|
/// Langsamer wischen gleitet nicht nach
|
||||||
|
const MIN_START_SPEED: f32 = 250.0;
|
||||||
|
/// Darunter hört das Gleiten auf
|
||||||
|
const MIN_SPEED: f32 = 40.0;
|
||||||
|
/// Liegt der Finger vor dem Abheben so lange still, gleitet nichts nach
|
||||||
|
const MAX_REST: std::time::Duration = std::time::Duration::from_millis(120);
|
||||||
|
/// Die Geschwindigkeit ergibt sich aus dem Weg in dieser Zeit vor dem Abheben. Über
|
||||||
|
/// mehrere Ereignisse gemessen, weil Touchscreens kurz vor dem Abheben oft nur noch
|
||||||
|
/// winzige Bewegungen melden und Ereignisse gebündelt ankommen, wenn ein Bild länger
|
||||||
|
/// zum Zeichnen braucht.
|
||||||
|
const WINDOW: std::time::Duration = std::time::Duration::from_millis(100);
|
||||||
|
|
||||||
|
/// Finger hat sich um `delta` verschoben.
|
||||||
|
pub fn track(&mut self, delta: Vec2, now: std::time::Instant) {
|
||||||
|
self.active = false;
|
||||||
|
let pos = self.trail.back().map_or(Vec2::ZERO, |&(_, p)| p) + delta;
|
||||||
|
self.trail.push_back((now, pos));
|
||||||
|
// Einen Punkt vor dem Fenster behalten, damit es ganz abgedeckt ist
|
||||||
|
while self.trail.len() > 2 && now.duration_since(self.trail[1].0) > Self::WINDOW {
|
||||||
|
self.trail.pop_front();
|
||||||
|
}
|
||||||
|
if delta != Vec2::ZERO {
|
||||||
|
self.last = Some(now);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finger abgehoben: gleitet weiter, wenn zuletzt schnell genug gewischt wurde. Gibt die
|
||||||
|
/// gemessene Geschwindigkeit zurück (für die Fehlersuche).
|
||||||
|
pub fn release(&mut self, now: std::time::Instant) -> Vec2 {
|
||||||
|
let resting = self
|
||||||
|
.last
|
||||||
|
.is_none_or(|last| now.duration_since(last) > Self::MAX_REST);
|
||||||
|
self.velocity = match (self.trail.front(), self.trail.back()) {
|
||||||
|
(Some(&(t0, p0)), Some(&(_, p1))) => {
|
||||||
|
// Bis zum Abheben gemessen; gebündelte Ereignisse zählen mindestens 10 ms
|
||||||
|
let dt = now.duration_since(t0).as_secs_f32().max(0.01);
|
||||||
|
(p1 - p0) / dt
|
||||||
|
}
|
||||||
|
_ => Vec2::ZERO,
|
||||||
|
};
|
||||||
|
self.trail.clear();
|
||||||
|
let velocity = self.velocity;
|
||||||
|
self.active = !resting && velocity.length() >= Self::MIN_START_SPEED;
|
||||||
|
self.last = Some(now);
|
||||||
|
if !self.active {
|
||||||
|
self.stop();
|
||||||
|
}
|
||||||
|
velocity
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hält an (neue Berührung, Mausklick, Mausrad).
|
||||||
|
pub fn stop(&mut self) {
|
||||||
|
*self = Self::default();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_active(&self) -> bool {
|
||||||
|
self.active
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verschiebung (Bildschirmpixel) seit dem letzten Schritt; `None`, wenn nichts gleitet.
|
||||||
|
pub fn step(&mut self, now: std::time::Instant) -> Option<Vec2> {
|
||||||
|
if !self.active {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let dt = self
|
||||||
|
.last
|
||||||
|
.map_or(0.0, |last| now.duration_since(last).as_secs_f32())
|
||||||
|
.min(0.1);
|
||||||
|
self.last = Some(now);
|
||||||
|
// Exakt integriert, damit die Strecke nicht von der Bildrate abhängt
|
||||||
|
let decay = (-Self::FRICTION * dt).exp();
|
||||||
|
let delta = self.velocity * (1.0 - decay) / Self::FRICTION;
|
||||||
|
self.velocity *= decay;
|
||||||
|
if self.velocity.length() < Self::MIN_SPEED {
|
||||||
|
self.stop();
|
||||||
|
}
|
||||||
|
Some(delta)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -316,6 +430,64 @@ mod tests {
|
|||||||
PageStack::new(vec![A4; count], current)
|
PageStack::new(vec![A4; count], current)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_fling_glides_and_slows_down() {
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
let t0 = Instant::now();
|
||||||
|
let ms = |n: u64| t0 + Duration::from_millis(n);
|
||||||
|
let mut fling = Fling::default();
|
||||||
|
// Schnell nach oben wischen: 30 px alle 10 ms = 3000 px/s
|
||||||
|
for i in 0..=10 {
|
||||||
|
fling.track(Vec2::new(0.0, -30.0), ms(i * 10));
|
||||||
|
}
|
||||||
|
fling.release(ms(105));
|
||||||
|
assert!(fling.is_active());
|
||||||
|
let first = fling.step(ms(121)).unwrap();
|
||||||
|
assert!(first.y < -20.0, "{first:?}");
|
||||||
|
let mut total = first;
|
||||||
|
let mut t = 121;
|
||||||
|
while let Some(d) = fling.step(ms(t)) {
|
||||||
|
total += d;
|
||||||
|
t += 16;
|
||||||
|
assert!(t < 10_000, "gleitet endlos");
|
||||||
|
}
|
||||||
|
// Gleitet ungefähr v / FRICTION = 1200 px weiter, dann ist Schluss
|
||||||
|
assert!(total.y < -800.0 && total.y > -1300.0, "{total:?}");
|
||||||
|
assert!(!fling.is_active());
|
||||||
|
|
||||||
|
// Langsam schieben oder vor dem Abheben stillhalten: kein Nachgleiten
|
||||||
|
let mut slow = Fling::default();
|
||||||
|
for i in 0..=10 {
|
||||||
|
slow.track(Vec2::new(0.0, -2.0), ms(i * 10));
|
||||||
|
}
|
||||||
|
slow.release(ms(105));
|
||||||
|
assert!(!slow.is_active());
|
||||||
|
let mut rested = Fling::default();
|
||||||
|
for i in 0..=10 {
|
||||||
|
rested.track(Vec2::new(0.0, -30.0), ms(i * 10));
|
||||||
|
}
|
||||||
|
rested.release(ms(400));
|
||||||
|
assert!(!rested.is_active());
|
||||||
|
|
||||||
|
// Touchscreens melden kurz vor dem Abheben oft nur noch winzige Bewegungen
|
||||||
|
let mut lifted = Fling::default();
|
||||||
|
for i in 0..=8 {
|
||||||
|
lifted.track(Vec2::new(0.0, -30.0), ms(i * 10));
|
||||||
|
}
|
||||||
|
lifted.track(Vec2::new(0.0, -1.0), ms(90));
|
||||||
|
lifted.track(Vec2::new(0.0, 0.0), ms(100));
|
||||||
|
lifted.release(ms(104));
|
||||||
|
assert!(lifted.is_active());
|
||||||
|
|
||||||
|
// Gebündelt ankommende Ereignisse (ein Bild brauchte 50 ms)
|
||||||
|
let mut batched = Fling::default();
|
||||||
|
for t in [0, 50, 50, 50, 50, 100, 100, 100, 100] {
|
||||||
|
batched.track(Vec2::new(0.0, -20.0), ms(t));
|
||||||
|
}
|
||||||
|
batched.release(ms(100));
|
||||||
|
assert!(batched.is_active());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_continuous_layout() {
|
fn test_continuous_layout() {
|
||||||
let stack = a4_stack(5, 1);
|
let stack = a4_stack(5, 1);
|
||||||
@@ -413,6 +585,28 @@ mod tests {
|
|||||||
assert!((c.x - A4.x).abs() < 0.1, "{c:?}");
|
assert!((c.x - A4.x).abs() < 0.1, "{c:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_endless_view_stays_right_of_and_below_the_limit() {
|
||||||
|
use crate::document::{ENDLESS_HOME, ENDLESS_PAGE_SIZE};
|
||||||
|
let page_vp = PageViewport::calculate_endless(1280.0, 850.0, 24.0, (0.0, 0.0));
|
||||||
|
let limit = ENDLESS_HOME - 100.0;
|
||||||
|
let mut vp = ViewportState::new();
|
||||||
|
// The A4 start frame is centered: the wide window shows space left of it
|
||||||
|
assert!(vp.clamp_top_left([0.0, 0.0], limit, &page_vp));
|
||||||
|
let corner = vp.screen_to_page_unclamped(0.0, 0.0, &page_vp);
|
||||||
|
assert!((corner.x - limit.x).abs() < 0.1, "{corner:?}");
|
||||||
|
assert!(corner.y >= limit.y - 0.1, "{corner:?}");
|
||||||
|
// Right and down stay free
|
||||||
|
vp.pan_by_screen_delta(-5000.0, -5000.0, &page_vp);
|
||||||
|
assert!(!vp.clamp_top_left([0.0, 0.0], limit, &page_vp));
|
||||||
|
// Back up and left: stops at the limit
|
||||||
|
vp.pan_by_screen_delta(20000.0, 20000.0, &page_vp);
|
||||||
|
assert!(vp.clamp_top_left([0.0, 0.0], limit, &page_vp));
|
||||||
|
let corner = vp.screen_to_page_unclamped(0.0, 0.0, &page_vp);
|
||||||
|
assert!((corner - limit).length() < 0.1, "{corner:?}");
|
||||||
|
assert!(corner.cmplt(ENDLESS_PAGE_SIZE).all());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_viewport_zoom_limits() {
|
fn test_viewport_zoom_limits() {
|
||||||
let mut vp = ViewportState::new();
|
let mut vp = ViewportState::new();
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
//! Das Flatpak baut ohne Netz aus `packaging/flatpak/cargo-sources.json`; jede Abhängigkeit
|
||||||
|
//! aus `Cargo.lock` muss dort stehen, sonst schlägt der Flatpak-Build fehl.
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cargo_sources_cover_cargo_lock() {
|
||||||
|
let lock = include_str!("../Cargo.lock");
|
||||||
|
let sources = include_str!("../packaging/flatpak/cargo-sources.json");
|
||||||
|
let mut missing = Vec::new();
|
||||||
|
for package in lock.split("[[package]]").skip(1) {
|
||||||
|
let field = |key: &str| {
|
||||||
|
package.lines().find_map(|line| {
|
||||||
|
line.strip_prefix(key)
|
||||||
|
.map(|rest| rest.trim().trim_matches('"').to_string())
|
||||||
|
})
|
||||||
|
};
|
||||||
|
// Nur Pakete aus crates.io (das eigene Paket hat keine Quelle)
|
||||||
|
if field("source = ").is_none() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (Some(name), Some(version)) = (field("name = "), field("version = ")) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let crate_file = format!("/{name}-{version}.crate\"");
|
||||||
|
if !sources.contains(&crate_file) {
|
||||||
|
missing.push(format!("{name} {version}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
missing.is_empty(),
|
||||||
|
"cargo-sources.json ist veraltet (flatpak-cargo-generator neu ausführen), es fehlen: {}",
|
||||||
|
missing.join(", ")
|
||||||
|
);
|
||||||
|
}
|
||||||
Vendored
+396
@@ -0,0 +1,396 @@
|
|||||||
|
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||||
|
#
|
||||||
|
# When uploading crates to the registry Cargo will automatically
|
||||||
|
# "normalize" Cargo.toml files for maximal compatibility
|
||||||
|
# with all versions of Cargo and also rewrite `path` dependencies
|
||||||
|
# to registry (e.g., crates.io) dependencies.
|
||||||
|
#
|
||||||
|
# If you are reading this file be aware that the original Cargo.toml
|
||||||
|
# will likely look very different (and much more reasonable).
|
||||||
|
# See Cargo.toml.orig for the original contents.
|
||||||
|
|
||||||
|
[package]
|
||||||
|
edition = "2021"
|
||||||
|
rust-version = "1.65.0"
|
||||||
|
name = "winit"
|
||||||
|
version = "0.29.15"
|
||||||
|
authors = [
|
||||||
|
"The winit contributors",
|
||||||
|
"Pierre Krieger <pierre.krieger1708@gmail.com>",
|
||||||
|
]
|
||||||
|
description = "Cross-platform window creation library."
|
||||||
|
documentation = "https://docs.rs/winit"
|
||||||
|
readme = "README.md"
|
||||||
|
keywords = ["windowing"]
|
||||||
|
categories = ["gui"]
|
||||||
|
license = "Apache-2.0"
|
||||||
|
repository = "https://github.com/rust-windowing/winit"
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
default-target = "x86_64-unknown-linux-gnu"
|
||||||
|
features = [
|
||||||
|
"rwh_04",
|
||||||
|
"rwh_05",
|
||||||
|
"rwh_06",
|
||||||
|
"serde",
|
||||||
|
"android-native-activity",
|
||||||
|
]
|
||||||
|
rustdoc-args = [
|
||||||
|
"--cfg",
|
||||||
|
"docsrs",
|
||||||
|
]
|
||||||
|
targets = [
|
||||||
|
"i686-pc-windows-msvc",
|
||||||
|
"x86_64-pc-windows-msvc",
|
||||||
|
"x86_64-apple-darwin",
|
||||||
|
"i686-unknown-linux-gnu",
|
||||||
|
"x86_64-unknown-linux-gnu",
|
||||||
|
"x86_64-apple-ios",
|
||||||
|
"aarch64-linux-android",
|
||||||
|
"wasm32-unknown-unknown",
|
||||||
|
]
|
||||||
|
|
||||||
|
[dependencies.bitflags]
|
||||||
|
version = "2"
|
||||||
|
|
||||||
|
[dependencies.cursor-icon]
|
||||||
|
version = "1.1.0"
|
||||||
|
|
||||||
|
[dependencies.log]
|
||||||
|
version = "0.4"
|
||||||
|
|
||||||
|
[dependencies.mint]
|
||||||
|
version = "0.5.6"
|
||||||
|
optional = true
|
||||||
|
|
||||||
|
[dependencies.once_cell]
|
||||||
|
version = "1.12"
|
||||||
|
|
||||||
|
[dependencies.rwh_04]
|
||||||
|
version = "0.4"
|
||||||
|
optional = true
|
||||||
|
package = "raw-window-handle"
|
||||||
|
|
||||||
|
[dependencies.rwh_05]
|
||||||
|
version = "0.5.2"
|
||||||
|
features = ["std"]
|
||||||
|
optional = true
|
||||||
|
package = "raw-window-handle"
|
||||||
|
|
||||||
|
[dependencies.rwh_06]
|
||||||
|
version = "0.6"
|
||||||
|
features = ["std"]
|
||||||
|
optional = true
|
||||||
|
package = "raw-window-handle"
|
||||||
|
|
||||||
|
[dependencies.serde]
|
||||||
|
version = "1"
|
||||||
|
features = ["serde_derive"]
|
||||||
|
optional = true
|
||||||
|
|
||||||
|
[dependencies.smol_str]
|
||||||
|
version = "0.2.0"
|
||||||
|
|
||||||
|
[dev-dependencies.image]
|
||||||
|
version = "0.24.0"
|
||||||
|
features = ["png"]
|
||||||
|
default-features = false
|
||||||
|
|
||||||
|
[dev-dependencies.simple_logger]
|
||||||
|
version = "4.2.0"
|
||||||
|
default_features = false
|
||||||
|
|
||||||
|
[build-dependencies.cfg_aliases]
|
||||||
|
version = "0.1.1"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
android-game-activity = ["android-activity/game-activity"]
|
||||||
|
android-native-activity = ["android-activity/native-activity"]
|
||||||
|
default = [
|
||||||
|
"rwh_06",
|
||||||
|
"x11",
|
||||||
|
"wayland",
|
||||||
|
"wayland-dlopen",
|
||||||
|
"wayland-csd-adwaita",
|
||||||
|
]
|
||||||
|
rwh_04 = [
|
||||||
|
"dep:rwh_04",
|
||||||
|
"ndk/rwh_04",
|
||||||
|
]
|
||||||
|
rwh_05 = [
|
||||||
|
"dep:rwh_05",
|
||||||
|
"ndk/rwh_05",
|
||||||
|
]
|
||||||
|
rwh_06 = [
|
||||||
|
"dep:rwh_06",
|
||||||
|
"ndk/rwh_06",
|
||||||
|
]
|
||||||
|
serde = [
|
||||||
|
"dep:serde",
|
||||||
|
"cursor-icon/serde",
|
||||||
|
"smol_str/serde",
|
||||||
|
]
|
||||||
|
wayland = [
|
||||||
|
"wayland-client",
|
||||||
|
"wayland-backend",
|
||||||
|
"wayland-protocols",
|
||||||
|
"wayland-protocols-plasma",
|
||||||
|
"sctk",
|
||||||
|
"ahash",
|
||||||
|
"memmap2",
|
||||||
|
]
|
||||||
|
wayland-csd-adwaita = [
|
||||||
|
"sctk-adwaita",
|
||||||
|
"sctk-adwaita/ab_glyph",
|
||||||
|
]
|
||||||
|
wayland-csd-adwaita-crossfont = [
|
||||||
|
"sctk-adwaita",
|
||||||
|
"sctk-adwaita/crossfont",
|
||||||
|
]
|
||||||
|
wayland-csd-adwaita-notitle = ["sctk-adwaita"]
|
||||||
|
wayland-dlopen = ["wayland-backend/dlopen"]
|
||||||
|
x11 = [
|
||||||
|
"x11-dl",
|
||||||
|
"bytemuck",
|
||||||
|
"percent-encoding",
|
||||||
|
"xkbcommon-dl/x11",
|
||||||
|
"x11rb",
|
||||||
|
]
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.ahash]
|
||||||
|
version = "0.8.3"
|
||||||
|
features = ["no-rng"]
|
||||||
|
optional = true
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.bytemuck]
|
||||||
|
version = "1.13.1"
|
||||||
|
optional = true
|
||||||
|
default-features = false
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.calloop]
|
||||||
|
version = "0.12.3"
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.libc]
|
||||||
|
version = "0.2.64"
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.memmap2]
|
||||||
|
version = "0.9.0"
|
||||||
|
optional = true
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.percent-encoding]
|
||||||
|
version = "2.0"
|
||||||
|
optional = true
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.rustix]
|
||||||
|
version = "0.38.4"
|
||||||
|
features = [
|
||||||
|
"std",
|
||||||
|
"system",
|
||||||
|
"thread",
|
||||||
|
"process",
|
||||||
|
]
|
||||||
|
default-features = false
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.sctk]
|
||||||
|
version = "0.18.0"
|
||||||
|
features = ["calloop"]
|
||||||
|
optional = true
|
||||||
|
default-features = false
|
||||||
|
package = "smithay-client-toolkit"
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.sctk-adwaita]
|
||||||
|
version = "0.8.0"
|
||||||
|
optional = true
|
||||||
|
default_features = false
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.wayland-backend]
|
||||||
|
version = "0.3.0"
|
||||||
|
features = ["client_system"]
|
||||||
|
optional = true
|
||||||
|
default_features = false
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.wayland-client]
|
||||||
|
version = "0.31.1"
|
||||||
|
optional = true
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.wayland-protocols]
|
||||||
|
version = "0.31.0"
|
||||||
|
features = ["staging"]
|
||||||
|
optional = true
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.wayland-protocols-plasma]
|
||||||
|
version = "0.2.0"
|
||||||
|
features = ["client"]
|
||||||
|
optional = true
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.x11-dl]
|
||||||
|
version = "2.19.1"
|
||||||
|
optional = true
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.x11rb]
|
||||||
|
version = "0.13.0"
|
||||||
|
features = [
|
||||||
|
"allow-unsafe-code",
|
||||||
|
"dl-libxcb",
|
||||||
|
"randr",
|
||||||
|
"resource_manager",
|
||||||
|
"xinput",
|
||||||
|
"xkb",
|
||||||
|
]
|
||||||
|
optional = true
|
||||||
|
default-features = false
|
||||||
|
|
||||||
|
[target."cfg(all(unix, not(any(target_os = \"redox\", target_family = \"wasm\", target_os = \"android\", target_os = \"ios\", target_os = \"macos\"))))".dependencies.xkbcommon-dl]
|
||||||
|
version = "0.4.2"
|
||||||
|
|
||||||
|
[target."cfg(any(target_os = \"ios\", target_os = \"macos\"))".dependencies.core-foundation]
|
||||||
|
version = "0.9.3"
|
||||||
|
|
||||||
|
[target."cfg(any(target_os = \"ios\", target_os = \"macos\"))".dependencies.objc2]
|
||||||
|
version = "0.4.1"
|
||||||
|
|
||||||
|
[target."cfg(not(any(target_os = \"android\", target_os = \"ios\")))".dev-dependencies.softbuffer]
|
||||||
|
version = "0.3.0"
|
||||||
|
|
||||||
|
[target."cfg(target_family = \"wasm\")".dependencies.atomic-waker]
|
||||||
|
version = "1"
|
||||||
|
|
||||||
|
[target."cfg(target_family = \"wasm\")".dependencies.js-sys]
|
||||||
|
version = "0.3.64"
|
||||||
|
|
||||||
|
[target."cfg(target_family = \"wasm\")".dependencies.wasm-bindgen]
|
||||||
|
version = "0.2"
|
||||||
|
|
||||||
|
[target."cfg(target_family = \"wasm\")".dependencies.wasm-bindgen-futures]
|
||||||
|
version = "0.4"
|
||||||
|
|
||||||
|
[target."cfg(target_family = \"wasm\")".dependencies.web-time]
|
||||||
|
version = "0.2"
|
||||||
|
|
||||||
|
[target."cfg(target_family = \"wasm\")".dependencies.web_sys]
|
||||||
|
version = "0.3.64"
|
||||||
|
features = [
|
||||||
|
"AbortController",
|
||||||
|
"AbortSignal",
|
||||||
|
"console",
|
||||||
|
"CssStyleDeclaration",
|
||||||
|
"Document",
|
||||||
|
"DomRect",
|
||||||
|
"DomRectReadOnly",
|
||||||
|
"Element",
|
||||||
|
"Event",
|
||||||
|
"EventTarget",
|
||||||
|
"FocusEvent",
|
||||||
|
"HtmlCanvasElement",
|
||||||
|
"HtmlElement",
|
||||||
|
"IntersectionObserver",
|
||||||
|
"IntersectionObserverEntry",
|
||||||
|
"KeyboardEvent",
|
||||||
|
"MediaQueryList",
|
||||||
|
"MessageChannel",
|
||||||
|
"MessagePort",
|
||||||
|
"Node",
|
||||||
|
"PageTransitionEvent",
|
||||||
|
"PointerEvent",
|
||||||
|
"ResizeObserver",
|
||||||
|
"ResizeObserverBoxOptions",
|
||||||
|
"ResizeObserverEntry",
|
||||||
|
"ResizeObserverOptions",
|
||||||
|
"ResizeObserverSize",
|
||||||
|
"VisibilityState",
|
||||||
|
"Window",
|
||||||
|
"WheelEvent",
|
||||||
|
]
|
||||||
|
package = "web-sys"
|
||||||
|
|
||||||
|
[target."cfg(target_family = \"wasm\")".dev-dependencies.console_log]
|
||||||
|
version = "1"
|
||||||
|
|
||||||
|
[target."cfg(target_family = \"wasm\")".dev-dependencies.web-sys]
|
||||||
|
version = "0.3.22"
|
||||||
|
features = ["CanvasRenderingContext2d"]
|
||||||
|
|
||||||
|
[target."cfg(target_os = \"android\")".dependencies.android-activity]
|
||||||
|
version = "0.5.0"
|
||||||
|
|
||||||
|
[target."cfg(target_os = \"android\")".dependencies.ndk]
|
||||||
|
version = "0.8.0"
|
||||||
|
default-features = false
|
||||||
|
|
||||||
|
[target."cfg(target_os = \"android\")".dependencies.ndk-sys]
|
||||||
|
version = "0.5.0"
|
||||||
|
|
||||||
|
[target."cfg(target_os = \"ios\")".dependencies.icrate]
|
||||||
|
version = "0.0.4"
|
||||||
|
features = [
|
||||||
|
"dispatch",
|
||||||
|
"Foundation",
|
||||||
|
"Foundation_NSArray",
|
||||||
|
"Foundation_NSString",
|
||||||
|
"Foundation_NSProcessInfo",
|
||||||
|
"Foundation_NSThread",
|
||||||
|
"Foundation_NSSet",
|
||||||
|
]
|
||||||
|
|
||||||
|
[target."cfg(target_os = \"macos\")".dependencies.core-graphics]
|
||||||
|
version = "0.23.1"
|
||||||
|
|
||||||
|
[target."cfg(target_os = \"macos\")".dependencies.icrate]
|
||||||
|
version = "0.0.4"
|
||||||
|
features = [
|
||||||
|
"dispatch",
|
||||||
|
"Foundation",
|
||||||
|
"Foundation_NSArray",
|
||||||
|
"Foundation_NSAttributedString",
|
||||||
|
"Foundation_NSMutableAttributedString",
|
||||||
|
"Foundation_NSData",
|
||||||
|
"Foundation_NSDictionary",
|
||||||
|
"Foundation_NSString",
|
||||||
|
"Foundation_NSProcessInfo",
|
||||||
|
"Foundation_NSThread",
|
||||||
|
"Foundation_NSNumber",
|
||||||
|
]
|
||||||
|
|
||||||
|
[target."cfg(target_os = \"redox\")".dependencies.orbclient]
|
||||||
|
version = "0.3.42"
|
||||||
|
default-features = false
|
||||||
|
|
||||||
|
[target."cfg(target_os = \"redox\")".dependencies.redox_syscall]
|
||||||
|
version = "0.3"
|
||||||
|
|
||||||
|
[target."cfg(target_os = \"windows\")".dependencies.unicode-segmentation]
|
||||||
|
version = "1.7.1"
|
||||||
|
|
||||||
|
[target."cfg(target_os = \"windows\")".dependencies.windows-sys]
|
||||||
|
version = "0.48"
|
||||||
|
features = [
|
||||||
|
"Win32_Devices_HumanInterfaceDevice",
|
||||||
|
"Win32_Foundation",
|
||||||
|
"Win32_Globalization",
|
||||||
|
"Win32_Graphics_Dwm",
|
||||||
|
"Win32_Graphics_Gdi",
|
||||||
|
"Win32_Media",
|
||||||
|
"Win32_System_Com_StructuredStorage",
|
||||||
|
"Win32_System_Com",
|
||||||
|
"Win32_System_LibraryLoader",
|
||||||
|
"Win32_System_Ole",
|
||||||
|
"Win32_System_SystemInformation",
|
||||||
|
"Win32_System_SystemServices",
|
||||||
|
"Win32_System_Threading",
|
||||||
|
"Win32_System_WindowsProgramming",
|
||||||
|
"Win32_UI_Accessibility",
|
||||||
|
"Win32_UI_Controls",
|
||||||
|
"Win32_UI_HiDpi",
|
||||||
|
"Win32_UI_Input_Ime",
|
||||||
|
"Win32_UI_Input_KeyboardAndMouse",
|
||||||
|
"Win32_UI_Input_Pointer",
|
||||||
|
"Win32_UI_Input_Touch",
|
||||||
|
"Win32_UI_Shell",
|
||||||
|
"Win32_UI_TextServices",
|
||||||
|
"Win32_UI_WindowsAndMessaging",
|
||||||
|
]
|
||||||
|
|
||||||
|
# ink-notes: the vendored copy is built as a path dependency, so silence warnings that the
|
||||||
|
# crates.io build caps anyway
|
||||||
|
[lints.rust]
|
||||||
|
warnings = "allow"
|
||||||
+226
@@ -0,0 +1,226 @@
|
|||||||
|
[package]
|
||||||
|
name = "winit"
|
||||||
|
version = "0.29.15"
|
||||||
|
authors = ["The winit contributors", "Pierre Krieger <pierre.krieger1708@gmail.com>"]
|
||||||
|
description = "Cross-platform window creation library."
|
||||||
|
edition = "2021"
|
||||||
|
keywords = ["windowing"]
|
||||||
|
license = "Apache-2.0"
|
||||||
|
readme = "README.md"
|
||||||
|
repository = "https://github.com/rust-windowing/winit"
|
||||||
|
documentation = "https://docs.rs/winit"
|
||||||
|
categories = ["gui"]
|
||||||
|
rust-version = "1.65.0"
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
features = [
|
||||||
|
"rwh_04",
|
||||||
|
"rwh_05",
|
||||||
|
"rwh_06",
|
||||||
|
"serde",
|
||||||
|
# Enabled to get docs to compile
|
||||||
|
"android-native-activity",
|
||||||
|
]
|
||||||
|
default-target = "x86_64-unknown-linux-gnu"
|
||||||
|
# These are all tested in CI
|
||||||
|
targets = [
|
||||||
|
# Windows
|
||||||
|
"i686-pc-windows-msvc",
|
||||||
|
"x86_64-pc-windows-msvc",
|
||||||
|
# macOS
|
||||||
|
"x86_64-apple-darwin",
|
||||||
|
# Unix (X11 & Wayland)
|
||||||
|
"i686-unknown-linux-gnu",
|
||||||
|
"x86_64-unknown-linux-gnu",
|
||||||
|
# iOS
|
||||||
|
"x86_64-apple-ios",
|
||||||
|
# Android
|
||||||
|
"aarch64-linux-android",
|
||||||
|
# WebAssembly
|
||||||
|
"wasm32-unknown-unknown",
|
||||||
|
]
|
||||||
|
rustdoc-args = ["--cfg", "docsrs"]
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["rwh_06", "x11", "wayland", "wayland-dlopen", "wayland-csd-adwaita"]
|
||||||
|
x11 = ["x11-dl", "bytemuck", "percent-encoding", "xkbcommon-dl/x11", "x11rb"]
|
||||||
|
wayland = ["wayland-client", "wayland-backend", "wayland-protocols", "wayland-protocols-plasma", "sctk", "ahash", "memmap2"]
|
||||||
|
wayland-dlopen = ["wayland-backend/dlopen"]
|
||||||
|
wayland-csd-adwaita = ["sctk-adwaita", "sctk-adwaita/ab_glyph"]
|
||||||
|
wayland-csd-adwaita-crossfont = ["sctk-adwaita", "sctk-adwaita/crossfont"]
|
||||||
|
wayland-csd-adwaita-notitle = ["sctk-adwaita"]
|
||||||
|
android-native-activity = ["android-activity/native-activity"]
|
||||||
|
android-game-activity = ["android-activity/game-activity"]
|
||||||
|
serde = ["dep:serde", "cursor-icon/serde", "smol_str/serde"]
|
||||||
|
rwh_04 = ["dep:rwh_04", "ndk/rwh_04"]
|
||||||
|
rwh_05 = ["dep:rwh_05", "ndk/rwh_05"]
|
||||||
|
rwh_06 = ["dep:rwh_06", "ndk/rwh_06"]
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
|
cfg_aliases = "0.1.1"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
bitflags = "2"
|
||||||
|
cursor-icon = "1.1.0"
|
||||||
|
log = "0.4"
|
||||||
|
mint = { version = "0.5.6", optional = true }
|
||||||
|
once_cell = "1.12"
|
||||||
|
rwh_04 = { package = "raw-window-handle", version = "0.4", optional = true }
|
||||||
|
rwh_05 = { package = "raw-window-handle", version = "0.5.2", features = ["std"], optional = true }
|
||||||
|
rwh_06 = { package = "raw-window-handle", version = "0.6", features = ["std"], optional = true }
|
||||||
|
serde = { version = "1", optional = true, features = ["serde_derive"] }
|
||||||
|
smol_str = "0.2.0"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
image = { version = "0.24.0", default-features = false, features = ["png"] }
|
||||||
|
simple_logger = { version = "4.2.0", default_features = false }
|
||||||
|
winit = { path = ".", features = ["rwh_05"] }
|
||||||
|
|
||||||
|
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dev-dependencies]
|
||||||
|
softbuffer = "0.3.0"
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "android")'.dependencies]
|
||||||
|
android-activity = "0.5.0"
|
||||||
|
ndk = { version = "0.8.0", default-features = false }
|
||||||
|
ndk-sys = "0.5.0"
|
||||||
|
|
||||||
|
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
|
||||||
|
core-foundation = "0.9.3"
|
||||||
|
objc2 = "0.4.1"
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "macos")'.dependencies]
|
||||||
|
core-graphics = "0.23.1"
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "macos")'.dependencies.icrate]
|
||||||
|
version = "0.0.4"
|
||||||
|
features = [
|
||||||
|
"dispatch",
|
||||||
|
"Foundation",
|
||||||
|
"Foundation_NSArray",
|
||||||
|
"Foundation_NSAttributedString",
|
||||||
|
"Foundation_NSMutableAttributedString",
|
||||||
|
"Foundation_NSData",
|
||||||
|
"Foundation_NSDictionary",
|
||||||
|
"Foundation_NSString",
|
||||||
|
"Foundation_NSProcessInfo",
|
||||||
|
"Foundation_NSThread",
|
||||||
|
"Foundation_NSNumber",
|
||||||
|
]
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "ios")'.dependencies.icrate]
|
||||||
|
version = "0.0.4"
|
||||||
|
features = [
|
||||||
|
"dispatch",
|
||||||
|
"Foundation",
|
||||||
|
"Foundation_NSArray",
|
||||||
|
"Foundation_NSString",
|
||||||
|
"Foundation_NSProcessInfo",
|
||||||
|
"Foundation_NSThread",
|
||||||
|
"Foundation_NSSet",
|
||||||
|
]
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "windows")'.dependencies]
|
||||||
|
unicode-segmentation = "1.7.1"
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "windows")'.dependencies.windows-sys]
|
||||||
|
version = "0.48"
|
||||||
|
features = [
|
||||||
|
"Win32_Devices_HumanInterfaceDevice",
|
||||||
|
"Win32_Foundation",
|
||||||
|
"Win32_Globalization",
|
||||||
|
"Win32_Graphics_Dwm",
|
||||||
|
"Win32_Graphics_Gdi",
|
||||||
|
"Win32_Media",
|
||||||
|
"Win32_System_Com_StructuredStorage",
|
||||||
|
"Win32_System_Com",
|
||||||
|
"Win32_System_LibraryLoader",
|
||||||
|
"Win32_System_Ole",
|
||||||
|
"Win32_System_SystemInformation",
|
||||||
|
"Win32_System_SystemServices",
|
||||||
|
"Win32_System_Threading",
|
||||||
|
"Win32_System_WindowsProgramming",
|
||||||
|
"Win32_UI_Accessibility",
|
||||||
|
"Win32_UI_Controls",
|
||||||
|
"Win32_UI_HiDpi",
|
||||||
|
"Win32_UI_Input_Ime",
|
||||||
|
"Win32_UI_Input_KeyboardAndMouse",
|
||||||
|
"Win32_UI_Input_Pointer",
|
||||||
|
"Win32_UI_Input_Touch",
|
||||||
|
"Win32_UI_Shell",
|
||||||
|
"Win32_UI_TextServices",
|
||||||
|
"Win32_UI_WindowsAndMessaging",
|
||||||
|
]
|
||||||
|
|
||||||
|
[target.'cfg(all(unix, not(any(target_os = "redox", target_family = "wasm", target_os = "android", target_os = "ios", target_os = "macos"))))'.dependencies]
|
||||||
|
ahash = { version = "0.8.3", features = ["no-rng"], optional = true }
|
||||||
|
bytemuck = { version = "1.13.1", default-features = false, optional = true }
|
||||||
|
calloop = "0.12.3"
|
||||||
|
libc = "0.2.64"
|
||||||
|
memmap2 = { version = "0.9.0", optional = true }
|
||||||
|
percent-encoding = { version = "2.0", optional = true }
|
||||||
|
rustix = { version = "0.38.4", default-features = false, features = ["std", "system", "thread", "process"] }
|
||||||
|
sctk = { package = "smithay-client-toolkit", version = "0.18.0", default-features = false, features = ["calloop"], optional = true }
|
||||||
|
sctk-adwaita = { version = "0.8.0", default_features = false, optional = true }
|
||||||
|
wayland-backend = { version = "0.3.0", default_features = false, features = ["client_system"], optional = true }
|
||||||
|
wayland-client = { version = "0.31.1", optional = true }
|
||||||
|
wayland-protocols = { version = "0.31.0", features = [ "staging"], optional = true }
|
||||||
|
wayland-protocols-plasma = { version = "0.2.0", features = [ "client" ], optional = true }
|
||||||
|
x11-dl = { version = "2.19.1", optional = true }
|
||||||
|
x11rb = { version = "0.13.0", default-features = false, features = ["allow-unsafe-code", "dl-libxcb", "randr", "resource_manager", "xinput", "xkb"], optional = true }
|
||||||
|
xkbcommon-dl = "0.4.2"
|
||||||
|
|
||||||
|
[target.'cfg(target_os = "redox")'.dependencies]
|
||||||
|
orbclient = { version = "0.3.42", default-features = false }
|
||||||
|
redox_syscall = "0.3"
|
||||||
|
|
||||||
|
[target.'cfg(target_family = "wasm")'.dependencies.web_sys]
|
||||||
|
package = "web-sys"
|
||||||
|
version = "0.3.64"
|
||||||
|
features = [
|
||||||
|
'AbortController',
|
||||||
|
'AbortSignal',
|
||||||
|
'console',
|
||||||
|
'CssStyleDeclaration',
|
||||||
|
'Document',
|
||||||
|
'DomRect',
|
||||||
|
'DomRectReadOnly',
|
||||||
|
'Element',
|
||||||
|
'Event',
|
||||||
|
'EventTarget',
|
||||||
|
'FocusEvent',
|
||||||
|
'HtmlCanvasElement',
|
||||||
|
'HtmlElement',
|
||||||
|
'IntersectionObserver',
|
||||||
|
'IntersectionObserverEntry',
|
||||||
|
'KeyboardEvent',
|
||||||
|
'MediaQueryList',
|
||||||
|
'MessageChannel',
|
||||||
|
'MessagePort',
|
||||||
|
'Node',
|
||||||
|
'PageTransitionEvent',
|
||||||
|
'PointerEvent',
|
||||||
|
'ResizeObserver',
|
||||||
|
'ResizeObserverBoxOptions',
|
||||||
|
'ResizeObserverEntry',
|
||||||
|
'ResizeObserverOptions',
|
||||||
|
'ResizeObserverSize',
|
||||||
|
'VisibilityState',
|
||||||
|
'Window',
|
||||||
|
'WheelEvent'
|
||||||
|
]
|
||||||
|
|
||||||
|
[target.'cfg(target_family = "wasm")'.dependencies]
|
||||||
|
atomic-waker = "1"
|
||||||
|
js-sys = "0.3.64"
|
||||||
|
wasm-bindgen = "0.2"
|
||||||
|
wasm-bindgen-futures = "0.4"
|
||||||
|
web-time = "0.2"
|
||||||
|
|
||||||
|
[target.'cfg(target_family = "wasm")'.dev-dependencies]
|
||||||
|
console_log = "1"
|
||||||
|
web-sys = { version = "0.3.22", features = ['CanvasRenderingContext2d'] }
|
||||||
|
|
||||||
|
[workspace]
|
||||||
|
members = [
|
||||||
|
"run-wasm",
|
||||||
|
]
|
||||||
Vendored
+201
@@ -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.
|
||||||
Vendored
+18
@@ -0,0 +1,18 @@
|
|||||||
|
# winit 0.29.15 for ink-notes
|
||||||
|
|
||||||
|
Copy of [winit 0.29.15](https://crates.io/crates/winit/0.29.15) (Apache-2.0, see
|
||||||
|
`LICENSE`), used through `[patch.crates-io]` in the top-level `Cargo.toml`. Examples, tests and
|
||||||
|
docs of the original crate were removed.
|
||||||
|
|
||||||
|
## Changes
|
||||||
|
|
||||||
|
- `src/platform_impl/linux/wayland/seat/touch/mod.rs`: on Wayland, winit draws the title bar
|
||||||
|
itself (client-side decorations) but only handles the mouse there. Touches on the title bar
|
||||||
|
are now passed to the frame like a left click: close, minimize and maximize work with a
|
||||||
|
finger, and dragging the title bar moves the window (Issue #36). All changes are marked with
|
||||||
|
`ink-notes patch`.
|
||||||
|
- `Cargo.toml`: `[lints.rust] warnings = "allow"`, because a path dependency is not built with
|
||||||
|
capped lints like a crates.io dependency.
|
||||||
|
|
||||||
|
Remove the copy and the `[patch.crates-io]` entry when ink-notes moves to a winit version that
|
||||||
|
handles touch on its decorations.
|
||||||
Vendored
+187
@@ -0,0 +1,187 @@
|
|||||||
|
# winit - Cross-platform window creation and management in Rust
|
||||||
|
|
||||||
|
[](https://crates.io/crates/winit)
|
||||||
|
[](https://docs.rs/winit)
|
||||||
|
[](https://github.com/rust-windowing/winit/actions)
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[dependencies]
|
||||||
|
winit = "0.29.15"
|
||||||
|
```
|
||||||
|
|
||||||
|
## [Documentation](https://docs.rs/winit)
|
||||||
|
|
||||||
|
For features _within_ the scope of winit, see [FEATURES.md](FEATURES.md).
|
||||||
|
|
||||||
|
For features _outside_ the scope of winit, see [Are we GUI Yet?](https://areweguiyet.com/) and [Are we game yet?](https://arewegameyet.rs/), depending on what kind of project you're looking to do.
|
||||||
|
|
||||||
|
## Contact Us
|
||||||
|
|
||||||
|
Join us in any of these:
|
||||||
|
|
||||||
|
[](https://matrix.to/#/#rust-windowing:matrix.org)
|
||||||
|
[](https://web.libera.chat/#winit)
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
Winit is a window creation and management library. It can create windows and lets you handle
|
||||||
|
events (for example: the window being resized, a key being pressed, a mouse movement, etc.)
|
||||||
|
produced by the window.
|
||||||
|
|
||||||
|
Winit is designed to be a low-level brick in a hierarchy of libraries. Consequently, in order to
|
||||||
|
show something on the window you need to use the platform-specific getters provided by winit, or
|
||||||
|
another library.
|
||||||
|
|
||||||
|
### Cargo Features
|
||||||
|
|
||||||
|
Winit provides the following features, which can be enabled in your `Cargo.toml` file:
|
||||||
|
* `serde`: Enables serialization/deserialization of certain types with [Serde](https://crates.io/crates/serde).
|
||||||
|
* `x11` (enabled by default): On Unix platform, compiles with the X11 backend
|
||||||
|
* `wayland` (enabled by default): On Unix platform, compiles with the Wayland backend
|
||||||
|
* `mint`: Enables mint (math interoperability standard types) conversions.
|
||||||
|
|
||||||
|
## MSRV Policy
|
||||||
|
|
||||||
|
This crate's Minimum Supported Rust Version (MSRV) is **1.65**. Changes to
|
||||||
|
the MSRV will be accompanied by a minor version bump.
|
||||||
|
|
||||||
|
As a **tentative** policy, the upper bound of the MSRV is given by the following
|
||||||
|
formula:
|
||||||
|
|
||||||
|
```
|
||||||
|
min(sid, stable - 3)
|
||||||
|
```
|
||||||
|
|
||||||
|
Where `sid` is the current version of `rustc` provided by [Debian Sid], and
|
||||||
|
`stable` is the latest stable version of Rust. This bound may be broken in case of a major ecosystem shift or a security vulnerability.
|
||||||
|
|
||||||
|
[Debian Sid]: https://packages.debian.org/sid/rustc
|
||||||
|
|
||||||
|
The exception is for the Android platform, where a higher Rust version
|
||||||
|
must be used for certain Android features. In this case, the MSRV will be
|
||||||
|
capped at the latest stable version of Rust minus three. This inconsistency is
|
||||||
|
not reflected in Cargo metadata, as it is not powerful enough to expose this
|
||||||
|
restriction.
|
||||||
|
|
||||||
|
All crates in the [`rust-windowing`] organizations have the
|
||||||
|
same MSRV policy.
|
||||||
|
|
||||||
|
[`rust-windowing`]: https://github.com/rust-windowing
|
||||||
|
|
||||||
|
### Platform-specific usage
|
||||||
|
|
||||||
|
#### Wayland
|
||||||
|
|
||||||
|
Note that windows don't appear on Wayland until you draw/present to them.
|
||||||
|
|
||||||
|
#### WebAssembly
|
||||||
|
|
||||||
|
To run the web example: `cargo run-wasm --example web`
|
||||||
|
|
||||||
|
Winit supports compiling to the `wasm32-unknown-unknown` target with `web-sys`.
|
||||||
|
|
||||||
|
On the web platform, a Winit window is backed by a `<canvas>` element. You can
|
||||||
|
either [provide Winit with a `<canvas>` element][web with_canvas], or [let Winit
|
||||||
|
create a `<canvas>` element which you can then retrieve][web canvas getter] and
|
||||||
|
insert it into the DOM yourself.
|
||||||
|
|
||||||
|
For the example code using Winit with WebAssembly, check out the [web example]. For
|
||||||
|
information on using Rust on WebAssembly, check out the [Rust and WebAssembly
|
||||||
|
book].
|
||||||
|
|
||||||
|
[web with_canvas]: https://docs.rs/winit/latest/wasm32-unknown-unknown/winit/platform/web/trait.WindowBuilderExtWebSys.html#tymethod.with_canvas
|
||||||
|
[web canvas getter]: https://docs.rs/winit/latest/wasm32-unknown-unknown/winit/platform/web/trait.WindowExtWebSys.html#tymethod.canvas
|
||||||
|
[web example]: ./examples/web.rs
|
||||||
|
[Rust and WebAssembly book]: https://rustwasm.github.io/book/
|
||||||
|
|
||||||
|
#### Android
|
||||||
|
|
||||||
|
The Android backend builds on (and exposes types from) the [`ndk`](https://docs.rs/ndk/latest/ndk/) crate.
|
||||||
|
|
||||||
|
Native Android applications need some form of "glue" crate that is responsible
|
||||||
|
for defining the main entry point for your Rust application as well as tracking
|
||||||
|
various life-cycle events and synchronizing with the main JVM thread.
|
||||||
|
|
||||||
|
Winit uses the [android-activity](https://github.com/rib/android-activity) as a
|
||||||
|
glue crate (prior to `0.28` it used
|
||||||
|
[ndk-glue](https://github.com/rust-windowing/android-ndk-rs/tree/master/ndk-glue)).
|
||||||
|
|
||||||
|
The version of the glue crate that your application depends on _must_ match the
|
||||||
|
version that Winit depends on because the glue crate is responsible for your
|
||||||
|
application's main entry point. If Cargo resolves multiple versions, they will
|
||||||
|
clash.
|
||||||
|
|
||||||
|
`winit` glue compatibility table:
|
||||||
|
|
||||||
|
| winit | ndk-glue |
|
||||||
|
| :---: | :--------------------------: |
|
||||||
|
| 0.29 | `android-activity = "0.5"` |
|
||||||
|
| 0.28 | `android-activity = "0.4"` |
|
||||||
|
| 0.27 | `ndk-glue = "0.7"` |
|
||||||
|
| 0.26 | `ndk-glue = "0.5"` |
|
||||||
|
| 0.25 | `ndk-glue = "0.3"` |
|
||||||
|
| 0.24 | `ndk-glue = "0.2"` |
|
||||||
|
|
||||||
|
The recommended way to avoid a conflict with the glue version is to avoid explicitly
|
||||||
|
depending on the `android-activity` crate, and instead consume the API that
|
||||||
|
is re-exported by Winit under `winit::platform::android::activity::*`
|
||||||
|
|
||||||
|
Running on an Android device needs a dynamic system library. Add this to Cargo.toml:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[lib]
|
||||||
|
name = "main"
|
||||||
|
crate-type = ["cdylib"]
|
||||||
|
```
|
||||||
|
|
||||||
|
All Android applications are based on an `Activity` subclass, and the
|
||||||
|
`android-activity` crate is designed to support different choices for this base
|
||||||
|
class. Your application _must_ specify the base class it needs via a feature flag:
|
||||||
|
|
||||||
|
| Base Class | Feature Flag | Notes |
|
||||||
|
| :--------------: | :---------------: | :-----: |
|
||||||
|
| `NativeActivity` | `android-native-activity` | Built-in to Android - it is possible to use without compiling any Java or Kotlin code. Java or Kotlin code may be needed to subclass `NativeActivity` to access some platform features. It does not derive from the [`AndroidAppCompat`] base class.|
|
||||||
|
| [`GameActivity`] | `android-game-activity` | Derives from [`AndroidAppCompat`], a defacto standard `Activity` base class that helps support a wider range of Android versions. Requires a build system that can compile Java or Kotlin and fetch Android dependencies from a [Maven repository][agdk_jetpack] (or link with an embedded [release][agdk_releases] of [`GameActivity`]) |
|
||||||
|
|
||||||
|
[`GameActivity`]: https://developer.android.com/games/agdk/game-activity
|
||||||
|
[`GameTextInput`]: https://developer.android.com/games/agdk/add-support-for-text-input
|
||||||
|
[`AndroidAppCompat`]: https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity
|
||||||
|
[agdk_jetpack]: https://developer.android.com/jetpack/androidx/releases/games
|
||||||
|
[agdk_releases]: https://developer.android.com/games/agdk/download#agdk-libraries
|
||||||
|
[Gradle]: https://developer.android.com/studio/build
|
||||||
|
|
||||||
|
For more details, refer to these `android-activity` [example applications](https://github.com/rust-mobile/android-activity/tree/main/examples).
|
||||||
|
|
||||||
|
##### Converting from `ndk-glue` to `android-activity`
|
||||||
|
|
||||||
|
If your application is currently based on `NativeActivity` via the `ndk-glue` crate and building with `cargo apk`, then the minimal changes would be:
|
||||||
|
1. Remove `ndk-glue` from your `Cargo.toml`
|
||||||
|
2. Enable the `"android-native-activity"` feature for Winit: `winit = { version = "0.29.15", features = [ "android-native-activity" ] }`
|
||||||
|
3. Add an `android_main` entrypoint (as above), instead of using the '`[ndk_glue::main]` proc macro from `ndk-macros` (optionally add a dependency on `android_logger` and initialize logging as above).
|
||||||
|
4. Pass a clone of the `AndroidApp` that your application receives to Winit when building your event loop (as shown above).
|
||||||
|
|
||||||
|
#### MacOS
|
||||||
|
|
||||||
|
A lot of functionality expects the application to be ready before you start
|
||||||
|
doing anything; this includes creating windows, fetching monitors, drawing,
|
||||||
|
and so on, see issues [#2238], [#2051] and [#2087].
|
||||||
|
|
||||||
|
If you encounter problems, you should try doing your initialization inside
|
||||||
|
`Event::Resumed`.
|
||||||
|
|
||||||
|
#### iOS
|
||||||
|
|
||||||
|
Similar to macOS, iOS's main `UIApplicationMain` does some init work that's required
|
||||||
|
by all UI-related code (see issue [#1705]). It would be best to consider creating your windows
|
||||||
|
inside `Event::Resumed`.
|
||||||
|
|
||||||
|
|
||||||
|
[#2238]: https://github.com/rust-windowing/winit/issues/2238
|
||||||
|
[#2051]: https://github.com/rust-windowing/winit/issues/2051
|
||||||
|
[#2087]: https://github.com/rust-windowing/winit/issues/2087
|
||||||
|
[#1705]: https://github.com/rust-windowing/winit/issues/1705
|
||||||
|
|
||||||
|
#### Redox OS
|
||||||
|
|
||||||
|
Redox OS has some functionality not yet present that will be implemented when
|
||||||
|
its orbital display server provides it.
|
||||||
Vendored
+24
@@ -0,0 +1,24 @@
|
|||||||
|
use cfg_aliases::cfg_aliases;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
// The script doesn't depend on our code
|
||||||
|
println!("cargo:rerun-if-changed=build.rs");
|
||||||
|
|
||||||
|
// Setup cfg aliases
|
||||||
|
cfg_aliases! {
|
||||||
|
// Systems.
|
||||||
|
android_platform: { target_os = "android" },
|
||||||
|
wasm_platform: { all(target_family = "wasm", not(target_os = "emscripten")) },
|
||||||
|
macos_platform: { target_os = "macos" },
|
||||||
|
ios_platform: { target_os = "ios" },
|
||||||
|
windows_platform: { target_os = "windows" },
|
||||||
|
apple: { any(target_os = "ios", target_os = "macos") },
|
||||||
|
free_unix: { all(unix, not(apple), not(android_platform), not(target_os = "emscripten")) },
|
||||||
|
redox: { target_os = "redox" },
|
||||||
|
|
||||||
|
// Native displays.
|
||||||
|
x11_platform: { all(feature = "x11", free_unix, not(wasm), not(redox)) },
|
||||||
|
wayland_platform: { all(feature = "wayland", free_unix, not(wasm), not(redox)) },
|
||||||
|
orbital_platform: { redox },
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+3
@@ -0,0 +1,3 @@
|
|||||||
|
force_explicit_abi=true
|
||||||
|
use_field_init_shorthand=true
|
||||||
|
# merge_imports=true
|
||||||
Vendored
+1001
File diff suppressed because it is too large.
Load diff
Vendored
+142
@@ -0,0 +1,142 @@
|
|||||||
|
use std::{error, fmt};
|
||||||
|
|
||||||
|
use crate::platform_impl;
|
||||||
|
|
||||||
|
// TODO: Rename
|
||||||
|
/// An error that may be generated when requesting Winit state
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum ExternalError {
|
||||||
|
/// The operation is not supported by the backend.
|
||||||
|
NotSupported(NotSupportedError),
|
||||||
|
/// The operation was ignored.
|
||||||
|
Ignored,
|
||||||
|
/// The OS cannot perform the operation.
|
||||||
|
Os(OsError),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The error type for when the requested operation is not supported by the backend.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct NotSupportedError {
|
||||||
|
_marker: (),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The error type for when the OS cannot perform the requested operation.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct OsError {
|
||||||
|
line: u32,
|
||||||
|
file: &'static str,
|
||||||
|
error: platform_impl::OsError,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A general error that may occur while running the Winit event loop
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum EventLoopError {
|
||||||
|
/// The operation is not supported by the backend.
|
||||||
|
NotSupported(NotSupportedError),
|
||||||
|
/// The OS cannot perform the operation.
|
||||||
|
Os(OsError),
|
||||||
|
/// The event loop can't be re-run while it's already running
|
||||||
|
AlreadyRunning,
|
||||||
|
/// The event loop can't be re-created.
|
||||||
|
RecreationAttempt,
|
||||||
|
/// Application has exit with an error status.
|
||||||
|
ExitFailure(i32),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<OsError> for EventLoopError {
|
||||||
|
fn from(value: OsError) -> Self {
|
||||||
|
Self::Os(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NotSupportedError {
|
||||||
|
#[inline]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) fn new() -> NotSupportedError {
|
||||||
|
NotSupportedError { _marker: () }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OsError {
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) fn new(line: u32, file: &'static str, error: platform_impl::OsError) -> OsError {
|
||||||
|
OsError { line, file, error }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(unused_macros)]
|
||||||
|
macro_rules! os_error {
|
||||||
|
($error:expr) => {{
|
||||||
|
crate::error::OsError::new(line!(), file!(), $error)
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for OsError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||||
|
f.pad(&format!(
|
||||||
|
"os error at {}:{}: {}",
|
||||||
|
self.file, self.line, self.error
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for ExternalError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||||
|
match self {
|
||||||
|
ExternalError::NotSupported(e) => e.fmt(f),
|
||||||
|
ExternalError::Ignored => write!(f, "Operation was ignored"),
|
||||||
|
ExternalError::Os(e) => e.fmt(f),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for NotSupportedError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||||
|
f.debug_struct("NotSupportedError").finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for NotSupportedError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||||
|
f.pad("the requested operation is not supported by Winit")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for EventLoopError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||||
|
match self {
|
||||||
|
EventLoopError::AlreadyRunning => write!(f, "EventLoop is already running"),
|
||||||
|
EventLoopError::RecreationAttempt => write!(f, "EventLoop can't be recreated"),
|
||||||
|
EventLoopError::NotSupported(e) => e.fmt(f),
|
||||||
|
EventLoopError::Os(e) => e.fmt(f),
|
||||||
|
EventLoopError::ExitFailure(status) => write!(f, "Exit Failure: {status}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl error::Error for OsError {}
|
||||||
|
impl error::Error for ExternalError {}
|
||||||
|
impl error::Error for NotSupportedError {}
|
||||||
|
impl error::Error for EventLoopError {}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::redundant_clone)]
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
// Eat attributes for testing
|
||||||
|
#[test]
|
||||||
|
fn ensure_fmt_does_not_panic() {
|
||||||
|
let _ = format!(
|
||||||
|
"{:?}, {}",
|
||||||
|
NotSupportedError::new(),
|
||||||
|
NotSupportedError::new().clone()
|
||||||
|
);
|
||||||
|
let _ = format!(
|
||||||
|
"{:?}, {}",
|
||||||
|
ExternalError::NotSupported(NotSupportedError::new()),
|
||||||
|
ExternalError::NotSupported(NotSupportedError::new())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+1342
File diff suppressed because it is too large.
Load diff
Vendored
+475
@@ -0,0 +1,475 @@
|
|||||||
|
//! The [`EventLoop`] struct and assorted supporting types, including
|
||||||
|
//! [`ControlFlow`].
|
||||||
|
//!
|
||||||
|
//! If you want to send custom events to the event loop, use
|
||||||
|
//! [`EventLoop::create_proxy`] to acquire an [`EventLoopProxy`] and call its
|
||||||
|
//! [`send_event`](`EventLoopProxy::send_event`) method.
|
||||||
|
//!
|
||||||
|
//! See the root-level documentation for information on how to create and use an event loop to
|
||||||
|
//! handle events.
|
||||||
|
use std::marker::PhantomData;
|
||||||
|
use std::ops::Deref;
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd};
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
|
use std::{error, fmt};
|
||||||
|
|
||||||
|
#[cfg(not(wasm_platform))]
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
#[cfg(wasm_platform)]
|
||||||
|
use web_time::{Duration, Instant};
|
||||||
|
|
||||||
|
use crate::error::EventLoopError;
|
||||||
|
use crate::{event::Event, monitor::MonitorHandle, platform_impl};
|
||||||
|
|
||||||
|
/// Provides a way to retrieve events from the system and from the windows that were registered to
|
||||||
|
/// the events loop.
|
||||||
|
///
|
||||||
|
/// An `EventLoop` can be seen more or less as a "context". Calling [`EventLoop::new`]
|
||||||
|
/// initializes everything that will be required to create windows. For example on Linux creating
|
||||||
|
/// an event loop opens a connection to the X or Wayland server.
|
||||||
|
///
|
||||||
|
/// To wake up an `EventLoop` from a another thread, see the [`EventLoopProxy`] docs.
|
||||||
|
///
|
||||||
|
/// Note that this cannot be shared across threads (due to platform-dependant logic
|
||||||
|
/// forbidding it), as such it is neither [`Send`] nor [`Sync`]. If you need cross-thread access, the
|
||||||
|
/// [`Window`] created from this _can_ be sent to an other thread, and the
|
||||||
|
/// [`EventLoopProxy`] allows you to wake up an `EventLoop` from another thread.
|
||||||
|
///
|
||||||
|
/// [`Window`]: crate::window::Window
|
||||||
|
pub struct EventLoop<T: 'static> {
|
||||||
|
pub(crate) event_loop: platform_impl::EventLoop<T>,
|
||||||
|
pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Target that associates windows with an [`EventLoop`].
|
||||||
|
///
|
||||||
|
/// This type exists to allow you to create new windows while Winit executes
|
||||||
|
/// your callback. [`EventLoop`] will coerce into this type (`impl<T> Deref for
|
||||||
|
/// EventLoop<T>`), so functions that take this as a parameter can also take
|
||||||
|
/// `&EventLoop`.
|
||||||
|
pub struct EventLoopWindowTarget<T: 'static> {
|
||||||
|
pub(crate) p: platform_impl::EventLoopWindowTarget<T>,
|
||||||
|
pub(crate) _marker: PhantomData<*mut ()>, // Not Send nor Sync
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Object that allows building the event loop.
|
||||||
|
///
|
||||||
|
/// This is used to make specifying options that affect the whole application
|
||||||
|
/// easier. But note that constructing multiple event loops is not supported.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct EventLoopBuilder<T: 'static> {
|
||||||
|
pub(crate) platform_specific: platform_impl::PlatformSpecificEventLoopAttributes,
|
||||||
|
_p: PhantomData<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopBuilder<()> {
|
||||||
|
/// Start building a new event loop.
|
||||||
|
#[inline]
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::with_user_event()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static EVENT_LOOP_CREATED: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
impl<T> EventLoopBuilder<T> {
|
||||||
|
/// Start building a new event loop, with the given type as the user event
|
||||||
|
/// type.
|
||||||
|
#[inline]
|
||||||
|
pub fn with_user_event() -> Self {
|
||||||
|
Self {
|
||||||
|
platform_specific: Default::default(),
|
||||||
|
_p: PhantomData,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds a new event loop.
|
||||||
|
///
|
||||||
|
/// ***For cross-platform compatibility, the [`EventLoop`] must be created on the main thread,
|
||||||
|
/// and only once per application.***
|
||||||
|
///
|
||||||
|
/// Calling this function will result in display backend initialisation.
|
||||||
|
///
|
||||||
|
/// ## Panics
|
||||||
|
///
|
||||||
|
/// Attempting to create the event loop off the main thread will panic. This
|
||||||
|
/// restriction isn't strictly necessary on all platforms, but is imposed to
|
||||||
|
/// eliminate any nasty surprises when porting to platforms that require it.
|
||||||
|
/// `EventLoopBuilderExt::any_thread` functions are exposed in the relevant
|
||||||
|
/// [`platform`] module if the target platform supports creating an event
|
||||||
|
/// loop on any thread.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **Wayland/X11:** to prevent running under `Wayland` or `X11` unset `WAYLAND_DISPLAY`
|
||||||
|
/// or `DISPLAY` respectively when building the event loop.
|
||||||
|
/// - **Android:** must be configured with an `AndroidApp` from `android_main()` by calling
|
||||||
|
/// [`.with_android_app(app)`] before calling `.build()`, otherwise it'll panic.
|
||||||
|
///
|
||||||
|
/// [`platform`]: crate::platform
|
||||||
|
#[cfg_attr(
|
||||||
|
android,
|
||||||
|
doc = "[`.with_android_app(app)`]: crate::platform::android::EventLoopBuilderExtAndroid::with_android_app"
|
||||||
|
)]
|
||||||
|
#[cfg_attr(
|
||||||
|
not(android),
|
||||||
|
doc = "[`.with_android_app(app)`]: #only-available-on-android"
|
||||||
|
)]
|
||||||
|
#[inline]
|
||||||
|
pub fn build(&mut self) -> Result<EventLoop<T>, EventLoopError> {
|
||||||
|
if EVENT_LOOP_CREATED.swap(true, Ordering::Relaxed) {
|
||||||
|
return Err(EventLoopError::RecreationAttempt);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Certain platforms accept a mutable reference in their API.
|
||||||
|
#[allow(clippy::unnecessary_mut_passed)]
|
||||||
|
Ok(EventLoop {
|
||||||
|
event_loop: platform_impl::EventLoop::new(&mut self.platform_specific)?,
|
||||||
|
_marker: PhantomData,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(wasm_platform)]
|
||||||
|
pub(crate) fn allow_event_loop_recreation() {
|
||||||
|
EVENT_LOOP_CREATED.store(false, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> fmt::Debug for EventLoop<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.pad("EventLoop { .. }")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> fmt::Debug for EventLoopWindowTarget<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.pad("EventLoopWindowTarget { .. }")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set through [`EventLoopWindowTarget::set_control_flow()`].
|
||||||
|
///
|
||||||
|
/// Indicates the desired behavior of the event loop after [`Event::AboutToWait`] is emitted.
|
||||||
|
///
|
||||||
|
/// Defaults to [`Wait`].
|
||||||
|
///
|
||||||
|
/// [`Wait`]: Self::Wait
|
||||||
|
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub enum ControlFlow {
|
||||||
|
/// When the current loop iteration finishes, immediately begin a new iteration regardless of
|
||||||
|
/// whether or not new events are available to process.
|
||||||
|
Poll,
|
||||||
|
|
||||||
|
/// When the current loop iteration finishes, suspend the thread until another event arrives.
|
||||||
|
#[default]
|
||||||
|
Wait,
|
||||||
|
|
||||||
|
/// When the current loop iteration finishes, suspend the thread until either another event
|
||||||
|
/// arrives or the given time is reached.
|
||||||
|
///
|
||||||
|
/// Useful for implementing efficient timers. Applications which want to render at the display's
|
||||||
|
/// native refresh rate should instead use [`Poll`] and the VSync functionality of a graphics API
|
||||||
|
/// to reduce odds of missed frames.
|
||||||
|
///
|
||||||
|
/// [`Poll`]: Self::Poll
|
||||||
|
WaitUntil(Instant),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ControlFlow {
|
||||||
|
/// Creates a [`ControlFlow`] that waits until a timeout has expired.
|
||||||
|
///
|
||||||
|
/// In most cases, this is set to [`WaitUntil`]. However, if the timeout overflows, it is
|
||||||
|
/// instead set to [`Wait`].
|
||||||
|
///
|
||||||
|
/// [`WaitUntil`]: Self::WaitUntil
|
||||||
|
/// [`Wait`]: Self::Wait
|
||||||
|
pub fn wait_duration(timeout: Duration) -> Self {
|
||||||
|
match Instant::now().checked_add(timeout) {
|
||||||
|
Some(instant) => Self::WaitUntil(instant),
|
||||||
|
None => Self::Wait,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoop<()> {
|
||||||
|
/// Alias for [`EventLoopBuilder::new().build()`].
|
||||||
|
///
|
||||||
|
/// [`EventLoopBuilder::new().build()`]: EventLoopBuilder::build
|
||||||
|
#[inline]
|
||||||
|
pub fn new() -> Result<EventLoop<()>, EventLoopError> {
|
||||||
|
EventLoopBuilder::new().build()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoop<T> {
|
||||||
|
#[deprecated = "Use `EventLoopBuilder::<T>::with_user_event().build()` instead."]
|
||||||
|
pub fn with_user_event() -> Result<EventLoop<T>, EventLoopError> {
|
||||||
|
EventLoopBuilder::<T>::with_user_event().build()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs the event loop in the calling thread and calls the given `event_handler` closure
|
||||||
|
/// to dispatch any pending events.
|
||||||
|
///
|
||||||
|
/// Since the closure is `'static`, it must be a `move` closure if it needs to
|
||||||
|
/// access any data from the calling context.
|
||||||
|
///
|
||||||
|
/// See the [`set_control_flow()`] docs on how to change the event loop's behavior.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **iOS:** Will never return to the caller and so values not passed to this function will
|
||||||
|
/// *not* be dropped before the process exits.
|
||||||
|
/// - **Web:** Will _act_ as if it never returns to the caller by throwing a Javascript exception
|
||||||
|
/// (that Rust doesn't see) that will also mean that the rest of the function is never executed
|
||||||
|
/// and any values not passed to this function will *not* be dropped.
|
||||||
|
///
|
||||||
|
/// Web applications are recommended to use
|
||||||
|
#[cfg_attr(
|
||||||
|
wasm_platform,
|
||||||
|
doc = "[`EventLoopExtWebSys::spawn()`][crate::platform::web::EventLoopExtWebSys::spawn()]"
|
||||||
|
)]
|
||||||
|
#[cfg_attr(not(wasm_platform), doc = "`EventLoopExtWebSys::spawn()`")]
|
||||||
|
/// [^1] instead of [`run()`] to avoid the need
|
||||||
|
/// for the Javascript exception trick, and to make it clearer that the event loop runs
|
||||||
|
/// asynchronously (via the browser's own, internal, event loop) and doesn't block the
|
||||||
|
/// current thread of execution like it does on other platforms.
|
||||||
|
///
|
||||||
|
/// This function won't be available with `target_feature = "exception-handling"`.
|
||||||
|
///
|
||||||
|
/// [`set_control_flow()`]: EventLoopWindowTarget::set_control_flow()
|
||||||
|
/// [`run()`]: Self::run()
|
||||||
|
/// [^1]: `EventLoopExtWebSys::spawn()` is only available on WASM.
|
||||||
|
#[inline]
|
||||||
|
#[cfg(not(all(wasm_platform, target_feature = "exception-handling")))]
|
||||||
|
pub fn run<F>(self, event_handler: F) -> Result<(), EventLoopError>
|
||||||
|
where
|
||||||
|
F: FnMut(Event<T>, &EventLoopWindowTarget<T>),
|
||||||
|
{
|
||||||
|
self.event_loop.run(event_handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates an [`EventLoopProxy`] that can be used to dispatch user events to the main event loop.
|
||||||
|
pub fn create_proxy(&self) -> EventLoopProxy<T> {
|
||||||
|
EventLoopProxy {
|
||||||
|
event_loop_proxy: self.event_loop.create_proxy(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_06")]
|
||||||
|
impl<T> rwh_06::HasDisplayHandle for EventLoop<T> {
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
rwh_06::HasDisplayHandle::display_handle(&**self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_05")]
|
||||||
|
unsafe impl<T> rwh_05::HasRawDisplayHandle for EventLoop<T> {
|
||||||
|
/// Returns a [`rwh_05::RawDisplayHandle`] for the event loop.
|
||||||
|
fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
|
||||||
|
rwh_05::HasRawDisplayHandle::raw_display_handle(&**self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
impl<T> AsFd for EventLoop<T> {
|
||||||
|
/// Get the underlying [EventLoop]'s `fd` which you can register
|
||||||
|
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
||||||
|
/// loop must be polled with the [`pump_events`] API.
|
||||||
|
///
|
||||||
|
/// [`calloop`]: https://crates.io/crates/calloop
|
||||||
|
/// [`mio`]: https://crates.io/crates/mio
|
||||||
|
/// [`pump_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_events
|
||||||
|
fn as_fd(&self) -> BorrowedFd<'_> {
|
||||||
|
self.event_loop.as_fd()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
impl<T> AsRawFd for EventLoop<T> {
|
||||||
|
/// Get the underlying [EventLoop]'s raw `fd` which you can register
|
||||||
|
/// into other event loop, like [`calloop`] or [`mio`]. When doing so, the
|
||||||
|
/// loop must be polled with the [`pump_events`] API.
|
||||||
|
///
|
||||||
|
/// [`calloop`]: https://crates.io/crates/calloop
|
||||||
|
/// [`mio`]: https://crates.io/crates/mio
|
||||||
|
/// [`pump_events`]: crate::platform::pump_events::EventLoopExtPumpEvents::pump_events
|
||||||
|
fn as_raw_fd(&self) -> RawFd {
|
||||||
|
self.event_loop.as_raw_fd()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Deref for EventLoop<T> {
|
||||||
|
type Target = EventLoopWindowTarget<T>;
|
||||||
|
fn deref(&self) -> &EventLoopWindowTarget<T> {
|
||||||
|
self.event_loop.window_target()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopWindowTarget<T> {
|
||||||
|
/// Returns the list of all the monitors available on the system.
|
||||||
|
#[inline]
|
||||||
|
pub fn available_monitors(&self) -> impl Iterator<Item = MonitorHandle> {
|
||||||
|
#[allow(clippy::useless_conversion)] // false positive on some platforms
|
||||||
|
self.p
|
||||||
|
.available_monitors()
|
||||||
|
.into_iter()
|
||||||
|
.map(|inner| MonitorHandle { inner })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the primary monitor of the system.
|
||||||
|
///
|
||||||
|
/// Returns `None` if it can't identify any monitor as a primary one.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// **Wayland / Web:** Always returns `None`.
|
||||||
|
#[inline]
|
||||||
|
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||||
|
self.p
|
||||||
|
.primary_monitor()
|
||||||
|
.map(|inner| MonitorHandle { inner })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Change if or when [`DeviceEvent`]s are captured.
|
||||||
|
///
|
||||||
|
/// Since the [`DeviceEvent`] capture can lead to high CPU usage for unfocused windows, winit
|
||||||
|
/// will ignore them by default for unfocused windows on Linux/BSD. This method allows changing
|
||||||
|
/// this at runtime to explicitly capture them again.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **Wayland / macOS / iOS / Android / Orbital:** Unsupported.
|
||||||
|
///
|
||||||
|
/// [`DeviceEvent`]: crate::event::DeviceEvent
|
||||||
|
pub fn listen_device_events(&self, allowed: DeviceEvents) {
|
||||||
|
self.p.listen_device_events(allowed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets the [`ControlFlow`].
|
||||||
|
pub fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||||
|
self.p.set_control_flow(control_flow)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets the current [`ControlFlow`].
|
||||||
|
pub fn control_flow(&self) -> ControlFlow {
|
||||||
|
self.p.control_flow()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This exits the event loop.
|
||||||
|
///
|
||||||
|
/// See [`LoopExiting`](Event::LoopExiting).
|
||||||
|
pub fn exit(&self) {
|
||||||
|
self.p.exit()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns if the [`EventLoop`] is about to stop.
|
||||||
|
///
|
||||||
|
/// See [`exit()`](Self::exit).
|
||||||
|
pub fn exiting(&self) -> bool {
|
||||||
|
self.p.exiting()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_06")]
|
||||||
|
impl<T> rwh_06::HasDisplayHandle for EventLoopWindowTarget<T> {
|
||||||
|
fn display_handle(&self) -> Result<rwh_06::DisplayHandle<'_>, rwh_06::HandleError> {
|
||||||
|
let raw = self.p.raw_display_handle_rwh_06()?;
|
||||||
|
// SAFETY: The display will never be deallocated while the event loop is alive.
|
||||||
|
Ok(unsafe { rwh_06::DisplayHandle::borrow_raw(raw) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_05")]
|
||||||
|
unsafe impl<T> rwh_05::HasRawDisplayHandle for EventLoopWindowTarget<T> {
|
||||||
|
/// Returns a [`rwh_05::RawDisplayHandle`] for the event loop.
|
||||||
|
fn raw_display_handle(&self) -> rwh_05::RawDisplayHandle {
|
||||||
|
self.p.raw_display_handle_rwh_05()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Used to send custom events to [`EventLoop`].
|
||||||
|
pub struct EventLoopProxy<T: 'static> {
|
||||||
|
event_loop_proxy: platform_impl::EventLoopProxy<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static> Clone for EventLoopProxy<T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self {
|
||||||
|
event_loop_proxy: self.event_loop_proxy.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static> EventLoopProxy<T> {
|
||||||
|
/// Send an event to the [`EventLoop`] from which this proxy was created. This emits a
|
||||||
|
/// `UserEvent(event)` event in the event loop, where `event` is the value passed to this
|
||||||
|
/// function.
|
||||||
|
///
|
||||||
|
/// Returns an `Err` if the associated [`EventLoop`] no longer exists.
|
||||||
|
///
|
||||||
|
/// [`UserEvent(event)`]: Event::UserEvent
|
||||||
|
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
|
||||||
|
self.event_loop_proxy.send_event(event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static> fmt::Debug for EventLoopProxy<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.pad("EventLoopProxy { .. }")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The error that is returned when an [`EventLoopProxy`] attempts to wake up an [`EventLoop`] that
|
||||||
|
/// no longer exists.
|
||||||
|
///
|
||||||
|
/// Contains the original event given to [`EventLoopProxy::send_event`].
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub struct EventLoopClosed<T>(pub T);
|
||||||
|
|
||||||
|
impl<T> fmt::Display for EventLoopClosed<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.write_str("Tried to wake up a closed `EventLoop`")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: fmt::Debug> error::Error for EventLoopClosed<T> {}
|
||||||
|
|
||||||
|
/// Control when device events are captured.
|
||||||
|
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default)]
|
||||||
|
pub enum DeviceEvents {
|
||||||
|
/// Report device events regardless of window focus.
|
||||||
|
Always,
|
||||||
|
/// Only capture device events while the window is focused.
|
||||||
|
#[default]
|
||||||
|
WhenFocused,
|
||||||
|
/// Never capture device events.
|
||||||
|
Never,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A unique identifier of the winit's async request.
|
||||||
|
///
|
||||||
|
/// This could be used to identify the async request once it's done
|
||||||
|
/// and a specific action must be taken.
|
||||||
|
///
|
||||||
|
/// One of the handling scenarious could be to maintain a working list
|
||||||
|
/// containing [`AsyncRequestSerial`] and some closure associated with it.
|
||||||
|
/// Then once event is arriving the working list is being traversed and a job
|
||||||
|
/// executed and removed from the list.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct AsyncRequestSerial {
|
||||||
|
serial: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsyncRequestSerial {
|
||||||
|
// TODO(kchibisov): Remove `cfg` when the clipboard will be added.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub(crate) fn get() -> Self {
|
||||||
|
static CURRENT_SERIAL: AtomicUsize = AtomicUsize::new(0);
|
||||||
|
// NOTE: We rely on wrap around here, while the user may just request
|
||||||
|
// in the loop usize::MAX times that's issue is considered on them.
|
||||||
|
let serial = CURRENT_SERIAL.fetch_add(1, Ordering::Relaxed);
|
||||||
|
Self { serial }
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+125
@@ -0,0 +1,125 @@
|
|||||||
|
use crate::platform_impl::PlatformIcon;
|
||||||
|
use std::{error::Error, fmt, io, mem};
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub(crate) struct Pixel {
|
||||||
|
pub(crate) r: u8,
|
||||||
|
pub(crate) g: u8,
|
||||||
|
pub(crate) b: u8,
|
||||||
|
pub(crate) a: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) const PIXEL_SIZE: usize = mem::size_of::<Pixel>();
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
/// An error produced when using [`Icon::from_rgba`] with invalid arguments.
|
||||||
|
pub enum BadIcon {
|
||||||
|
/// Produced when the length of the `rgba` argument isn't divisible by 4, thus `rgba` can't be
|
||||||
|
/// safely interpreted as 32bpp RGBA pixels.
|
||||||
|
ByteCountNotDivisibleBy4 { byte_count: usize },
|
||||||
|
/// Produced when the number of pixels (`rgba.len() / 4`) isn't equal to `width * height`.
|
||||||
|
/// At least one of your arguments is incorrect.
|
||||||
|
DimensionsVsPixelCount {
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
width_x_height: usize,
|
||||||
|
pixel_count: usize,
|
||||||
|
},
|
||||||
|
/// Produced when underlying OS functionality failed to create the icon
|
||||||
|
OsError(io::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for BadIcon {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
BadIcon::ByteCountNotDivisibleBy4 { byte_count } => write!(f,
|
||||||
|
"The length of the `rgba` argument ({byte_count:?}) isn't divisible by 4, making it impossible to interpret as 32bpp RGBA pixels.",
|
||||||
|
),
|
||||||
|
BadIcon::DimensionsVsPixelCount {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
width_x_height,
|
||||||
|
pixel_count,
|
||||||
|
} => write!(f,
|
||||||
|
"The specified dimensions ({width:?}x{height:?}) don't match the number of pixels supplied by the `rgba` argument ({pixel_count:?}). For those dimensions, the expected pixel count is {width_x_height:?}.",
|
||||||
|
),
|
||||||
|
BadIcon::OsError(e) => write!(f, "OS error when instantiating the icon: {e:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Error for BadIcon {}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub(crate) struct RgbaIcon {
|
||||||
|
pub(crate) rgba: Vec<u8>,
|
||||||
|
pub(crate) width: u32,
|
||||||
|
pub(crate) height: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For platforms which don't have window icons (e.g. web)
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub(crate) struct NoIcon;
|
||||||
|
|
||||||
|
#[allow(dead_code)] // These are not used on every platform
|
||||||
|
mod constructors {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
impl RgbaIcon {
|
||||||
|
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
||||||
|
if rgba.len() % PIXEL_SIZE != 0 {
|
||||||
|
return Err(BadIcon::ByteCountNotDivisibleBy4 {
|
||||||
|
byte_count: rgba.len(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let pixel_count = rgba.len() / PIXEL_SIZE;
|
||||||
|
if pixel_count != (width * height) as usize {
|
||||||
|
Err(BadIcon::DimensionsVsPixelCount {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
width_x_height: (width * height) as usize,
|
||||||
|
pixel_count,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
Ok(RgbaIcon {
|
||||||
|
rgba,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NoIcon {
|
||||||
|
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
||||||
|
// Create the rgba icon anyway to validate the input
|
||||||
|
let _ = RgbaIcon::from_rgba(rgba, width, height)?;
|
||||||
|
Ok(NoIcon)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An icon used for the window titlebar, taskbar, etc.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Icon {
|
||||||
|
pub(crate) inner: PlatformIcon,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for Icon {
|
||||||
|
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
|
||||||
|
fmt::Debug::fmt(&self.inner, formatter)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Icon {
|
||||||
|
/// Creates an icon from 32bpp RGBA data.
|
||||||
|
///
|
||||||
|
/// The length of `rgba` must be divisible by 4, and `width * height` must equal
|
||||||
|
/// `rgba.len() / 4`. Otherwise, this will return a `BadIcon` error.
|
||||||
|
pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
|
||||||
|
Ok(Icon {
|
||||||
|
inner: PlatformIcon::from_rgba(rgba, width, height)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+1798
File diff suppressed because it is too large.
Load diff
Vendored
+198
@@ -0,0 +1,198 @@
|
|||||||
|
//! Winit is a cross-platform window creation and event loop management library.
|
||||||
|
//!
|
||||||
|
//! # Building windows
|
||||||
|
//!
|
||||||
|
//! Before you can build a [`Window`], you first need to build an [`EventLoop`]. This is done with the
|
||||||
|
//! [`EventLoop::new()`] function.
|
||||||
|
//!
|
||||||
|
//! ```no_run
|
||||||
|
//! use winit::event_loop::EventLoop;
|
||||||
|
//! let event_loop = EventLoop::new().unwrap();
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! Once this is done, there are two ways to create a [`Window`]:
|
||||||
|
//!
|
||||||
|
//! - Calling [`Window::new(&event_loop)`][window_new].
|
||||||
|
//! - Calling [`let builder = WindowBuilder::new()`][window_builder_new] then [`builder.build(&event_loop)`][window_builder_build].
|
||||||
|
//!
|
||||||
|
//! The first method is the simplest and will give you default values for everything. The second
|
||||||
|
//! method allows you to customize the way your [`Window`] will look and behave by modifying the
|
||||||
|
//! fields of the [`WindowBuilder`] object before you create the [`Window`].
|
||||||
|
//!
|
||||||
|
//! # Event handling
|
||||||
|
//!
|
||||||
|
//! Once a [`Window`] has been created, it will generate different *events*. A [`Window`] object can
|
||||||
|
//! generate [`WindowEvent`]s when certain input events occur, such as a cursor moving over the
|
||||||
|
//! window or a key getting pressed while the window is focused. Devices can generate
|
||||||
|
//! [`DeviceEvent`]s, which contain unfiltered event data that isn't specific to a certain window.
|
||||||
|
//! Some user activity, like mouse movement, can generate both a [`WindowEvent`] *and* a
|
||||||
|
//! [`DeviceEvent`]. You can also create and handle your own custom [`Event::UserEvent`]s, if desired.
|
||||||
|
//!
|
||||||
|
//! You can retrieve events by calling [`EventLoop::run()`]. This function will
|
||||||
|
//! dispatch events for every [`Window`] that was created with that particular [`EventLoop`], and
|
||||||
|
//! will run until [`exit()`] is used, at which point [`Event::LoopExiting`].
|
||||||
|
//!
|
||||||
|
//! Winit no longer uses a `EventLoop::poll_events() -> impl Iterator<Event>`-based event loop
|
||||||
|
//! model, since that can't be implemented properly on some platforms (e.g web, iOS) and works poorly on
|
||||||
|
//! most other platforms. However, this model can be re-implemented to an extent with
|
||||||
|
#![cfg_attr(
|
||||||
|
any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
android_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform
|
||||||
|
),
|
||||||
|
doc = "[`EventLoopExtPumpEvents::pump_events()`][platform::pump_events::EventLoopExtPumpEvents::pump_events()]"
|
||||||
|
)]
|
||||||
|
#![cfg_attr(
|
||||||
|
not(any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
android_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform
|
||||||
|
)),
|
||||||
|
doc = "`EventLoopExtPumpEvents::pump_events()`"
|
||||||
|
)]
|
||||||
|
//! [^1]. See that method's documentation for more reasons about why
|
||||||
|
//! it's discouraged beyond compatibility reasons.
|
||||||
|
//!
|
||||||
|
//!
|
||||||
|
//! ```no_run
|
||||||
|
//! use winit::{
|
||||||
|
//! event::{Event, WindowEvent},
|
||||||
|
//! event_loop::{ControlFlow, EventLoop},
|
||||||
|
//! window::WindowBuilder,
|
||||||
|
//! };
|
||||||
|
//!
|
||||||
|
//! let event_loop = EventLoop::new().unwrap();
|
||||||
|
//! let window = WindowBuilder::new().build(&event_loop).unwrap();
|
||||||
|
//!
|
||||||
|
//! // ControlFlow::Poll continuously runs the event loop, even if the OS hasn't
|
||||||
|
//! // dispatched any events. This is ideal for games and similar applications.
|
||||||
|
//! event_loop.set_control_flow(ControlFlow::Poll);
|
||||||
|
//!
|
||||||
|
//! // ControlFlow::Wait pauses the event loop if no events are available to process.
|
||||||
|
//! // This is ideal for non-game applications that only update in response to user
|
||||||
|
//! // input, and uses significantly less power/CPU time than ControlFlow::Poll.
|
||||||
|
//! event_loop.set_control_flow(ControlFlow::Wait);
|
||||||
|
//!
|
||||||
|
//! event_loop.run(move |event, elwt| {
|
||||||
|
//! match event {
|
||||||
|
//! Event::WindowEvent {
|
||||||
|
//! event: WindowEvent::CloseRequested,
|
||||||
|
//! ..
|
||||||
|
//! } => {
|
||||||
|
//! println!("The close button was pressed; stopping");
|
||||||
|
//! elwt.exit();
|
||||||
|
//! },
|
||||||
|
//! Event::AboutToWait => {
|
||||||
|
//! // Application update code.
|
||||||
|
//!
|
||||||
|
//! // Queue a RedrawRequested event.
|
||||||
|
//! //
|
||||||
|
//! // You only need to call this if you've determined that you need to redraw in
|
||||||
|
//! // applications which do not always need to. Applications that redraw continuously
|
||||||
|
//! // can render here instead.
|
||||||
|
//! window.request_redraw();
|
||||||
|
//! },
|
||||||
|
//! Event::WindowEvent {
|
||||||
|
//! event: WindowEvent::RedrawRequested,
|
||||||
|
//! ..
|
||||||
|
//! } => {
|
||||||
|
//! // Redraw the application.
|
||||||
|
//! //
|
||||||
|
//! // It's preferable for applications that do not render continuously to render in
|
||||||
|
//! // this event rather than in AboutToWait, since rendering in here allows
|
||||||
|
//! // the program to gracefully handle redraws requested by the OS.
|
||||||
|
//! },
|
||||||
|
//! _ => ()
|
||||||
|
//! }
|
||||||
|
//! });
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! [`WindowEvent`] has a [`WindowId`] member. In multi-window environments, it should be
|
||||||
|
//! compared to the value returned by [`Window::id()`] to determine which [`Window`]
|
||||||
|
//! dispatched the event.
|
||||||
|
//!
|
||||||
|
//! # Drawing on the window
|
||||||
|
//!
|
||||||
|
//! Winit doesn't directly provide any methods for drawing on a [`Window`]. However, it allows you to
|
||||||
|
//! retrieve the raw handle of the window and display (see the [`platform`] module and/or the
|
||||||
|
//! [`raw_window_handle`] and [`raw_display_handle`] methods), which in turn allows
|
||||||
|
//! you to create an OpenGL/Vulkan/DirectX/Metal/etc. context that can be used to render graphics.
|
||||||
|
//!
|
||||||
|
//! Note that many platforms will display garbage data in the window's client area if the
|
||||||
|
//! application doesn't render anything to the window by the time the desktop compositor is ready to
|
||||||
|
//! display the window to the user. If you notice this happening, you should create the window with
|
||||||
|
//! [`visible` set to `false`](crate::window::WindowBuilder::with_visible) and explicitly make the
|
||||||
|
//! window visible only once you're ready to render into it.
|
||||||
|
//!
|
||||||
|
//! [`EventLoop`]: event_loop::EventLoop
|
||||||
|
//! [`EventLoop::new()`]: event_loop::EventLoop::new
|
||||||
|
//! [`EventLoop::run()`]: event_loop::EventLoop::run
|
||||||
|
//! [`exit()`]: event_loop::EventLoopWindowTarget::exit
|
||||||
|
//! [`Window`]: window::Window
|
||||||
|
//! [`WindowId`]: window::WindowId
|
||||||
|
//! [`WindowBuilder`]: window::WindowBuilder
|
||||||
|
//! [window_new]: window::Window::new
|
||||||
|
//! [window_builder_new]: window::WindowBuilder::new
|
||||||
|
//! [window_builder_build]: window::WindowBuilder::build
|
||||||
|
//! [`Window::id()`]: window::Window::id
|
||||||
|
//! [`WindowEvent`]: event::WindowEvent
|
||||||
|
//! [`DeviceEvent`]: event::DeviceEvent
|
||||||
|
//! [`Event::UserEvent`]: event::Event::UserEvent
|
||||||
|
//! [`Event::LoopExiting`]: event::Event::LoopExiting
|
||||||
|
//! [`raw_window_handle`]: ./window/struct.Window.html#method.raw_window_handle
|
||||||
|
//! [`raw_display_handle`]: ./window/struct.Window.html#method.raw_display_handle
|
||||||
|
//! [^1]: `EventLoopExtPumpEvents::pump_events()` is only available on Windows, macOS, Android, X11 and Wayland.
|
||||||
|
|
||||||
|
#![deny(rust_2018_idioms)]
|
||||||
|
#![deny(rustdoc::broken_intra_doc_links)]
|
||||||
|
#![deny(clippy::all)]
|
||||||
|
#![deny(unsafe_op_in_unsafe_fn)]
|
||||||
|
#![cfg_attr(feature = "cargo-clippy", deny(warnings))]
|
||||||
|
// Doc feature labels can be tested locally by running RUSTDOCFLAGS="--cfg=docsrs" cargo +nightly doc
|
||||||
|
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||||
|
#![allow(clippy::missing_safety_doc)]
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_06")]
|
||||||
|
pub use rwh_06 as raw_window_handle;
|
||||||
|
|
||||||
|
#[allow(unused_imports)]
|
||||||
|
#[macro_use]
|
||||||
|
extern crate log;
|
||||||
|
#[cfg(feature = "serde")]
|
||||||
|
#[macro_use]
|
||||||
|
extern crate serde;
|
||||||
|
#[macro_use]
|
||||||
|
extern crate bitflags;
|
||||||
|
|
||||||
|
pub mod dpi;
|
||||||
|
#[macro_use]
|
||||||
|
pub mod error;
|
||||||
|
pub mod event;
|
||||||
|
pub mod event_loop;
|
||||||
|
mod icon;
|
||||||
|
pub mod keyboard;
|
||||||
|
pub mod monitor;
|
||||||
|
mod platform_impl;
|
||||||
|
pub mod window;
|
||||||
|
|
||||||
|
pub mod platform;
|
||||||
|
|
||||||
|
/// Wrapper for objects which winit will access on the main thread so they are effectively `Send`
|
||||||
|
/// and `Sync`, since they always execute on a single thread.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
///
|
||||||
|
/// Winit can run only one event loop at a time, and the event loop itself is tied to some thread.
|
||||||
|
/// The objects could be sent across the threads, but once passed to winit, they execute on the
|
||||||
|
/// main thread if the platform demands it. Thus, marking such objects as `Send + Sync` is safe.
|
||||||
|
#[doc(hidden)]
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub(crate) struct SendSyncWrapper<T>(pub(crate) T);
|
||||||
|
|
||||||
|
unsafe impl<T> Send for SendSyncWrapper<T> {}
|
||||||
|
unsafe impl<T> Sync for SendSyncWrapper<T> {}
|
||||||
Vendored
+169
@@ -0,0 +1,169 @@
|
|||||||
|
//! Types useful for interacting with a user's monitors.
|
||||||
|
//!
|
||||||
|
//! If you want to get basic information about a monitor, you can use the
|
||||||
|
//! [`MonitorHandle`] type. This is retrieved from one of the following
|
||||||
|
//! methods, which return an iterator of [`MonitorHandle`]:
|
||||||
|
//! - [`EventLoopWindowTarget::available_monitors`](crate::event_loop::EventLoopWindowTarget::available_monitors).
|
||||||
|
//! - [`Window::available_monitors`](crate::window::Window::available_monitors).
|
||||||
|
use crate::{
|
||||||
|
dpi::{PhysicalPosition, PhysicalSize},
|
||||||
|
platform_impl,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Describes a fullscreen video mode of a monitor.
|
||||||
|
///
|
||||||
|
/// Can be acquired with [`MonitorHandle::video_modes`].
|
||||||
|
#[derive(Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub struct VideoMode {
|
||||||
|
pub(crate) video_mode: platform_impl::VideoMode,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for VideoMode {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
self.video_mode.fmt(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialOrd for VideoMode {
|
||||||
|
fn partial_cmp(&self, other: &VideoMode) -> Option<std::cmp::Ordering> {
|
||||||
|
Some(self.cmp(other))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ord for VideoMode {
|
||||||
|
fn cmp(&self, other: &VideoMode) -> std::cmp::Ordering {
|
||||||
|
self.monitor().cmp(&other.monitor()).then(
|
||||||
|
self.size()
|
||||||
|
.cmp(&other.size())
|
||||||
|
.then(
|
||||||
|
self.refresh_rate_millihertz()
|
||||||
|
.cmp(&other.refresh_rate_millihertz())
|
||||||
|
.then(self.bit_depth().cmp(&other.bit_depth())),
|
||||||
|
)
|
||||||
|
.reverse(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VideoMode {
|
||||||
|
/// Returns the resolution of this video mode.
|
||||||
|
#[inline]
|
||||||
|
pub fn size(&self) -> PhysicalSize<u32> {
|
||||||
|
self.video_mode.size()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the bit depth of this video mode, as in how many bits you have
|
||||||
|
/// available per color. This is generally 24 bits or 32 bits on modern
|
||||||
|
/// systems, depending on whether the alpha channel is counted or not.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **Wayland / Orbital:** Always returns 32.
|
||||||
|
/// - **iOS:** Always returns 32.
|
||||||
|
#[inline]
|
||||||
|
pub fn bit_depth(&self) -> u16 {
|
||||||
|
self.video_mode.bit_depth()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the refresh rate of this video mode in mHz.
|
||||||
|
#[inline]
|
||||||
|
pub fn refresh_rate_millihertz(&self) -> u32 {
|
||||||
|
self.video_mode.refresh_rate_millihertz()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the monitor that this video mode is valid for. Each monitor has
|
||||||
|
/// a separate set of valid video modes.
|
||||||
|
#[inline]
|
||||||
|
pub fn monitor(&self) -> MonitorHandle {
|
||||||
|
MonitorHandle {
|
||||||
|
inner: self.video_mode.monitor(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for VideoMode {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(
|
||||||
|
f,
|
||||||
|
"{}x{} @ {} mHz ({} bpp)",
|
||||||
|
self.size().width,
|
||||||
|
self.size().height,
|
||||||
|
self.refresh_rate_millihertz(),
|
||||||
|
self.bit_depth()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handle to a monitor.
|
||||||
|
///
|
||||||
|
/// Allows you to retrieve information about a given monitor and can be used in [`Window`] creation.
|
||||||
|
///
|
||||||
|
/// [`Window`]: crate::window::Window
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
pub struct MonitorHandle {
|
||||||
|
pub(crate) inner: platform_impl::MonitorHandle,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonitorHandle {
|
||||||
|
/// Returns a human-readable name of the monitor.
|
||||||
|
///
|
||||||
|
/// Returns `None` if the monitor doesn't exist anymore.
|
||||||
|
#[inline]
|
||||||
|
pub fn name(&self) -> Option<String> {
|
||||||
|
self.inner.name()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the monitor's resolution.
|
||||||
|
#[inline]
|
||||||
|
pub fn size(&self) -> PhysicalSize<u32> {
|
||||||
|
self.inner.size()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the top-left corner position of the monitor relative to the larger full
|
||||||
|
/// screen area.
|
||||||
|
#[inline]
|
||||||
|
pub fn position(&self) -> PhysicalPosition<i32> {
|
||||||
|
self.inner.position()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The monitor refresh rate used by the system.
|
||||||
|
///
|
||||||
|
/// Return `Some` if succeed, or `None` if failed, which usually happens when the monitor
|
||||||
|
/// the window is on is removed.
|
||||||
|
///
|
||||||
|
/// When using exclusive fullscreen, the refresh rate of the [`VideoMode`] that was used to
|
||||||
|
/// enter fullscreen should be used instead.
|
||||||
|
#[inline]
|
||||||
|
pub fn refresh_rate_millihertz(&self) -> Option<u32> {
|
||||||
|
self.inner.refresh_rate_millihertz()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the scale factor of the underlying monitor. To map logical pixels to physical
|
||||||
|
/// pixels and vice versa, use [`Window::scale_factor`].
|
||||||
|
///
|
||||||
|
/// See the [`dpi`](crate::dpi) module for more information.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **X11:** Can be overridden using the `WINIT_X11_SCALE_FACTOR` environment variable.
|
||||||
|
/// - **Wayland:** May differ from [`Window::scale_factor`].
|
||||||
|
/// - **Android:** Always returns 1.0.
|
||||||
|
///
|
||||||
|
/// [`Window::scale_factor`]: crate::window::Window::scale_factor
|
||||||
|
#[inline]
|
||||||
|
pub fn scale_factor(&self) -> f64 {
|
||||||
|
self.inner.scale_factor()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns all fullscreen video modes supported by this monitor.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
///
|
||||||
|
/// - **Web:** Always returns an empty iterator
|
||||||
|
#[inline]
|
||||||
|
pub fn video_modes(&self) -> impl Iterator<Item = VideoMode> {
|
||||||
|
self.inner
|
||||||
|
.video_modes()
|
||||||
|
.map(|video_mode| VideoMode { video_mode })
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+93
@@ -0,0 +1,93 @@
|
|||||||
|
use crate::{
|
||||||
|
event_loop::{EventLoop, EventLoopBuilder, EventLoopWindowTarget},
|
||||||
|
window::{Window, WindowBuilder},
|
||||||
|
};
|
||||||
|
|
||||||
|
use android_activity::{AndroidApp, ConfigurationRef, Rect};
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoop`] that are specific to Android.
|
||||||
|
pub trait EventLoopExtAndroid {}
|
||||||
|
|
||||||
|
impl<T> EventLoopExtAndroid for EventLoop<T> {}
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoopWindowTarget`] that are specific to Android.
|
||||||
|
pub trait EventLoopWindowTargetExtAndroid {}
|
||||||
|
|
||||||
|
/// Additional methods on [`Window`] that are specific to Android.
|
||||||
|
pub trait WindowExtAndroid {
|
||||||
|
fn content_rect(&self) -> Rect;
|
||||||
|
|
||||||
|
fn config(&self) -> ConfigurationRef;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowExtAndroid for Window {
|
||||||
|
fn content_rect(&self) -> Rect {
|
||||||
|
self.window.content_rect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn config(&self) -> ConfigurationRef {
|
||||||
|
self.window.config()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopWindowTargetExtAndroid for EventLoopWindowTarget<T> {}
|
||||||
|
|
||||||
|
/// Additional methods on [`WindowBuilder`] that are specific to Android.
|
||||||
|
pub trait WindowBuilderExtAndroid {}
|
||||||
|
|
||||||
|
impl WindowBuilderExtAndroid for WindowBuilder {}
|
||||||
|
|
||||||
|
pub trait EventLoopBuilderExtAndroid {
|
||||||
|
/// Associates the `AndroidApp` that was passed to `android_main()` with the event loop
|
||||||
|
///
|
||||||
|
/// This must be called on Android since the `AndroidApp` is not global state.
|
||||||
|
fn with_android_app(&mut self, app: AndroidApp) -> &mut Self;
|
||||||
|
|
||||||
|
/// Calling this will mark the volume keys to be manually handled by the application
|
||||||
|
///
|
||||||
|
/// Default is to let the operating system handle the volume keys
|
||||||
|
fn handle_volume_keys(&mut self) -> &mut Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopBuilderExtAndroid for EventLoopBuilder<T> {
|
||||||
|
fn with_android_app(&mut self, app: AndroidApp) -> &mut Self {
|
||||||
|
self.platform_specific.android_app = Some(app);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_volume_keys(&mut self) -> &mut Self {
|
||||||
|
self.platform_specific.ignore_volume_keys = false;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-export of the `android_activity` API
|
||||||
|
///
|
||||||
|
/// Winit re-exports the `android_activity` API for convenience so that most
|
||||||
|
/// applications can rely on the Winit crate to resolve the required version of
|
||||||
|
/// `android_activity` and avoid any chance of a conflict between Winit and the
|
||||||
|
/// application crate.
|
||||||
|
///
|
||||||
|
/// Unlike most libraries there can only be a single implementation
|
||||||
|
/// of the `android_activity` glue crate linked with an application because
|
||||||
|
/// it is responsible for the application's `android_main()` entry point.
|
||||||
|
///
|
||||||
|
/// Since Winit depends on a specific version of `android_activity` the simplest
|
||||||
|
/// way to avoid creating a conflict is for applications to avoid explicitly
|
||||||
|
/// depending on the `android_activity` crate, and instead consume the API that
|
||||||
|
/// is re-exported by Winit.
|
||||||
|
///
|
||||||
|
/// For compatibility applications should then import the `AndroidApp` type for
|
||||||
|
/// their `android_main(app: AndroidApp)` function like:
|
||||||
|
/// ```rust
|
||||||
|
/// #[cfg(target_os="android")]
|
||||||
|
/// use winit::platform::android::activity::AndroidApp;
|
||||||
|
/// ```
|
||||||
|
pub mod activity {
|
||||||
|
// We enable the `"native-activity"` feature just so that we can build the
|
||||||
|
// docs, but it'll be very confusing for users to see the docs with that
|
||||||
|
// feature enabled, so we avoid inlining it so that they're forced to view
|
||||||
|
// it on the crate's own docs.rs page.
|
||||||
|
#[doc(no_inline)]
|
||||||
|
pub use android_activity::*;
|
||||||
|
}
|
||||||
Vendored
+308
@@ -0,0 +1,308 @@
|
|||||||
|
use std::os::raw::c_void;
|
||||||
|
|
||||||
|
use icrate::Foundation::MainThreadMarker;
|
||||||
|
use objc2::rc::Id;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
event_loop::EventLoop,
|
||||||
|
monitor::{MonitorHandle, VideoMode},
|
||||||
|
window::{Window, WindowBuilder},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoop`] that are specific to iOS.
|
||||||
|
pub trait EventLoopExtIOS {
|
||||||
|
/// Returns the [`Idiom`] (phone/tablet/tv/etc) for the current device.
|
||||||
|
fn idiom(&self) -> Idiom;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static> EventLoopExtIOS for EventLoop<T> {
|
||||||
|
fn idiom(&self) -> Idiom {
|
||||||
|
self.event_loop.idiom()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`Window`] that are specific to iOS.
|
||||||
|
pub trait WindowExtIOS {
|
||||||
|
/// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `scale_factor`.
|
||||||
|
///
|
||||||
|
/// The default value is device dependent, and it's recommended GLES or Metal applications set
|
||||||
|
/// this to [`MonitorHandle::scale_factor()`].
|
||||||
|
///
|
||||||
|
/// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc
|
||||||
|
/// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc
|
||||||
|
fn set_scale_factor(&self, scale_factor: f64);
|
||||||
|
|
||||||
|
/// Sets the valid orientations for the [`Window`].
|
||||||
|
///
|
||||||
|
/// The default value is [`ValidOrientations::LandscapeAndPortrait`].
|
||||||
|
///
|
||||||
|
/// This changes the value returned by
|
||||||
|
/// [`-[UIViewController supportedInterfaceOrientations]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621435-supportedinterfaceorientations?language=objc),
|
||||||
|
/// and then calls
|
||||||
|
/// [`-[UIViewController attemptRotationToDeviceOrientation]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621400-attemptrotationtodeviceorientati?language=objc).
|
||||||
|
fn set_valid_orientations(&self, valid_orientations: ValidOrientations);
|
||||||
|
|
||||||
|
/// Sets whether the [`Window`] prefers the home indicator hidden.
|
||||||
|
///
|
||||||
|
/// The default is to prefer showing the home indicator.
|
||||||
|
///
|
||||||
|
/// This changes the value returned by
|
||||||
|
/// [`-[UIViewController prefersHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887510-prefershomeindicatorautohidden?language=objc),
|
||||||
|
/// and then calls
|
||||||
|
/// [`-[UIViewController setNeedsUpdateOfHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887509-setneedsupdateofhomeindicatoraut?language=objc).
|
||||||
|
///
|
||||||
|
/// This only has an effect on iOS 11.0+.
|
||||||
|
fn set_prefers_home_indicator_hidden(&self, hidden: bool);
|
||||||
|
|
||||||
|
/// Sets the screen edges for which the system gestures will take a lower priority than the
|
||||||
|
/// application's touch handling.
|
||||||
|
///
|
||||||
|
/// This changes the value returned by
|
||||||
|
/// [`-[UIViewController preferredScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887512-preferredscreenedgesdeferringsys?language=objc),
|
||||||
|
/// and then calls
|
||||||
|
/// [`-[UIViewController setNeedsUpdateOfScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887507-setneedsupdateofscreenedgesdefer?language=objc).
|
||||||
|
///
|
||||||
|
/// This only has an effect on iOS 11.0+.
|
||||||
|
fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge);
|
||||||
|
|
||||||
|
/// Sets whether the [`Window`] prefers the status bar hidden.
|
||||||
|
///
|
||||||
|
/// The default is to prefer showing the status bar.
|
||||||
|
///
|
||||||
|
/// This sets the value of the
|
||||||
|
/// [`prefersStatusBarHidden`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621440-prefersstatusbarhidden?language=objc)
|
||||||
|
/// property.
|
||||||
|
///
|
||||||
|
/// [`setNeedsStatusBarAppearanceUpdate()`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621354-setneedsstatusbarappearanceupdat?language=objc)
|
||||||
|
/// is also called for you.
|
||||||
|
fn set_prefers_status_bar_hidden(&self, hidden: bool);
|
||||||
|
|
||||||
|
/// Sets the preferred status bar style for the [`Window`].
|
||||||
|
///
|
||||||
|
/// The default is system-defined.
|
||||||
|
///
|
||||||
|
/// This sets the value of the
|
||||||
|
/// [`preferredStatusBarStyle`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621416-preferredstatusbarstyle?language=objc)
|
||||||
|
/// property.
|
||||||
|
///
|
||||||
|
/// [`setNeedsStatusBarAppearanceUpdate()`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621354-setneedsstatusbarappearanceupdat?language=objc)
|
||||||
|
/// is also called for you.
|
||||||
|
fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowExtIOS for Window {
|
||||||
|
#[inline]
|
||||||
|
fn set_scale_factor(&self, scale_factor: f64) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_scale_factor(scale_factor))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_valid_orientations(&self, valid_orientations: ValidOrientations) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_valid_orientations(valid_orientations))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_prefers_home_indicator_hidden(&self, hidden: bool) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_prefers_home_indicator_hidden(hidden))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_preferred_screen_edges_deferring_system_gestures(&self, edges: ScreenEdge) {
|
||||||
|
self.window.maybe_queue_on_main(move |w| {
|
||||||
|
w.set_preferred_screen_edges_deferring_system_gestures(edges)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_prefers_status_bar_hidden(&self, hidden: bool) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_prefers_status_bar_hidden(hidden))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_preferred_status_bar_style(&self, status_bar_style: StatusBarStyle) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_preferred_status_bar_style(status_bar_style))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`WindowBuilder`] that are specific to iOS.
|
||||||
|
pub trait WindowBuilderExtIOS {
|
||||||
|
/// Sets the [`contentScaleFactor`] of the underlying [`UIWindow`] to `scale_factor`.
|
||||||
|
///
|
||||||
|
/// The default value is device dependent, and it's recommended GLES or Metal applications set
|
||||||
|
/// this to [`MonitorHandle::scale_factor()`].
|
||||||
|
///
|
||||||
|
/// [`UIWindow`]: https://developer.apple.com/documentation/uikit/uiwindow?language=objc
|
||||||
|
/// [`contentScaleFactor`]: https://developer.apple.com/documentation/uikit/uiview/1622657-contentscalefactor?language=objc
|
||||||
|
fn with_scale_factor(self, scale_factor: f64) -> Self;
|
||||||
|
|
||||||
|
/// Sets the valid orientations for the [`Window`].
|
||||||
|
///
|
||||||
|
/// The default value is [`ValidOrientations::LandscapeAndPortrait`].
|
||||||
|
///
|
||||||
|
/// This sets the initial value returned by
|
||||||
|
/// [`-[UIViewController supportedInterfaceOrientations]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621435-supportedinterfaceorientations?language=objc).
|
||||||
|
fn with_valid_orientations(self, valid_orientations: ValidOrientations) -> Self;
|
||||||
|
|
||||||
|
/// Sets whether the [`Window`] prefers the home indicator hidden.
|
||||||
|
///
|
||||||
|
/// The default is to prefer showing the home indicator.
|
||||||
|
///
|
||||||
|
/// This sets the initial value returned by
|
||||||
|
/// [`-[UIViewController prefersHomeIndicatorAutoHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887510-prefershomeindicatorautohidden?language=objc).
|
||||||
|
///
|
||||||
|
/// This only has an effect on iOS 11.0+.
|
||||||
|
fn with_prefers_home_indicator_hidden(self, hidden: bool) -> Self;
|
||||||
|
|
||||||
|
/// Sets the screen edges for which the system gestures will take a lower priority than the
|
||||||
|
/// application's touch handling.
|
||||||
|
///
|
||||||
|
/// This sets the initial value returned by
|
||||||
|
/// [`-[UIViewController preferredScreenEdgesDeferringSystemGestures]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/2887512-preferredscreenedgesdeferringsys?language=objc).
|
||||||
|
///
|
||||||
|
/// This only has an effect on iOS 11.0+.
|
||||||
|
fn with_preferred_screen_edges_deferring_system_gestures(self, edges: ScreenEdge) -> Self;
|
||||||
|
|
||||||
|
/// Sets whether the [`Window`] prefers the status bar hidden.
|
||||||
|
///
|
||||||
|
/// The default is to prefer showing the status bar.
|
||||||
|
///
|
||||||
|
/// This sets the initial value returned by
|
||||||
|
/// [`-[UIViewController prefersStatusBarHidden]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621440-prefersstatusbarhidden?language=objc).
|
||||||
|
fn with_prefers_status_bar_hidden(self, hidden: bool) -> Self;
|
||||||
|
|
||||||
|
/// Sets the style of the [`Window`]'s status bar.
|
||||||
|
///
|
||||||
|
/// The default is system-defined.
|
||||||
|
///
|
||||||
|
/// This sets the initial value returned by
|
||||||
|
/// [`-[UIViewController preferredStatusBarStyle]`](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621416-preferredstatusbarstyle?language=objc),
|
||||||
|
fn with_preferred_status_bar_style(self, status_bar_style: StatusBarStyle) -> Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowBuilderExtIOS for WindowBuilder {
|
||||||
|
#[inline]
|
||||||
|
fn with_scale_factor(mut self, scale_factor: f64) -> Self {
|
||||||
|
self.platform_specific.scale_factor = Some(scale_factor);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_valid_orientations(mut self, valid_orientations: ValidOrientations) -> Self {
|
||||||
|
self.platform_specific.valid_orientations = valid_orientations;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_prefers_home_indicator_hidden(mut self, hidden: bool) -> Self {
|
||||||
|
self.platform_specific.prefers_home_indicator_hidden = hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_preferred_screen_edges_deferring_system_gestures(mut self, edges: ScreenEdge) -> Self {
|
||||||
|
self.platform_specific
|
||||||
|
.preferred_screen_edges_deferring_system_gestures = edges;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_prefers_status_bar_hidden(mut self, hidden: bool) -> Self {
|
||||||
|
self.platform_specific.prefers_status_bar_hidden = hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_preferred_status_bar_style(mut self, status_bar_style: StatusBarStyle) -> Self {
|
||||||
|
self.platform_specific.preferred_status_bar_style = status_bar_style;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`MonitorHandle`] that are specific to iOS.
|
||||||
|
pub trait MonitorHandleExtIOS {
|
||||||
|
/// Returns a pointer to the [`UIScreen`] that is used by this monitor.
|
||||||
|
///
|
||||||
|
/// [`UIScreen`]: https://developer.apple.com/documentation/uikit/uiscreen?language=objc
|
||||||
|
fn ui_screen(&self) -> *mut c_void;
|
||||||
|
|
||||||
|
/// Returns the preferred [`VideoMode`] for this monitor.
|
||||||
|
///
|
||||||
|
/// This translates to a call to [`-[UIScreen preferredMode]`](https://developer.apple.com/documentation/uikit/uiscreen/1617823-preferredmode?language=objc).
|
||||||
|
fn preferred_video_mode(&self) -> VideoMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonitorHandleExtIOS for MonitorHandle {
|
||||||
|
#[inline]
|
||||||
|
fn ui_screen(&self) -> *mut c_void {
|
||||||
|
// SAFETY: The marker is only used to get the pointer of the screen
|
||||||
|
let mtm = unsafe { MainThreadMarker::new_unchecked() };
|
||||||
|
Id::as_ptr(self.inner.ui_screen(mtm)) as *mut c_void
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn preferred_video_mode(&self) -> VideoMode {
|
||||||
|
VideoMode {
|
||||||
|
video_mode: self.inner.preferred_video_mode(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Valid orientations for a particular [`Window`].
|
||||||
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub enum ValidOrientations {
|
||||||
|
/// Excludes `PortraitUpsideDown` on iphone
|
||||||
|
#[default]
|
||||||
|
LandscapeAndPortrait,
|
||||||
|
|
||||||
|
Landscape,
|
||||||
|
|
||||||
|
/// Excludes `PortraitUpsideDown` on iphone
|
||||||
|
Portrait,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The device [idiom].
|
||||||
|
///
|
||||||
|
/// [idiom]: https://developer.apple.com/documentation/uikit/uidevice/1620037-userinterfaceidiom?language=objc
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub enum Idiom {
|
||||||
|
Unspecified,
|
||||||
|
|
||||||
|
/// iPhone and iPod touch.
|
||||||
|
Phone,
|
||||||
|
|
||||||
|
/// iPad.
|
||||||
|
Pad,
|
||||||
|
|
||||||
|
/// tvOS and Apple TV.
|
||||||
|
TV,
|
||||||
|
CarPlay,
|
||||||
|
}
|
||||||
|
|
||||||
|
bitflags! {
|
||||||
|
/// The [edges] of a screen.
|
||||||
|
///
|
||||||
|
/// [edges]: https://developer.apple.com/documentation/uikit/uirectedge?language=objc
|
||||||
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub struct ScreenEdge: u8 {
|
||||||
|
const NONE = 0;
|
||||||
|
const TOP = 1 << 0;
|
||||||
|
const LEFT = 1 << 1;
|
||||||
|
const BOTTOM = 1 << 2;
|
||||||
|
const RIGHT = 1 << 3;
|
||||||
|
const ALL = ScreenEdge::TOP.bits() | ScreenEdge::LEFT.bits()
|
||||||
|
| ScreenEdge::BOTTOM.bits() | ScreenEdge::RIGHT.bits();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub enum StatusBarStyle {
|
||||||
|
#[default]
|
||||||
|
Default,
|
||||||
|
LightContent,
|
||||||
|
DarkContent,
|
||||||
|
}
|
||||||
Vendored
+422
@@ -0,0 +1,422 @@
|
|||||||
|
use std::os::raw::c_void;
|
||||||
|
|
||||||
|
use objc2::rc::Id;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
event_loop::{EventLoopBuilder, EventLoopWindowTarget},
|
||||||
|
monitor::MonitorHandle,
|
||||||
|
window::{Window, WindowBuilder},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Additional methods on [`Window`] that are specific to MacOS.
|
||||||
|
pub trait WindowExtMacOS {
|
||||||
|
/// Returns whether or not the window is in simple fullscreen mode.
|
||||||
|
fn simple_fullscreen(&self) -> bool;
|
||||||
|
|
||||||
|
/// Toggles a fullscreen mode that doesn't require a new macOS space.
|
||||||
|
/// Returns a boolean indicating whether the transition was successful (this
|
||||||
|
/// won't work if the window was already in the native fullscreen).
|
||||||
|
///
|
||||||
|
/// This is how fullscreen used to work on macOS in versions before Lion.
|
||||||
|
/// And allows the user to have a fullscreen window without using another
|
||||||
|
/// space or taking control over the entire monitor.
|
||||||
|
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool;
|
||||||
|
|
||||||
|
/// Returns whether or not the window has shadow.
|
||||||
|
fn has_shadow(&self) -> bool;
|
||||||
|
|
||||||
|
/// Sets whether or not the window has shadow.
|
||||||
|
fn set_has_shadow(&self, has_shadow: bool);
|
||||||
|
|
||||||
|
/// Group windows together by using the same tabbing identifier.
|
||||||
|
///
|
||||||
|
/// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
|
||||||
|
fn set_tabbing_identifier(&self, identifier: &str);
|
||||||
|
|
||||||
|
/// Returns the window's tabbing identifier.
|
||||||
|
fn tabbing_identifier(&self) -> String;
|
||||||
|
|
||||||
|
/// Select next tab.
|
||||||
|
fn select_next_tab(&self);
|
||||||
|
|
||||||
|
/// Select previous tab.
|
||||||
|
fn select_previous_tab(&self);
|
||||||
|
|
||||||
|
/// Select the tab with the given index.
|
||||||
|
///
|
||||||
|
/// Will no-op when the index is out of bounds.
|
||||||
|
fn select_tab_at_index(&self, index: usize);
|
||||||
|
|
||||||
|
/// Get the number of tabs in the window tab group.
|
||||||
|
fn num_tabs(&self) -> usize;
|
||||||
|
|
||||||
|
/// Get the window's edit state.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
///
|
||||||
|
/// ```ignore
|
||||||
|
/// WindowEvent::CloseRequested => {
|
||||||
|
/// if window.is_document_edited() {
|
||||||
|
/// // Show the user a save pop-up or similar
|
||||||
|
/// } else {
|
||||||
|
/// // Close the window
|
||||||
|
/// drop(window);
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
fn is_document_edited(&self) -> bool;
|
||||||
|
|
||||||
|
/// Put the window in a state which indicates a file save is required.
|
||||||
|
fn set_document_edited(&self, edited: bool);
|
||||||
|
|
||||||
|
/// Set option as alt behavior as described in [`OptionAsAlt`].
|
||||||
|
///
|
||||||
|
/// This will ignore diacritical marks and accent characters from
|
||||||
|
/// being processed as received characters. Instead, the input
|
||||||
|
/// device's raw character will be placed in event queues with the
|
||||||
|
/// Alt modifier set.
|
||||||
|
fn set_option_as_alt(&self, option_as_alt: OptionAsAlt);
|
||||||
|
|
||||||
|
/// Getter for the [`WindowExtMacOS::set_option_as_alt`].
|
||||||
|
fn option_as_alt(&self) -> OptionAsAlt;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowExtMacOS for Window {
|
||||||
|
#[inline]
|
||||||
|
fn simple_fullscreen(&self) -> bool {
|
||||||
|
self.window.maybe_wait_on_main(|w| w.simple_fullscreen())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_simple_fullscreen(&self, fullscreen: bool) -> bool {
|
||||||
|
self.window
|
||||||
|
.maybe_wait_on_main(move |w| w.set_simple_fullscreen(fullscreen))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn has_shadow(&self) -> bool {
|
||||||
|
self.window.maybe_wait_on_main(|w| w.has_shadow())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_has_shadow(&self, has_shadow: bool) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_has_shadow(has_shadow))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_tabbing_identifier(&self, identifier: &str) {
|
||||||
|
self.window
|
||||||
|
.maybe_wait_on_main(|w| w.set_tabbing_identifier(identifier))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn tabbing_identifier(&self) -> String {
|
||||||
|
self.window.maybe_wait_on_main(|w| w.tabbing_identifier())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn select_next_tab(&self) {
|
||||||
|
self.window.maybe_queue_on_main(|w| w.select_next_tab())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn select_previous_tab(&self) {
|
||||||
|
self.window.maybe_queue_on_main(|w| w.select_previous_tab())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn select_tab_at_index(&self, index: usize) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.select_tab_at_index(index))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn num_tabs(&self) -> usize {
|
||||||
|
self.window.maybe_wait_on_main(|w| w.num_tabs())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn is_document_edited(&self) -> bool {
|
||||||
|
self.window.maybe_wait_on_main(|w| w.is_document_edited())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_document_edited(&self, edited: bool) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_document_edited(edited))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_option_as_alt(&self, option_as_alt: OptionAsAlt) {
|
||||||
|
self.window
|
||||||
|
.maybe_queue_on_main(move |w| w.set_option_as_alt(option_as_alt))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn option_as_alt(&self) -> OptionAsAlt {
|
||||||
|
self.window.maybe_wait_on_main(|w| w.option_as_alt())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Corresponds to `NSApplicationActivationPolicy`.
|
||||||
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub enum ActivationPolicy {
|
||||||
|
/// Corresponds to `NSApplicationActivationPolicyRegular`.
|
||||||
|
#[default]
|
||||||
|
Regular,
|
||||||
|
|
||||||
|
/// Corresponds to `NSApplicationActivationPolicyAccessory`.
|
||||||
|
Accessory,
|
||||||
|
|
||||||
|
/// Corresponds to `NSApplicationActivationPolicyProhibited`.
|
||||||
|
Prohibited,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`WindowBuilder`] that are specific to MacOS.
|
||||||
|
///
|
||||||
|
/// **Note:** Properties dealing with the titlebar will be overwritten by the [`WindowBuilder::with_decorations`] method:
|
||||||
|
/// - `with_titlebar_transparent`
|
||||||
|
/// - `with_title_hidden`
|
||||||
|
/// - `with_titlebar_hidden`
|
||||||
|
/// - `with_titlebar_buttons_hidden`
|
||||||
|
/// - `with_fullsize_content_view`
|
||||||
|
pub trait WindowBuilderExtMacOS {
|
||||||
|
/// Enables click-and-drag behavior for the entire window, not just the titlebar.
|
||||||
|
fn with_movable_by_window_background(self, movable_by_window_background: bool) -> Self;
|
||||||
|
/// Makes the titlebar transparent and allows the content to appear behind it.
|
||||||
|
fn with_titlebar_transparent(self, titlebar_transparent: bool) -> Self;
|
||||||
|
/// Hides the window title.
|
||||||
|
fn with_title_hidden(self, title_hidden: bool) -> Self;
|
||||||
|
/// Hides the window titlebar.
|
||||||
|
fn with_titlebar_hidden(self, titlebar_hidden: bool) -> Self;
|
||||||
|
/// Hides the window titlebar buttons.
|
||||||
|
fn with_titlebar_buttons_hidden(self, titlebar_buttons_hidden: bool) -> Self;
|
||||||
|
/// Makes the window content appear behind the titlebar.
|
||||||
|
fn with_fullsize_content_view(self, fullsize_content_view: bool) -> Self;
|
||||||
|
fn with_disallow_hidpi(self, disallow_hidpi: bool) -> Self;
|
||||||
|
fn with_has_shadow(self, has_shadow: bool) -> Self;
|
||||||
|
/// Window accepts click-through mouse events.
|
||||||
|
fn with_accepts_first_mouse(self, accepts_first_mouse: bool) -> Self;
|
||||||
|
/// Defines the window tabbing identifier.
|
||||||
|
///
|
||||||
|
/// <https://developer.apple.com/documentation/appkit/nswindow/1644704-tabbingidentifier>
|
||||||
|
fn with_tabbing_identifier(self, identifier: &str) -> Self;
|
||||||
|
/// Set how the <kbd>Option</kbd> keys are interpreted.
|
||||||
|
///
|
||||||
|
/// See [`WindowExtMacOS::set_option_as_alt`] for details on what this means if set.
|
||||||
|
fn with_option_as_alt(self, option_as_alt: OptionAsAlt) -> Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowBuilderExtMacOS for WindowBuilder {
|
||||||
|
#[inline]
|
||||||
|
fn with_movable_by_window_background(mut self, movable_by_window_background: bool) -> Self {
|
||||||
|
self.platform_specific.movable_by_window_background = movable_by_window_background;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_titlebar_transparent(mut self, titlebar_transparent: bool) -> Self {
|
||||||
|
self.platform_specific.titlebar_transparent = titlebar_transparent;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_titlebar_hidden(mut self, titlebar_hidden: bool) -> Self {
|
||||||
|
self.platform_specific.titlebar_hidden = titlebar_hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_titlebar_buttons_hidden(mut self, titlebar_buttons_hidden: bool) -> Self {
|
||||||
|
self.platform_specific.titlebar_buttons_hidden = titlebar_buttons_hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_title_hidden(mut self, title_hidden: bool) -> Self {
|
||||||
|
self.platform_specific.title_hidden = title_hidden;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_fullsize_content_view(mut self, fullsize_content_view: bool) -> Self {
|
||||||
|
self.platform_specific.fullsize_content_view = fullsize_content_view;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_disallow_hidpi(mut self, disallow_hidpi: bool) -> Self {
|
||||||
|
self.platform_specific.disallow_hidpi = disallow_hidpi;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_has_shadow(mut self, has_shadow: bool) -> Self {
|
||||||
|
self.platform_specific.has_shadow = has_shadow;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_accepts_first_mouse(mut self, accepts_first_mouse: bool) -> Self {
|
||||||
|
self.platform_specific.accepts_first_mouse = accepts_first_mouse;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_tabbing_identifier(mut self, tabbing_identifier: &str) -> Self {
|
||||||
|
self.platform_specific
|
||||||
|
.tabbing_identifier
|
||||||
|
.replace(tabbing_identifier.to_string());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_option_as_alt(mut self, option_as_alt: OptionAsAlt) -> Self {
|
||||||
|
self.platform_specific.option_as_alt = option_as_alt;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait EventLoopBuilderExtMacOS {
|
||||||
|
/// Sets the activation policy for the application.
|
||||||
|
///
|
||||||
|
/// It is set to [`ActivationPolicy::Regular`] by default.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// Set the activation policy to "accessory".
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use winit::event_loop::EventLoopBuilder;
|
||||||
|
/// #[cfg(target_os = "macos")]
|
||||||
|
/// use winit::platform::macos::{EventLoopBuilderExtMacOS, ActivationPolicy};
|
||||||
|
///
|
||||||
|
/// let mut builder = EventLoopBuilder::new();
|
||||||
|
/// #[cfg(target_os = "macos")]
|
||||||
|
/// builder.with_activation_policy(ActivationPolicy::Accessory);
|
||||||
|
/// # if false { // We can't test this part
|
||||||
|
/// let event_loop = builder.build();
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
fn with_activation_policy(&mut self, activation_policy: ActivationPolicy) -> &mut Self;
|
||||||
|
|
||||||
|
/// Used to control whether a default menubar menu is created.
|
||||||
|
///
|
||||||
|
/// Menu creation is enabled by default.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// Disable creating a default menubar.
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use winit::event_loop::EventLoopBuilder;
|
||||||
|
/// #[cfg(target_os = "macos")]
|
||||||
|
/// use winit::platform::macos::EventLoopBuilderExtMacOS;
|
||||||
|
///
|
||||||
|
/// let mut builder = EventLoopBuilder::new();
|
||||||
|
/// #[cfg(target_os = "macos")]
|
||||||
|
/// builder.with_default_menu(false);
|
||||||
|
/// # if false { // We can't test this part
|
||||||
|
/// let event_loop = builder.build();
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
fn with_default_menu(&mut self, enable: bool) -> &mut Self;
|
||||||
|
|
||||||
|
/// Used to prevent the application from automatically activating when launched if
|
||||||
|
/// another application is already active.
|
||||||
|
///
|
||||||
|
/// The default behavior is to ignore other applications and activate when launched.
|
||||||
|
fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopBuilderExtMacOS for EventLoopBuilder<T> {
|
||||||
|
#[inline]
|
||||||
|
fn with_activation_policy(&mut self, activation_policy: ActivationPolicy) -> &mut Self {
|
||||||
|
self.platform_specific.activation_policy = activation_policy;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_default_menu(&mut self, enable: bool) -> &mut Self {
|
||||||
|
self.platform_specific.default_menu = enable;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_activate_ignoring_other_apps(&mut self, ignore: bool) -> &mut Self {
|
||||||
|
self.platform_specific.activate_ignoring_other_apps = ignore;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`MonitorHandle`] that are specific to MacOS.
|
||||||
|
pub trait MonitorHandleExtMacOS {
|
||||||
|
/// Returns the identifier of the monitor for Cocoa.
|
||||||
|
fn native_id(&self) -> u32;
|
||||||
|
/// Returns a pointer to the NSScreen representing this monitor.
|
||||||
|
fn ns_screen(&self) -> Option<*mut c_void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonitorHandleExtMacOS for MonitorHandle {
|
||||||
|
#[inline]
|
||||||
|
fn native_id(&self) -> u32 {
|
||||||
|
self.inner.native_identifier()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ns_screen(&self) -> Option<*mut c_void> {
|
||||||
|
self.inner.ns_screen().map(|s| Id::as_ptr(&s) as _)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoopWindowTarget`] that are specific to macOS.
|
||||||
|
pub trait EventLoopWindowTargetExtMacOS {
|
||||||
|
/// Hide the entire application. In most applications this is typically triggered with Command-H.
|
||||||
|
fn hide_application(&self);
|
||||||
|
/// Hide the other applications. In most applications this is typically triggered with Command+Option-H.
|
||||||
|
fn hide_other_applications(&self);
|
||||||
|
/// Set whether the system can automatically organize windows into tabs.
|
||||||
|
///
|
||||||
|
/// <https://developer.apple.com/documentation/appkit/nswindow/1646657-allowsautomaticwindowtabbing>
|
||||||
|
fn set_allows_automatic_window_tabbing(&self, enabled: bool);
|
||||||
|
/// Returns whether the system can automatically organize windows into tabs.
|
||||||
|
fn allows_automatic_window_tabbing(&self) -> bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopWindowTargetExtMacOS for EventLoopWindowTarget<T> {
|
||||||
|
fn hide_application(&self) {
|
||||||
|
self.p.hide_application()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hide_other_applications(&self) {
|
||||||
|
self.p.hide_other_applications()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_allows_automatic_window_tabbing(&self, enabled: bool) {
|
||||||
|
self.p.set_allows_automatic_window_tabbing(enabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn allows_automatic_window_tabbing(&self) -> bool {
|
||||||
|
self.p.allows_automatic_window_tabbing()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Option as alt behavior.
|
||||||
|
///
|
||||||
|
/// The default is `None`.
|
||||||
|
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
|
||||||
|
pub enum OptionAsAlt {
|
||||||
|
/// The left `Option` key is treated as `Alt`.
|
||||||
|
OnlyLeft,
|
||||||
|
|
||||||
|
/// The right `Option` key is treated as `Alt`.
|
||||||
|
OnlyRight,
|
||||||
|
|
||||||
|
/// Both `Option` keys are treated as `Alt`.
|
||||||
|
Both,
|
||||||
|
|
||||||
|
/// No special handling is applied for `Option` key.
|
||||||
|
#[default]
|
||||||
|
None,
|
||||||
|
}
|
||||||
Vendored
+65
@@ -0,0 +1,65 @@
|
|||||||
|
//! Contains traits with platform-specific methods in them.
|
||||||
|
//!
|
||||||
|
//! Contains the follow OS-specific modules:
|
||||||
|
//!
|
||||||
|
//! - `android`
|
||||||
|
//! - `ios`
|
||||||
|
//! - `macos`
|
||||||
|
//! - `unix`
|
||||||
|
//! - `windows`
|
||||||
|
//! - `web`
|
||||||
|
//!
|
||||||
|
//! And the following platform-specific modules:
|
||||||
|
//!
|
||||||
|
//! - `run_on_demand` (available on `windows`, `unix`, `macos`, `android`)
|
||||||
|
//! - `pump_events` (available on `windows`, `unix`, `macos`, `android`)
|
||||||
|
//!
|
||||||
|
//! However only the module corresponding to the platform you're compiling to will be available.
|
||||||
|
|
||||||
|
#[cfg(android_platform)]
|
||||||
|
pub mod android;
|
||||||
|
#[cfg(ios_platform)]
|
||||||
|
pub mod ios;
|
||||||
|
#[cfg(macos_platform)]
|
||||||
|
pub mod macos;
|
||||||
|
#[cfg(orbital_platform)]
|
||||||
|
pub mod orbital;
|
||||||
|
#[cfg(any(x11_platform, wayland_platform))]
|
||||||
|
pub mod startup_notify;
|
||||||
|
#[cfg(wayland_platform)]
|
||||||
|
pub mod wayland;
|
||||||
|
#[cfg(wasm_platform)]
|
||||||
|
pub mod web;
|
||||||
|
#[cfg(windows_platform)]
|
||||||
|
pub mod windows;
|
||||||
|
#[cfg(x11_platform)]
|
||||||
|
pub mod x11;
|
||||||
|
|
||||||
|
#[cfg(any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
android_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform
|
||||||
|
))]
|
||||||
|
pub mod run_on_demand;
|
||||||
|
|
||||||
|
#[cfg(any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
android_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform
|
||||||
|
))]
|
||||||
|
pub mod pump_events;
|
||||||
|
|
||||||
|
#[cfg(any(
|
||||||
|
windows_platform,
|
||||||
|
macos_platform,
|
||||||
|
x11_platform,
|
||||||
|
wayland_platform,
|
||||||
|
orbital_platform,
|
||||||
|
docsrs
|
||||||
|
))]
|
||||||
|
pub mod modifier_supplement;
|
||||||
|
pub mod scancode;
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
#![cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform))]
|
||||||
|
|
||||||
|
use crate::keyboard::Key;
|
||||||
|
|
||||||
|
/// Additional methods for the `KeyEvent` which cannot be implemented on all
|
||||||
|
/// platforms.
|
||||||
|
pub trait KeyEventExtModifierSupplement {
|
||||||
|
/// Identical to `KeyEvent::text` but this is affected by <kbd>Ctrl</kbd>.
|
||||||
|
///
|
||||||
|
/// For example, pressing <kbd>Ctrl</kbd>+<kbd>a</kbd> produces `Some("\x01")`.
|
||||||
|
fn text_with_all_modifiers(&self) -> Option<&str>;
|
||||||
|
|
||||||
|
/// This value ignores all modifiers including,
|
||||||
|
/// but not limited to <kbd>Shift</kbd>, <kbd>Caps Lock</kbd>,
|
||||||
|
/// and <kbd>Ctrl</kbd>. In most cases this means that the
|
||||||
|
/// unicode character in the resulting string is lowercase.
|
||||||
|
///
|
||||||
|
/// This is useful for key-bindings / shortcut key combinations.
|
||||||
|
///
|
||||||
|
/// In case `logical_key` reports `Dead`, this will still report the
|
||||||
|
/// key as `Character` according to the current keyboard layout. This value
|
||||||
|
/// cannot be `Dead`.
|
||||||
|
fn key_without_modifiers(&self) -> Key;
|
||||||
|
}
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
// There are no Orbital specific traits yet.
|
||||||
+189
@@ -0,0 +1,189 @@
|
|||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
event::Event,
|
||||||
|
event_loop::{EventLoop, EventLoopWindowTarget},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The return status for `pump_events`
|
||||||
|
pub enum PumpStatus {
|
||||||
|
/// Continue running external loop.
|
||||||
|
Continue,
|
||||||
|
/// Exit external loop.
|
||||||
|
Exit(i32),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoop`] for pumping events within an external event loop
|
||||||
|
pub trait EventLoopExtPumpEvents {
|
||||||
|
/// A type provided by the user that can be passed through [`Event::UserEvent`].
|
||||||
|
type UserEvent;
|
||||||
|
|
||||||
|
/// Pump the `EventLoop` to check for and dispatch pending events.
|
||||||
|
///
|
||||||
|
/// This API is designed to enable applications to integrate Winit into an
|
||||||
|
/// external event loop, for platforms that can support this.
|
||||||
|
///
|
||||||
|
/// The given `timeout` limits how long it may block waiting for new events.
|
||||||
|
///
|
||||||
|
/// Passing a `timeout` of `Some(Duration::ZERO)` would ensure your external
|
||||||
|
/// event loop is never blocked but you would likely need to consider how
|
||||||
|
/// to throttle your own external loop.
|
||||||
|
///
|
||||||
|
/// Passing a `timeout` of `None` means that it may wait indefinitely for new
|
||||||
|
/// events before returning control back to the external loop.
|
||||||
|
///
|
||||||
|
/// ## Example
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// # // Copied from examples/window_pump_events.rs
|
||||||
|
/// # #[cfg(any(
|
||||||
|
/// # windows_platform,
|
||||||
|
/// # macos_platform,
|
||||||
|
/// # x11_platform,
|
||||||
|
/// # wayland_platform,
|
||||||
|
/// # android_platform,
|
||||||
|
/// # ))]
|
||||||
|
/// fn main() -> std::process::ExitCode {
|
||||||
|
/// # use std::{process::ExitCode, thread::sleep, time::Duration};
|
||||||
|
/// #
|
||||||
|
/// # use simple_logger::SimpleLogger;
|
||||||
|
/// # use winit::{
|
||||||
|
/// # event::{Event, WindowEvent},
|
||||||
|
/// # event_loop::EventLoop,
|
||||||
|
/// # platform::pump_events::{EventLoopExtPumpEvents, PumpStatus},
|
||||||
|
/// # window::WindowBuilder,
|
||||||
|
/// # };
|
||||||
|
/// let mut event_loop = EventLoop::new().unwrap();
|
||||||
|
/// #
|
||||||
|
/// # SimpleLogger::new().init().unwrap();
|
||||||
|
/// let window = WindowBuilder::new()
|
||||||
|
/// .with_title("A fantastic window!")
|
||||||
|
/// .build(&event_loop)
|
||||||
|
/// .unwrap();
|
||||||
|
///
|
||||||
|
/// 'main: loop {
|
||||||
|
/// let timeout = Some(Duration::ZERO);
|
||||||
|
/// let status = event_loop.pump_events(timeout, |event, elwt| {
|
||||||
|
/// # if let Event::WindowEvent { event, .. } = &event {
|
||||||
|
/// # // Print only Window events to reduce noise
|
||||||
|
/// # println!("{event:?}");
|
||||||
|
/// # }
|
||||||
|
/// #
|
||||||
|
/// match event {
|
||||||
|
/// Event::WindowEvent {
|
||||||
|
/// event: WindowEvent::CloseRequested,
|
||||||
|
/// window_id,
|
||||||
|
/// } if window_id == window.id() => elwt.exit(),
|
||||||
|
/// Event::AboutToWait => {
|
||||||
|
/// window.request_redraw();
|
||||||
|
/// }
|
||||||
|
/// _ => (),
|
||||||
|
/// }
|
||||||
|
/// });
|
||||||
|
/// if let PumpStatus::Exit(exit_code) = status {
|
||||||
|
/// break 'main ExitCode::from(exit_code as u8);
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// // Sleep for 1/60 second to simulate application work
|
||||||
|
/// //
|
||||||
|
/// // Since `pump_events` doesn't block it will be important to
|
||||||
|
/// // throttle the loop in the app somehow.
|
||||||
|
/// println!("Update()");
|
||||||
|
/// sleep(Duration::from_millis(16));
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// **Note:** This is not a portable API, and its usage involves a number of
|
||||||
|
/// caveats and trade offs that should be considered before using this API!
|
||||||
|
///
|
||||||
|
/// You almost certainly shouldn't use this API, unless you absolutely know it's
|
||||||
|
/// the only practical option you have.
|
||||||
|
///
|
||||||
|
/// ## Synchronous events
|
||||||
|
///
|
||||||
|
/// Some events _must_ only be handled synchronously via the closure that
|
||||||
|
/// is passed to Winit so that the handler will also be synchronized with
|
||||||
|
/// the window system and operating system.
|
||||||
|
///
|
||||||
|
/// This is because some events are driven by a window system callback
|
||||||
|
/// where the window systems expects the application to have handled the
|
||||||
|
/// event before returning.
|
||||||
|
///
|
||||||
|
/// **These events can not be buffered and handled outside of the closure
|
||||||
|
/// passed to Winit.**
|
||||||
|
///
|
||||||
|
/// As a general rule it is not recommended to ever buffer events to handle
|
||||||
|
/// them outside of the closure passed to Winit since it's difficult to
|
||||||
|
/// provide guarantees about which events are safe to buffer across all
|
||||||
|
/// operating systems.
|
||||||
|
///
|
||||||
|
/// Notable events that will certainly create portability problems if
|
||||||
|
/// buffered and handled outside of Winit include:
|
||||||
|
/// - `RedrawRequested` events, used to schedule rendering.
|
||||||
|
///
|
||||||
|
/// macOS for example uses a `drawRect` callback to drive rendering
|
||||||
|
/// within applications and expects rendering to be finished before
|
||||||
|
/// the `drawRect` callback returns.
|
||||||
|
///
|
||||||
|
/// For portability it's strongly recommended that applications should
|
||||||
|
/// keep their rendering inside the closure provided to Winit.
|
||||||
|
/// - Any lifecycle events, such as `Suspended` / `Resumed`.
|
||||||
|
///
|
||||||
|
/// The handling of these events needs to be synchronized with the
|
||||||
|
/// operating system and it would never be appropriate to buffer a
|
||||||
|
/// notification that your application has been suspended or resumed and
|
||||||
|
/// then handled that later since there would always be a chance that
|
||||||
|
/// other lifecycle events occur while the event is buffered.
|
||||||
|
///
|
||||||
|
/// ## Supported Platforms
|
||||||
|
/// - Windows
|
||||||
|
/// - Linux
|
||||||
|
/// - MacOS
|
||||||
|
/// - Android
|
||||||
|
///
|
||||||
|
/// ## Unsupported Platforms
|
||||||
|
/// - **Web:** This API is fundamentally incompatible with the event-based way in which
|
||||||
|
/// Web browsers work because it's not possible to have a long-running external
|
||||||
|
/// loop that would block the browser and there is nothing that can be
|
||||||
|
/// polled to ask for new new events. Events are delivered via callbacks based
|
||||||
|
/// on an event loop that is internal to the browser itself.
|
||||||
|
/// - **iOS:** It's not possible to stop and start an `NSApplication` repeatedly on iOS so
|
||||||
|
/// there's no way to support the same approach to polling as on MacOS.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
/// - **Windows**: The implementation will use `PeekMessage` when checking for
|
||||||
|
/// window messages to avoid blocking your external event loop.
|
||||||
|
///
|
||||||
|
/// - **MacOS**: The implementation works in terms of stopping the global `NSApp`
|
||||||
|
/// whenever the application `RunLoop` indicates that it is preparing to block
|
||||||
|
/// and wait for new events.
|
||||||
|
///
|
||||||
|
/// This is very different to the polling APIs that are available on other
|
||||||
|
/// platforms (the lower level polling primitives on MacOS are private
|
||||||
|
/// implementation details for `NSApp` which aren't accessible to application
|
||||||
|
/// developers)
|
||||||
|
///
|
||||||
|
/// It's likely this will be less efficient than polling on other OSs and
|
||||||
|
/// it also means the `NSApp` is stopped while outside of the Winit
|
||||||
|
/// event loop - and that's observable (for example to crates like `rfd`)
|
||||||
|
/// because the `NSApp` is global state.
|
||||||
|
///
|
||||||
|
/// If you render outside of Winit you are likely to see window resizing artifacts
|
||||||
|
/// since MacOS expects applications to render synchronously during any `drawRect`
|
||||||
|
/// callback.
|
||||||
|
fn pump_events<F>(&mut self, timeout: Option<Duration>, event_handler: F) -> PumpStatus
|
||||||
|
where
|
||||||
|
F: FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget<Self::UserEvent>);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopExtPumpEvents for EventLoop<T> {
|
||||||
|
type UserEvent = T;
|
||||||
|
|
||||||
|
fn pump_events<F>(&mut self, timeout: Option<Duration>, event_handler: F) -> PumpStatus
|
||||||
|
where
|
||||||
|
F: FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget<Self::UserEvent>),
|
||||||
|
{
|
||||||
|
self.event_loop.pump_events(timeout, event_handler)
|
||||||
|
}
|
||||||
|
}
|
||||||
+89
@@ -0,0 +1,89 @@
|
|||||||
|
use crate::{
|
||||||
|
error::EventLoopError,
|
||||||
|
event::Event,
|
||||||
|
event_loop::{EventLoop, EventLoopWindowTarget},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(doc)]
|
||||||
|
use crate::{platform::pump_events::EventLoopExtPumpEvents, window::Window};
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoop`] to return control flow to the caller.
|
||||||
|
pub trait EventLoopExtRunOnDemand {
|
||||||
|
/// A type provided by the user that can be passed through [`Event::UserEvent`].
|
||||||
|
type UserEvent;
|
||||||
|
|
||||||
|
/// Runs the event loop in the calling thread and calls the given `event_handler` closure
|
||||||
|
/// to dispatch any window system events.
|
||||||
|
///
|
||||||
|
/// Unlike [`EventLoop::run`], this function accepts non-`'static` (i.e. non-`move`) closures
|
||||||
|
/// and it is possible to return control back to the caller without
|
||||||
|
/// consuming the `EventLoop` (by using [`exit()`]) and
|
||||||
|
/// so the event loop can be re-run after it has exit.
|
||||||
|
///
|
||||||
|
/// It's expected that each run of the loop will be for orthogonal instantiations of your
|
||||||
|
/// Winit application, but internally each instantiation may re-use some common window
|
||||||
|
/// system resources, such as a display server connection.
|
||||||
|
///
|
||||||
|
/// This API is not designed to run an event loop in bursts that you can exit from and return
|
||||||
|
/// to while maintaining the full state of your application. (If you need something like this
|
||||||
|
/// you can look at the [`EventLoopExtPumpEvents::pump_events()`] API)
|
||||||
|
///
|
||||||
|
/// Each time `run_on_demand` is called the `event_handler` can expect to receive a
|
||||||
|
/// `NewEvents(Init)` and `Resumed` event (even on platforms that have no suspend/resume
|
||||||
|
/// lifecycle) - which can be used to consistently initialize application state.
|
||||||
|
///
|
||||||
|
/// See the [`set_control_flow()`] docs on how to change the event loop's behavior.
|
||||||
|
///
|
||||||
|
/// # Caveats
|
||||||
|
/// - This extension isn't available on all platforms, since it's not always possible to return
|
||||||
|
/// to the caller (specifically this is impossible on iOS and Web - though with the Web
|
||||||
|
/// backend it is possible to use `EventLoopExtWebSys::spawn()`[^1] more than once instead).
|
||||||
|
/// - No [`Window`] state can be carried between separate runs of the event loop.
|
||||||
|
///
|
||||||
|
/// You are strongly encouraged to use [`EventLoop::run()`] for portability, unless you specifically need
|
||||||
|
/// the ability to re-run a single event loop more than once
|
||||||
|
///
|
||||||
|
/// # Supported Platforms
|
||||||
|
/// - Windows
|
||||||
|
/// - Linux
|
||||||
|
/// - macOS
|
||||||
|
/// - Android
|
||||||
|
///
|
||||||
|
/// # Unsupported Platforms
|
||||||
|
/// - **Web:** This API is fundamentally incompatible with the event-based way in which
|
||||||
|
/// Web browsers work because it's not possible to have a long-running external
|
||||||
|
/// loop that would block the browser and there is nothing that can be
|
||||||
|
/// polled to ask for new events. Events are delivered via callbacks based
|
||||||
|
/// on an event loop that is internal to the browser itself.
|
||||||
|
/// - **iOS:** It's not possible to stop and start an `NSApplication` repeatedly on iOS.
|
||||||
|
///
|
||||||
|
#[cfg_attr(
|
||||||
|
not(wasm_platform),
|
||||||
|
doc = "[^1]: `spawn()` is only available on `wasm` platforms."
|
||||||
|
)]
|
||||||
|
///
|
||||||
|
/// [`exit()`]: EventLoopWindowTarget::exit()
|
||||||
|
/// [`set_control_flow()`]: EventLoopWindowTarget::set_control_flow()
|
||||||
|
fn run_on_demand<F>(&mut self, event_handler: F) -> Result<(), EventLoopError>
|
||||||
|
where
|
||||||
|
F: FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget<Self::UserEvent>);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopExtRunOnDemand for EventLoop<T> {
|
||||||
|
type UserEvent = T;
|
||||||
|
|
||||||
|
fn run_on_demand<F>(&mut self, event_handler: F) -> Result<(), EventLoopError>
|
||||||
|
where
|
||||||
|
F: FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget<Self::UserEvent>),
|
||||||
|
{
|
||||||
|
self.event_loop.window_target().clear_exit();
|
||||||
|
self.event_loop.run_on_demand(event_handler)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopWindowTarget<T> {
|
||||||
|
/// Clear exit status.
|
||||||
|
pub(crate) fn clear_exit(&self) {
|
||||||
|
self.p.clear_exit()
|
||||||
|
}
|
||||||
|
}
|
||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
#![cfg(any(windows_platform, macos_platform, x11_platform, wayland_platform))]
|
||||||
|
|
||||||
|
use crate::keyboard::{KeyCode, PhysicalKey};
|
||||||
|
|
||||||
|
// TODO: Describe what this value contains for each platform
|
||||||
|
|
||||||
|
/// Additional methods for the [`PhysicalKey`] type that allow the user to access the platform-specific
|
||||||
|
/// scancode.
|
||||||
|
///
|
||||||
|
/// [`PhysicalKey`]: crate::keyboard::PhysicalKey
|
||||||
|
pub trait PhysicalKeyExtScancode {
|
||||||
|
/// The raw value of the platform-specific physical key identifier.
|
||||||
|
///
|
||||||
|
/// Returns `Some(key_id)` if the conversion was succesful; returns `None` otherwise.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
/// - **Windows:** A 16bit extended scancode
|
||||||
|
/// - **Wayland/X11**: A 32-bit linux scancode, which is X11/Wayland keycode subtracted by 8.
|
||||||
|
fn to_scancode(self) -> Option<u32>;
|
||||||
|
|
||||||
|
/// Constructs a `PhysicalKey` from a platform-specific physical key identifier.
|
||||||
|
///
|
||||||
|
/// Note that this conversion may be lossy, i.e. converting the returned `PhysicalKey` back
|
||||||
|
/// using `to_scancode` might not yield the original value.
|
||||||
|
///
|
||||||
|
/// ## Platform-specific
|
||||||
|
/// - **Wayland/X11**: A 32-bit linux scancode. When building from X11/Wayland keycode subtract
|
||||||
|
/// `8` to get the value you wanted.
|
||||||
|
fn from_scancode(scancode: u32) -> PhysicalKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PhysicalKeyExtScancode for KeyCode
|
||||||
|
where
|
||||||
|
PhysicalKey: PhysicalKeyExtScancode,
|
||||||
|
{
|
||||||
|
#[inline]
|
||||||
|
fn from_scancode(scancode: u32) -> PhysicalKey {
|
||||||
|
<PhysicalKey as PhysicalKeyExtScancode>::from_scancode(scancode)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn to_scancode(self) -> Option<u32> {
|
||||||
|
<PhysicalKey as PhysicalKeyExtScancode>::to_scancode(PhysicalKey::Code(self))
|
||||||
|
}
|
||||||
|
}
|
||||||
+99
@@ -0,0 +1,99 @@
|
|||||||
|
//! Window startup notification to handle window raising.
|
||||||
|
//!
|
||||||
|
//! The [`ActivationToken`] is essential to ensure that your newly
|
||||||
|
//! created window will obtain the focus, otherwise the user could
|
||||||
|
//! be requered to click on the window.
|
||||||
|
//!
|
||||||
|
//! Such token is usually delivered via the environment variable and
|
||||||
|
//! could be read from it with the [`EventLoopExtStartupNotify::read_token_from_env`].
|
||||||
|
//!
|
||||||
|
//! Such token must also be reset after reading it from your environment with
|
||||||
|
//! [`reset_activation_token_env`] otherwise child processes could inherit it.
|
||||||
|
//!
|
||||||
|
//! When starting a new child process with a newly obtained [`ActivationToken`] from
|
||||||
|
//! [`WindowExtStartupNotify::request_activation_token`] the [`set_activation_token_env`]
|
||||||
|
//! must be used to propagate it to the child
|
||||||
|
//!
|
||||||
|
//! To ensure the delivery of such token by other processes to you, the user should
|
||||||
|
//! set `StartupNotify=true` inside the `.desktop` file of their application.
|
||||||
|
//!
|
||||||
|
//! The specification could be found [`here`].
|
||||||
|
//!
|
||||||
|
//! [`here`]: https://specifications.freedesktop.org/startup-notification-spec/startup-notification-latest.txt
|
||||||
|
|
||||||
|
use std::env;
|
||||||
|
|
||||||
|
use crate::error::NotSupportedError;
|
||||||
|
use crate::event_loop::{AsyncRequestSerial, EventLoopWindowTarget};
|
||||||
|
use crate::window::{ActivationToken, Window, WindowBuilder};
|
||||||
|
|
||||||
|
/// The variable which is used mostly on X11.
|
||||||
|
const X11_VAR: &str = "DESKTOP_STARTUP_ID";
|
||||||
|
|
||||||
|
/// The variable which is used mostly on Wayland.
|
||||||
|
const WAYLAND_VAR: &str = "XDG_ACTIVATION_TOKEN";
|
||||||
|
|
||||||
|
pub trait EventLoopExtStartupNotify {
|
||||||
|
/// Read the token from the environment.
|
||||||
|
///
|
||||||
|
/// It's recommended **to unset** this environment variable for child processes.
|
||||||
|
fn read_token_from_env(&self) -> Option<ActivationToken>;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait WindowExtStartupNotify {
|
||||||
|
/// Request a new activation token.
|
||||||
|
///
|
||||||
|
/// The token will be delivered inside
|
||||||
|
fn request_activation_token(&self) -> Result<AsyncRequestSerial, NotSupportedError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait WindowBuilderExtStartupNotify {
|
||||||
|
/// Use this [`ActivationToken`] during window creation.
|
||||||
|
///
|
||||||
|
/// Not using such a token upon a window could make your window not gaining
|
||||||
|
/// focus until the user clicks on the window.
|
||||||
|
fn with_activation_token(self, token: ActivationToken) -> Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopExtStartupNotify for EventLoopWindowTarget<T> {
|
||||||
|
fn read_token_from_env(&self) -> Option<ActivationToken> {
|
||||||
|
match self.p {
|
||||||
|
#[cfg(wayland_platform)]
|
||||||
|
crate::platform_impl::EventLoopWindowTarget::Wayland(_) => env::var(WAYLAND_VAR),
|
||||||
|
#[cfg(x11_platform)]
|
||||||
|
crate::platform_impl::EventLoopWindowTarget::X(_) => env::var(X11_VAR),
|
||||||
|
}
|
||||||
|
.ok()
|
||||||
|
.map(ActivationToken::_new)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowExtStartupNotify for Window {
|
||||||
|
fn request_activation_token(&self) -> Result<AsyncRequestSerial, NotSupportedError> {
|
||||||
|
self.window.request_activation_token()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowBuilderExtStartupNotify for WindowBuilder {
|
||||||
|
fn with_activation_token(mut self, token: ActivationToken) -> Self {
|
||||||
|
self.platform_specific.activation_token = Some(token);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove the activation environment variables from the current process.
|
||||||
|
///
|
||||||
|
/// This is wise to do before running child processes,
|
||||||
|
/// which may not to support the activation token.
|
||||||
|
pub fn reset_activation_token_env() {
|
||||||
|
env::remove_var(X11_VAR);
|
||||||
|
env::remove_var(WAYLAND_VAR);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set environment variables responsible for activation token.
|
||||||
|
///
|
||||||
|
/// This could be used before running daemon processes.
|
||||||
|
pub fn set_activation_token_env(token: ActivationToken) {
|
||||||
|
env::set_var(X11_VAR, &token._token);
|
||||||
|
env::set_var(WAYLAND_VAR, token._token);
|
||||||
|
}
|
||||||
Vendored
+86
@@ -0,0 +1,86 @@
|
|||||||
|
use crate::{
|
||||||
|
event_loop::{EventLoopBuilder, EventLoopWindowTarget},
|
||||||
|
monitor::MonitorHandle,
|
||||||
|
window::{Window, WindowBuilder},
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::platform_impl::{ApplicationName, Backend};
|
||||||
|
|
||||||
|
pub use crate::window::Theme;
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoopWindowTarget`] that are specific to Wayland.
|
||||||
|
pub trait EventLoopWindowTargetExtWayland {
|
||||||
|
/// True if the [`EventLoopWindowTarget`] uses Wayland.
|
||||||
|
fn is_wayland(&self) -> bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopWindowTargetExtWayland for EventLoopWindowTarget<T> {
|
||||||
|
#[inline]
|
||||||
|
fn is_wayland(&self) -> bool {
|
||||||
|
self.p.is_wayland()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoopBuilder`] that are specific to Wayland.
|
||||||
|
pub trait EventLoopBuilderExtWayland {
|
||||||
|
/// Force using Wayland.
|
||||||
|
fn with_wayland(&mut self) -> &mut Self;
|
||||||
|
|
||||||
|
/// Whether to allow the event loop to be created off of the main thread.
|
||||||
|
///
|
||||||
|
/// By default, the window is only allowed to be created on the main
|
||||||
|
/// thread, to make platform compatibility easier.
|
||||||
|
fn with_any_thread(&mut self, any_thread: bool) -> &mut Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopBuilderExtWayland for EventLoopBuilder<T> {
|
||||||
|
#[inline]
|
||||||
|
fn with_wayland(&mut self) -> &mut Self {
|
||||||
|
self.platform_specific.forced_backend = Some(Backend::Wayland);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_any_thread(&mut self, any_thread: bool) -> &mut Self {
|
||||||
|
self.platform_specific.any_thread = any_thread;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`Window`] that are specific to Wayland.
|
||||||
|
pub trait WindowExtWayland {}
|
||||||
|
|
||||||
|
impl WindowExtWayland for Window {}
|
||||||
|
|
||||||
|
/// Additional methods on [`WindowBuilder`] that are specific to Wayland.
|
||||||
|
pub trait WindowBuilderExtWayland {
|
||||||
|
/// Build window with the given name.
|
||||||
|
///
|
||||||
|
/// The `general` name sets an application ID, which should match the `.desktop`
|
||||||
|
/// file destributed with your program. The `instance` is a `no-op`.
|
||||||
|
///
|
||||||
|
/// For details about application ID conventions, see the
|
||||||
|
/// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id)
|
||||||
|
fn with_name(self, general: impl Into<String>, instance: impl Into<String>) -> Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowBuilderExtWayland for WindowBuilder {
|
||||||
|
#[inline]
|
||||||
|
fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self {
|
||||||
|
self.platform_specific.name = Some(ApplicationName::new(general.into(), instance.into()));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on `MonitorHandle` that are specific to Wayland.
|
||||||
|
pub trait MonitorHandleExtWayland {
|
||||||
|
/// Returns the inner identifier of the monitor.
|
||||||
|
fn native_id(&self) -> u32;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonitorHandleExtWayland for MonitorHandle {
|
||||||
|
#[inline]
|
||||||
|
fn native_id(&self) -> u32 {
|
||||||
|
self.inner.native_identifier()
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+202
@@ -0,0 +1,202 @@
|
|||||||
|
//! The web target does not automatically insert the canvas element object into the web page, to
|
||||||
|
//! allow end users to determine how the page should be laid out. Use the [`WindowExtWebSys`] trait
|
||||||
|
//! to retrieve the canvas from the Window. Alternatively, use the [`WindowBuilderExtWebSys`] trait
|
||||||
|
//! to provide your own canvas.
|
||||||
|
//!
|
||||||
|
//! It is recommended **not** to apply certain CSS properties to the canvas:
|
||||||
|
//! - [`transform`]
|
||||||
|
//! - [`border`]
|
||||||
|
//! - [`padding`]
|
||||||
|
//!
|
||||||
|
//! The following APIs can't take them into account and will therefore provide inaccurate results:
|
||||||
|
//! - [`WindowEvent::Resized`] and [`Window::(set_)inner_size()`]
|
||||||
|
//! - [`WindowEvent::Occluded`]
|
||||||
|
//! - [`WindowEvent::CursorMoved`], [`WindowEvent::CursorEntered`], [`WindowEvent::CursorLeft`],
|
||||||
|
//! and [`WindowEvent::Touch`].
|
||||||
|
//! - [`Window::set_outer_position()`]
|
||||||
|
//!
|
||||||
|
//! [`WindowEvent::Resized`]: crate::event::WindowEvent::Resized
|
||||||
|
//! [`Window::(set_)inner_size()`]: crate::window::Window::inner_size()
|
||||||
|
//! [`WindowEvent::Occluded`]: crate::event::WindowEvent::Occluded
|
||||||
|
//! [`WindowEvent::CursorMoved`]: crate::event::WindowEvent::CursorMoved
|
||||||
|
//! [`WindowEvent::CursorEntered`]: crate::event::WindowEvent::CursorEntered
|
||||||
|
//! [`WindowEvent::CursorLeft`]: crate::event::WindowEvent::CursorLeft
|
||||||
|
//! [`WindowEvent::Touch`]: crate::event::WindowEvent::Touch
|
||||||
|
//! [`Window::set_outer_position()`]: crate::window::Window::set_outer_position()
|
||||||
|
//! [`transform`]: https://developer.mozilla.org/en-US/docs/Web/CSS/transform
|
||||||
|
//! [`border`]: https://developer.mozilla.org/en-US/docs/Web/CSS/border
|
||||||
|
//! [`padding`]: https://developer.mozilla.org/en-US/docs/Web/CSS/padding
|
||||||
|
|
||||||
|
use crate::event::Event;
|
||||||
|
use crate::event_loop::EventLoop;
|
||||||
|
use crate::event_loop::EventLoopWindowTarget;
|
||||||
|
use crate::window::{Window, WindowBuilder};
|
||||||
|
use crate::SendSyncWrapper;
|
||||||
|
|
||||||
|
use web_sys::HtmlCanvasElement;
|
||||||
|
|
||||||
|
pub trait WindowExtWebSys {
|
||||||
|
/// Only returns the canvas if called from inside the window.
|
||||||
|
fn canvas(&self) -> Option<HtmlCanvasElement>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowExtWebSys for Window {
|
||||||
|
#[inline]
|
||||||
|
fn canvas(&self) -> Option<HtmlCanvasElement> {
|
||||||
|
self.window.canvas()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait WindowBuilderExtWebSys {
|
||||||
|
/// Pass an [`HtmlCanvasElement`] to be used for this [`Window`]. If [`None`],
|
||||||
|
/// [`WindowBuilder::build()`] will create one.
|
||||||
|
///
|
||||||
|
/// In any case, the canvas won't be automatically inserted into the web page.
|
||||||
|
///
|
||||||
|
/// [`None`] by default.
|
||||||
|
fn with_canvas(self, canvas: Option<HtmlCanvasElement>) -> Self;
|
||||||
|
|
||||||
|
/// Whether `event.preventDefault` should be automatically called to prevent event propagation
|
||||||
|
/// when appropriate.
|
||||||
|
///
|
||||||
|
/// For example, mouse wheel events are only handled by the canvas by default. This avoids
|
||||||
|
/// the default behavior of scrolling the page.
|
||||||
|
///
|
||||||
|
/// Some events are impossible to prevent. E.g. Firefox allows to access the native browser
|
||||||
|
/// context menu with Shift+Rightclick.
|
||||||
|
///
|
||||||
|
/// Enabled by default.
|
||||||
|
fn with_prevent_default(self, prevent_default: bool) -> Self;
|
||||||
|
|
||||||
|
/// Whether the canvas should be focusable using the tab key. This is necessary to capture
|
||||||
|
/// canvas keyboard events.
|
||||||
|
///
|
||||||
|
/// Enabled by default.
|
||||||
|
fn with_focusable(self, focusable: bool) -> Self;
|
||||||
|
|
||||||
|
/// On window creation, append the canvas element to the web page if it isn't already.
|
||||||
|
///
|
||||||
|
/// Disabled by default.
|
||||||
|
fn with_append(self, append: bool) -> Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowBuilderExtWebSys for WindowBuilder {
|
||||||
|
fn with_canvas(mut self, canvas: Option<HtmlCanvasElement>) -> Self {
|
||||||
|
self.platform_specific.canvas = SendSyncWrapper(canvas);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn with_prevent_default(mut self, prevent_default: bool) -> Self {
|
||||||
|
self.platform_specific.prevent_default = prevent_default;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn with_focusable(mut self, focusable: bool) -> Self {
|
||||||
|
self.platform_specific.focusable = focusable;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn with_append(mut self, append: bool) -> Self {
|
||||||
|
self.platform_specific.append = append;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on `EventLoop` that are specific to the web.
|
||||||
|
pub trait EventLoopExtWebSys {
|
||||||
|
/// A type provided by the user that can be passed through `Event::UserEvent`.
|
||||||
|
type UserEvent;
|
||||||
|
|
||||||
|
/// Initializes the winit event loop.
|
||||||
|
///
|
||||||
|
/// Unlike
|
||||||
|
#[cfg_attr(
|
||||||
|
all(wasm_platform, target_feature = "exception-handling"),
|
||||||
|
doc = "`run()`"
|
||||||
|
)]
|
||||||
|
#[cfg_attr(
|
||||||
|
not(all(wasm_platform, target_feature = "exception-handling")),
|
||||||
|
doc = "[`run()`]"
|
||||||
|
)]
|
||||||
|
/// [^1], this returns immediately, and doesn't throw an exception in order to
|
||||||
|
/// satisfy its [`!`] return type.
|
||||||
|
///
|
||||||
|
/// Once the event loop has been destroyed, it's possible to reinitialize another event loop
|
||||||
|
/// by calling this function again. This can be useful if you want to recreate the event loop
|
||||||
|
/// while the WebAssembly module is still loaded. For example, this can be used to recreate the
|
||||||
|
/// event loop when switching between tabs on a single page application.
|
||||||
|
///
|
||||||
|
#[cfg_attr(
|
||||||
|
not(all(wasm_platform, target_feature = "exception-handling")),
|
||||||
|
doc = "[`run()`]: EventLoop::run()"
|
||||||
|
)]
|
||||||
|
/// [^1]: `run()` is _not_ available on WASM when the target supports `exception-handling`.
|
||||||
|
fn spawn<F>(self, event_handler: F)
|
||||||
|
where
|
||||||
|
F: 'static + FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget<Self::UserEvent>);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopExtWebSys for EventLoop<T> {
|
||||||
|
type UserEvent = T;
|
||||||
|
|
||||||
|
fn spawn<F>(self, event_handler: F)
|
||||||
|
where
|
||||||
|
F: 'static + FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget<Self::UserEvent>),
|
||||||
|
{
|
||||||
|
self.event_loop.spawn(event_handler)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait EventLoopWindowTargetExtWebSys {
|
||||||
|
/// Sets the strategy for [`ControlFlow::Poll`].
|
||||||
|
///
|
||||||
|
/// See [`PollStrategy`].
|
||||||
|
///
|
||||||
|
/// [`ControlFlow::Poll`]: crate::event_loop::ControlFlow::Poll
|
||||||
|
fn set_poll_strategy(&self, strategy: PollStrategy);
|
||||||
|
|
||||||
|
/// Gets the strategy for [`ControlFlow::Poll`].
|
||||||
|
///
|
||||||
|
/// See [`PollStrategy`].
|
||||||
|
///
|
||||||
|
/// [`ControlFlow::Poll`]: crate::event_loop::ControlFlow::Poll
|
||||||
|
fn poll_strategy(&self) -> PollStrategy;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopWindowTargetExtWebSys for EventLoopWindowTarget<T> {
|
||||||
|
#[inline]
|
||||||
|
fn set_poll_strategy(&self, strategy: PollStrategy) {
|
||||||
|
self.p.set_poll_strategy(strategy);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn poll_strategy(&self) -> PollStrategy {
|
||||||
|
self.p.poll_strategy()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strategy used for [`ControlFlow::Poll`](crate::event_loop::ControlFlow::Poll).
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub enum PollStrategy {
|
||||||
|
/// Uses [`Window.requestIdleCallback()`] to queue the next event loop. If not available
|
||||||
|
/// this will fallback to [`setTimeout()`].
|
||||||
|
///
|
||||||
|
/// This strategy will wait for the browser to enter an idle period before running and might
|
||||||
|
/// be affected by browser throttling.
|
||||||
|
///
|
||||||
|
/// [`Window.requestIdleCallback()`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback
|
||||||
|
/// [`setTimeout()`]: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
|
||||||
|
IdleCallback,
|
||||||
|
/// Uses the [Prioritized Task Scheduling API] to queue the next event loop. If not available
|
||||||
|
/// this will fallback to [`setTimeout()`].
|
||||||
|
///
|
||||||
|
/// This strategy will run as fast as possible without disturbing users from interacting with
|
||||||
|
/// the page and is not affected by browser throttling.
|
||||||
|
///
|
||||||
|
/// This is the default strategy.
|
||||||
|
///
|
||||||
|
/// [Prioritized Task Scheduling API]: https://developer.mozilla.org/en-US/docs/Web/API/Prioritized_Task_Scheduling_API
|
||||||
|
/// [`setTimeout()`]: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout
|
||||||
|
#[default]
|
||||||
|
Scheduler,
|
||||||
|
}
|
||||||
Vendored
+354
@@ -0,0 +1,354 @@
|
|||||||
|
use std::{ffi::c_void, path::Path};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
dpi::PhysicalSize,
|
||||||
|
event::{DeviceId, KeyEvent},
|
||||||
|
event_loop::EventLoopBuilder,
|
||||||
|
keyboard::Key,
|
||||||
|
monitor::MonitorHandle,
|
||||||
|
platform::modifier_supplement::KeyEventExtModifierSupplement,
|
||||||
|
platform_impl::WinIcon,
|
||||||
|
window::{BadIcon, Icon, Window, WindowBuilder},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Window Handle type used by Win32 API
|
||||||
|
pub type HWND = isize;
|
||||||
|
/// Menu Handle type used by Win32 API
|
||||||
|
pub type HMENU = isize;
|
||||||
|
/// Monitor Handle type used by Win32 API
|
||||||
|
pub type HMONITOR = isize;
|
||||||
|
|
||||||
|
/// Additional methods on `EventLoop` that are specific to Windows.
|
||||||
|
pub trait EventLoopBuilderExtWindows {
|
||||||
|
/// Whether to allow the event loop to be created off of the main thread.
|
||||||
|
///
|
||||||
|
/// By default, the window is only allowed to be created on the main
|
||||||
|
/// thread, to make platform compatibility easier.
|
||||||
|
///
|
||||||
|
/// # `Window` caveats
|
||||||
|
///
|
||||||
|
/// Note that any `Window` created on the new thread will be destroyed when the thread
|
||||||
|
/// terminates. Attempting to use a `Window` after its parent thread terminates has
|
||||||
|
/// unspecified, although explicitly not undefined, behavior.
|
||||||
|
fn with_any_thread(&mut self, any_thread: bool) -> &mut Self;
|
||||||
|
|
||||||
|
/// Whether to enable process-wide DPI awareness.
|
||||||
|
///
|
||||||
|
/// By default, `winit` will attempt to enable process-wide DPI awareness. If
|
||||||
|
/// that's undesirable, you can disable it with this function.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// Disable process-wide DPI awareness.
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// use winit::event_loop::EventLoopBuilder;
|
||||||
|
/// #[cfg(target_os = "windows")]
|
||||||
|
/// use winit::platform::windows::EventLoopBuilderExtWindows;
|
||||||
|
///
|
||||||
|
/// let mut builder = EventLoopBuilder::new();
|
||||||
|
/// #[cfg(target_os = "windows")]
|
||||||
|
/// builder.with_dpi_aware(false);
|
||||||
|
/// # if false { // We can't test this part
|
||||||
|
/// let event_loop = builder.build();
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
fn with_dpi_aware(&mut self, dpi_aware: bool) -> &mut Self;
|
||||||
|
|
||||||
|
/// A callback to be executed before dispatching a win32 message to the window procedure.
|
||||||
|
/// Return true to disable winit's internal message dispatching.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// # use windows_sys::Win32::UI::WindowsAndMessaging::{ACCEL, CreateAcceleratorTableW, TranslateAcceleratorW, DispatchMessageW, TranslateMessage, MSG};
|
||||||
|
/// use winit::event_loop::EventLoopBuilder;
|
||||||
|
/// #[cfg(target_os = "windows")]
|
||||||
|
/// use winit::platform::windows::EventLoopBuilderExtWindows;
|
||||||
|
///
|
||||||
|
/// let mut builder = EventLoopBuilder::new();
|
||||||
|
/// #[cfg(target_os = "windows")]
|
||||||
|
/// builder.with_msg_hook(|msg|{
|
||||||
|
/// let msg = msg as *const MSG;
|
||||||
|
/// # let accels: Vec<ACCEL> = Vec::new();
|
||||||
|
/// let translated = unsafe {
|
||||||
|
/// TranslateAcceleratorW(
|
||||||
|
/// (*msg).hwnd,
|
||||||
|
/// CreateAcceleratorTableW(accels.as_ptr() as _, 1),
|
||||||
|
/// msg,
|
||||||
|
/// ) == 1
|
||||||
|
/// };
|
||||||
|
/// translated
|
||||||
|
/// });
|
||||||
|
/// ```
|
||||||
|
fn with_msg_hook<F>(&mut self, callback: F) -> &mut Self
|
||||||
|
where
|
||||||
|
F: FnMut(*const c_void) -> bool + 'static;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopBuilderExtWindows for EventLoopBuilder<T> {
|
||||||
|
#[inline]
|
||||||
|
fn with_any_thread(&mut self, any_thread: bool) -> &mut Self {
|
||||||
|
self.platform_specific.any_thread = any_thread;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_dpi_aware(&mut self, dpi_aware: bool) -> &mut Self {
|
||||||
|
self.platform_specific.dpi_aware = dpi_aware;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_msg_hook<F>(&mut self, callback: F) -> &mut Self
|
||||||
|
where
|
||||||
|
F: FnMut(*const c_void) -> bool + 'static,
|
||||||
|
{
|
||||||
|
self.platform_specific.msg_hook = Some(Box::new(callback));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on `Window` that are specific to Windows.
|
||||||
|
pub trait WindowExtWindows {
|
||||||
|
/// Enables or disables mouse and keyboard input to the specified window.
|
||||||
|
///
|
||||||
|
/// A window must be enabled before it can be activated.
|
||||||
|
/// If an application has create a modal dialog box by disabling its owner window
|
||||||
|
/// (as described in [`WindowBuilderExtWindows::with_owner_window`]), the application must enable
|
||||||
|
/// the owner window before destroying the dialog box.
|
||||||
|
/// Otherwise, another window will receive the keyboard focus and be activated.
|
||||||
|
///
|
||||||
|
/// If a child window is disabled, it is ignored when the system tries to determine which
|
||||||
|
/// window should receive mouse messages.
|
||||||
|
///
|
||||||
|
/// For more information, see <https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enablewindow#remarks>
|
||||||
|
/// and <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#disabled-windows>
|
||||||
|
fn set_enable(&self, enabled: bool);
|
||||||
|
|
||||||
|
/// This sets `ICON_BIG`. A good ceiling here is 256x256.
|
||||||
|
fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>);
|
||||||
|
|
||||||
|
/// Whether to show or hide the window icon in the taskbar.
|
||||||
|
fn set_skip_taskbar(&self, skip: bool);
|
||||||
|
|
||||||
|
/// Shows or hides the background drop shadow for undecorated windows.
|
||||||
|
///
|
||||||
|
/// Enabling the shadow causes a thin 1px line to appear on the top of the window.
|
||||||
|
fn set_undecorated_shadow(&self, shadow: bool);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowExtWindows for Window {
|
||||||
|
#[inline]
|
||||||
|
fn set_enable(&self, enabled: bool) {
|
||||||
|
self.window.set_enable(enabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_taskbar_icon(&self, taskbar_icon: Option<Icon>) {
|
||||||
|
self.window.set_taskbar_icon(taskbar_icon)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_skip_taskbar(&self, skip: bool) {
|
||||||
|
self.window.set_skip_taskbar(skip)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn set_undecorated_shadow(&self, shadow: bool) {
|
||||||
|
self.window.set_undecorated_shadow(shadow)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on `WindowBuilder` that are specific to Windows.
|
||||||
|
#[allow(rustdoc::broken_intra_doc_links)]
|
||||||
|
pub trait WindowBuilderExtWindows {
|
||||||
|
/// Set an owner to the window to be created. Can be used to create a dialog box, for example.
|
||||||
|
/// This only works when [`WindowBuilder::with_parent_window`] isn't called or set to `None`.
|
||||||
|
/// Can be used in combination with [`WindowExtWindows::set_enable(false)`](WindowExtWindows::set_enable)
|
||||||
|
/// on the owner window to create a modal dialog box.
|
||||||
|
///
|
||||||
|
/// From MSDN:
|
||||||
|
/// - An owned window is always above its owner in the z-order.
|
||||||
|
/// - The system automatically destroys an owned window when its owner is destroyed.
|
||||||
|
/// - An owned window is hidden when its owner is minimized.
|
||||||
|
///
|
||||||
|
/// For more information, see <https://docs.microsoft.com/en-us/windows/win32/winmsg/window-features#owned-windows>
|
||||||
|
fn with_owner_window(self, parent: HWND) -> Self;
|
||||||
|
|
||||||
|
/// Sets a menu on the window to be created.
|
||||||
|
///
|
||||||
|
/// Parent and menu are mutually exclusive; a child window cannot have a menu!
|
||||||
|
///
|
||||||
|
/// The menu must have been manually created beforehand with [`CreateMenu`] or similar.
|
||||||
|
///
|
||||||
|
/// Note: Dark mode cannot be supported for win32 menus, it's simply not possible to change how the menus look.
|
||||||
|
/// If you use this, it is recommended that you combine it with `with_theme(Some(Theme::Light))` to avoid a jarring effect.
|
||||||
|
///
|
||||||
|
/// [`CreateMenu`]: windows_sys::Win32::UI::WindowsAndMessaging::CreateMenu
|
||||||
|
fn with_menu(self, menu: HMENU) -> Self;
|
||||||
|
|
||||||
|
/// This sets `ICON_BIG`. A good ceiling here is 256x256.
|
||||||
|
fn with_taskbar_icon(self, taskbar_icon: Option<Icon>) -> Self;
|
||||||
|
|
||||||
|
/// This sets `WS_EX_NOREDIRECTIONBITMAP`.
|
||||||
|
fn with_no_redirection_bitmap(self, flag: bool) -> Self;
|
||||||
|
|
||||||
|
/// Enables or disables drag and drop support (enabled by default). Will interfere with other crates
|
||||||
|
/// that use multi-threaded COM API (`CoInitializeEx` with `COINIT_MULTITHREADED` instead of
|
||||||
|
/// `COINIT_APARTMENTTHREADED`) on the same thread. Note that winit may still attempt to initialize
|
||||||
|
/// COM API regardless of this option. Currently only fullscreen mode does that, but there may be more in the future.
|
||||||
|
/// If you need COM API with `COINIT_MULTITHREADED` you must initialize it before calling any winit functions.
|
||||||
|
/// See <https://docs.microsoft.com/en-us/windows/win32/api/objbase/nf-objbase-coinitialize#remarks> for more information.
|
||||||
|
fn with_drag_and_drop(self, flag: bool) -> Self;
|
||||||
|
|
||||||
|
/// Whether show or hide the window icon in the taskbar.
|
||||||
|
fn with_skip_taskbar(self, skip: bool) -> Self;
|
||||||
|
|
||||||
|
/// Customize the window class name.
|
||||||
|
fn with_class_name<S: Into<String>>(self, class_name: S) -> Self;
|
||||||
|
|
||||||
|
/// Shows or hides the background drop shadow for undecorated windows.
|
||||||
|
///
|
||||||
|
/// The shadow is hidden by default.
|
||||||
|
/// Enabling the shadow causes a thin 1px line to appear on the top of the window.
|
||||||
|
fn with_undecorated_shadow(self, shadow: bool) -> Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowBuilderExtWindows for WindowBuilder {
|
||||||
|
#[inline]
|
||||||
|
fn with_owner_window(mut self, parent: HWND) -> Self {
|
||||||
|
self.platform_specific.owner = Some(parent);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_menu(mut self, menu: HMENU) -> Self {
|
||||||
|
self.platform_specific.menu = Some(menu);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_taskbar_icon(mut self, taskbar_icon: Option<Icon>) -> Self {
|
||||||
|
self.platform_specific.taskbar_icon = taskbar_icon;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_no_redirection_bitmap(mut self, flag: bool) -> Self {
|
||||||
|
self.platform_specific.no_redirection_bitmap = flag;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_drag_and_drop(mut self, flag: bool) -> Self {
|
||||||
|
self.platform_specific.drag_and_drop = flag;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_skip_taskbar(mut self, skip: bool) -> Self {
|
||||||
|
self.platform_specific.skip_taskbar = skip;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_class_name<S: Into<String>>(mut self, class_name: S) -> Self {
|
||||||
|
self.platform_specific.class_name = class_name.into();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_undecorated_shadow(mut self, shadow: bool) -> Self {
|
||||||
|
self.platform_specific.decoration_shadow = shadow;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on `MonitorHandle` that are specific to Windows.
|
||||||
|
pub trait MonitorHandleExtWindows {
|
||||||
|
/// Returns the name of the monitor adapter specific to the Win32 API.
|
||||||
|
fn native_id(&self) -> String;
|
||||||
|
|
||||||
|
/// Returns the handle of the monitor - `HMONITOR`.
|
||||||
|
fn hmonitor(&self) -> HMONITOR;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonitorHandleExtWindows for MonitorHandle {
|
||||||
|
#[inline]
|
||||||
|
fn native_id(&self) -> String {
|
||||||
|
self.inner.native_identifier()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn hmonitor(&self) -> HMONITOR {
|
||||||
|
self.inner.hmonitor()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on `DeviceId` that are specific to Windows.
|
||||||
|
pub trait DeviceIdExtWindows {
|
||||||
|
/// Returns an identifier that persistently refers to this specific device.
|
||||||
|
///
|
||||||
|
/// Will return `None` if the device is no longer available.
|
||||||
|
fn persistent_identifier(&self) -> Option<String>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DeviceIdExtWindows for DeviceId {
|
||||||
|
#[inline]
|
||||||
|
fn persistent_identifier(&self) -> Option<String> {
|
||||||
|
self.0.persistent_identifier()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on `Icon` that are specific to Windows.
|
||||||
|
pub trait IconExtWindows: Sized {
|
||||||
|
/// Create an icon from a file path.
|
||||||
|
///
|
||||||
|
/// Specify `size` to load a specific icon size from the file, or `None` to load the default
|
||||||
|
/// icon size from the file.
|
||||||
|
///
|
||||||
|
/// In cases where the specified size does not exist in the file, Windows may perform scaling
|
||||||
|
/// to get an icon of the desired size.
|
||||||
|
fn from_path<P: AsRef<Path>>(path: P, size: Option<PhysicalSize<u32>>)
|
||||||
|
-> Result<Self, BadIcon>;
|
||||||
|
|
||||||
|
/// Create an icon from a resource embedded in this executable or library.
|
||||||
|
///
|
||||||
|
/// Specify `size` to load a specific icon size from the file, or `None` to load the default
|
||||||
|
/// icon size from the file.
|
||||||
|
///
|
||||||
|
/// In cases where the specified size does not exist in the file, Windows may perform scaling
|
||||||
|
/// to get an icon of the desired size.
|
||||||
|
fn from_resource(ordinal: u16, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IconExtWindows for Icon {
|
||||||
|
fn from_path<P: AsRef<Path>>(
|
||||||
|
path: P,
|
||||||
|
size: Option<PhysicalSize<u32>>,
|
||||||
|
) -> Result<Self, BadIcon> {
|
||||||
|
let win_icon = WinIcon::from_path(path, size)?;
|
||||||
|
Ok(Icon { inner: win_icon })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_resource(ordinal: u16, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon> {
|
||||||
|
let win_icon = WinIcon::from_resource(ordinal, size)?;
|
||||||
|
Ok(Icon { inner: win_icon })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KeyEventExtModifierSupplement for KeyEvent {
|
||||||
|
#[inline]
|
||||||
|
fn text_with_all_modifiers(&self) -> Option<&str> {
|
||||||
|
self.platform_specific
|
||||||
|
.text_with_all_modifers
|
||||||
|
.as_ref()
|
||||||
|
.map(|s| s.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn key_without_modifiers(&self) -> Key {
|
||||||
|
self.platform_specific.key_without_modifiers.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+198
@@ -0,0 +1,198 @@
|
|||||||
|
use crate::{
|
||||||
|
event_loop::{EventLoopBuilder, EventLoopWindowTarget},
|
||||||
|
monitor::MonitorHandle,
|
||||||
|
window::{Window, WindowBuilder},
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::dpi::Size;
|
||||||
|
use crate::platform_impl::{ApplicationName, Backend, XLIB_ERROR_HOOKS};
|
||||||
|
|
||||||
|
pub use crate::platform_impl::{x11::util::WindowType as XWindowType, XNotSupported};
|
||||||
|
|
||||||
|
/// The first argument in the provided hook will be the pointer to `XDisplay`
|
||||||
|
/// and the second one the pointer to [`XErrorEvent`]. The returned `bool` is an
|
||||||
|
/// indicator whether the error was handled by the callback.
|
||||||
|
///
|
||||||
|
/// [`XErrorEvent`]: https://linux.die.net/man/3/xerrorevent
|
||||||
|
pub type XlibErrorHook =
|
||||||
|
Box<dyn Fn(*mut std::ffi::c_void, *mut std::ffi::c_void) -> bool + Send + Sync>;
|
||||||
|
|
||||||
|
/// A unique identifer for an X11 visual.
|
||||||
|
pub type XVisualID = u32;
|
||||||
|
|
||||||
|
/// A unique identifier for an X11 window.
|
||||||
|
pub type XWindow = u32;
|
||||||
|
|
||||||
|
/// Hook to winit's xlib error handling callback.
|
||||||
|
///
|
||||||
|
/// This method is provided as a safe way to handle the errors comming from X11
|
||||||
|
/// when using xlib in external crates, like glutin for GLX access. Trying to
|
||||||
|
/// handle errors by speculating with `XSetErrorHandler` is [`unsafe`].
|
||||||
|
///
|
||||||
|
/// **Be aware that your hook is always invoked and returning `true` from it will
|
||||||
|
/// prevent `winit` from getting the error itself. It's wise to always return
|
||||||
|
/// `false` if you're not initiated the `Sync`.**
|
||||||
|
///
|
||||||
|
/// [`unsafe`]: https://www.remlab.net/op/xlib.shtml
|
||||||
|
#[inline]
|
||||||
|
pub fn register_xlib_error_hook(hook: XlibErrorHook) {
|
||||||
|
// Append new hook.
|
||||||
|
unsafe {
|
||||||
|
XLIB_ERROR_HOOKS.lock().unwrap().push(hook);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoopWindowTarget`] that are specific to X11.
|
||||||
|
pub trait EventLoopWindowTargetExtX11 {
|
||||||
|
/// True if the [`EventLoopWindowTarget`] uses X11.
|
||||||
|
fn is_x11(&self) -> bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopWindowTargetExtX11 for EventLoopWindowTarget<T> {
|
||||||
|
#[inline]
|
||||||
|
fn is_x11(&self) -> bool {
|
||||||
|
!self.p.is_wayland()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`EventLoopBuilder`] that are specific to X11.
|
||||||
|
pub trait EventLoopBuilderExtX11 {
|
||||||
|
/// Force using X11.
|
||||||
|
fn with_x11(&mut self) -> &mut Self;
|
||||||
|
|
||||||
|
/// Whether to allow the event loop to be created off of the main thread.
|
||||||
|
///
|
||||||
|
/// By default, the window is only allowed to be created on the main
|
||||||
|
/// thread, to make platform compatibility easier.
|
||||||
|
fn with_any_thread(&mut self, any_thread: bool) -> &mut Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopBuilderExtX11 for EventLoopBuilder<T> {
|
||||||
|
#[inline]
|
||||||
|
fn with_x11(&mut self) -> &mut Self {
|
||||||
|
self.platform_specific.forced_backend = Some(Backend::X);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_any_thread(&mut self, any_thread: bool) -> &mut Self {
|
||||||
|
self.platform_specific.any_thread = any_thread;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on [`Window`] that are specific to X11.
|
||||||
|
pub trait WindowExtX11 {}
|
||||||
|
|
||||||
|
impl WindowExtX11 for Window {}
|
||||||
|
|
||||||
|
/// Additional methods on [`WindowBuilder`] that are specific to X11.
|
||||||
|
pub trait WindowBuilderExtX11 {
|
||||||
|
/// Create this window with a specific X11 visual.
|
||||||
|
fn with_x11_visual(self, visual_id: XVisualID) -> Self;
|
||||||
|
|
||||||
|
fn with_x11_screen(self, screen_id: i32) -> Self;
|
||||||
|
|
||||||
|
/// Build window with the given `general` and `instance` names.
|
||||||
|
///
|
||||||
|
/// The `general` sets general class of `WM_CLASS(STRING)`, while `instance` set the
|
||||||
|
/// instance part of it. The resulted property looks like `WM_CLASS(STRING) = "instance", "general"`.
|
||||||
|
///
|
||||||
|
/// For details about application ID conventions, see the
|
||||||
|
/// [Desktop Entry Spec](https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#desktop-file-id)
|
||||||
|
fn with_name(self, general: impl Into<String>, instance: impl Into<String>) -> Self;
|
||||||
|
|
||||||
|
/// Build window with override-redirect flag; defaults to false. Only relevant on X11.
|
||||||
|
fn with_override_redirect(self, override_redirect: bool) -> Self;
|
||||||
|
|
||||||
|
/// Build window with `_NET_WM_WINDOW_TYPE` hints; defaults to `Normal`. Only relevant on X11.
|
||||||
|
fn with_x11_window_type(self, x11_window_type: Vec<XWindowType>) -> Self;
|
||||||
|
|
||||||
|
/// Build window with base size hint. Only implemented on X11.
|
||||||
|
///
|
||||||
|
/// ```
|
||||||
|
/// # use winit::dpi::{LogicalSize, PhysicalSize};
|
||||||
|
/// # use winit::window::WindowBuilder;
|
||||||
|
/// # use winit::platform::x11::WindowBuilderExtX11;
|
||||||
|
/// // Specify the size in logical dimensions like this:
|
||||||
|
/// WindowBuilder::new().with_base_size(LogicalSize::new(400.0, 200.0));
|
||||||
|
///
|
||||||
|
/// // Or specify the size in physical dimensions like this:
|
||||||
|
/// WindowBuilder::new().with_base_size(PhysicalSize::new(400, 200));
|
||||||
|
/// ```
|
||||||
|
fn with_base_size<S: Into<Size>>(self, base_size: S) -> Self;
|
||||||
|
|
||||||
|
/// Embed this window into another parent window.
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// use winit::window::WindowBuilder;
|
||||||
|
/// use winit::platform::x11::{XWindow, WindowBuilderExtX11};
|
||||||
|
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
/// let event_loop = winit::event_loop::EventLoop::new().unwrap();
|
||||||
|
/// let parent_window_id = std::env::args().nth(1).unwrap().parse::<XWindow>()?;
|
||||||
|
/// let window = WindowBuilder::new()
|
||||||
|
/// .with_embed_parent_window(parent_window_id)
|
||||||
|
/// .build(&event_loop)?;
|
||||||
|
/// # Ok(()) }
|
||||||
|
/// ```
|
||||||
|
fn with_embed_parent_window(self, parent_window_id: XWindow) -> Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WindowBuilderExtX11 for WindowBuilder {
|
||||||
|
#[inline]
|
||||||
|
fn with_x11_visual(mut self, visual_id: XVisualID) -> Self {
|
||||||
|
self.platform_specific.x11.visual_id = Some(visual_id);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_x11_screen(mut self, screen_id: i32) -> Self {
|
||||||
|
self.platform_specific.x11.screen_id = Some(screen_id);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_name(mut self, general: impl Into<String>, instance: impl Into<String>) -> Self {
|
||||||
|
self.platform_specific.name = Some(ApplicationName::new(general.into(), instance.into()));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_override_redirect(mut self, override_redirect: bool) -> Self {
|
||||||
|
self.platform_specific.x11.override_redirect = override_redirect;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_x11_window_type(mut self, x11_window_types: Vec<XWindowType>) -> Self {
|
||||||
|
self.platform_specific.x11.x11_window_types = x11_window_types;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_base_size<S: Into<Size>>(mut self, base_size: S) -> Self {
|
||||||
|
self.platform_specific.x11.base_size = Some(base_size.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn with_embed_parent_window(mut self, parent_window_id: XWindow) -> Self {
|
||||||
|
self.platform_specific.x11.embed_window = Some(parent_window_id);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Additional methods on `MonitorHandle` that are specific to X11.
|
||||||
|
pub trait MonitorHandleExtX11 {
|
||||||
|
/// Returns the inner identifier of the monitor.
|
||||||
|
fn native_id(&self) -> u32;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonitorHandleExtX11 for MonitorHandle {
|
||||||
|
#[inline]
|
||||||
|
fn native_id(&self) -> u32 {
|
||||||
|
self.inner.native_identifier()
|
||||||
|
}
|
||||||
|
}
|
||||||
+607
@@ -0,0 +1,607 @@
|
|||||||
|
use android_activity::{
|
||||||
|
input::{KeyAction, KeyEvent, KeyMapChar, Keycode},
|
||||||
|
AndroidApp,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::keyboard::{Key, KeyCode, KeyLocation, NamedKey, NativeKey, NativeKeyCode, PhysicalKey};
|
||||||
|
|
||||||
|
pub fn to_physical_key(keycode: Keycode) -> PhysicalKey {
|
||||||
|
PhysicalKey::Code(match keycode {
|
||||||
|
Keycode::A => KeyCode::KeyA,
|
||||||
|
Keycode::B => KeyCode::KeyB,
|
||||||
|
Keycode::C => KeyCode::KeyC,
|
||||||
|
Keycode::D => KeyCode::KeyD,
|
||||||
|
Keycode::E => KeyCode::KeyE,
|
||||||
|
Keycode::F => KeyCode::KeyF,
|
||||||
|
Keycode::G => KeyCode::KeyG,
|
||||||
|
Keycode::H => KeyCode::KeyH,
|
||||||
|
Keycode::I => KeyCode::KeyI,
|
||||||
|
Keycode::J => KeyCode::KeyJ,
|
||||||
|
Keycode::K => KeyCode::KeyK,
|
||||||
|
Keycode::L => KeyCode::KeyL,
|
||||||
|
Keycode::M => KeyCode::KeyM,
|
||||||
|
Keycode::N => KeyCode::KeyN,
|
||||||
|
Keycode::O => KeyCode::KeyO,
|
||||||
|
Keycode::P => KeyCode::KeyP,
|
||||||
|
Keycode::Q => KeyCode::KeyQ,
|
||||||
|
Keycode::R => KeyCode::KeyR,
|
||||||
|
Keycode::S => KeyCode::KeyS,
|
||||||
|
Keycode::T => KeyCode::KeyT,
|
||||||
|
Keycode::U => KeyCode::KeyU,
|
||||||
|
Keycode::V => KeyCode::KeyV,
|
||||||
|
Keycode::W => KeyCode::KeyW,
|
||||||
|
Keycode::X => KeyCode::KeyX,
|
||||||
|
Keycode::Y => KeyCode::KeyY,
|
||||||
|
Keycode::Z => KeyCode::KeyZ,
|
||||||
|
|
||||||
|
Keycode::Keycode0 => KeyCode::Digit0,
|
||||||
|
Keycode::Keycode1 => KeyCode::Digit1,
|
||||||
|
Keycode::Keycode2 => KeyCode::Digit2,
|
||||||
|
Keycode::Keycode3 => KeyCode::Digit3,
|
||||||
|
Keycode::Keycode4 => KeyCode::Digit4,
|
||||||
|
Keycode::Keycode5 => KeyCode::Digit5,
|
||||||
|
Keycode::Keycode6 => KeyCode::Digit6,
|
||||||
|
Keycode::Keycode7 => KeyCode::Digit7,
|
||||||
|
Keycode::Keycode8 => KeyCode::Digit8,
|
||||||
|
Keycode::Keycode9 => KeyCode::Digit9,
|
||||||
|
|
||||||
|
Keycode::Numpad0 => KeyCode::Numpad0,
|
||||||
|
Keycode::Numpad1 => KeyCode::Numpad1,
|
||||||
|
Keycode::Numpad2 => KeyCode::Numpad2,
|
||||||
|
Keycode::Numpad3 => KeyCode::Numpad3,
|
||||||
|
Keycode::Numpad4 => KeyCode::Numpad4,
|
||||||
|
Keycode::Numpad5 => KeyCode::Numpad5,
|
||||||
|
Keycode::Numpad6 => KeyCode::Numpad6,
|
||||||
|
Keycode::Numpad7 => KeyCode::Numpad7,
|
||||||
|
Keycode::Numpad8 => KeyCode::Numpad8,
|
||||||
|
Keycode::Numpad9 => KeyCode::Numpad9,
|
||||||
|
|
||||||
|
Keycode::NumpadAdd => KeyCode::NumpadAdd,
|
||||||
|
Keycode::NumpadSubtract => KeyCode::NumpadSubtract,
|
||||||
|
Keycode::NumpadMultiply => KeyCode::NumpadMultiply,
|
||||||
|
Keycode::NumpadDivide => KeyCode::NumpadDivide,
|
||||||
|
Keycode::NumpadEnter => KeyCode::NumpadEnter,
|
||||||
|
Keycode::NumpadEquals => KeyCode::NumpadEqual,
|
||||||
|
Keycode::NumpadComma => KeyCode::NumpadComma,
|
||||||
|
Keycode::NumpadDot => KeyCode::NumpadDecimal,
|
||||||
|
Keycode::NumLock => KeyCode::NumLock,
|
||||||
|
|
||||||
|
Keycode::DpadLeft => KeyCode::ArrowLeft,
|
||||||
|
Keycode::DpadRight => KeyCode::ArrowRight,
|
||||||
|
Keycode::DpadUp => KeyCode::ArrowUp,
|
||||||
|
Keycode::DpadDown => KeyCode::ArrowDown,
|
||||||
|
|
||||||
|
Keycode::F1 => KeyCode::F1,
|
||||||
|
Keycode::F2 => KeyCode::F2,
|
||||||
|
Keycode::F3 => KeyCode::F3,
|
||||||
|
Keycode::F4 => KeyCode::F4,
|
||||||
|
Keycode::F5 => KeyCode::F5,
|
||||||
|
Keycode::F6 => KeyCode::F6,
|
||||||
|
Keycode::F7 => KeyCode::F7,
|
||||||
|
Keycode::F8 => KeyCode::F8,
|
||||||
|
Keycode::F9 => KeyCode::F9,
|
||||||
|
Keycode::F10 => KeyCode::F10,
|
||||||
|
Keycode::F11 => KeyCode::F11,
|
||||||
|
Keycode::F12 => KeyCode::F12,
|
||||||
|
|
||||||
|
Keycode::Space => KeyCode::Space,
|
||||||
|
Keycode::Escape => KeyCode::Escape,
|
||||||
|
Keycode::Enter => KeyCode::Enter, // not on the Numpad
|
||||||
|
Keycode::Tab => KeyCode::Tab,
|
||||||
|
|
||||||
|
Keycode::PageUp => KeyCode::PageUp,
|
||||||
|
Keycode::PageDown => KeyCode::PageDown,
|
||||||
|
Keycode::MoveHome => KeyCode::Home,
|
||||||
|
Keycode::MoveEnd => KeyCode::End,
|
||||||
|
Keycode::Insert => KeyCode::Insert,
|
||||||
|
|
||||||
|
Keycode::Del => KeyCode::Backspace, // Backspace (above Enter)
|
||||||
|
Keycode::ForwardDel => KeyCode::Delete, // Delete (below Insert)
|
||||||
|
|
||||||
|
Keycode::Copy => KeyCode::Copy,
|
||||||
|
Keycode::Paste => KeyCode::Paste,
|
||||||
|
Keycode::Cut => KeyCode::Cut,
|
||||||
|
|
||||||
|
Keycode::VolumeUp => KeyCode::AudioVolumeUp,
|
||||||
|
Keycode::VolumeDown => KeyCode::AudioVolumeDown,
|
||||||
|
Keycode::VolumeMute => KeyCode::AudioVolumeMute,
|
||||||
|
//Keycode::Mute => None, // Microphone mute
|
||||||
|
Keycode::MediaPlayPause => KeyCode::MediaPlayPause,
|
||||||
|
Keycode::MediaStop => KeyCode::MediaStop,
|
||||||
|
Keycode::MediaNext => KeyCode::MediaTrackNext,
|
||||||
|
Keycode::MediaPrevious => KeyCode::MediaTrackPrevious,
|
||||||
|
|
||||||
|
Keycode::Plus => KeyCode::Equal,
|
||||||
|
Keycode::Minus => KeyCode::Minus,
|
||||||
|
// Winit doesn't differentiate both '+' and '=', considering they are usually
|
||||||
|
// on the same physical key
|
||||||
|
Keycode::Equals => KeyCode::Equal,
|
||||||
|
Keycode::Semicolon => KeyCode::Semicolon,
|
||||||
|
Keycode::Slash => KeyCode::Slash,
|
||||||
|
Keycode::Backslash => KeyCode::Backslash,
|
||||||
|
Keycode::Comma => KeyCode::Comma,
|
||||||
|
Keycode::Period => KeyCode::Period,
|
||||||
|
Keycode::Apostrophe => KeyCode::Quote,
|
||||||
|
Keycode::Grave => KeyCode::Backquote,
|
||||||
|
|
||||||
|
// Winit doesn't expose a SysRq code, so map to PrintScreen since it's
|
||||||
|
// usually the same physical key
|
||||||
|
Keycode::Sysrq => KeyCode::PrintScreen,
|
||||||
|
// These are usually the same (Pause/Break)
|
||||||
|
Keycode::Break => KeyCode::Pause,
|
||||||
|
// These are exactly the same
|
||||||
|
Keycode::ScrollLock => KeyCode::ScrollLock,
|
||||||
|
|
||||||
|
Keycode::Yen => KeyCode::IntlYen,
|
||||||
|
Keycode::Kana => KeyCode::Lang1,
|
||||||
|
Keycode::KatakanaHiragana => KeyCode::KanaMode,
|
||||||
|
|
||||||
|
Keycode::CtrlLeft => KeyCode::ControlLeft,
|
||||||
|
Keycode::CtrlRight => KeyCode::ControlRight,
|
||||||
|
|
||||||
|
Keycode::ShiftLeft => KeyCode::ShiftLeft,
|
||||||
|
Keycode::ShiftRight => KeyCode::ShiftRight,
|
||||||
|
|
||||||
|
Keycode::AltLeft => KeyCode::AltLeft,
|
||||||
|
Keycode::AltRight => KeyCode::AltRight,
|
||||||
|
|
||||||
|
Keycode::MetaLeft => KeyCode::SuperLeft,
|
||||||
|
Keycode::MetaRight => KeyCode::SuperRight,
|
||||||
|
|
||||||
|
Keycode::LeftBracket => KeyCode::BracketLeft,
|
||||||
|
Keycode::RightBracket => KeyCode::BracketRight,
|
||||||
|
|
||||||
|
Keycode::Power => KeyCode::Power,
|
||||||
|
Keycode::Sleep => KeyCode::Sleep, // what about SoftSleep?
|
||||||
|
Keycode::Wakeup => KeyCode::WakeUp,
|
||||||
|
|
||||||
|
keycode => return PhysicalKey::Unidentified(NativeKeyCode::Android(keycode.into())),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tries to map the `key_event` to a `KeyMapChar` containing a unicode character or dead key accent
|
||||||
|
///
|
||||||
|
/// This takes a `KeyEvent` and looks up its corresponding `KeyCharacterMap` and
|
||||||
|
/// uses that to try and map the `key_code` + `meta_state` to a unicode
|
||||||
|
/// character or a dead key that can be combined with the next key press.
|
||||||
|
pub fn character_map_and_combine_key(
|
||||||
|
app: &AndroidApp,
|
||||||
|
key_event: &KeyEvent<'_>,
|
||||||
|
combining_accent: &mut Option<char>,
|
||||||
|
) -> Option<KeyMapChar> {
|
||||||
|
let device_id = key_event.device_id();
|
||||||
|
|
||||||
|
let key_map = match app.device_key_character_map(device_id) {
|
||||||
|
Ok(key_map) => key_map,
|
||||||
|
Err(err) => {
|
||||||
|
log::warn!("Failed to look up `KeyCharacterMap` for device {device_id}: {err:?}");
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match key_map.get(key_event.key_code(), key_event.meta_state()) {
|
||||||
|
Ok(KeyMapChar::Unicode(unicode)) => {
|
||||||
|
// Only do dead key combining on key down
|
||||||
|
if key_event.action() == KeyAction::Down {
|
||||||
|
let combined_unicode = if let Some(accent) = combining_accent {
|
||||||
|
match key_map.get_dead_char(*accent, unicode) {
|
||||||
|
Ok(Some(key)) => Some(key),
|
||||||
|
Ok(None) => None,
|
||||||
|
Err(err) => {
|
||||||
|
log::warn!("KeyEvent: Failed to combine 'dead key' accent '{accent}' with '{unicode}': {err:?}");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Some(unicode)
|
||||||
|
};
|
||||||
|
*combining_accent = None;
|
||||||
|
combined_unicode.map(KeyMapChar::Unicode)
|
||||||
|
} else {
|
||||||
|
Some(KeyMapChar::Unicode(unicode))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(KeyMapChar::CombiningAccent(accent)) => {
|
||||||
|
if key_event.action() == KeyAction::Down {
|
||||||
|
*combining_accent = Some(accent);
|
||||||
|
}
|
||||||
|
Some(KeyMapChar::CombiningAccent(accent))
|
||||||
|
}
|
||||||
|
Ok(KeyMapChar::None) => {
|
||||||
|
// Leave any combining_accent state in tact (seems to match how other
|
||||||
|
// Android apps work)
|
||||||
|
None
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
log::warn!("KeyEvent: Failed to get key map character: {err:?}");
|
||||||
|
*combining_accent = None;
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_logical(key_char: Option<KeyMapChar>, keycode: Keycode) -> Key {
|
||||||
|
use android_activity::input::Keycode::*;
|
||||||
|
|
||||||
|
let native = NativeKey::Android(keycode.into());
|
||||||
|
|
||||||
|
match key_char {
|
||||||
|
Some(KeyMapChar::Unicode(c)) => Key::Character(smol_str::SmolStr::from_iter([c])),
|
||||||
|
Some(KeyMapChar::CombiningAccent(c)) => Key::Dead(Some(c)),
|
||||||
|
None | Some(KeyMapChar::None) => match keycode {
|
||||||
|
// Using `BrowserHome` instead of `GoHome` according to
|
||||||
|
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values
|
||||||
|
Home => Key::Named(NamedKey::BrowserHome),
|
||||||
|
Back => Key::Named(NamedKey::BrowserBack),
|
||||||
|
Call => Key::Named(NamedKey::Call),
|
||||||
|
Endcall => Key::Named(NamedKey::EndCall),
|
||||||
|
|
||||||
|
//-------------------------------------------------------------------------------
|
||||||
|
// These should be redundant because they should have already been matched
|
||||||
|
// as `KeyMapChar::Unicode`, but also matched here as a fallback
|
||||||
|
Keycode0 => Key::Character("0".into()),
|
||||||
|
Keycode1 => Key::Character("1".into()),
|
||||||
|
Keycode2 => Key::Character("2".into()),
|
||||||
|
Keycode3 => Key::Character("3".into()),
|
||||||
|
Keycode4 => Key::Character("4".into()),
|
||||||
|
Keycode5 => Key::Character("5".into()),
|
||||||
|
Keycode6 => Key::Character("6".into()),
|
||||||
|
Keycode7 => Key::Character("7".into()),
|
||||||
|
Keycode8 => Key::Character("8".into()),
|
||||||
|
Keycode9 => Key::Character("9".into()),
|
||||||
|
Star => Key::Character("*".into()),
|
||||||
|
Pound => Key::Character("#".into()),
|
||||||
|
A => Key::Character("a".into()),
|
||||||
|
B => Key::Character("b".into()),
|
||||||
|
C => Key::Character("c".into()),
|
||||||
|
D => Key::Character("d".into()),
|
||||||
|
E => Key::Character("e".into()),
|
||||||
|
F => Key::Character("f".into()),
|
||||||
|
G => Key::Character("g".into()),
|
||||||
|
H => Key::Character("h".into()),
|
||||||
|
I => Key::Character("i".into()),
|
||||||
|
J => Key::Character("j".into()),
|
||||||
|
K => Key::Character("k".into()),
|
||||||
|
L => Key::Character("l".into()),
|
||||||
|
M => Key::Character("m".into()),
|
||||||
|
N => Key::Character("n".into()),
|
||||||
|
O => Key::Character("o".into()),
|
||||||
|
P => Key::Character("p".into()),
|
||||||
|
Q => Key::Character("q".into()),
|
||||||
|
R => Key::Character("r".into()),
|
||||||
|
S => Key::Character("s".into()),
|
||||||
|
T => Key::Character("t".into()),
|
||||||
|
U => Key::Character("u".into()),
|
||||||
|
V => Key::Character("v".into()),
|
||||||
|
W => Key::Character("w".into()),
|
||||||
|
X => Key::Character("x".into()),
|
||||||
|
Y => Key::Character("y".into()),
|
||||||
|
Z => Key::Character("z".into()),
|
||||||
|
Comma => Key::Character(",".into()),
|
||||||
|
Period => Key::Character(".".into()),
|
||||||
|
Grave => Key::Character("`".into()),
|
||||||
|
Minus => Key::Character("-".into()),
|
||||||
|
Equals => Key::Character("=".into()),
|
||||||
|
LeftBracket => Key::Character("[".into()),
|
||||||
|
RightBracket => Key::Character("]".into()),
|
||||||
|
Backslash => Key::Character("\\".into()),
|
||||||
|
Semicolon => Key::Character(";".into()),
|
||||||
|
Apostrophe => Key::Character("'".into()),
|
||||||
|
Slash => Key::Character("/".into()),
|
||||||
|
At => Key::Character("@".into()),
|
||||||
|
Plus => Key::Character("+".into()),
|
||||||
|
//-------------------------------------------------------------------------------
|
||||||
|
DpadUp => Key::Named(NamedKey::ArrowUp),
|
||||||
|
DpadDown => Key::Named(NamedKey::ArrowDown),
|
||||||
|
DpadLeft => Key::Named(NamedKey::ArrowLeft),
|
||||||
|
DpadRight => Key::Named(NamedKey::ArrowRight),
|
||||||
|
DpadCenter => Key::Named(NamedKey::Enter),
|
||||||
|
|
||||||
|
VolumeUp => Key::Named(NamedKey::AudioVolumeUp),
|
||||||
|
VolumeDown => Key::Named(NamedKey::AudioVolumeDown),
|
||||||
|
Power => Key::Named(NamedKey::Power),
|
||||||
|
Camera => Key::Named(NamedKey::Camera),
|
||||||
|
Clear => Key::Named(NamedKey::Clear),
|
||||||
|
|
||||||
|
AltLeft => Key::Named(NamedKey::Alt),
|
||||||
|
AltRight => Key::Named(NamedKey::Alt),
|
||||||
|
ShiftLeft => Key::Named(NamedKey::Shift),
|
||||||
|
ShiftRight => Key::Named(NamedKey::Shift),
|
||||||
|
Tab => Key::Named(NamedKey::Tab),
|
||||||
|
Space => Key::Named(NamedKey::Space),
|
||||||
|
Sym => Key::Named(NamedKey::Symbol),
|
||||||
|
Explorer => Key::Named(NamedKey::LaunchWebBrowser),
|
||||||
|
Envelope => Key::Named(NamedKey::LaunchMail),
|
||||||
|
Enter => Key::Named(NamedKey::Enter),
|
||||||
|
Del => Key::Named(NamedKey::Backspace),
|
||||||
|
|
||||||
|
// According to https://developer.android.com/reference/android/view/KeyEvent#KEYCODE_NUM
|
||||||
|
Num => Key::Named(NamedKey::Alt),
|
||||||
|
|
||||||
|
Headsethook => Key::Named(NamedKey::HeadsetHook),
|
||||||
|
Focus => Key::Named(NamedKey::CameraFocus),
|
||||||
|
|
||||||
|
Notification => Key::Named(NamedKey::Notification),
|
||||||
|
Search => Key::Named(NamedKey::BrowserSearch),
|
||||||
|
MediaPlayPause => Key::Named(NamedKey::MediaPlayPause),
|
||||||
|
MediaStop => Key::Named(NamedKey::MediaStop),
|
||||||
|
MediaNext => Key::Named(NamedKey::MediaTrackNext),
|
||||||
|
MediaPrevious => Key::Named(NamedKey::MediaTrackPrevious),
|
||||||
|
MediaRewind => Key::Named(NamedKey::MediaRewind),
|
||||||
|
MediaFastForward => Key::Named(NamedKey::MediaFastForward),
|
||||||
|
Mute => Key::Named(NamedKey::MicrophoneVolumeMute),
|
||||||
|
PageUp => Key::Named(NamedKey::PageUp),
|
||||||
|
PageDown => Key::Named(NamedKey::PageDown),
|
||||||
|
|
||||||
|
Escape => Key::Named(NamedKey::Escape),
|
||||||
|
ForwardDel => Key::Named(NamedKey::Delete),
|
||||||
|
CtrlLeft => Key::Named(NamedKey::Control),
|
||||||
|
CtrlRight => Key::Named(NamedKey::Control),
|
||||||
|
CapsLock => Key::Named(NamedKey::CapsLock),
|
||||||
|
ScrollLock => Key::Named(NamedKey::ScrollLock),
|
||||||
|
MetaLeft => Key::Named(NamedKey::Super),
|
||||||
|
MetaRight => Key::Named(NamedKey::Super),
|
||||||
|
Function => Key::Named(NamedKey::Fn),
|
||||||
|
Sysrq => Key::Named(NamedKey::PrintScreen),
|
||||||
|
Break => Key::Named(NamedKey::Pause),
|
||||||
|
MoveHome => Key::Named(NamedKey::Home),
|
||||||
|
MoveEnd => Key::Named(NamedKey::End),
|
||||||
|
Insert => Key::Named(NamedKey::Insert),
|
||||||
|
Forward => Key::Named(NamedKey::BrowserForward),
|
||||||
|
MediaPlay => Key::Named(NamedKey::MediaPlay),
|
||||||
|
MediaPause => Key::Named(NamedKey::MediaPause),
|
||||||
|
MediaClose => Key::Named(NamedKey::MediaClose),
|
||||||
|
MediaEject => Key::Named(NamedKey::Eject),
|
||||||
|
MediaRecord => Key::Named(NamedKey::MediaRecord),
|
||||||
|
F1 => Key::Named(NamedKey::F1),
|
||||||
|
F2 => Key::Named(NamedKey::F2),
|
||||||
|
F3 => Key::Named(NamedKey::F3),
|
||||||
|
F4 => Key::Named(NamedKey::F4),
|
||||||
|
F5 => Key::Named(NamedKey::F5),
|
||||||
|
F6 => Key::Named(NamedKey::F6),
|
||||||
|
F7 => Key::Named(NamedKey::F7),
|
||||||
|
F8 => Key::Named(NamedKey::F8),
|
||||||
|
F9 => Key::Named(NamedKey::F9),
|
||||||
|
F10 => Key::Named(NamedKey::F10),
|
||||||
|
F11 => Key::Named(NamedKey::F11),
|
||||||
|
F12 => Key::Named(NamedKey::F12),
|
||||||
|
NumLock => Key::Named(NamedKey::NumLock),
|
||||||
|
Numpad0 => Key::Character("0".into()),
|
||||||
|
Numpad1 => Key::Character("1".into()),
|
||||||
|
Numpad2 => Key::Character("2".into()),
|
||||||
|
Numpad3 => Key::Character("3".into()),
|
||||||
|
Numpad4 => Key::Character("4".into()),
|
||||||
|
Numpad5 => Key::Character("5".into()),
|
||||||
|
Numpad6 => Key::Character("6".into()),
|
||||||
|
Numpad7 => Key::Character("7".into()),
|
||||||
|
Numpad8 => Key::Character("8".into()),
|
||||||
|
Numpad9 => Key::Character("9".into()),
|
||||||
|
NumpadDivide => Key::Character("/".into()),
|
||||||
|
NumpadMultiply => Key::Character("*".into()),
|
||||||
|
NumpadSubtract => Key::Character("-".into()),
|
||||||
|
NumpadAdd => Key::Character("+".into()),
|
||||||
|
NumpadDot => Key::Character(".".into()),
|
||||||
|
NumpadComma => Key::Character(",".into()),
|
||||||
|
NumpadEnter => Key::Named(NamedKey::Enter),
|
||||||
|
NumpadEquals => Key::Character("=".into()),
|
||||||
|
NumpadLeftParen => Key::Character("(".into()),
|
||||||
|
NumpadRightParen => Key::Character(")".into()),
|
||||||
|
|
||||||
|
VolumeMute => Key::Named(NamedKey::AudioVolumeMute),
|
||||||
|
Info => Key::Named(NamedKey::Info),
|
||||||
|
ChannelUp => Key::Named(NamedKey::ChannelUp),
|
||||||
|
ChannelDown => Key::Named(NamedKey::ChannelDown),
|
||||||
|
ZoomIn => Key::Named(NamedKey::ZoomIn),
|
||||||
|
ZoomOut => Key::Named(NamedKey::ZoomOut),
|
||||||
|
Tv => Key::Named(NamedKey::TV),
|
||||||
|
Guide => Key::Named(NamedKey::Guide),
|
||||||
|
Dvr => Key::Named(NamedKey::DVR),
|
||||||
|
Bookmark => Key::Named(NamedKey::BrowserFavorites),
|
||||||
|
Captions => Key::Named(NamedKey::ClosedCaptionToggle),
|
||||||
|
Settings => Key::Named(NamedKey::Settings),
|
||||||
|
TvPower => Key::Named(NamedKey::TVPower),
|
||||||
|
TvInput => Key::Named(NamedKey::TVInput),
|
||||||
|
StbPower => Key::Named(NamedKey::STBPower),
|
||||||
|
StbInput => Key::Named(NamedKey::STBInput),
|
||||||
|
AvrPower => Key::Named(NamedKey::AVRPower),
|
||||||
|
AvrInput => Key::Named(NamedKey::AVRInput),
|
||||||
|
ProgRed => Key::Named(NamedKey::ColorF0Red),
|
||||||
|
ProgGreen => Key::Named(NamedKey::ColorF1Green),
|
||||||
|
ProgYellow => Key::Named(NamedKey::ColorF2Yellow),
|
||||||
|
ProgBlue => Key::Named(NamedKey::ColorF3Blue),
|
||||||
|
AppSwitch => Key::Named(NamedKey::AppSwitch),
|
||||||
|
LanguageSwitch => Key::Named(NamedKey::GroupNext),
|
||||||
|
MannerMode => Key::Named(NamedKey::MannerMode),
|
||||||
|
Keycode3dMode => Key::Named(NamedKey::TV3DMode),
|
||||||
|
Contacts => Key::Named(NamedKey::LaunchContacts),
|
||||||
|
Calendar => Key::Named(NamedKey::LaunchCalendar),
|
||||||
|
Music => Key::Named(NamedKey::LaunchMusicPlayer),
|
||||||
|
Calculator => Key::Named(NamedKey::LaunchApplication2),
|
||||||
|
ZenkakuHankaku => Key::Named(NamedKey::ZenkakuHankaku),
|
||||||
|
Eisu => Key::Named(NamedKey::Eisu),
|
||||||
|
Muhenkan => Key::Named(NamedKey::NonConvert),
|
||||||
|
Henkan => Key::Named(NamedKey::Convert),
|
||||||
|
KatakanaHiragana => Key::Named(NamedKey::HiraganaKatakana),
|
||||||
|
Kana => Key::Named(NamedKey::KanjiMode),
|
||||||
|
BrightnessDown => Key::Named(NamedKey::BrightnessDown),
|
||||||
|
BrightnessUp => Key::Named(NamedKey::BrightnessUp),
|
||||||
|
MediaAudioTrack => Key::Named(NamedKey::MediaAudioTrack),
|
||||||
|
Sleep => Key::Named(NamedKey::Standby),
|
||||||
|
Wakeup => Key::Named(NamedKey::WakeUp),
|
||||||
|
Pairing => Key::Named(NamedKey::Pairing),
|
||||||
|
MediaTopMenu => Key::Named(NamedKey::MediaTopMenu),
|
||||||
|
LastChannel => Key::Named(NamedKey::MediaLast),
|
||||||
|
TvDataService => Key::Named(NamedKey::TVDataService),
|
||||||
|
VoiceAssist => Key::Named(NamedKey::VoiceDial),
|
||||||
|
TvRadioService => Key::Named(NamedKey::TVRadioService),
|
||||||
|
TvTeletext => Key::Named(NamedKey::Teletext),
|
||||||
|
TvNumberEntry => Key::Named(NamedKey::TVNumberEntry),
|
||||||
|
TvTerrestrialAnalog => Key::Named(NamedKey::TVTerrestrialAnalog),
|
||||||
|
TvTerrestrialDigital => Key::Named(NamedKey::TVTerrestrialDigital),
|
||||||
|
TvSatellite => Key::Named(NamedKey::TVSatellite),
|
||||||
|
TvSatelliteBs => Key::Named(NamedKey::TVSatelliteBS),
|
||||||
|
TvSatelliteCs => Key::Named(NamedKey::TVSatelliteCS),
|
||||||
|
TvSatelliteService => Key::Named(NamedKey::TVSatelliteToggle),
|
||||||
|
TvNetwork => Key::Named(NamedKey::TVNetwork),
|
||||||
|
TvAntennaCable => Key::Named(NamedKey::TVAntennaCable),
|
||||||
|
TvInputHdmi1 => Key::Named(NamedKey::TVInputHDMI1),
|
||||||
|
TvInputHdmi2 => Key::Named(NamedKey::TVInputHDMI2),
|
||||||
|
TvInputHdmi3 => Key::Named(NamedKey::TVInputHDMI3),
|
||||||
|
TvInputHdmi4 => Key::Named(NamedKey::TVInputHDMI4),
|
||||||
|
TvInputComposite1 => Key::Named(NamedKey::TVInputComposite1),
|
||||||
|
TvInputComposite2 => Key::Named(NamedKey::TVInputComposite2),
|
||||||
|
TvInputComponent1 => Key::Named(NamedKey::TVInputComponent1),
|
||||||
|
TvInputComponent2 => Key::Named(NamedKey::TVInputComponent2),
|
||||||
|
TvInputVga1 => Key::Named(NamedKey::TVInputVGA1),
|
||||||
|
TvAudioDescription => Key::Named(NamedKey::TVAudioDescription),
|
||||||
|
TvAudioDescriptionMixUp => Key::Named(NamedKey::TVAudioDescriptionMixUp),
|
||||||
|
TvAudioDescriptionMixDown => Key::Named(NamedKey::TVAudioDescriptionMixDown),
|
||||||
|
TvZoomMode => Key::Named(NamedKey::ZoomToggle),
|
||||||
|
TvContentsMenu => Key::Named(NamedKey::TVContentsMenu),
|
||||||
|
TvMediaContextMenu => Key::Named(NamedKey::TVMediaContext),
|
||||||
|
TvTimerProgramming => Key::Named(NamedKey::TVTimer),
|
||||||
|
Help => Key::Named(NamedKey::Help),
|
||||||
|
NavigatePrevious => Key::Named(NamedKey::NavigatePrevious),
|
||||||
|
NavigateNext => Key::Named(NamedKey::NavigateNext),
|
||||||
|
NavigateIn => Key::Named(NamedKey::NavigateIn),
|
||||||
|
NavigateOut => Key::Named(NamedKey::NavigateOut),
|
||||||
|
MediaSkipForward => Key::Named(NamedKey::MediaSkipForward),
|
||||||
|
MediaSkipBackward => Key::Named(NamedKey::MediaSkipBackward),
|
||||||
|
MediaStepForward => Key::Named(NamedKey::MediaStepForward),
|
||||||
|
MediaStepBackward => Key::Named(NamedKey::MediaStepBackward),
|
||||||
|
Cut => Key::Named(NamedKey::Cut),
|
||||||
|
Copy => Key::Named(NamedKey::Copy),
|
||||||
|
Paste => Key::Named(NamedKey::Paste),
|
||||||
|
Refresh => Key::Named(NamedKey::BrowserRefresh),
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
// Keycodes that don't have a logical Key mapping
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
Unknown => Key::Unidentified(native),
|
||||||
|
|
||||||
|
// Can be added on demand
|
||||||
|
SoftLeft => Key::Unidentified(native),
|
||||||
|
SoftRight => Key::Unidentified(native),
|
||||||
|
|
||||||
|
Menu => Key::Unidentified(native),
|
||||||
|
|
||||||
|
Pictsymbols => Key::Unidentified(native),
|
||||||
|
SwitchCharset => Key::Unidentified(native),
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
// Gamepad events should be exposed through a separate API, not
|
||||||
|
// keyboard events
|
||||||
|
ButtonA => Key::Unidentified(native),
|
||||||
|
ButtonB => Key::Unidentified(native),
|
||||||
|
ButtonC => Key::Unidentified(native),
|
||||||
|
ButtonX => Key::Unidentified(native),
|
||||||
|
ButtonY => Key::Unidentified(native),
|
||||||
|
ButtonZ => Key::Unidentified(native),
|
||||||
|
ButtonL1 => Key::Unidentified(native),
|
||||||
|
ButtonR1 => Key::Unidentified(native),
|
||||||
|
ButtonL2 => Key::Unidentified(native),
|
||||||
|
ButtonR2 => Key::Unidentified(native),
|
||||||
|
ButtonThumbl => Key::Unidentified(native),
|
||||||
|
ButtonThumbr => Key::Unidentified(native),
|
||||||
|
ButtonStart => Key::Unidentified(native),
|
||||||
|
ButtonSelect => Key::Unidentified(native),
|
||||||
|
ButtonMode => Key::Unidentified(native),
|
||||||
|
// -----------------------------------------------------------------
|
||||||
|
Window => Key::Unidentified(native),
|
||||||
|
|
||||||
|
Button1 => Key::Unidentified(native),
|
||||||
|
Button2 => Key::Unidentified(native),
|
||||||
|
Button3 => Key::Unidentified(native),
|
||||||
|
Button4 => Key::Unidentified(native),
|
||||||
|
Button5 => Key::Unidentified(native),
|
||||||
|
Button6 => Key::Unidentified(native),
|
||||||
|
Button7 => Key::Unidentified(native),
|
||||||
|
Button8 => Key::Unidentified(native),
|
||||||
|
Button9 => Key::Unidentified(native),
|
||||||
|
Button10 => Key::Unidentified(native),
|
||||||
|
Button11 => Key::Unidentified(native),
|
||||||
|
Button12 => Key::Unidentified(native),
|
||||||
|
Button13 => Key::Unidentified(native),
|
||||||
|
Button14 => Key::Unidentified(native),
|
||||||
|
Button15 => Key::Unidentified(native),
|
||||||
|
Button16 => Key::Unidentified(native),
|
||||||
|
|
||||||
|
Yen => Key::Unidentified(native),
|
||||||
|
Ro => Key::Unidentified(native),
|
||||||
|
|
||||||
|
Assist => Key::Unidentified(native),
|
||||||
|
|
||||||
|
Keycode11 => Key::Unidentified(native),
|
||||||
|
Keycode12 => Key::Unidentified(native),
|
||||||
|
|
||||||
|
StemPrimary => Key::Unidentified(native),
|
||||||
|
Stem1 => Key::Unidentified(native),
|
||||||
|
Stem2 => Key::Unidentified(native),
|
||||||
|
Stem3 => Key::Unidentified(native),
|
||||||
|
|
||||||
|
DpadUpLeft => Key::Unidentified(native),
|
||||||
|
DpadDownLeft => Key::Unidentified(native),
|
||||||
|
DpadUpRight => Key::Unidentified(native),
|
||||||
|
DpadDownRight => Key::Unidentified(native),
|
||||||
|
|
||||||
|
SoftSleep => Key::Unidentified(native),
|
||||||
|
|
||||||
|
SystemNavigationUp => Key::Unidentified(native),
|
||||||
|
SystemNavigationDown => Key::Unidentified(native),
|
||||||
|
SystemNavigationLeft => Key::Unidentified(native),
|
||||||
|
SystemNavigationRight => Key::Unidentified(native),
|
||||||
|
|
||||||
|
AllApps => Key::Unidentified(native),
|
||||||
|
ThumbsUp => Key::Unidentified(native),
|
||||||
|
ThumbsDown => Key::Unidentified(native),
|
||||||
|
ProfileSwitch => Key::Unidentified(native),
|
||||||
|
|
||||||
|
// It's always possible that new versions of Android could introduce
|
||||||
|
// key codes we can't know about at compile time.
|
||||||
|
_ => Key::Unidentified(native),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_location(keycode: Keycode) -> KeyLocation {
|
||||||
|
use android_activity::input::Keycode::*;
|
||||||
|
|
||||||
|
match keycode {
|
||||||
|
AltLeft => KeyLocation::Left,
|
||||||
|
AltRight => KeyLocation::Right,
|
||||||
|
ShiftLeft => KeyLocation::Left,
|
||||||
|
ShiftRight => KeyLocation::Right,
|
||||||
|
|
||||||
|
// According to https://developer.android.com/reference/android/view/KeyEvent#KEYCODE_NUM
|
||||||
|
Num => KeyLocation::Left,
|
||||||
|
|
||||||
|
CtrlLeft => KeyLocation::Left,
|
||||||
|
CtrlRight => KeyLocation::Right,
|
||||||
|
MetaLeft => KeyLocation::Left,
|
||||||
|
MetaRight => KeyLocation::Right,
|
||||||
|
|
||||||
|
NumLock => KeyLocation::Numpad,
|
||||||
|
Numpad0 => KeyLocation::Numpad,
|
||||||
|
Numpad1 => KeyLocation::Numpad,
|
||||||
|
Numpad2 => KeyLocation::Numpad,
|
||||||
|
Numpad3 => KeyLocation::Numpad,
|
||||||
|
Numpad4 => KeyLocation::Numpad,
|
||||||
|
Numpad5 => KeyLocation::Numpad,
|
||||||
|
Numpad6 => KeyLocation::Numpad,
|
||||||
|
Numpad7 => KeyLocation::Numpad,
|
||||||
|
Numpad8 => KeyLocation::Numpad,
|
||||||
|
Numpad9 => KeyLocation::Numpad,
|
||||||
|
NumpadDivide => KeyLocation::Numpad,
|
||||||
|
NumpadMultiply => KeyLocation::Numpad,
|
||||||
|
NumpadSubtract => KeyLocation::Numpad,
|
||||||
|
NumpadAdd => KeyLocation::Numpad,
|
||||||
|
NumpadDot => KeyLocation::Numpad,
|
||||||
|
NumpadComma => KeyLocation::Numpad,
|
||||||
|
NumpadEnter => KeyLocation::Numpad,
|
||||||
|
NumpadEquals => KeyLocation::Numpad,
|
||||||
|
NumpadLeftParen => KeyLocation::Numpad,
|
||||||
|
NumpadRightParen => KeyLocation::Numpad,
|
||||||
|
|
||||||
|
_ => KeyLocation::Standard,
|
||||||
|
}
|
||||||
|
}
|
||||||
+1126
File diff suppressed because it is too large.
Load diff
+968
@@ -0,0 +1,968 @@
|
|||||||
|
#![deny(unused_results)]
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
cell::{RefCell, RefMut},
|
||||||
|
collections::HashSet,
|
||||||
|
mem,
|
||||||
|
os::raw::c_void,
|
||||||
|
ptr,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
time::Instant,
|
||||||
|
};
|
||||||
|
|
||||||
|
use core_foundation::base::CFRelease;
|
||||||
|
use core_foundation::date::CFAbsoluteTimeGetCurrent;
|
||||||
|
use core_foundation::runloop::{
|
||||||
|
kCFRunLoopCommonModes, CFRunLoopAddTimer, CFRunLoopGetMain, CFRunLoopRef, CFRunLoopTimerCreate,
|
||||||
|
CFRunLoopTimerInvalidate, CFRunLoopTimerRef, CFRunLoopTimerSetNextFireDate,
|
||||||
|
};
|
||||||
|
use icrate::Foundation::{
|
||||||
|
CGRect, CGSize, MainThreadMarker, NSInteger, NSOperatingSystemVersion, NSProcessInfo,
|
||||||
|
};
|
||||||
|
use objc2::rc::Id;
|
||||||
|
use objc2::runtime::AnyObject;
|
||||||
|
use objc2::{msg_send, sel};
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
|
||||||
|
use super::event_loop::{EventHandler, Never};
|
||||||
|
use super::uikit::UIView;
|
||||||
|
use super::view::WinitUIWindow;
|
||||||
|
use crate::{
|
||||||
|
dpi::PhysicalSize,
|
||||||
|
event::{Event, InnerSizeWriter, StartCause, WindowEvent},
|
||||||
|
event_loop::ControlFlow,
|
||||||
|
window::WindowId as RootWindowId,
|
||||||
|
};
|
||||||
|
|
||||||
|
macro_rules! bug {
|
||||||
|
($($msg:tt)*) => {
|
||||||
|
panic!("winit iOS bug, file an issue: {}", format!($($msg)*))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! bug_assert {
|
||||||
|
($test:expr, $($msg:tt)*) => {
|
||||||
|
assert!($test, "winit iOS bug, file an issue: {}", format!($($msg)*))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum EventWrapper {
|
||||||
|
StaticEvent(Event<Never>),
|
||||||
|
ScaleFactorChanged(ScaleFactorChanged),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ScaleFactorChanged {
|
||||||
|
pub(super) window: Id<WinitUIWindow>,
|
||||||
|
pub(super) suggested_size: PhysicalSize<u32>,
|
||||||
|
pub(super) scale_factor: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum UserCallbackTransitionResult<'a> {
|
||||||
|
Success {
|
||||||
|
event_handler: Box<dyn EventHandler>,
|
||||||
|
active_control_flow: ControlFlow,
|
||||||
|
processing_redraws: bool,
|
||||||
|
},
|
||||||
|
ReentrancyPrevented {
|
||||||
|
queued_events: &'a mut Vec<EventWrapper>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Event<Never> {
|
||||||
|
fn is_redraw(&self) -> bool {
|
||||||
|
matches!(
|
||||||
|
self,
|
||||||
|
Event::WindowEvent {
|
||||||
|
event: WindowEvent::RedrawRequested,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// this is the state machine for the app lifecycle
|
||||||
|
#[derive(Debug)]
|
||||||
|
#[must_use = "dropping `AppStateImpl` without inspecting it is probably a bug"]
|
||||||
|
enum AppStateImpl {
|
||||||
|
NotLaunched {
|
||||||
|
queued_windows: Vec<Id<WinitUIWindow>>,
|
||||||
|
queued_events: Vec<EventWrapper>,
|
||||||
|
queued_gpu_redraws: HashSet<Id<WinitUIWindow>>,
|
||||||
|
},
|
||||||
|
Launching {
|
||||||
|
queued_windows: Vec<Id<WinitUIWindow>>,
|
||||||
|
queued_events: Vec<EventWrapper>,
|
||||||
|
queued_event_handler: Box<dyn EventHandler>,
|
||||||
|
queued_gpu_redraws: HashSet<Id<WinitUIWindow>>,
|
||||||
|
},
|
||||||
|
ProcessingEvents {
|
||||||
|
event_handler: Box<dyn EventHandler>,
|
||||||
|
queued_gpu_redraws: HashSet<Id<WinitUIWindow>>,
|
||||||
|
active_control_flow: ControlFlow,
|
||||||
|
},
|
||||||
|
// special state to deal with reentrancy and prevent mutable aliasing.
|
||||||
|
InUserCallback {
|
||||||
|
queued_events: Vec<EventWrapper>,
|
||||||
|
queued_gpu_redraws: HashSet<Id<WinitUIWindow>>,
|
||||||
|
},
|
||||||
|
ProcessingRedraws {
|
||||||
|
event_handler: Box<dyn EventHandler>,
|
||||||
|
active_control_flow: ControlFlow,
|
||||||
|
},
|
||||||
|
Waiting {
|
||||||
|
waiting_event_handler: Box<dyn EventHandler>,
|
||||||
|
start: Instant,
|
||||||
|
},
|
||||||
|
PollFinished {
|
||||||
|
waiting_event_handler: Box<dyn EventHandler>,
|
||||||
|
},
|
||||||
|
Terminated,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct AppState {
|
||||||
|
// This should never be `None`, except for briefly during a state transition.
|
||||||
|
app_state: Option<AppStateImpl>,
|
||||||
|
control_flow: ControlFlow,
|
||||||
|
waker: EventLoopWaker,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppState {
|
||||||
|
pub(crate) fn get_mut(_mtm: MainThreadMarker) -> RefMut<'static, AppState> {
|
||||||
|
// basically everything in UIKit requires the main thread, so it's pointless to use the
|
||||||
|
// std::sync APIs.
|
||||||
|
// must be mut because plain `static` requires `Sync`
|
||||||
|
static mut APP_STATE: RefCell<Option<AppState>> = RefCell::new(None);
|
||||||
|
|
||||||
|
let mut guard = unsafe { APP_STATE.borrow_mut() };
|
||||||
|
if guard.is_none() {
|
||||||
|
#[inline(never)]
|
||||||
|
#[cold]
|
||||||
|
fn init_guard(guard: &mut RefMut<'static, Option<AppState>>) {
|
||||||
|
let waker = EventLoopWaker::new(unsafe { CFRunLoopGetMain() });
|
||||||
|
**guard = Some(AppState {
|
||||||
|
app_state: Some(AppStateImpl::NotLaunched {
|
||||||
|
queued_windows: Vec::new(),
|
||||||
|
queued_events: Vec::new(),
|
||||||
|
queued_gpu_redraws: HashSet::new(),
|
||||||
|
}),
|
||||||
|
control_flow: ControlFlow::default(),
|
||||||
|
waker,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
init_guard(&mut guard);
|
||||||
|
}
|
||||||
|
RefMut::map(guard, |state| state.as_mut().unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state(&self) -> &AppStateImpl {
|
||||||
|
match &self.app_state {
|
||||||
|
Some(ref state) => state,
|
||||||
|
None => bug!("`AppState` previously failed a state transition"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state_mut(&mut self) -> &mut AppStateImpl {
|
||||||
|
match &mut self.app_state {
|
||||||
|
Some(ref mut state) => state,
|
||||||
|
None => bug!("`AppState` previously failed a state transition"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn take_state(&mut self) -> AppStateImpl {
|
||||||
|
match self.app_state.take() {
|
||||||
|
Some(state) => state,
|
||||||
|
None => bug!("`AppState` previously failed a state transition"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_state(&mut self, new_state: AppStateImpl) {
|
||||||
|
bug_assert!(
|
||||||
|
self.app_state.is_none(),
|
||||||
|
"attempted to set an `AppState` without calling `take_state` first {:?}",
|
||||||
|
self.app_state
|
||||||
|
);
|
||||||
|
self.app_state = Some(new_state)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn replace_state(&mut self, new_state: AppStateImpl) -> AppStateImpl {
|
||||||
|
match &mut self.app_state {
|
||||||
|
Some(ref mut state) => mem::replace(state, new_state),
|
||||||
|
None => bug!("`AppState` previously failed a state transition"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_launched(&self) -> bool {
|
||||||
|
!matches!(
|
||||||
|
self.state(),
|
||||||
|
AppStateImpl::NotLaunched { .. } | AppStateImpl::Launching { .. }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_terminated(&self) -> bool {
|
||||||
|
matches!(self.state(), AppStateImpl::Terminated)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn will_launch_transition(&mut self, queued_event_handler: Box<dyn EventHandler>) {
|
||||||
|
let (queued_windows, queued_events, queued_gpu_redraws) = match self.take_state() {
|
||||||
|
AppStateImpl::NotLaunched {
|
||||||
|
queued_windows,
|
||||||
|
queued_events,
|
||||||
|
queued_gpu_redraws,
|
||||||
|
} => (queued_windows, queued_events, queued_gpu_redraws),
|
||||||
|
s => bug!("unexpected state {:?}", s),
|
||||||
|
};
|
||||||
|
self.set_state(AppStateImpl::Launching {
|
||||||
|
queued_windows,
|
||||||
|
queued_events,
|
||||||
|
queued_event_handler,
|
||||||
|
queued_gpu_redraws,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn did_finish_launching_transition(&mut self) -> (Vec<Id<WinitUIWindow>>, Vec<EventWrapper>) {
|
||||||
|
let (windows, events, event_handler, queued_gpu_redraws) = match self.take_state() {
|
||||||
|
AppStateImpl::Launching {
|
||||||
|
queued_windows,
|
||||||
|
queued_events,
|
||||||
|
queued_event_handler,
|
||||||
|
queued_gpu_redraws,
|
||||||
|
} => (
|
||||||
|
queued_windows,
|
||||||
|
queued_events,
|
||||||
|
queued_event_handler,
|
||||||
|
queued_gpu_redraws,
|
||||||
|
),
|
||||||
|
s => bug!("unexpected state {:?}", s),
|
||||||
|
};
|
||||||
|
self.set_state(AppStateImpl::ProcessingEvents {
|
||||||
|
event_handler,
|
||||||
|
active_control_flow: self.control_flow,
|
||||||
|
queued_gpu_redraws,
|
||||||
|
});
|
||||||
|
(windows, events)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wakeup_transition(&mut self) -> Option<EventWrapper> {
|
||||||
|
// before `AppState::did_finish_launching` is called, pretend there is no running
|
||||||
|
// event loop.
|
||||||
|
if !self.has_launched() || self.has_terminated() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (event_handler, event) = match (self.control_flow, self.take_state()) {
|
||||||
|
(
|
||||||
|
ControlFlow::Poll,
|
||||||
|
AppStateImpl::PollFinished {
|
||||||
|
waiting_event_handler,
|
||||||
|
},
|
||||||
|
) => (
|
||||||
|
waiting_event_handler,
|
||||||
|
EventWrapper::StaticEvent(Event::NewEvents(StartCause::Poll)),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ControlFlow::Wait,
|
||||||
|
AppStateImpl::Waiting {
|
||||||
|
waiting_event_handler,
|
||||||
|
start,
|
||||||
|
},
|
||||||
|
) => (
|
||||||
|
waiting_event_handler,
|
||||||
|
EventWrapper::StaticEvent(Event::NewEvents(StartCause::WaitCancelled {
|
||||||
|
start,
|
||||||
|
requested_resume: None,
|
||||||
|
})),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ControlFlow::WaitUntil(requested_resume),
|
||||||
|
AppStateImpl::Waiting {
|
||||||
|
waiting_event_handler,
|
||||||
|
start,
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
let event = if Instant::now() >= requested_resume {
|
||||||
|
EventWrapper::StaticEvent(Event::NewEvents(StartCause::ResumeTimeReached {
|
||||||
|
start,
|
||||||
|
requested_resume,
|
||||||
|
}))
|
||||||
|
} else {
|
||||||
|
EventWrapper::StaticEvent(Event::NewEvents(StartCause::WaitCancelled {
|
||||||
|
start,
|
||||||
|
requested_resume: Some(requested_resume),
|
||||||
|
}))
|
||||||
|
};
|
||||||
|
(waiting_event_handler, event)
|
||||||
|
}
|
||||||
|
s => bug!("`EventHandler` unexpectedly woke up {:?}", s),
|
||||||
|
};
|
||||||
|
|
||||||
|
self.set_state(AppStateImpl::ProcessingEvents {
|
||||||
|
event_handler,
|
||||||
|
queued_gpu_redraws: Default::default(),
|
||||||
|
active_control_flow: self.control_flow,
|
||||||
|
});
|
||||||
|
Some(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_user_callback_transition(&mut self) -> UserCallbackTransitionResult<'_> {
|
||||||
|
// If we're not able to process an event due to recursion or `Init` not having been sent out
|
||||||
|
// yet, then queue the events up.
|
||||||
|
match self.state_mut() {
|
||||||
|
&mut AppStateImpl::Launching {
|
||||||
|
ref mut queued_events,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
| &mut AppStateImpl::NotLaunched {
|
||||||
|
ref mut queued_events,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
| &mut AppStateImpl::InUserCallback {
|
||||||
|
ref mut queued_events,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
// A lifetime cast: early returns are not currently handled well with NLL, but
|
||||||
|
// polonius handles them well. This transmute is a safe workaround.
|
||||||
|
return unsafe {
|
||||||
|
mem::transmute::<
|
||||||
|
UserCallbackTransitionResult<'_>,
|
||||||
|
UserCallbackTransitionResult<'_>,
|
||||||
|
>(UserCallbackTransitionResult::ReentrancyPrevented {
|
||||||
|
queued_events,
|
||||||
|
})
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
&mut AppStateImpl::ProcessingEvents { .. }
|
||||||
|
| &mut AppStateImpl::ProcessingRedraws { .. } => {}
|
||||||
|
|
||||||
|
s @ &mut AppStateImpl::PollFinished { .. }
|
||||||
|
| s @ &mut AppStateImpl::Waiting { .. }
|
||||||
|
| s @ &mut AppStateImpl::Terminated => {
|
||||||
|
bug!("unexpected attempted to process an event {:?}", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let (event_handler, queued_gpu_redraws, active_control_flow, processing_redraws) =
|
||||||
|
match self.take_state() {
|
||||||
|
AppStateImpl::Launching { .. }
|
||||||
|
| AppStateImpl::NotLaunched { .. }
|
||||||
|
| AppStateImpl::InUserCallback { .. } => unreachable!(),
|
||||||
|
AppStateImpl::ProcessingEvents {
|
||||||
|
event_handler,
|
||||||
|
queued_gpu_redraws,
|
||||||
|
active_control_flow,
|
||||||
|
} => (
|
||||||
|
event_handler,
|
||||||
|
queued_gpu_redraws,
|
||||||
|
active_control_flow,
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
AppStateImpl::ProcessingRedraws {
|
||||||
|
event_handler,
|
||||||
|
active_control_flow,
|
||||||
|
} => (event_handler, Default::default(), active_control_flow, true),
|
||||||
|
AppStateImpl::PollFinished { .. }
|
||||||
|
| AppStateImpl::Waiting { .. }
|
||||||
|
| AppStateImpl::Terminated => unreachable!(),
|
||||||
|
};
|
||||||
|
self.set_state(AppStateImpl::InUserCallback {
|
||||||
|
queued_events: Vec::new(),
|
||||||
|
queued_gpu_redraws,
|
||||||
|
});
|
||||||
|
UserCallbackTransitionResult::Success {
|
||||||
|
event_handler,
|
||||||
|
active_control_flow,
|
||||||
|
processing_redraws,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main_events_cleared_transition(&mut self) -> HashSet<Id<WinitUIWindow>> {
|
||||||
|
let (event_handler, queued_gpu_redraws, active_control_flow) = match self.take_state() {
|
||||||
|
AppStateImpl::ProcessingEvents {
|
||||||
|
event_handler,
|
||||||
|
queued_gpu_redraws,
|
||||||
|
active_control_flow,
|
||||||
|
} => (event_handler, queued_gpu_redraws, active_control_flow),
|
||||||
|
s => bug!("unexpected state {:?}", s),
|
||||||
|
};
|
||||||
|
self.set_state(AppStateImpl::ProcessingRedraws {
|
||||||
|
event_handler,
|
||||||
|
active_control_flow,
|
||||||
|
});
|
||||||
|
queued_gpu_redraws
|
||||||
|
}
|
||||||
|
|
||||||
|
fn events_cleared_transition(&mut self) {
|
||||||
|
if !self.has_launched() || self.has_terminated() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let (waiting_event_handler, old) = match self.take_state() {
|
||||||
|
AppStateImpl::ProcessingRedraws {
|
||||||
|
event_handler,
|
||||||
|
active_control_flow,
|
||||||
|
} => (event_handler, active_control_flow),
|
||||||
|
s => bug!("unexpected state {:?}", s),
|
||||||
|
};
|
||||||
|
|
||||||
|
let new = self.control_flow;
|
||||||
|
match (old, new) {
|
||||||
|
(ControlFlow::Wait, ControlFlow::Wait) => {
|
||||||
|
let start = Instant::now();
|
||||||
|
self.set_state(AppStateImpl::Waiting {
|
||||||
|
waiting_event_handler,
|
||||||
|
start,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
(ControlFlow::WaitUntil(old_instant), ControlFlow::WaitUntil(new_instant))
|
||||||
|
if old_instant == new_instant =>
|
||||||
|
{
|
||||||
|
let start = Instant::now();
|
||||||
|
self.set_state(AppStateImpl::Waiting {
|
||||||
|
waiting_event_handler,
|
||||||
|
start,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
(_, ControlFlow::Wait) => {
|
||||||
|
let start = Instant::now();
|
||||||
|
self.set_state(AppStateImpl::Waiting {
|
||||||
|
waiting_event_handler,
|
||||||
|
start,
|
||||||
|
});
|
||||||
|
self.waker.stop()
|
||||||
|
}
|
||||||
|
(_, ControlFlow::WaitUntil(new_instant)) => {
|
||||||
|
let start = Instant::now();
|
||||||
|
self.set_state(AppStateImpl::Waiting {
|
||||||
|
waiting_event_handler,
|
||||||
|
start,
|
||||||
|
});
|
||||||
|
self.waker.start_at(new_instant)
|
||||||
|
}
|
||||||
|
// Unlike on macOS, handle Poll to Poll transition here to call the waker
|
||||||
|
(_, ControlFlow::Poll) => {
|
||||||
|
self.set_state(AppStateImpl::PollFinished {
|
||||||
|
waiting_event_handler,
|
||||||
|
});
|
||||||
|
self.waker.start()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn terminated_transition(&mut self) -> Box<dyn EventHandler> {
|
||||||
|
match self.replace_state(AppStateImpl::Terminated) {
|
||||||
|
AppStateImpl::ProcessingEvents { event_handler, .. } => event_handler,
|
||||||
|
s => bug!("`LoopExiting` happened while not processing events {:?}", s),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn set_control_flow(&mut self, control_flow: ControlFlow) {
|
||||||
|
self.control_flow = control_flow;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn control_flow(&self) -> ControlFlow {
|
||||||
|
self.control_flow
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn set_key_window(mtm: MainThreadMarker, window: &Id<WinitUIWindow>) {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
match this.state_mut() {
|
||||||
|
&mut AppStateImpl::NotLaunched {
|
||||||
|
ref mut queued_windows,
|
||||||
|
..
|
||||||
|
} => return queued_windows.push(window.clone()),
|
||||||
|
&mut AppStateImpl::ProcessingEvents { .. }
|
||||||
|
| &mut AppStateImpl::InUserCallback { .. }
|
||||||
|
| &mut AppStateImpl::ProcessingRedraws { .. } => {}
|
||||||
|
s @ &mut AppStateImpl::Launching { .. }
|
||||||
|
| s @ &mut AppStateImpl::Waiting { .. }
|
||||||
|
| s @ &mut AppStateImpl::PollFinished { .. } => bug!("unexpected state {:?}", s),
|
||||||
|
&mut AppStateImpl::Terminated => {
|
||||||
|
panic!("Attempt to create a `Window` after the app has terminated")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
drop(this);
|
||||||
|
window.makeKeyAndVisible();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn queue_gl_or_metal_redraw(mtm: MainThreadMarker, window: Id<WinitUIWindow>) {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
match this.state_mut() {
|
||||||
|
&mut AppStateImpl::NotLaunched {
|
||||||
|
ref mut queued_gpu_redraws,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
| &mut AppStateImpl::Launching {
|
||||||
|
ref mut queued_gpu_redraws,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
| &mut AppStateImpl::ProcessingEvents {
|
||||||
|
ref mut queued_gpu_redraws,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
| &mut AppStateImpl::InUserCallback {
|
||||||
|
ref mut queued_gpu_redraws,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
let _ = queued_gpu_redraws.insert(window);
|
||||||
|
}
|
||||||
|
s @ &mut AppStateImpl::ProcessingRedraws { .. }
|
||||||
|
| s @ &mut AppStateImpl::Waiting { .. }
|
||||||
|
| s @ &mut AppStateImpl::PollFinished { .. } => bug!("unexpected state {:?}", s),
|
||||||
|
&mut AppStateImpl::Terminated => {
|
||||||
|
panic!("Attempt to create a `Window` after the app has terminated")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn will_launch(mtm: MainThreadMarker, queued_event_handler: Box<dyn EventHandler>) {
|
||||||
|
AppState::get_mut(mtm).will_launch_transition(queued_event_handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn did_finish_launching(mtm: MainThreadMarker) {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
let windows = match this.state_mut() {
|
||||||
|
AppStateImpl::Launching { queued_windows, .. } => mem::take(queued_windows),
|
||||||
|
s => bug!("unexpected state {:?}", s),
|
||||||
|
};
|
||||||
|
|
||||||
|
this.waker.start();
|
||||||
|
|
||||||
|
// have to drop RefMut because the window setup code below can trigger new events
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
for window in windows {
|
||||||
|
// Do a little screen dance here to account for windows being created before
|
||||||
|
// `UIApplicationMain` is called. This fixes visual issues such as being
|
||||||
|
// offcenter and sized incorrectly. Additionally, to fix orientation issues, we
|
||||||
|
// gotta reset the `rootViewController`.
|
||||||
|
//
|
||||||
|
// relevant iOS log:
|
||||||
|
// ```
|
||||||
|
// [ApplicationLifecycle] Windows were created before application initialzation
|
||||||
|
// completed. This may result in incorrect visual appearance.
|
||||||
|
// ```
|
||||||
|
let screen = window.screen();
|
||||||
|
let _: () = unsafe { msg_send![&window, setScreen: ptr::null::<AnyObject>()] };
|
||||||
|
window.setScreen(&screen);
|
||||||
|
|
||||||
|
let controller = window.rootViewController();
|
||||||
|
window.setRootViewController(None);
|
||||||
|
window.setRootViewController(controller.as_deref());
|
||||||
|
|
||||||
|
window.makeKeyAndVisible();
|
||||||
|
}
|
||||||
|
|
||||||
|
let (windows, events) = AppState::get_mut(mtm).did_finish_launching_transition();
|
||||||
|
|
||||||
|
let events = std::iter::once(EventWrapper::StaticEvent(Event::NewEvents(
|
||||||
|
StartCause::Init,
|
||||||
|
)))
|
||||||
|
.chain(events);
|
||||||
|
handle_nonuser_events(mtm, events);
|
||||||
|
|
||||||
|
// the above window dance hack, could possibly trigger new windows to be created.
|
||||||
|
// we can just set those windows up normally, as they were created after didFinishLaunching
|
||||||
|
for window in windows {
|
||||||
|
window.makeKeyAndVisible();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// AppState::did_finish_launching handles the special transition `Init`
|
||||||
|
pub fn handle_wakeup_transition(mtm: MainThreadMarker) {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
let wakeup_event = match this.wakeup_transition() {
|
||||||
|
None => return,
|
||||||
|
Some(wakeup_event) => wakeup_event,
|
||||||
|
};
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
handle_nonuser_event(mtm, wakeup_event)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn handle_nonuser_event(mtm: MainThreadMarker, event: EventWrapper) {
|
||||||
|
handle_nonuser_events(mtm, std::iter::once(event))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn handle_nonuser_events<I: IntoIterator<Item = EventWrapper>>(
|
||||||
|
mtm: MainThreadMarker,
|
||||||
|
events: I,
|
||||||
|
) {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
if this.has_terminated() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (mut event_handler, active_control_flow, processing_redraws) =
|
||||||
|
match this.try_user_callback_transition() {
|
||||||
|
UserCallbackTransitionResult::ReentrancyPrevented { queued_events } => {
|
||||||
|
queued_events.extend(events);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
UserCallbackTransitionResult::Success {
|
||||||
|
event_handler,
|
||||||
|
active_control_flow,
|
||||||
|
processing_redraws,
|
||||||
|
} => (event_handler, active_control_flow, processing_redraws),
|
||||||
|
};
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
for wrapper in events {
|
||||||
|
match wrapper {
|
||||||
|
EventWrapper::StaticEvent(event) => {
|
||||||
|
if !processing_redraws && event.is_redraw() {
|
||||||
|
log::info!("processing `RedrawRequested` during the main event loop");
|
||||||
|
} else if processing_redraws && !event.is_redraw() {
|
||||||
|
log::warn!(
|
||||||
|
"processing non `RedrawRequested` event after the main event loop: {:#?}",
|
||||||
|
event
|
||||||
|
);
|
||||||
|
}
|
||||||
|
event_handler.handle_nonuser_event(event)
|
||||||
|
}
|
||||||
|
EventWrapper::ScaleFactorChanged(event) => {
|
||||||
|
handle_hidpi_proxy(&mut event_handler, event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
let queued_events = match this.state_mut() {
|
||||||
|
&mut AppStateImpl::InUserCallback {
|
||||||
|
ref mut queued_events,
|
||||||
|
queued_gpu_redraws: _,
|
||||||
|
} => mem::take(queued_events),
|
||||||
|
s => bug!("unexpected state {:?}", s),
|
||||||
|
};
|
||||||
|
if queued_events.is_empty() {
|
||||||
|
let queued_gpu_redraws = match this.take_state() {
|
||||||
|
AppStateImpl::InUserCallback {
|
||||||
|
queued_events: _,
|
||||||
|
queued_gpu_redraws,
|
||||||
|
} => queued_gpu_redraws,
|
||||||
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
this.app_state = Some(if processing_redraws {
|
||||||
|
bug_assert!(
|
||||||
|
queued_gpu_redraws.is_empty(),
|
||||||
|
"redraw queued while processing redraws"
|
||||||
|
);
|
||||||
|
AppStateImpl::ProcessingRedraws {
|
||||||
|
event_handler,
|
||||||
|
active_control_flow,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
AppStateImpl::ProcessingEvents {
|
||||||
|
event_handler,
|
||||||
|
queued_gpu_redraws,
|
||||||
|
active_control_flow,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
for wrapper in queued_events {
|
||||||
|
match wrapper {
|
||||||
|
EventWrapper::StaticEvent(event) => {
|
||||||
|
if !processing_redraws && event.is_redraw() {
|
||||||
|
log::info!("processing `RedrawRequested` during the main event loop");
|
||||||
|
} else if processing_redraws && !event.is_redraw() {
|
||||||
|
log::warn!(
|
||||||
|
"processing non-`RedrawRequested` event after the main event loop: {:#?}",
|
||||||
|
event
|
||||||
|
);
|
||||||
|
}
|
||||||
|
event_handler.handle_nonuser_event(event)
|
||||||
|
}
|
||||||
|
EventWrapper::ScaleFactorChanged(event) => {
|
||||||
|
handle_hidpi_proxy(&mut event_handler, event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_user_events(mtm: MainThreadMarker) {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
let (mut event_handler, active_control_flow, processing_redraws) =
|
||||||
|
match this.try_user_callback_transition() {
|
||||||
|
UserCallbackTransitionResult::ReentrancyPrevented { .. } => {
|
||||||
|
bug!("unexpected attempted to process an event")
|
||||||
|
}
|
||||||
|
UserCallbackTransitionResult::Success {
|
||||||
|
event_handler,
|
||||||
|
active_control_flow,
|
||||||
|
processing_redraws,
|
||||||
|
} => (event_handler, active_control_flow, processing_redraws),
|
||||||
|
};
|
||||||
|
if processing_redraws {
|
||||||
|
bug!("user events attempted to be sent out while `ProcessingRedraws`");
|
||||||
|
}
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
event_handler.handle_user_events();
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
let queued_events = match this.state_mut() {
|
||||||
|
&mut AppStateImpl::InUserCallback {
|
||||||
|
ref mut queued_events,
|
||||||
|
queued_gpu_redraws: _,
|
||||||
|
} => mem::take(queued_events),
|
||||||
|
s => bug!("unexpected state {:?}", s),
|
||||||
|
};
|
||||||
|
if queued_events.is_empty() {
|
||||||
|
let queued_gpu_redraws = match this.take_state() {
|
||||||
|
AppStateImpl::InUserCallback {
|
||||||
|
queued_events: _,
|
||||||
|
queued_gpu_redraws,
|
||||||
|
} => queued_gpu_redraws,
|
||||||
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
this.app_state = Some(AppStateImpl::ProcessingEvents {
|
||||||
|
event_handler,
|
||||||
|
queued_gpu_redraws,
|
||||||
|
active_control_flow,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
for wrapper in queued_events {
|
||||||
|
match wrapper {
|
||||||
|
EventWrapper::StaticEvent(event) => event_handler.handle_nonuser_event(event),
|
||||||
|
EventWrapper::ScaleFactorChanged(event) => {
|
||||||
|
handle_hidpi_proxy(&mut event_handler, event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
event_handler.handle_user_events();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn handle_main_events_cleared(mtm: MainThreadMarker) {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
if !this.has_launched() || this.has_terminated() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match this.state_mut() {
|
||||||
|
AppStateImpl::ProcessingEvents { .. } => {}
|
||||||
|
_ => bug!("`ProcessingRedraws` happened unexpectedly"),
|
||||||
|
};
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
handle_user_events(mtm);
|
||||||
|
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
let redraw_events: Vec<EventWrapper> = this
|
||||||
|
.main_events_cleared_transition()
|
||||||
|
.into_iter()
|
||||||
|
.map(|window| {
|
||||||
|
EventWrapper::StaticEvent(Event::WindowEvent {
|
||||||
|
window_id: RootWindowId(window.id()),
|
||||||
|
event: WindowEvent::RedrawRequested,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
handle_nonuser_events(mtm, redraw_events);
|
||||||
|
handle_nonuser_event(mtm, EventWrapper::StaticEvent(Event::AboutToWait));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn handle_events_cleared(mtm: MainThreadMarker) {
|
||||||
|
AppState::get_mut(mtm).events_cleared_transition();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn terminated(mtm: MainThreadMarker) {
|
||||||
|
let mut this = AppState::get_mut(mtm);
|
||||||
|
let mut event_handler = this.terminated_transition();
|
||||||
|
drop(this);
|
||||||
|
|
||||||
|
event_handler.handle_nonuser_event(Event::LoopExiting)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_hidpi_proxy(event_handler: &mut Box<dyn EventHandler>, event: ScaleFactorChanged) {
|
||||||
|
let ScaleFactorChanged {
|
||||||
|
suggested_size,
|
||||||
|
scale_factor,
|
||||||
|
window,
|
||||||
|
} = event;
|
||||||
|
let new_inner_size = Arc::new(Mutex::new(suggested_size));
|
||||||
|
let event = Event::WindowEvent {
|
||||||
|
window_id: RootWindowId(window.id()),
|
||||||
|
event: WindowEvent::ScaleFactorChanged {
|
||||||
|
scale_factor,
|
||||||
|
inner_size_writer: InnerSizeWriter::new(Arc::downgrade(&new_inner_size)),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
event_handler.handle_nonuser_event(event);
|
||||||
|
let (view, screen_frame) = get_view_and_screen_frame(&window);
|
||||||
|
let physical_size = *new_inner_size.lock().unwrap();
|
||||||
|
drop(new_inner_size);
|
||||||
|
let logical_size = physical_size.to_logical(scale_factor);
|
||||||
|
let size = CGSize::new(logical_size.width, logical_size.height);
|
||||||
|
let new_frame: CGRect = CGRect::new(screen_frame.origin, size);
|
||||||
|
view.setFrame(new_frame);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_view_and_screen_frame(window: &WinitUIWindow) -> (Id<UIView>, CGRect) {
|
||||||
|
let view_controller = window.rootViewController().unwrap();
|
||||||
|
let view = view_controller.view().unwrap();
|
||||||
|
let bounds = window.bounds();
|
||||||
|
let screen = window.screen();
|
||||||
|
let screen_space = screen.coordinateSpace();
|
||||||
|
let screen_frame = window.convertRect_toCoordinateSpace(bounds, &screen_space);
|
||||||
|
(view, screen_frame)
|
||||||
|
}
|
||||||
|
|
||||||
|
struct EventLoopWaker {
|
||||||
|
timer: CFRunLoopTimerRef,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for EventLoopWaker {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
CFRunLoopTimerInvalidate(self.timer);
|
||||||
|
CFRelease(self.timer as _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EventLoopWaker {
|
||||||
|
fn new(rl: CFRunLoopRef) -> EventLoopWaker {
|
||||||
|
extern "C" fn wakeup_main_loop(_timer: CFRunLoopTimerRef, _info: *mut c_void) {}
|
||||||
|
unsafe {
|
||||||
|
// Create a timer with a 0.1µs interval (1ns does not work) to mimic polling.
|
||||||
|
// It is initially setup with a first fire time really far into the
|
||||||
|
// future, but that gets changed to fire immediately in did_finish_launching
|
||||||
|
let timer = CFRunLoopTimerCreate(
|
||||||
|
ptr::null_mut(),
|
||||||
|
std::f64::MAX,
|
||||||
|
0.000_000_1,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
wakeup_main_loop,
|
||||||
|
ptr::null_mut(),
|
||||||
|
);
|
||||||
|
CFRunLoopAddTimer(rl, timer, kCFRunLoopCommonModes);
|
||||||
|
|
||||||
|
EventLoopWaker { timer }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stop(&mut self) {
|
||||||
|
unsafe { CFRunLoopTimerSetNextFireDate(self.timer, std::f64::MAX) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start(&mut self) {
|
||||||
|
unsafe { CFRunLoopTimerSetNextFireDate(self.timer, std::f64::MIN) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_at(&mut self, instant: Instant) {
|
||||||
|
let now = Instant::now();
|
||||||
|
if now >= instant {
|
||||||
|
self.start();
|
||||||
|
} else {
|
||||||
|
unsafe {
|
||||||
|
let current = CFAbsoluteTimeGetCurrent();
|
||||||
|
let duration = instant - now;
|
||||||
|
let fsecs =
|
||||||
|
duration.subsec_nanos() as f64 / 1_000_000_000.0 + duration.as_secs() as f64;
|
||||||
|
CFRunLoopTimerSetNextFireDate(self.timer, current + fsecs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! os_capabilities {
|
||||||
|
(
|
||||||
|
$(
|
||||||
|
$(#[$attr:meta])*
|
||||||
|
$error_name:ident: $objc_call:literal,
|
||||||
|
$name:ident: $major:literal-$minor:literal
|
||||||
|
),*
|
||||||
|
$(,)*
|
||||||
|
) => {
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct OSCapabilities {
|
||||||
|
$(
|
||||||
|
pub $name: bool,
|
||||||
|
)*
|
||||||
|
|
||||||
|
os_version: NSOperatingSystemVersion,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<NSOperatingSystemVersion> for OSCapabilities {
|
||||||
|
fn from(os_version: NSOperatingSystemVersion) -> OSCapabilities {
|
||||||
|
$(let $name = meets_requirements(os_version, $major, $minor);)*
|
||||||
|
OSCapabilities { $($name,)* os_version, }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OSCapabilities {$(
|
||||||
|
$(#[$attr])*
|
||||||
|
pub fn $error_name(&self, extra_msg: &str) {
|
||||||
|
log::warn!(
|
||||||
|
concat!("`", $objc_call, "` requires iOS {}.{}+. This device is running iOS {}.{}.{}. {}"),
|
||||||
|
$major, $minor, self.os_version.majorVersion, self.os_version.minorVersion, self.os_version.patchVersion,
|
||||||
|
extra_msg
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)*}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
os_capabilities! {
|
||||||
|
/// <https://developer.apple.com/documentation/uikit/uiview/2891103-safeareainsets?language=objc>
|
||||||
|
#[allow(unused)] // error message unused
|
||||||
|
safe_area_err_msg: "-[UIView safeAreaInsets]",
|
||||||
|
safe_area: 11-0,
|
||||||
|
/// <https://developer.apple.com/documentation/uikit/uiviewcontroller/2887509-setneedsupdateofhomeindicatoraut?language=objc>
|
||||||
|
home_indicator_hidden_err_msg: "-[UIViewController setNeedsUpdateOfHomeIndicatorAutoHidden]",
|
||||||
|
home_indicator_hidden: 11-0,
|
||||||
|
/// <https://developer.apple.com/documentation/uikit/uiviewcontroller/2887507-setneedsupdateofscreenedgesdefer?language=objc>
|
||||||
|
defer_system_gestures_err_msg: "-[UIViewController setNeedsUpdateOfScreenEdgesDeferringSystem]",
|
||||||
|
defer_system_gestures: 11-0,
|
||||||
|
/// <https://developer.apple.com/documentation/uikit/uiscreen/2806814-maximumframespersecond?language=objc>
|
||||||
|
maximum_frames_per_second_err_msg: "-[UIScreen maximumFramesPerSecond]",
|
||||||
|
maximum_frames_per_second: 10-3,
|
||||||
|
/// <https://developer.apple.com/documentation/uikit/uitouch/1618110-force?language=objc>
|
||||||
|
#[allow(unused)] // error message unused
|
||||||
|
force_touch_err_msg: "-[UITouch force]",
|
||||||
|
force_touch: 9-0,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn meets_requirements(
|
||||||
|
version: NSOperatingSystemVersion,
|
||||||
|
required_major: NSInteger,
|
||||||
|
required_minor: NSInteger,
|
||||||
|
) -> bool {
|
||||||
|
(version.majorVersion, version.minorVersion) >= (required_major, required_minor)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn os_capabilities() -> OSCapabilities {
|
||||||
|
static OS_CAPABILITIES: Lazy<OSCapabilities> = Lazy::new(|| {
|
||||||
|
let version: NSOperatingSystemVersion = unsafe {
|
||||||
|
let process_info = NSProcessInfo::processInfo();
|
||||||
|
let atleast_ios_8: bool = msg_send![
|
||||||
|
&process_info,
|
||||||
|
respondsToSelector: sel!(operatingSystemVersion)
|
||||||
|
];
|
||||||
|
// winit requires atleast iOS 8 because no one has put the time into supporting earlier os versions.
|
||||||
|
// Older iOS versions are increasingly difficult to test. For example, Xcode 11 does not support
|
||||||
|
// debugging on devices with an iOS version of less than 8. Another example, in order to use an iOS
|
||||||
|
// simulator older than iOS 8, you must download an older version of Xcode (<9), and at least Xcode 7
|
||||||
|
// has been tested to not even run on macOS 10.15 - Xcode 8 might?
|
||||||
|
//
|
||||||
|
// The minimum required iOS version is likely to grow in the future.
|
||||||
|
assert!(atleast_ios_8, "`winit` requires iOS version 8 or greater");
|
||||||
|
process_info.operatingSystemVersion()
|
||||||
|
};
|
||||||
|
version.into()
|
||||||
|
});
|
||||||
|
OS_CAPABILITIES.clone()
|
||||||
|
}
|
||||||
+380
@@ -0,0 +1,380 @@
|
|||||||
|
use std::{
|
||||||
|
collections::VecDeque,
|
||||||
|
ffi::c_void,
|
||||||
|
fmt::{self, Debug},
|
||||||
|
marker::PhantomData,
|
||||||
|
ptr,
|
||||||
|
sync::mpsc::{self, Receiver, Sender},
|
||||||
|
};
|
||||||
|
|
||||||
|
use core_foundation::base::{CFIndex, CFRelease};
|
||||||
|
use core_foundation::runloop::{
|
||||||
|
kCFRunLoopAfterWaiting, kCFRunLoopBeforeWaiting, kCFRunLoopCommonModes, kCFRunLoopDefaultMode,
|
||||||
|
kCFRunLoopExit, CFRunLoopActivity, CFRunLoopAddObserver, CFRunLoopAddSource, CFRunLoopGetMain,
|
||||||
|
CFRunLoopObserverCreate, CFRunLoopObserverRef, CFRunLoopSourceContext, CFRunLoopSourceCreate,
|
||||||
|
CFRunLoopSourceInvalidate, CFRunLoopSourceRef, CFRunLoopSourceSignal, CFRunLoopWakeUp,
|
||||||
|
};
|
||||||
|
use icrate::Foundation::{MainThreadMarker, NSString};
|
||||||
|
use objc2::ClassType;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
error::EventLoopError,
|
||||||
|
event::Event,
|
||||||
|
event_loop::{
|
||||||
|
ControlFlow, DeviceEvents, EventLoopClosed,
|
||||||
|
EventLoopWindowTarget as RootEventLoopWindowTarget,
|
||||||
|
},
|
||||||
|
platform::ios::Idiom,
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::{app_state, monitor, view, MonitorHandle};
|
||||||
|
use super::{
|
||||||
|
app_state::AppState,
|
||||||
|
uikit::{UIApplication, UIApplicationMain, UIDevice, UIScreen},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct EventLoopWindowTarget<T: 'static> {
|
||||||
|
pub(super) mtm: MainThreadMarker,
|
||||||
|
p: PhantomData<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static> EventLoopWindowTarget<T> {
|
||||||
|
pub fn available_monitors(&self) -> VecDeque<MonitorHandle> {
|
||||||
|
monitor::uiscreens(self.mtm)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn primary_monitor(&self) -> Option<MonitorHandle> {
|
||||||
|
Some(MonitorHandle::new(UIScreen::main(self.mtm)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn listen_device_events(&self, _allowed: DeviceEvents) {}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_05")]
|
||||||
|
#[inline]
|
||||||
|
pub fn raw_display_handle_rwh_05(&self) -> rwh_05::RawDisplayHandle {
|
||||||
|
rwh_05::RawDisplayHandle::UiKit(rwh_05::UiKitDisplayHandle::empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rwh_06")]
|
||||||
|
#[inline]
|
||||||
|
pub fn raw_display_handle_rwh_06(
|
||||||
|
&self,
|
||||||
|
) -> Result<rwh_06::RawDisplayHandle, rwh_06::HandleError> {
|
||||||
|
Ok(rwh_06::RawDisplayHandle::UiKit(
|
||||||
|
rwh_06::UiKitDisplayHandle::new(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn set_control_flow(&self, control_flow: ControlFlow) {
|
||||||
|
AppState::get_mut(self.mtm).set_control_flow(control_flow)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn control_flow(&self) -> ControlFlow {
|
||||||
|
AppState::get_mut(self.mtm).control_flow()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn exit(&self) {
|
||||||
|
// https://developer.apple.com/library/archive/qa/qa1561/_index.html
|
||||||
|
// it is not possible to quit an iOS app gracefully and programatically
|
||||||
|
warn!("`ControlFlow::Exit` ignored on iOS");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn exiting(&self) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct EventLoop<T: 'static> {
|
||||||
|
mtm: MainThreadMarker,
|
||||||
|
sender: Sender<T>,
|
||||||
|
receiver: Receiver<T>,
|
||||||
|
window_target: RootEventLoopWindowTarget<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub(crate) struct PlatformSpecificEventLoopAttributes {}
|
||||||
|
|
||||||
|
impl<T: 'static> EventLoop<T> {
|
||||||
|
pub(crate) fn new(
|
||||||
|
_: &PlatformSpecificEventLoopAttributes,
|
||||||
|
) -> Result<EventLoop<T>, EventLoopError> {
|
||||||
|
let mtm = MainThreadMarker::new()
|
||||||
|
.expect("On iOS, `EventLoop` must be created on the main thread");
|
||||||
|
|
||||||
|
static mut SINGLETON_INIT: bool = false;
|
||||||
|
unsafe {
|
||||||
|
assert!(
|
||||||
|
!SINGLETON_INIT,
|
||||||
|
"Only one `EventLoop` is supported on iOS. \
|
||||||
|
`EventLoopProxy` might be helpful"
|
||||||
|
);
|
||||||
|
SINGLETON_INIT = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (sender, receiver) = mpsc::channel();
|
||||||
|
|
||||||
|
// this line sets up the main run loop before `UIApplicationMain`
|
||||||
|
setup_control_flow_observers();
|
||||||
|
|
||||||
|
Ok(EventLoop {
|
||||||
|
mtm,
|
||||||
|
sender,
|
||||||
|
receiver,
|
||||||
|
window_target: RootEventLoopWindowTarget {
|
||||||
|
p: EventLoopWindowTarget {
|
||||||
|
mtm,
|
||||||
|
p: PhantomData,
|
||||||
|
},
|
||||||
|
_marker: PhantomData,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn run<F>(self, event_handler: F) -> !
|
||||||
|
where
|
||||||
|
F: FnMut(Event<T>, &RootEventLoopWindowTarget<T>),
|
||||||
|
{
|
||||||
|
unsafe {
|
||||||
|
let application = UIApplication::shared(self.mtm);
|
||||||
|
assert!(
|
||||||
|
application.is_none(),
|
||||||
|
"\
|
||||||
|
`EventLoop` cannot be `run` after a call to `UIApplicationMain` on iOS\n\
|
||||||
|
Note: `EventLoop::run` calls `UIApplicationMain` on iOS",
|
||||||
|
);
|
||||||
|
|
||||||
|
let event_handler = std::mem::transmute::<
|
||||||
|
Box<dyn FnMut(Event<T>, &RootEventLoopWindowTarget<T>)>,
|
||||||
|
Box<EventHandlerCallback<T>>,
|
||||||
|
>(Box::new(event_handler));
|
||||||
|
|
||||||
|
let handler = EventLoopHandler {
|
||||||
|
f: event_handler,
|
||||||
|
receiver: self.receiver,
|
||||||
|
event_loop: self.window_target,
|
||||||
|
};
|
||||||
|
|
||||||
|
app_state::will_launch(self.mtm, Box::new(handler));
|
||||||
|
|
||||||
|
// Ensure application delegate is initialized
|
||||||
|
view::WinitApplicationDelegate::class();
|
||||||
|
|
||||||
|
UIApplicationMain(
|
||||||
|
0,
|
||||||
|
ptr::null(),
|
||||||
|
None,
|
||||||
|
Some(&NSString::from_str("WinitApplicationDelegate")),
|
||||||
|
);
|
||||||
|
unreachable!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_proxy(&self) -> EventLoopProxy<T> {
|
||||||
|
EventLoopProxy::new(self.sender.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn window_target(&self) -> &RootEventLoopWindowTarget<T> {
|
||||||
|
&self.window_target
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// EventLoopExtIOS
|
||||||
|
impl<T: 'static> EventLoop<T> {
|
||||||
|
pub fn idiom(&self) -> Idiom {
|
||||||
|
UIDevice::current(self.mtm).userInterfaceIdiom().into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct EventLoopProxy<T> {
|
||||||
|
sender: Sender<T>,
|
||||||
|
source: CFRunLoopSourceRef,
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl<T: Send> Send for EventLoopProxy<T> {}
|
||||||
|
|
||||||
|
impl<T> Clone for EventLoopProxy<T> {
|
||||||
|
fn clone(&self) -> EventLoopProxy<T> {
|
||||||
|
EventLoopProxy::new(self.sender.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> Drop for EventLoopProxy<T> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
CFRunLoopSourceInvalidate(self.source);
|
||||||
|
CFRelease(self.source as _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> EventLoopProxy<T> {
|
||||||
|
fn new(sender: Sender<T>) -> EventLoopProxy<T> {
|
||||||
|
unsafe {
|
||||||
|
// just wake up the eventloop
|
||||||
|
extern "C" fn event_loop_proxy_handler(_: *const c_void) {}
|
||||||
|
|
||||||
|
// adding a Source to the main CFRunLoop lets us wake it up and
|
||||||
|
// process user events through the normal OS EventLoop mechanisms.
|
||||||
|
let rl = CFRunLoopGetMain();
|
||||||
|
let mut context = CFRunLoopSourceContext {
|
||||||
|
version: 0,
|
||||||
|
info: ptr::null_mut(),
|
||||||
|
retain: None,
|
||||||
|
release: None,
|
||||||
|
copyDescription: None,
|
||||||
|
equal: None,
|
||||||
|
hash: None,
|
||||||
|
schedule: None,
|
||||||
|
cancel: None,
|
||||||
|
perform: event_loop_proxy_handler,
|
||||||
|
};
|
||||||
|
let source =
|
||||||
|
CFRunLoopSourceCreate(ptr::null_mut(), CFIndex::max_value() - 1, &mut context);
|
||||||
|
CFRunLoopAddSource(rl, source, kCFRunLoopCommonModes);
|
||||||
|
CFRunLoopWakeUp(rl);
|
||||||
|
|
||||||
|
EventLoopProxy { sender, source }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send_event(&self, event: T) -> Result<(), EventLoopClosed<T>> {
|
||||||
|
self.sender
|
||||||
|
.send(event)
|
||||||
|
.map_err(|::std::sync::mpsc::SendError(x)| EventLoopClosed(x))?;
|
||||||
|
unsafe {
|
||||||
|
// let the main thread know there's a new event
|
||||||
|
CFRunLoopSourceSignal(self.source);
|
||||||
|
let rl = CFRunLoopGetMain();
|
||||||
|
CFRunLoopWakeUp(rl);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn setup_control_flow_observers() {
|
||||||
|
unsafe {
|
||||||
|
// begin is queued with the highest priority to ensure it is processed before other observers
|
||||||
|
extern "C" fn control_flow_begin_handler(
|
||||||
|
_: CFRunLoopObserverRef,
|
||||||
|
activity: CFRunLoopActivity,
|
||||||
|
_: *mut c_void,
|
||||||
|
) {
|
||||||
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
#[allow(non_upper_case_globals)]
|
||||||
|
match activity {
|
||||||
|
kCFRunLoopAfterWaiting => app_state::handle_wakeup_transition(mtm),
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Core Animation registers its `CFRunLoopObserver` that performs drawing operations in
|
||||||
|
// `CA::Transaction::ensure_implicit` with a priority of `0x1e8480`. We set the main_end
|
||||||
|
// priority to be 0, in order to send AboutToWait before RedrawRequested. This value was
|
||||||
|
// chosen conservatively to guard against apple using different priorities for their redraw
|
||||||
|
// observers in different OS's or on different devices. If it so happens that it's too
|
||||||
|
// conservative, the main symptom would be non-redraw events coming in after `AboutToWait`.
|
||||||
|
//
|
||||||
|
// The value of `0x1e8480` was determined by inspecting stack traces and the associated
|
||||||
|
// registers for every `CFRunLoopAddObserver` call on an iPad Air 2 running iOS 11.4.
|
||||||
|
//
|
||||||
|
// Also tested to be `0x1e8480` on iPhone 8, iOS 13 beta 4.
|
||||||
|
extern "C" fn control_flow_main_end_handler(
|
||||||
|
_: CFRunLoopObserverRef,
|
||||||
|
activity: CFRunLoopActivity,
|
||||||
|
_: *mut c_void,
|
||||||
|
) {
|
||||||
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
#[allow(non_upper_case_globals)]
|
||||||
|
match activity {
|
||||||
|
kCFRunLoopBeforeWaiting => app_state::handle_main_events_cleared(mtm),
|
||||||
|
kCFRunLoopExit => {} // may happen when running on macOS
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// end is queued with the lowest priority to ensure it is processed after other observers
|
||||||
|
extern "C" fn control_flow_end_handler(
|
||||||
|
_: CFRunLoopObserverRef,
|
||||||
|
activity: CFRunLoopActivity,
|
||||||
|
_: *mut c_void,
|
||||||
|
) {
|
||||||
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
#[allow(non_upper_case_globals)]
|
||||||
|
match activity {
|
||||||
|
kCFRunLoopBeforeWaiting => app_state::handle_events_cleared(mtm),
|
||||||
|
kCFRunLoopExit => {} // may happen when running on macOS
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let main_loop = CFRunLoopGetMain();
|
||||||
|
|
||||||
|
let begin_observer = CFRunLoopObserverCreate(
|
||||||
|
ptr::null_mut(),
|
||||||
|
kCFRunLoopAfterWaiting,
|
||||||
|
1, // repeat = true
|
||||||
|
CFIndex::min_value(),
|
||||||
|
control_flow_begin_handler,
|
||||||
|
ptr::null_mut(),
|
||||||
|
);
|
||||||
|
CFRunLoopAddObserver(main_loop, begin_observer, kCFRunLoopDefaultMode);
|
||||||
|
|
||||||
|
let main_end_observer = CFRunLoopObserverCreate(
|
||||||
|
ptr::null_mut(),
|
||||||
|
kCFRunLoopExit | kCFRunLoopBeforeWaiting,
|
||||||
|
1, // repeat = true
|
||||||
|
0, // see comment on `control_flow_main_end_handler`
|
||||||
|
control_flow_main_end_handler,
|
||||||
|
ptr::null_mut(),
|
||||||
|
);
|
||||||
|
CFRunLoopAddObserver(main_loop, main_end_observer, kCFRunLoopDefaultMode);
|
||||||
|
|
||||||
|
let end_observer = CFRunLoopObserverCreate(
|
||||||
|
ptr::null_mut(),
|
||||||
|
kCFRunLoopExit | kCFRunLoopBeforeWaiting,
|
||||||
|
1, // repeat = true
|
||||||
|
CFIndex::max_value(),
|
||||||
|
control_flow_end_handler,
|
||||||
|
ptr::null_mut(),
|
||||||
|
);
|
||||||
|
CFRunLoopAddObserver(main_loop, end_observer, kCFRunLoopDefaultMode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum Never {}
|
||||||
|
|
||||||
|
type EventHandlerCallback<T> = dyn FnMut(Event<T>, &RootEventLoopWindowTarget<T>) + 'static;
|
||||||
|
|
||||||
|
pub trait EventHandler: Debug {
|
||||||
|
fn handle_nonuser_event(&mut self, event: Event<Never>);
|
||||||
|
fn handle_user_events(&mut self);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct EventLoopHandler<T: 'static> {
|
||||||
|
f: Box<EventHandlerCallback<T>>,
|
||||||
|
receiver: Receiver<T>,
|
||||||
|
event_loop: RootEventLoopWindowTarget<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static> Debug for EventLoopHandler<T> {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("EventLoopHandler")
|
||||||
|
.field("event_loop", &self.event_loop)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: 'static> EventHandler for EventLoopHandler<T> {
|
||||||
|
fn handle_nonuser_event(&mut self, event: Event<Never>) {
|
||||||
|
(self.f)(event.map_nonuser_event().unwrap(), &self.event_loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_user_events(&mut self) {
|
||||||
|
for event in self.receiver.try_iter() {
|
||||||
|
(self.f)(Event::UserEvent(event), &self.event_loop);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+76
@@ -0,0 +1,76 @@
|
|||||||
|
#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals)]
|
||||||
|
|
||||||
|
use icrate::Foundation::{NSInteger, NSUInteger};
|
||||||
|
use objc2::encode::{Encode, Encoding};
|
||||||
|
|
||||||
|
use crate::platform::ios::{Idiom, ScreenEdge};
|
||||||
|
|
||||||
|
#[repr(transparent)]
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct UIUserInterfaceIdiom(NSInteger);
|
||||||
|
|
||||||
|
unsafe impl Encode for UIUserInterfaceIdiom {
|
||||||
|
const ENCODING: Encoding = NSInteger::ENCODING;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UIUserInterfaceIdiom {
|
||||||
|
pub const Unspecified: UIUserInterfaceIdiom = UIUserInterfaceIdiom(-1);
|
||||||
|
pub const Phone: UIUserInterfaceIdiom = UIUserInterfaceIdiom(0);
|
||||||
|
pub const Pad: UIUserInterfaceIdiom = UIUserInterfaceIdiom(1);
|
||||||
|
pub const TV: UIUserInterfaceIdiom = UIUserInterfaceIdiom(2);
|
||||||
|
pub const CarPlay: UIUserInterfaceIdiom = UIUserInterfaceIdiom(3);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Idiom> for UIUserInterfaceIdiom {
|
||||||
|
fn from(idiom: Idiom) -> UIUserInterfaceIdiom {
|
||||||
|
match idiom {
|
||||||
|
Idiom::Unspecified => UIUserInterfaceIdiom::Unspecified,
|
||||||
|
Idiom::Phone => UIUserInterfaceIdiom::Phone,
|
||||||
|
Idiom::Pad => UIUserInterfaceIdiom::Pad,
|
||||||
|
Idiom::TV => UIUserInterfaceIdiom::TV,
|
||||||
|
Idiom::CarPlay => UIUserInterfaceIdiom::CarPlay,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl From<UIUserInterfaceIdiom> for Idiom {
|
||||||
|
fn from(ui_idiom: UIUserInterfaceIdiom) -> Idiom {
|
||||||
|
match ui_idiom {
|
||||||
|
UIUserInterfaceIdiom::Unspecified => Idiom::Unspecified,
|
||||||
|
UIUserInterfaceIdiom::Phone => Idiom::Phone,
|
||||||
|
UIUserInterfaceIdiom::Pad => Idiom::Pad,
|
||||||
|
UIUserInterfaceIdiom::TV => Idiom::TV,
|
||||||
|
UIUserInterfaceIdiom::CarPlay => Idiom::CarPlay,
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(transparent)]
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct UIRectEdge(NSUInteger);
|
||||||
|
|
||||||
|
impl UIRectEdge {
|
||||||
|
pub(crate) const NONE: Self = Self(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl Encode for UIRectEdge {
|
||||||
|
const ENCODING: Encoding = NSUInteger::ENCODING;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<ScreenEdge> for UIRectEdge {
|
||||||
|
fn from(screen_edge: ScreenEdge) -> UIRectEdge {
|
||||||
|
assert_eq!(
|
||||||
|
screen_edge.bits() & !ScreenEdge::ALL.bits(),
|
||||||
|
0,
|
||||||
|
"invalid `ScreenEdge`"
|
||||||
|
);
|
||||||
|
UIRectEdge(screen_edge.bits().into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<UIRectEdge> for ScreenEdge {
|
||||||
|
fn from(ui_rect_edge: UIRectEdge) -> ScreenEdge {
|
||||||
|
let bits: u8 = ui_rect_edge.0.try_into().expect("invalid `UIRectEdge`");
|
||||||
|
ScreenEdge::from_bits(bits).expect("invalid `ScreenEdge`")
|
||||||
|
}
|
||||||
|
}
|
||||||
+109
@@ -0,0 +1,109 @@
|
|||||||
|
//! iOS support
|
||||||
|
//!
|
||||||
|
//! # Building app
|
||||||
|
//! To build ios app you will need rustc built for this targets:
|
||||||
|
//!
|
||||||
|
//! - armv7-apple-ios
|
||||||
|
//! - armv7s-apple-ios
|
||||||
|
//! - i386-apple-ios
|
||||||
|
//! - aarch64-apple-ios
|
||||||
|
//! - x86_64-apple-ios
|
||||||
|
//!
|
||||||
|
//! Then
|
||||||
|
//!
|
||||||
|
//! ```
|
||||||
|
//! cargo build --target=...
|
||||||
|
//! ```
|
||||||
|
//! The simplest way to integrate your app into xcode environment is to build it
|
||||||
|
//! as a static library. Wrap your main function and export it.
|
||||||
|
//!
|
||||||
|
//! ```rust, ignore
|
||||||
|
//! #[no_mangle]
|
||||||
|
//! pub extern fn start_winit_app() {
|
||||||
|
//! start_inner()
|
||||||
|
//! }
|
||||||
|
//!
|
||||||
|
//! fn start_inner() {
|
||||||
|
//! ...
|
||||||
|
//! }
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! Compile project and then drag resulting .a into Xcode project. Add winit.h to xcode.
|
||||||
|
//!
|
||||||
|
//! ```ignore
|
||||||
|
//! void start_winit_app();
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! Use start_winit_app inside your xcode's main function.
|
||||||
|
//!
|
||||||
|
//!
|
||||||
|
//! # App lifecycle and events
|
||||||
|
//!
|
||||||
|
//! iOS environment is very different from other platforms and you must be very
|
||||||
|
//! careful with it's events. Familiarize yourself with
|
||||||
|
//! [app lifecycle](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/).
|
||||||
|
//!
|
||||||
|
//!
|
||||||
|
//! This is how those event are represented in winit:
|
||||||
|
//!
|
||||||
|
//! - applicationDidBecomeActive is Resumed
|
||||||
|
//! - applicationWillResignActive is Suspended
|
||||||
|
//! - applicationWillTerminate is LoopExiting
|
||||||
|
//!
|
||||||
|
//! Keep in mind that after LoopExiting event is received every attempt to draw with
|
||||||
|
//! opengl will result in segfault.
|
||||||
|
//!
|
||||||
|
//! Also note that app may not receive the LoopExiting event if suspended; it might be SIGKILL'ed.
|
||||||
|
|
||||||
|
#![cfg(ios_platform)]
|
||||||
|
#![allow(clippy::let_unit_value)]
|
||||||
|
|
||||||
|
mod app_state;
|
||||||
|
mod event_loop;
|
||||||
|
mod ffi;
|
||||||
|
mod monitor;
|
||||||
|
mod uikit;
|
||||||
|
mod view;
|
||||||
|
mod window;
|
||||||
|
|
||||||
|
use std::fmt;
|
||||||
|
|
||||||
|
pub(crate) use self::{
|
||||||
|
event_loop::{
|
||||||
|
EventLoop, EventLoopProxy, EventLoopWindowTarget, PlatformSpecificEventLoopAttributes,
|
||||||
|
},
|
||||||
|
monitor::{MonitorHandle, VideoMode},
|
||||||
|
window::{PlatformSpecificWindowBuilderAttributes, Window, WindowId},
|
||||||
|
};
|
||||||
|
|
||||||
|
use self::uikit::UIScreen;
|
||||||
|
pub(crate) use crate::icon::NoIcon as PlatformIcon;
|
||||||
|
pub(crate) use crate::platform_impl::Fullscreen;
|
||||||
|
|
||||||
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
|
pub struct DeviceId {
|
||||||
|
uiscreen: *const UIScreen,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DeviceId {
|
||||||
|
pub const unsafe fn dummy() -> Self {
|
||||||
|
DeviceId {
|
||||||
|
uiscreen: std::ptr::null(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl Send for DeviceId {}
|
||||||
|
unsafe impl Sync for DeviceId {}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
|
pub struct KeyEventExtra {}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum OsError {}
|
||||||
|
|
||||||
|
impl fmt::Display for OsError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "os error")
|
||||||
|
}
|
||||||
|
}
|
||||||
+268
@@ -0,0 +1,268 @@
|
|||||||
|
#![allow(clippy::unnecessary_cast)]
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
collections::{BTreeSet, VecDeque},
|
||||||
|
fmt, hash, ptr,
|
||||||
|
};
|
||||||
|
|
||||||
|
use icrate::Foundation::{MainThreadBound, MainThreadMarker, NSInteger};
|
||||||
|
use objc2::mutability::IsRetainable;
|
||||||
|
use objc2::rc::Id;
|
||||||
|
|
||||||
|
use super::uikit::{UIScreen, UIScreenMode};
|
||||||
|
use crate::{
|
||||||
|
dpi::{PhysicalPosition, PhysicalSize},
|
||||||
|
monitor::VideoMode as RootVideoMode,
|
||||||
|
platform_impl::platform::app_state,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Workaround for `MainThreadBound` implementing almost no traits
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct MainThreadBoundDelegateImpls<T>(MainThreadBound<Id<T>>);
|
||||||
|
|
||||||
|
impl<T: IsRetainable> Clone for MainThreadBoundDelegateImpls<T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self(
|
||||||
|
self.0
|
||||||
|
.get_on_main(|inner, mtm| MainThreadBound::new(Id::clone(inner), mtm)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: IsRetainable> hash::Hash for MainThreadBoundDelegateImpls<T> {
|
||||||
|
fn hash<H: hash::Hasher>(&self, state: &mut H) {
|
||||||
|
// SAFETY: Marker only used to get the pointer
|
||||||
|
let mtm = unsafe { MainThreadMarker::new_unchecked() };
|
||||||
|
Id::as_ptr(self.0.get(mtm)).hash(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: IsRetainable> PartialEq for MainThreadBoundDelegateImpls<T> {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
// SAFETY: Marker only used to get the pointer
|
||||||
|
let mtm = unsafe { MainThreadMarker::new_unchecked() };
|
||||||
|
Id::as_ptr(self.0.get(mtm)) == Id::as_ptr(other.0.get(mtm))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: IsRetainable> Eq for MainThreadBoundDelegateImpls<T> {}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
|
||||||
|
pub struct VideoMode {
|
||||||
|
pub(crate) size: (u32, u32),
|
||||||
|
pub(crate) bit_depth: u16,
|
||||||
|
pub(crate) refresh_rate_millihertz: u32,
|
||||||
|
screen_mode: MainThreadBoundDelegateImpls<UIScreenMode>,
|
||||||
|
pub(crate) monitor: MonitorHandle,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VideoMode {
|
||||||
|
fn new(
|
||||||
|
uiscreen: Id<UIScreen>,
|
||||||
|
screen_mode: Id<UIScreenMode>,
|
||||||
|
mtm: MainThreadMarker,
|
||||||
|
) -> VideoMode {
|
||||||
|
let refresh_rate_millihertz = refresh_rate_millihertz(&uiscreen);
|
||||||
|
let size = screen_mode.size();
|
||||||
|
VideoMode {
|
||||||
|
size: (size.width as u32, size.height as u32),
|
||||||
|
bit_depth: 32,
|
||||||
|
refresh_rate_millihertz,
|
||||||
|
screen_mode: MainThreadBoundDelegateImpls(MainThreadBound::new(screen_mode, mtm)),
|
||||||
|
monitor: MonitorHandle::new(uiscreen),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn size(&self) -> PhysicalSize<u32> {
|
||||||
|
self.size.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bit_depth(&self) -> u16 {
|
||||||
|
self.bit_depth
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn refresh_rate_millihertz(&self) -> u32 {
|
||||||
|
self.refresh_rate_millihertz
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn monitor(&self) -> MonitorHandle {
|
||||||
|
self.monitor.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn screen_mode(&self, mtm: MainThreadMarker) -> &Id<UIScreenMode> {
|
||||||
|
self.screen_mode.0.get(mtm)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct MonitorHandle {
|
||||||
|
ui_screen: MainThreadBound<Id<UIScreen>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Clone for MonitorHandle {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self {
|
||||||
|
ui_screen: self
|
||||||
|
.ui_screen
|
||||||
|
.get_on_main(|inner, mtm| MainThreadBound::new(inner.clone(), mtm)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl hash::Hash for MonitorHandle {
|
||||||
|
fn hash<H: hash::Hasher>(&self, state: &mut H) {
|
||||||
|
(self as *const Self).hash(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for MonitorHandle {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
ptr::eq(self, other)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Eq for MonitorHandle {}
|
||||||
|
|
||||||
|
impl PartialOrd for MonitorHandle {
|
||||||
|
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||||
|
Some(self.cmp(other))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ord for MonitorHandle {
|
||||||
|
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
|
||||||
|
// TODO: Make a better ordering
|
||||||
|
(self as *const Self).cmp(&(other as *const Self))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for MonitorHandle {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
// TODO: Do this using the proper fmt API
|
||||||
|
#[derive(Debug)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
struct MonitorHandle {
|
||||||
|
name: Option<String>,
|
||||||
|
size: PhysicalSize<u32>,
|
||||||
|
position: PhysicalPosition<i32>,
|
||||||
|
scale_factor: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
let monitor_id_proxy = MonitorHandle {
|
||||||
|
name: self.name(),
|
||||||
|
size: self.size(),
|
||||||
|
position: self.position(),
|
||||||
|
scale_factor: self.scale_factor(),
|
||||||
|
};
|
||||||
|
|
||||||
|
monitor_id_proxy.fmt(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MonitorHandle {
|
||||||
|
pub(crate) fn new(ui_screen: Id<UIScreen>) -> Self {
|
||||||
|
// Holding `Id<UIScreen>` implies we're on the main thread.
|
||||||
|
let mtm = MainThreadMarker::new().unwrap();
|
||||||
|
Self {
|
||||||
|
ui_screen: MainThreadBound::new(ui_screen, mtm),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn name(&self) -> Option<String> {
|
||||||
|
self.ui_screen.get_on_main(|ui_screen, mtm| {
|
||||||
|
let main = UIScreen::main(mtm);
|
||||||
|
if *ui_screen == main {
|
||||||
|
Some("Primary".to_string())
|
||||||
|
} else if *ui_screen == main.mirroredScreen() {
|
||||||
|
Some("Mirrored".to_string())
|
||||||
|
} else {
|
||||||
|
UIScreen::screens(mtm)
|
||||||
|
.iter()
|
||||||
|
.position(|rhs| rhs == &**ui_screen)
|
||||||
|
.map(|idx| idx.to_string())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn size(&self) -> PhysicalSize<u32> {
|
||||||
|
let bounds = self
|
||||||
|
.ui_screen
|
||||||
|
.get_on_main(|ui_screen, _| ui_screen.nativeBounds());
|
||||||
|
PhysicalSize::new(bounds.size.width as u32, bounds.size.height as u32)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn position(&self) -> PhysicalPosition<i32> {
|
||||||
|
let bounds = self
|
||||||
|
.ui_screen
|
||||||
|
.get_on_main(|ui_screen, _| ui_screen.nativeBounds());
|
||||||
|
(bounds.origin.x as f64, bounds.origin.y as f64).into()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn scale_factor(&self) -> f64 {
|
||||||
|
self.ui_screen
|
||||||
|
.get_on_main(|ui_screen, _| ui_screen.nativeScale()) as f64
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn refresh_rate_millihertz(&self) -> Option<u32> {
|
||||||
|
Some(
|
||||||
|
self.ui_screen
|
||||||
|
.get_on_main(|ui_screen, _| refresh_rate_millihertz(ui_screen)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn video_modes(&self) -> impl Iterator<Item = VideoMode> {
|
||||||
|
self.ui_screen.get_on_main(|ui_screen, mtm| {
|
||||||
|
// Use Ord impl of RootVideoMode
|
||||||
|
|
||||||
|
let modes: BTreeSet<_> = ui_screen
|
||||||
|
.availableModes()
|
||||||
|
.into_iter()
|
||||||
|
.map(|mode| RootVideoMode {
|
||||||
|
video_mode: VideoMode::new(ui_screen.clone(), mode, mtm),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
modes.into_iter().map(|mode| mode.video_mode)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn ui_screen(&self, mtm: MainThreadMarker) -> &Id<UIScreen> {
|
||||||
|
self.ui_screen.get(mtm)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn preferred_video_mode(&self) -> VideoMode {
|
||||||
|
self.ui_screen.get_on_main(|ui_screen, mtm| {
|
||||||
|
VideoMode::new(ui_screen.clone(), ui_screen.preferredMode().unwrap(), mtm)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refresh_rate_millihertz(uiscreen: &UIScreen) -> u32 {
|
||||||
|
let refresh_rate_millihertz: NSInteger = {
|
||||||
|
let os_capabilities = app_state::os_capabilities();
|
||||||
|
if os_capabilities.maximum_frames_per_second {
|
||||||
|
uiscreen.maximumFramesPerSecond()
|
||||||
|
} else {
|
||||||
|
// https://developer.apple.com/library/archive/technotes/tn2460/_index.html
|
||||||
|
// https://en.wikipedia.org/wiki/IPad_Pro#Model_comparison
|
||||||
|
//
|
||||||
|
// All iOS devices support 60 fps, and on devices where `maximumFramesPerSecond` is not
|
||||||
|
// supported, they are all guaranteed to have 60hz refresh rates. This does not
|
||||||
|
// correctly handle external displays. ProMotion displays support 120fps, but they were
|
||||||
|
// introduced at the same time as the `maximumFramesPerSecond` API.
|
||||||
|
//
|
||||||
|
// FIXME: earlier OSs could calculate the refresh rate using
|
||||||
|
// `-[CADisplayLink duration]`.
|
||||||
|
os_capabilities.maximum_frames_per_second_err_msg("defaulting to 60 fps");
|
||||||
|
60
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
refresh_rate_millihertz as u32 * 1000
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn uiscreens(mtm: MainThreadMarker) -> VecDeque<MonitorHandle> {
|
||||||
|
UIScreen::screens(mtm)
|
||||||
|
.into_iter()
|
||||||
|
.map(MonitorHandle::new)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
use icrate::Foundation::{CGRect, MainThreadMarker, NSArray, NSObject};
|
||||||
|
use objc2::rc::Id;
|
||||||
|
use objc2::{extern_class, extern_methods, msg_send_id, mutability, ClassType};
|
||||||
|
|
||||||
|
use super::{UIResponder, UIWindow};
|
||||||
|
|
||||||
|
extern_class!(
|
||||||
|
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub(crate) struct UIApplication;
|
||||||
|
|
||||||
|
unsafe impl ClassType for UIApplication {
|
||||||
|
#[inherits(NSObject)]
|
||||||
|
type Super = UIResponder;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
extern_methods!(
|
||||||
|
unsafe impl UIApplication {
|
||||||
|
pub fn shared(_mtm: MainThreadMarker) -> Option<Id<Self>> {
|
||||||
|
unsafe { msg_send_id![Self::class(), sharedApplication] }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn windows(&self) -> Id<NSArray<UIWindow>> {
|
||||||
|
unsafe { msg_send_id![self, windows] }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(statusBarFrame)]
|
||||||
|
pub fn statusBarFrame(&self) -> CGRect;
|
||||||
|
}
|
||||||
|
);
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
use icrate::Foundation::NSObject;
|
||||||
|
use objc2::{extern_class, mutability, ClassType};
|
||||||
|
|
||||||
|
extern_class!(
|
||||||
|
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub(crate) struct UICoordinateSpace;
|
||||||
|
|
||||||
|
unsafe impl ClassType for UICoordinateSpace {
|
||||||
|
type Super = NSObject;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
|
}
|
||||||
|
);
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
use icrate::Foundation::{MainThreadMarker, NSObject};
|
||||||
|
use objc2::rc::Id;
|
||||||
|
use objc2::{extern_class, extern_methods, msg_send_id, mutability, ClassType};
|
||||||
|
|
||||||
|
use super::super::ffi::UIUserInterfaceIdiom;
|
||||||
|
|
||||||
|
extern_class!(
|
||||||
|
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub(crate) struct UIDevice;
|
||||||
|
|
||||||
|
unsafe impl ClassType for UIDevice {
|
||||||
|
type Super = NSObject;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
extern_methods!(
|
||||||
|
unsafe impl UIDevice {
|
||||||
|
pub fn current(_mtm: MainThreadMarker) -> Id<Self> {
|
||||||
|
unsafe { msg_send_id![Self::class(), currentDevice] }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(userInterfaceIdiom)]
|
||||||
|
pub fn userInterfaceIdiom(&self) -> UIUserInterfaceIdiom;
|
||||||
|
}
|
||||||
|
);
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
use icrate::Foundation::NSObject;
|
||||||
|
use objc2::{extern_class, mutability, ClassType};
|
||||||
|
|
||||||
|
extern_class!(
|
||||||
|
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub(crate) struct UIEvent;
|
||||||
|
|
||||||
|
unsafe impl ClassType for UIEvent {
|
||||||
|
type Super = NSObject;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
|
}
|
||||||
|
);
|
||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
#![allow(non_snake_case)]
|
||||||
|
#![allow(non_upper_case_globals)]
|
||||||
|
|
||||||
|
use std::os::raw::{c_char, c_int};
|
||||||
|
|
||||||
|
use icrate::Foundation::NSString;
|
||||||
|
|
||||||
|
mod application;
|
||||||
|
mod coordinate_space;
|
||||||
|
mod device;
|
||||||
|
mod event;
|
||||||
|
mod responder;
|
||||||
|
mod screen;
|
||||||
|
mod screen_mode;
|
||||||
|
mod status_bar_style;
|
||||||
|
mod touch;
|
||||||
|
mod trait_collection;
|
||||||
|
mod view;
|
||||||
|
mod view_controller;
|
||||||
|
mod window;
|
||||||
|
|
||||||
|
pub(crate) use self::application::UIApplication;
|
||||||
|
pub(crate) use self::coordinate_space::UICoordinateSpace;
|
||||||
|
pub(crate) use self::device::UIDevice;
|
||||||
|
pub(crate) use self::event::UIEvent;
|
||||||
|
pub(crate) use self::responder::UIResponder;
|
||||||
|
pub(crate) use self::screen::{UIScreen, UIScreenOverscanCompensation};
|
||||||
|
pub(crate) use self::screen_mode::UIScreenMode;
|
||||||
|
pub(crate) use self::status_bar_style::UIStatusBarStyle;
|
||||||
|
pub(crate) use self::touch::{UITouch, UITouchPhase, UITouchType};
|
||||||
|
pub(crate) use self::trait_collection::{UIForceTouchCapability, UITraitCollection};
|
||||||
|
#[allow(unused_imports)]
|
||||||
|
pub(crate) use self::view::{UIEdgeInsets, UIView};
|
||||||
|
pub(crate) use self::view_controller::{UIInterfaceOrientationMask, UIViewController};
|
||||||
|
pub(crate) use self::window::UIWindow;
|
||||||
|
|
||||||
|
#[link(name = "UIKit", kind = "framework")]
|
||||||
|
extern "C" {
|
||||||
|
pub fn UIApplicationMain(
|
||||||
|
argc: c_int,
|
||||||
|
argv: *const c_char,
|
||||||
|
principalClassName: Option<&NSString>,
|
||||||
|
delegateClassName: Option<&NSString>,
|
||||||
|
) -> c_int;
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
use icrate::Foundation::NSObject;
|
||||||
|
use objc2::{extern_class, mutability, ClassType};
|
||||||
|
|
||||||
|
extern_class!(
|
||||||
|
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub(crate) struct UIResponder;
|
||||||
|
|
||||||
|
unsafe impl ClassType for UIResponder {
|
||||||
|
type Super = NSObject;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
|
}
|
||||||
|
);
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
use icrate::Foundation::{CGFloat, CGRect, MainThreadMarker, NSArray, NSInteger, NSObject};
|
||||||
|
use objc2::encode::{Encode, Encoding};
|
||||||
|
use objc2::rc::Id;
|
||||||
|
use objc2::{extern_class, extern_methods, msg_send_id, mutability, ClassType};
|
||||||
|
|
||||||
|
use super::{UICoordinateSpace, UIScreenMode};
|
||||||
|
|
||||||
|
extern_class!(
|
||||||
|
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub(crate) struct UIScreen;
|
||||||
|
|
||||||
|
unsafe impl ClassType for UIScreen {
|
||||||
|
type Super = NSObject;
|
||||||
|
type Mutability = mutability::InteriorMutable;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
extern_methods!(
|
||||||
|
unsafe impl UIScreen {
|
||||||
|
pub fn main(_mtm: MainThreadMarker) -> Id<Self> {
|
||||||
|
unsafe { msg_send_id![Self::class(), mainScreen] }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn screens(_mtm: MainThreadMarker) -> Id<NSArray<Self>> {
|
||||||
|
unsafe { msg_send_id![Self::class(), screens] }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(bounds)]
|
||||||
|
pub fn bounds(&self) -> CGRect;
|
||||||
|
|
||||||
|
#[method(scale)]
|
||||||
|
pub fn scale(&self) -> CGFloat;
|
||||||
|
|
||||||
|
#[method(nativeBounds)]
|
||||||
|
pub fn nativeBounds(&self) -> CGRect;
|
||||||
|
|
||||||
|
#[method(nativeScale)]
|
||||||
|
pub fn nativeScale(&self) -> CGFloat;
|
||||||
|
|
||||||
|
#[method(maximumFramesPerSecond)]
|
||||||
|
pub fn maximumFramesPerSecond(&self) -> NSInteger;
|
||||||
|
|
||||||
|
pub fn mirroredScreen(&self) -> Id<Self> {
|
||||||
|
unsafe { msg_send_id![Self::class(), mirroredScreen] }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn preferredMode(&self) -> Option<Id<UIScreenMode>> {
|
||||||
|
unsafe { msg_send_id![self, preferredMode] }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(setCurrentMode:)]
|
||||||
|
pub fn setCurrentMode(&self, mode: Option<&UIScreenMode>);
|
||||||
|
|
||||||
|
pub fn availableModes(&self) -> Id<NSArray<UIScreenMode>> {
|
||||||
|
unsafe { msg_send_id![self, availableModes] }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[method(setOverscanCompensation:)]
|
||||||
|
pub fn setOverscanCompensation(&self, overscanCompensation: UIScreenOverscanCompensation);
|
||||||
|
|
||||||
|
pub fn coordinateSpace(&self) -> Id<UICoordinateSpace> {
|
||||||
|
unsafe { msg_send_id![self, coordinateSpace] }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
#[repr(transparent)]
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct UIScreenOverscanCompensation(NSInteger);
|
||||||
|
|
||||||
|
unsafe impl Encode for UIScreenOverscanCompensation {
|
||||||
|
const ENCODING: Encoding = NSInteger::ENCODING;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl UIScreenOverscanCompensation {
|
||||||
|
pub const Scale: Self = Self(0);
|
||||||
|
pub const InsetBounds: Self = Self(1);
|
||||||
|
pub const None: Self = Self(2);
|
||||||
|
}
|
||||||
Loaded 100 of 250 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user