Resize/Expand rework + basic readme

This commit is contained in:
Jonathan Johnson 2023-11-02 14:23:36 -07:00
parent a9498abf1a
commit 0026a6db0d
No known key found for this signature in database
GPG key ID: A66D6A34D6620579
22 changed files with 999 additions and 130 deletions

44
.crate-docs.md Normal file
View file

@ -0,0 +1,44 @@
![Gooey is considered experimental and unsupported](https://img.shields.io/badge/status-prototype-blueviolet)
[![crate version](https://img.shields.io/crates/v/gooey.svg)](https://crates.io/crates/gooey)
[![Documentation for `main` branch](https://img.shields.io/badge/docs-main-informational)](https://gooey.rs/main/gooey/)
Gooey is an experimental Graphical User Interface (GUI) crate for the Rust
programming language. It is built using [`Kludgine`][kludgine], which is powered
by [`winit`][winit] and [`wgpu`][wgpu]. It is incredibly early in development,
and is being developed for a game that will hopefully be developed shortly.
The [`Widget`][widget] trait is the building block of Gooey: Every user
interface element implements `Widget`. A full list of built-in widgets can be
found in the [`gooey::widgets`][widgets] module.
Gooey uses a reactive data model. To see [an example][button-example] of how
reactive data models work, consider this example that displays a button that
increments its own label:
```rust
// Create a dynamic usize.
let count = Dynamic::new(0_usize);
// Create a new button with a label that is produced by mapping the contents
// of `count`.
Button::new(count.map_each(ToString::to_string))
// Set the `on_click` callback to a closure that increments the counter.
.on_click(count.with_clone(|count| move |_| count.set(count.get() + 1)))
// Run the button as an an application.
.run()
```
[widget]: crate::widget::Widget
[kludgine]: https://github.com/khonsulabs/kludgine
[wgpu]: https://github.com/gfx-rs/wgpu
[winit]: https://github.com/rust-windowing/winit
[widgets]: mod@crate::widgets
[button-example]: https://github.com/khonsulabs/gooey/tree/main/examples/button.rs
## Open-source Licenses
This project, like all projects from [Khonsu Labs](https://khonsulabs.com/), is open-source.
This repository is available under the [MIT License](./LICENSE-MIT) or the
[Apache License 2.0](./LICENSE-APACHE).
To learn more about contributing, please see [CONTRIBUTING.md](./CONTRIBUTING.md).

52
.rustme/config.ron Normal file
View file

@ -0,0 +1,52 @@
Configuration(
files: {
"../README.md": [
"header.md",
"docs.md",
"https://github.com/khonsulabs/.github/raw/main/snippets/readme-footer.md",
],
"../.crate-docs.md": (
for_docs: true,
sections: [
"docs.md",
"https://github.com/khonsulabs/.github/raw/main/snippets/readme-footer.md",
],
),
"../CONTRIBUTING.md": [
"https://github.com/khonsulabs/.github/raw/main/docs/CONTRIBUTING.md",
],
"../CODE_OF_CONDUCT.md": [
"https://github.com/khonsulabs/.github/raw/main/docs/CODE_OF_CONDUCT.md",
],
"../LICENSE-APACHE": [
"https://github.com/khonsulabs/.github/raw/main/licenses/LICENSE-APACHE",
],
"../LICENSE-MIT": [
"https://github.com/khonsulabs/.github/raw/main/licenses/LICENSE-MIT",
],
},
glossaries: [
"https://github.com/khonsulabs/.github/raw/main/snippets/glossary.ron",
{
// "msrv": "1.70",
"ref-name": (
default: "main",
release: "v0.1.0",
),
"docs": (
default: "https://gooey.rs/main/gooey/",
release: "https://docs.rs/gooey",
),
"widget": (
default: "https://gooey.rs/main/gooey/widget/trait.Widget.html",
release: "https://docs.rs/gooey/*/gooey/widget/trait.Widget.html",
for_docs: "crate::widget::Widget",
),
"widgets": (
default: "https://gooey.rs/main/gooey/widgets/index.html",
release: "https://docs.rs/gooey/*/gooey/widgets/index.html",
for_docs: "mod@crate::widgets",
),
},
],
)

27
.rustme/docs.md Normal file
View file

@ -0,0 +1,27 @@
![Gooey is considered experimental and unsupported](https://img.shields.io/badge/status-prototype-blueviolet)
[![crate version](https://img.shields.io/crates/v/gooey.svg)](https://crates.io/crates/gooey)
[![Documentation for `main` branch](https://img.shields.io/badge/docs-main-informational)]($docs$)
Gooey is an experimental Graphical User Interface (GUI) crate for the Rust
programming language. It is built using [`Kludgine`][kludgine], which is powered
by [`winit`][winit] and [`wgpu`][wgpu]. It is incredibly early in development,
and is being developed for a game that will hopefully be developed shortly.
The [`Widget`][widget] trait is the building block of Gooey: Every user
interface element implements `Widget`. A full list of built-in widgets can be
found in the [`gooey::widgets`][widgets] module.
Gooey uses a reactive data model. To see [an example][button-example] of how
reactive data models work, consider this example that displays a button that
increments its own label:
```rust
$../examples/button.rs:readme$
```
[widget]: $widget$
[kludgine]: https://github.com/khonsulabs/kludgine
[wgpu]: https://github.com/gfx-rs/wgpu
[winit]: https://github.com/rust-windowing/winit
[widgets]: $widgets$
[button-example]: https://github.com/khonsulabs/gooey/tree/$ref-name$/examples/button.rs

1
.rustme/header.md Normal file
View file

@ -0,0 +1 @@
# Gooey

128
CODE_OF_CONDUCT.md Normal file
View file

@ -0,0 +1,128 @@
# 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, 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
moderators@khonsulabs.com.
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.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

55
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,55 @@
# Contributing to our projects
Thank you for your interest in contributing to one of our projects. We want
everyone to have a positive experience contributing, so please carefully review
our only requirements for contributing:
- All contributors must agree to [our Contributor License
Agreement](https://gist.github.com/ecton/b2e1e72abfa122da5e69ed30164f739e).
This will be asked for during your first pull request.
- All contributors must uphold the standards of our [Code of
Conduct](./CODE_OF_CONDUCT.md).
The rest of this document is recommendations/guidelines to help consistency and
communication within our projects.
## Creating Issues
### Reporting Bugs
To us, if something isn't behaving as you expect it to, that's a bug. Even if
it's misbehaving due to a misunderstanding, that means there's an opportunity to
improve our documentation or examples. Please don't hesitate to let us know if
you run into any issues while working with one of our projects.
### Requesting New Features
When requesting new features, please include details about what problem you're
trying to solve, not just a solution to your problem. By helping the community
understand the underlying problem, we can better evaluate what the best solution
to the problem might be.
## Contributing Changes
We openly welcome pull requests on our projects. We don't like bugs, and if
you've found one and wish to submit a fix, we greatly appreciate it.
If you find that fixing a bug requires a significant change, or you are wanting
to add a somewhat large feature, please submit a proposal as an issue first. We
want to make sure that your efforts have the highest chance of success, and a
short discussion before starting can go a long way towards a pull request being
merged with less revisions.
When working on an existing issue, update the issue to reflect that you're
working on it. This will help prevent duplicated efforts.
If you begin working on something but need some assistance, don't hesitate to
reach out inside of the issue, on [our
forums](https://community.khonsulabs.com/), or in [our
Discord](https://discord.khonsulabs.com/). We will do our best to help you.
### Project-specific requirements
Be sure to check if a project's README contains additional contributing
guidelines. Each project may have different tools and commands that should be
run to validate that changes pass all requirements.

201
LICENSE-APACHE Normal file
View file

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

8
LICENSE-MIT Normal file
View file

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

46
README.md Normal file
View file

@ -0,0 +1,46 @@
# Gooey
![Gooey is considered experimental and unsupported](https://img.shields.io/badge/status-prototype-blueviolet)
[![crate version](https://img.shields.io/crates/v/gooey.svg)](https://crates.io/crates/gooey)
[![Documentation for `main` branch](https://img.shields.io/badge/docs-main-informational)](https://gooey.rs/main/gooey/)
Gooey is an experimental Graphical User Interface (GUI) crate for the Rust
programming language. It is built using [`Kludgine`][kludgine], which is powered
by [`winit`][winit] and [`wgpu`][wgpu]. It is incredibly early in development,
and is being developed for a game that will hopefully be developed shortly.
The [`Widget`][widget] trait is the building block of Gooey: Every user
interface element implements `Widget`. A full list of built-in widgets can be
found in the [`gooey::widgets`][widgets] module.
Gooey uses a reactive data model. To see [an example][button-example] of how
reactive data models work, consider this example that displays a button that
increments its own label:
```rust
// Create a dynamic usize.
let count = Dynamic::new(0_usize);
// Create a new button with a label that is produced by mapping the contents
// of `count`.
Button::new(count.map_each(ToString::to_string))
// Set the `on_click` callback to a closure that increments the counter.
.on_click(count.with_clone(|count| move |_| count.set(count.get() + 1)))
// Run the button as an an application.
.run()
```
[widget]: https://gooey.rs/main/gooey/widget/trait.Widget.html
[kludgine]: https://github.com/khonsulabs/kludgine
[wgpu]: https://github.com/gfx-rs/wgpu
[winit]: https://github.com/rust-windowing/winit
[widgets]: https://gooey.rs/main/gooey/widgets/index.html
[button-example]: https://github.com/khonsulabs/gooey/tree/main/examples/button.rs
## Open-source Licenses
This project, like all projects from [Khonsu Labs](https://khonsulabs.com/), is open-source.
This repository is available under the [MIT License](./LICENSE-MIT) or the
[Apache License 2.0](./LICENSE-APACHE).
To learn more about contributing, please see [CONTRIBUTING.md](./CONTRIBUTING.md).

View file

@ -3,8 +3,16 @@ use gooey::widgets::Button;
use gooey::Run;
fn main() -> gooey::Result {
// begin rustme snippet: readme
// Create a dynamic usize.
let count = Dynamic::new(0_usize);
// Create a new button with a label that is produced by mapping the contents
// of `count`.
Button::new(count.map_each(ToString::to_string))
// Set the `on_click` callback to a closure that increments the counter.
.on_click(count.with_clone(|count| move |_| count.set(count.get() + 1)))
// Run the button as an an application.
.run()
// end rustme snippet
}

View file

@ -1,14 +1,15 @@
use std::string::ToString;
use gooey::value::Dynamic;
use gooey::widgets::{Button, Label, Spacing, Stack};
use gooey::widgets::{Align, Button, Expand, Label, Resize, Stack};
use gooey::{widgets, Run};
use kludgine::figures::units::Lp;
fn main() -> gooey::Result {
let counter = Dynamic::new(0i32);
let label = counter.map_each(ToString::to_string);
Spacing::auto(Stack::columns(widgets![
Label::new(label),
Expand::new(Align::centered(Stack::columns(widgets![
Resize::width(Lp::points(100), Label::new(label)),
Button::new("+").on_click(counter.with_clone(|counter| {
move |_| {
counter.set(counter.get() + 1);
@ -19,6 +20,6 @@ fn main() -> gooey::Result {
counter.set(counter.get() - 1);
}
})),
]))
])))
.run()
}

View file

@ -58,7 +58,10 @@ impl<'context, 'window> EventContext<'context, 'window> {
/// Invokes [`Widget::hit_test()`](crate::widget::Widget::hit_test) on this
/// context's widget and returns the result.
pub fn hit_test(&mut self, location: Point<Px>) -> bool {
self.current_node.lock().hit_test(location, self)
self.current_node
.lock()
.as_widget()
.hit_test(location, self)
}
/// Invokes [`Widget::mouse_down()`](crate::widget::Widget::mouse_down) on
@ -71,6 +74,7 @@ impl<'context, 'window> EventContext<'context, 'window> {
) -> EventHandling {
self.current_node
.lock()
.as_widget()
.mouse_down(location, device_id, button, self)
}
@ -79,6 +83,7 @@ impl<'context, 'window> EventContext<'context, 'window> {
pub fn mouse_drag(&mut self, location: Point<Px>, device_id: DeviceId, button: MouseButton) {
self.current_node
.lock()
.as_widget()
.mouse_drag(location, device_id, button, self);
}
@ -92,6 +97,7 @@ impl<'context, 'window> EventContext<'context, 'window> {
) {
self.current_node
.lock()
.as_widget()
.mouse_up(location, device_id, button, self);
}
@ -105,13 +111,14 @@ impl<'context, 'window> EventContext<'context, 'window> {
) -> EventHandling {
self.current_node
.lock()
.as_widget()
.keyboard_input(device_id, input, is_synthetic, self)
}
/// Invokes [`Widget::ime()`](crate::widget::Widget::ime) on this
/// context's widget and returns the result.
pub fn ime(&mut self, ime: Ime) -> EventHandling {
self.current_node.lock().ime(ime, self)
self.current_node.lock().as_widget().ime(ime, self)
}
/// Invokes [`Widget::mouse_wheel()`](crate::widget::Widget::mouse_wheel) on this
@ -124,6 +131,7 @@ impl<'context, 'window> EventContext<'context, 'window> {
) -> EventHandling {
self.current_node
.lock()
.as_widget()
.mouse_wheel(device_id, delta, phase, self)
}
@ -131,11 +139,11 @@ impl<'context, 'window> EventContext<'context, 'window> {
let changes = self.current_node.tree.hover(Some(self.current_node));
for unhovered in changes.unhovered {
let mut context = self.for_other(&unhovered);
unhovered.lock().unhover(&mut context);
unhovered.lock().as_widget().unhover(&mut context);
}
for hover in changes.hovered {
let mut context = self.for_other(&hover);
hover.lock().hover(location, &mut context);
hover.lock().as_widget().hover(location, &mut context);
}
}
@ -145,7 +153,7 @@ impl<'context, 'window> EventContext<'context, 'window> {
for old_hover in changes.unhovered {
let mut old_hover_context = self.for_other(&old_hover);
old_hover.lock().unhover(&mut old_hover_context);
old_hover.lock().as_widget().unhover(&mut old_hover_context);
}
}
@ -156,7 +164,7 @@ impl<'context, 'window> EventContext<'context, 'window> {
Ok(old) => {
if let Some(old) = old {
let mut old_context = self.for_other(&old);
old.lock().deactivate(&mut old_context);
old.lock().as_widget().deactivate(&mut old_context);
}
true
}
@ -164,7 +172,10 @@ impl<'context, 'window> EventContext<'context, 'window> {
};
if new {
if let Some(active) = active {
active.lock().activate(&mut self.for_other(&active));
active
.lock()
.as_widget()
.activate(&mut self.for_other(&active));
}
}
}
@ -175,7 +186,7 @@ impl<'context, 'window> EventContext<'context, 'window> {
Ok(old) => {
if let Some(old) = old {
let mut old_context = self.for_other(&old);
old.lock().blur(&mut old_context);
old.lock().as_widget().blur(&mut old_context);
}
true
}
@ -183,7 +194,7 @@ impl<'context, 'window> EventContext<'context, 'window> {
};
if new {
if let Some(focus) = focus {
focus.lock().focus(&mut self.for_other(&focus));
focus.lock().as_widget().focus(&mut self.for_other(&focus));
}
}
}
@ -302,14 +313,17 @@ impl<'context, 'window, 'clip, 'gfx, 'pass> GraphicsContext<'context, 'window, '
/// Invokes [`Widget::measure()`](crate::widget::Widget::measure) on this
/// context's widget and returns the result.
pub fn measure(&mut self, available_space: Size<ConstraintLimit>) -> Size<UPx> {
self.current_node.lock().measure(available_space, self)
self.current_node
.lock()
.as_widget()
.measure(available_space, self)
}
/// Invokes [`Widget::redraw()`](crate::widget::Widget::redraw) on this
/// context's widget.
pub fn redraw(&mut self) {
self.current_node.note_rendered_rect(self.graphics.region());
self.current_node.lock().redraw(self);
self.current_node.lock().as_widget().redraw(self);
}
}
@ -347,6 +361,7 @@ pub trait AsEventContext<'window> {
.push_boxed(child, Some(context.current_node));
pushed_widget
.lock()
.as_widget()
.mounted(&mut context.for_other(&pushed_widget));
pushed_widget
}
@ -358,7 +373,10 @@ pub trait AsEventContext<'window> {
.current_node
.tree
.remove_child(child, context.current_node);
child.lock().unmounted(&mut context.for_other(child));
child
.lock()
.as_widget()
.unmounted(&mut context.for_other(child));
}
}

View file

@ -1,4 +1,4 @@
//! A reactive, `wgpu`-based Graphical User Interface (GUI) crate for Rust.
#![doc = include_str!("../.crate-docs.md")]
#![warn(clippy::pedantic, missing_docs)]
#![allow(clippy::module_name_repetitions, clippy::missing_errors_doc)]

View file

@ -80,9 +80,7 @@ impl ComponentDefinition for HighlightColor {
/// Intrinsic, uniform padding for a widget.
///
/// This component is opt-in and does not automatically work for all widgets. To
/// apply arbitrary, non-uniform padding around another widget, use a
/// [`Spacing`](crate::widgets::Spacing).
/// This component is opt-in and does not automatically work for all widgets.
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub struct IntrinsicPadding;

View file

@ -1,5 +1,6 @@
//! Types for creating reusable widgets (aka components or views).
use std::any::Any;
use std::clone::Clone;
use std::fmt::Debug;
use std::ops::{ControlFlow, Deref};
@ -12,7 +13,7 @@ use kludgine::app::winit::event::{
use kludgine::figures::units::{Px, UPx};
use kludgine::figures::{Point, Rect, Size};
use crate::context::{EventContext, GraphicsContext};
use crate::context::{AsEventContext, EventContext, GraphicsContext};
use crate::styles::Styles;
use crate::tree::{Tree, WidgetId};
use crate::widgets::Style;
@ -145,11 +146,6 @@ pub trait Widget: Send + UnwindSafe + Debug + 'static {
IGNORED
}
// #[allow(unused_variables)]
// fn query_component(&self, group: Group, name: &str) -> Option<Component> {
// None
// }
/// Associates `styles` with this widget.
///
/// This is equivalent to `Style::new(styles, self)`.
@ -207,9 +203,27 @@ pub const HANDLED: EventHandling = EventHandling::Break(EventHandled);
/// An [`EventHandling`] value that represents an ignored event.
pub const IGNORED: EventHandling = EventHandling::Continue(EventIgnored);
pub(crate) trait AnyWidget: Widget {
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
}
impl<T> AnyWidget for T
where
T: Widget,
{
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
/// An instance of a [`Widget`].
#[derive(Clone, Debug)]
pub struct WidgetInstance(Arc<Mutex<dyn Widget>>);
pub struct WidgetInstance(Arc<Mutex<dyn AnyWidget>>);
impl WidgetInstance {
/// Returns a new instance containing `widget`.
@ -220,8 +234,11 @@ impl WidgetInstance {
Self(Arc::new(Mutex::new(widget)))
}
pub(crate) fn lock(&self) -> MutexGuard<'_, dyn Widget> {
self.0.lock().map_or_else(PoisonError::into_inner, |g| g)
/// Locks the widget for exclusive access. Locking widgets should only be
/// done for brief moments of time when you are certain no deadlocks can
/// occur due to other widget locks being held.
pub fn lock(&self) -> WidgetGuard<'_> {
WidgetGuard(self.0.lock().map_or_else(PoisonError::into_inner, |g| g))
}
}
@ -311,7 +328,11 @@ impl Debug for ManagedWidget {
}
impl ManagedWidget {
pub(crate) fn lock(&self) -> MutexGuard<'_, dyn Widget> {
/// Locks the widget for exclusive access. Locking widgets should only be
/// done for brief moments of time when you are certain no deadlocks can
/// occur due to other widget locks being held.
#[must_use]
pub fn lock(&self) -> WidgetGuard<'_> {
self.widget.lock()
}
@ -372,6 +393,36 @@ impl PartialEq<WidgetInstance> for ManagedWidget {
}
}
/// Exclusive access to a widget.
///
/// This type is powered by a `Mutex`, which means care must be taken to prevent
/// deadlocks.
pub struct WidgetGuard<'a>(MutexGuard<'a, dyn AnyWidget>);
impl WidgetGuard<'_> {
pub(crate) fn as_widget(&mut self) -> &mut dyn AnyWidget {
&mut *self.0
}
/// Returns a reference to `T` if it is the type contained.
#[must_use]
pub fn downcast_ref<T>(&self) -> Option<&T>
where
T: 'static,
{
self.0.as_any().downcast_ref()
}
/// Returns an exclusive reference to `T` if it is the type contained.
#[must_use]
pub fn downcast_mut<T>(&mut self) -> Option<&mut T>
where
T: 'static,
{
self.0.as_any_mut().downcast_mut()
}
}
/// A list of [`Widget`]s.
#[derive(Debug, Default)]
#[must_use]
@ -443,3 +494,31 @@ impl Deref for Widgets {
&self.ordered
}
}
/// A child widget
#[derive(Debug, Clone)]
pub enum ChildWidget {
/// An unmounted child widget
Unmounted(WidgetInstance),
/// A mounted child widget
Mounted(ManagedWidget),
}
impl ChildWidget {
/// Returns a new unmounted child
pub fn new(widget: impl MakeWidget) -> Self {
Self::Unmounted(widget.make_widget())
}
/// Returns this child, mounting it in the process if necessary.
pub fn mounted(&mut self, context: &mut EventContext<'_, '_>) -> ManagedWidget {
if let ChildWidget::Unmounted(instance) = self {
*self = ChildWidget::Mounted(context.push_child(instance.clone()));
}
let Self::Mounted(widget) = self else {
unreachable!("just initialized")
};
widget.clone()
}
}

View file

@ -1,21 +1,25 @@
//! Built-in [`Widget`](crate::widget::Widget) implementations.
mod align;
pub mod button;
mod canvas;
mod expand;
mod input;
mod label;
mod resize;
pub mod scroll;
mod spacing;
pub mod stack;
mod style;
mod tilemap;
pub use align::Align;
pub use button::Button;
pub use canvas::Canvas;
pub use expand::Expand;
pub use input::Input;
pub use label::Label;
pub use resize::Resize;
pub use scroll::Scroll;
pub use spacing::Spacing;
pub use stack::Stack;
pub use style::Style;
pub use tilemap::TileMap;

View file

@ -3,44 +3,35 @@ use std::fmt::Debug;
use kludgine::figures::units::UPx;
use kludgine::figures::{Fraction, IntoSigned, IntoUnsigned, Point, Rect, ScreenScale, Size};
use crate::context::{AsEventContext, EventContext, GraphicsContext};
use crate::context::{AsEventContext, GraphicsContext};
use crate::styles::{Edges, FlexibleDimension};
use crate::value::{IntoValue, Value};
use crate::widget::{MakeWidget, ManagedWidget, Widget, WidgetInstance};
use crate::widget::{ChildWidget, MakeWidget, Widget};
use crate::ConstraintLimit;
/// A widget that provides spacing (padding) around its contents.
/// A widget aligns its contents to its container's boundaries.
#[derive(Debug)]
pub struct Spacing {
child: WidgetInstance,
mounted: Option<ManagedWidget>,
pub struct Align {
child: ChildWidget,
edges: Value<Edges<FlexibleDimension>>,
}
impl Spacing {
impl Align {
/// Returns a new spacing widget containing `widget`, surrounding it with
/// `margin`.
pub fn new(margin: impl IntoValue<Edges<FlexibleDimension>>, widget: impl MakeWidget) -> Self {
Self {
child: widget.make_widget(),
mounted: None,
child: ChildWidget::new(widget),
edges: margin.into_value(),
}
}
/// Returns a new spacing widget that centers `widget` vertically and
/// horizontally.
pub fn auto(widget: impl MakeWidget) -> Self {
pub fn centered(widget: impl MakeWidget) -> Self {
Self::new(FlexibleDimension::Auto, widget)
}
fn child(&mut self, context: &mut EventContext<'_, '_>) -> ManagedWidget {
if self.mounted.is_none() {
self.mounted = Some(context.push_child(self.child.clone()));
}
self.mounted.as_ref().expect("always initialized").clone()
}
fn measure(
&mut self,
available_space: Size<ConstraintLimit>,
@ -55,13 +46,13 @@ impl Spacing {
vertical.child_constraint(available_space.height),
);
let child = self.child(&mut context.as_event_context());
let child = self.child.mounted(&mut context.as_event_context());
let content_size = context.for_other(&child).measure(content_available);
let (left, right, width) = horizontal.measure(available_space.width, content_size.width);
let (top, bottom, height) = vertical.measure(available_space.height, content_size.height);
Layout {
dbg!(Layout {
margin: Edges {
left,
right,
@ -69,7 +60,7 @@ impl Spacing {
bottom,
},
content: Size::new(width, height),
}
})
}
}
@ -134,7 +125,7 @@ impl FrameInfo {
}
}
impl Widget for Spacing {
impl Widget for Align {
fn redraw(&mut self, context: &mut GraphicsContext<'_, '_, '_, '_, '_>) {
let layout = self.measure(
Size::new(
@ -143,7 +134,7 @@ impl Widget for Spacing {
),
context,
);
let child = self.child(&mut context.as_event_context());
let child = self.child.mounted(&mut context.as_event_context());
context
.for_child(
&child,
@ -169,6 +160,7 @@ impl Widget for Spacing {
}
}
#[derive(Debug)]
struct Layout {
margin: Edges<UPx>,
content: Size<UPx>,
@ -176,6 +168,6 @@ struct Layout {
impl Layout {
pub fn size(&self) -> Size<UPx> {
self.margin.size()
self.margin.size() + self.content
}
}

67
src/widgets/expand.rs Normal file
View file

@ -0,0 +1,67 @@
use kludgine::figures::units::UPx;
use kludgine::figures::Size;
use crate::context::{AsEventContext, GraphicsContext};
use crate::widget::{ChildWidget, MakeWidget, Widget};
use crate::ConstraintLimit;
/// A widget that expands its child widget to fill the parent.
///
/// Some parent widgets support weighting children when there is more than one
/// [`Expand`]ed widget.
#[derive(Debug)]
pub struct Expand {
/// The weight to use when splitting available space with multiple
/// [`Expand`] widgets.
pub weight: u8,
child: ChildWidget,
}
impl Expand {
/// Returns a widget that expands `child` to fill the parent widget.
#[must_use]
pub fn new(child: impl MakeWidget) -> Self {
Self {
child: ChildWidget::new(child),
weight: 1,
}
}
/// Returns a widget that expands `child` to fill the parent widget, using
/// `weight` when competing with available space with other [`Expand`]s.
///
/// Note: Not all container widgets support weighted expansion.
#[must_use]
pub fn weighted(weight: u8, child: impl MakeWidget) -> Self {
Self {
child: ChildWidget::new(child),
weight,
}
}
/// Returns a reference to the child widget.
#[must_use]
pub fn child(&self) -> &ChildWidget {
&self.child
}
}
impl Widget for Expand {
fn redraw(&mut self, context: &mut GraphicsContext<'_, '_, '_, '_, '_>) {
let child = self.child.mounted(&mut context.as_event_context());
context.for_other(&child).redraw();
}
fn measure(
&mut self,
available_space: Size<ConstraintLimit>,
context: &mut GraphicsContext<'_, '_, '_, '_, '_>,
) -> Size<UPx> {
let available_space = Size::new(
ConstraintLimit::Known(available_space.width.max()),
ConstraintLimit::Known(available_space.height.max()),
);
let child = self.child.mounted(&mut context.as_event_context());
context.for_other(&child).measure(available_space)
}
}

101
src/widgets/resize.rs Normal file
View file

@ -0,0 +1,101 @@
use kludgine::figures::units::UPx;
use kludgine::figures::{Fraction, IntoUnsigned, ScreenScale, Size};
use crate::context::{AsEventContext, GraphicsContext};
use crate::styles::Dimension;
use crate::widget::{ChildWidget, MakeWidget, Widget};
use crate::ConstraintLimit;
/// A widget that resizes its contained widget to an explicit size.
#[derive(Debug)]
pub struct Resize {
/// If present, the width to apply to the child widget.
pub width: Option<Dimension>,
/// If present, the height to apply to the child widget.
pub height: Option<Dimension>,
child: ChildWidget,
}
impl Resize {
/// Returns a reference to the child widget.
#[must_use]
pub fn child(&self) -> &ChildWidget {
&self.child
}
/// Resizes `child` to `size`.
#[must_use]
pub fn to<T>(size: Size<T>, child: impl MakeWidget) -> Self
where
T: Into<Dimension>,
{
Self {
child: ChildWidget::new(child),
width: Some(size.width.into()),
height: Some(size.height.into()),
}
}
/// Resizes `child`'s width to `width`.
#[must_use]
pub fn width(width: impl Into<Dimension>, child: impl MakeWidget) -> Self {
Self {
child: ChildWidget::new(child),
width: Some(width.into()),
height: None,
}
}
/// Resizes `child`'s height to `height`.
#[must_use]
pub fn height(height: impl Into<Dimension>, child: impl MakeWidget) -> Self {
Self {
child: ChildWidget::new(child),
width: None,
height: Some(height.into()),
}
}
}
impl Widget for Resize {
fn redraw(&mut self, context: &mut GraphicsContext<'_, '_, '_, '_, '_>) {
let child = self.child.mounted(&mut context.as_event_context());
context.for_other(&child).redraw();
}
fn measure(
&mut self,
available_space: Size<ConstraintLimit>,
context: &mut GraphicsContext<'_, '_, '_, '_, '_>,
) -> Size<UPx> {
if let (Some(width), Some(height)) = (self.width, self.height) {
Size::new(
width.into_px(context.graphics.scale()).into_unsigned(),
height.into_px(context.graphics.scale()).into_unsigned(),
)
} else {
let available_space = Size::new(
override_constraint(available_space.width, self.width, context.graphics.scale()),
override_constraint(
available_space.height,
self.height,
context.graphics.scale(),
),
);
let child = self.child.mounted(&mut context.as_event_context());
context.for_other(&child).measure(available_space)
}
}
}
fn override_constraint(
constraint: ConstraintLimit,
explicit: Option<Dimension>,
scale: Fraction,
) -> ConstraintLimit {
if let Some(size) = explicit {
ConstraintLimit::Known(size.into_px(scale).into_unsigned())
} else {
constraint
}
}

View file

@ -1,14 +1,17 @@
//! A widget that combines an array of [`Widgets`] into one.
// TODO on scale change, all Lp children need to resize
use std::ops::Deref;
use alot::{LotId, OrderedLots};
use kludgine::figures::units::UPx;
use kludgine::figures::{IntoSigned, Point, Rect, Size};
use kludgine::figures::units::{Lp, UPx};
use kludgine::figures::{Fraction, IntoSigned, IntoUnsigned, Point, Rect, ScreenScale, Size};
use crate::context::{AsEventContext, EventContext, GraphicsContext};
use crate::styles::Dimension;
use crate::value::{Generation, IntoValue, Value};
use crate::widget::{ManagedWidget, Widget, Widgets};
use crate::widget::{ChildWidget, ManagedWidget, Widget, Widgets};
use crate::widgets::{Expand, Resize};
use crate::ConstraintLimit;
/// A widget that displays a collection of [`Widgets`] in a
@ -81,9 +84,36 @@ impl Stack {
self.layout.swap(index, swap_index);
} else {
// This is a brand new child.
self.synced_children
.insert(index, context.push_child(widget.clone()));
self.layout.insert(index, StackDimension::FitContent);
let guard = widget.lock();
let (mut widget, dimension) =
if let Some(expand) = guard.downcast_ref::<Expand>() {
(
expand.child().clone(),
StackDimension::Fractional {
weight: expand.weight,
},
)
} else if let Some((child, size)) =
guard.downcast_ref::<Resize>().and_then(|r| {
match self.layout.orientation.orientation {
StackOrientation::Row => r.height,
StackOrientation::Column => r.width,
}
.map(|size| (r.child().clone(), size))
})
{
(child, StackDimension::Exact(size))
} else {
(
ChildWidget::Unmounted(widget.clone()),
StackDimension::FitContent,
)
};
drop(guard);
self.synced_children.insert(index, widget.mounted(context));
self.layout
.insert(index, dimension, context.kludgine.scale());
}
}
}
@ -107,6 +137,7 @@ impl Widget for Stack {
ConstraintLimit::Known(context.graphics.size().width),
ConstraintLimit::Known(context.graphics.size().height),
),
context.graphics.scale(),
|child_index, constraints| {
context
.for_other(&self.synced_children[child_index])
@ -143,12 +174,15 @@ impl Widget for Stack {
) -> Size<UPx> {
self.synchronize_children(&mut context.as_event_context());
self.layout
.update(available_space, |child_index, constraints| {
self.layout.update(
available_space,
context.graphics.scale(),
|child_index, constraints| {
context
.for_other(&self.synced_children[child_index])
.measure(constraints)
})
},
)
}
}
@ -156,7 +190,7 @@ impl Widget for Stack {
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct StackDirection {
/// The orientation of the widgets.
pub orientation: StackOrientationn,
pub orientation: StackOrientation,
/// If true, the widgets will be laid out in reverse order.
pub reverse: bool,
}
@ -166,7 +200,7 @@ impl StackDirection {
#[must_use]
pub const fn columns() -> Self {
Self {
orientation: StackOrientationn::Column,
orientation: StackOrientation::Column,
reverse: false,
}
}
@ -175,7 +209,7 @@ impl StackDirection {
#[must_use]
pub const fn columns_rev() -> Self {
Self {
orientation: StackOrientationn::Column,
orientation: StackOrientation::Column,
reverse: true,
}
}
@ -184,7 +218,7 @@ impl StackDirection {
#[must_use]
pub const fn rows() -> Self {
Self {
orientation: StackOrientationn::Row,
orientation: StackOrientation::Row,
reverse: false,
}
}
@ -193,7 +227,7 @@ impl StackDirection {
#[must_use]
pub const fn rows_rev() -> Self {
Self {
orientation: StackOrientationn::Row,
orientation: StackOrientation::Row,
reverse: true,
}
}
@ -201,24 +235,24 @@ impl StackDirection {
/// Splits a size into its measured and other parts.
pub(crate) fn split_size<U>(self, s: Size<U>) -> (U, U) {
match self.orientation {
StackOrientationn::Row => (s.height, s.width),
StackOrientationn::Column => (s.width, s.height),
StackOrientation::Row => (s.height, s.width),
StackOrientation::Column => (s.width, s.height),
}
}
/// Combines split values into a [`Size`].
pub(crate) fn make_size<U>(self, measured: U, other: U) -> Size<U> {
match self.orientation {
StackOrientationn::Row => Size::new(other, measured),
StackOrientationn::Column => Size::new(measured, other),
StackOrientation::Row => Size::new(other, measured),
StackOrientation::Column => Size::new(measured, other),
}
}
/// Combines split values into a [`Point`].
pub(crate) fn make_point<U>(self, measured: U, other: U) -> Point<U> {
match self.orientation {
StackOrientationn::Row => Point::new(other, measured),
StackOrientationn::Column => Point::new(measured, other),
StackOrientation::Row => Point::new(other, measured),
StackOrientation::Column => Point::new(measured, other),
}
}
}
@ -226,7 +260,7 @@ impl StackDirection {
/// The orientation (Row/Column) of an [`Stack`] widget.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum StackOrientationn {
pub enum StackOrientation {
/// The child widgets should be displayed as rows.
Row,
/// The child widgets should be displayed as columns.
@ -234,7 +268,7 @@ pub enum StackOrientationn {
}
/// The strategy to use when laying a widget out inside of an [`Stack`].
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[derive(Debug, Clone, Copy)]
pub enum StackDimension {
/// Attempt to lay out the widget based on its contents.
FitContent,
@ -245,7 +279,7 @@ pub enum StackDimension {
weight: u8,
},
/// Use an exact measurement for this widget's size.
Exact(UPx),
Exact(Dimension),
}
#[derive(Debug)]
@ -254,7 +288,7 @@ struct Layout {
layouts: Vec<StackLayout>,
pub other: UPx,
total_weights: u32,
allocated_space: UPx,
allocated_space: (UPx, Lp),
fractional: Vec<(LotId, u8)>,
measured: Vec<LotId>,
pub orientation: StackDirection,
@ -274,15 +308,15 @@ impl Layout {
layouts: Vec::new(),
other: UPx(0),
total_weights: 0,
allocated_space: UPx(0),
allocated_space: (UPx(0), Lp(0)),
fractional: Vec::new(),
measured: Vec::new(),
}
}
#[cfg(test)] // only used in testing
pub fn push(&mut self, child: StackDimension) {
self.insert(self.len(), child);
pub fn push(&mut self, child: StackDimension, scale: Fraction) {
self.insert(self.len(), child, scale);
}
pub fn remove(&mut self, index: usize) -> StackDimension {
@ -297,9 +331,14 @@ impl Layout {
self.fractional.retain(|(measured, _)| *measured != id);
self.total_weights -= u32::from(weight);
}
StackDimension::Exact(size) => {
self.allocated_space -= size;
}
StackDimension::Exact(size) => match size {
Dimension::Px(pixels) => {
self.allocated_space.0 -= pixels.into_unsigned();
}
Dimension::Lp(lp) => {
self.allocated_space.1 -= lp;
}
},
}
dimension
@ -315,7 +354,7 @@ impl Layout {
self.children.swap(a, b);
}
pub fn insert(&mut self, index: usize, child: StackDimension) {
pub fn insert(&mut self, index: usize, child: StackDimension, scale: Fraction) {
let id = self.children.insert(index, child);
let layout = match child {
StackDimension::FitContent => {
@ -328,8 +367,11 @@ impl Layout {
UPx(0)
}
StackDimension::Exact(size) => {
self.allocated_space += size;
size
match size {
Dimension::Px(size) => self.allocated_space.0 += size.into_unsigned(),
Dimension::Lp(size) => self.allocated_space.1 += size,
}
size.into_px(scale).into_unsigned()
}
};
self.layouts.insert(
@ -344,11 +386,14 @@ impl Layout {
pub fn update(
&mut self,
available: Size<ConstraintLimit>,
scale: Fraction,
mut measure: impl FnMut(usize, Size<ConstraintLimit>) -> Size<UPx>,
) -> Size<UPx> {
let (space_constraint, other_constraint) = self.orientation.split_size(available);
let available_space = space_constraint.max();
let mut remaining = available_space.saturating_sub(self.allocated_space);
let allocated_space =
self.allocated_space.0 + self.allocated_space.1.into_px(scale).into_unsigned();
let mut remaining = available_space.saturating_sub(allocated_space);
// Measure the children that fit their content
for &id in &self.measured {
@ -372,8 +417,7 @@ impl Layout {
remaining %= self.total_weights;
for (fractional_index, &(id, weight)) in self.fractional.iter().enumerate() {
let index = self.children.index_of_id(id).expect("child not found");
let size = space_per_weight * u32::from(weight);
self.layouts[index].size = size;
let mut size = space_per_weight * u32::from(weight);
// If we have fractional amounts remaining, divide the pixels
if remaining > 0 {
@ -382,9 +426,11 @@ impl Layout {
if remaining >= from_end {
let amount = (remaining + from_end - 1) / from_end;
remaining -= amount;
self.layouts[index].size += amount;
size += amount;
}
}
self.layouts[index].size = size;
}
}
@ -398,7 +444,7 @@ impl Layout {
let (_, measured) = self.orientation.split_size(measure(
index,
self.orientation.make_size(
ConstraintLimit::Known(self.layouts[index].size),
ConstraintLimit::Known(self.layouts[index].size.into_px(scale).into_unsigned()),
other_constraint,
),
));
@ -427,9 +473,10 @@ mod tests {
use std::cmp::Ordering;
use kludgine::figures::units::UPx;
use kludgine::figures::Size;
use kludgine::figures::{Fraction, IntoSigned, Size};
use super::{Layout, StackDimension, StackDirection};
use crate::styles::Dimension;
use crate::ConstraintLimit;
struct Child {
@ -450,7 +497,7 @@ mod tests {
}
pub fn fixed_size(mut self, size: UPx) -> Self {
self.dimension = StackDimension::Exact(size);
self.dimension = StackDimension::Exact(Dimension::Px(size.into_signed()));
self
}
@ -475,10 +522,10 @@ mod tests {
assert_eq!(children.len(), expected.len());
let mut flex = Layout::new(orientation);
for child in children {
flex.push(child.dimension);
flex.push(child.dimension, Fraction::ONE);
}
let computed_size = flex.update(available, |index, constraints| {
let computed_size = flex.update(available, Fraction::ONE, |index, constraints| {
let (measured_constraint, _other_constraint) = orientation.split_size(constraints);
let child = &children[index];
let maximum_measured = measured_constraint.max();

View file

@ -3,25 +3,23 @@ use kludgine::figures::Size;
use crate::context::{AsEventContext, EventContext, GraphicsContext};
use crate::styles::Styles;
use crate::widget::{ManagedWidget, Widget, WidgetInstance};
use crate::widget::{ChildWidget, MakeWidget, Widget};
use crate::ConstraintLimit;
/// A widget that applies a set of [`Styles`] to all contained widgets.
#[derive(Debug)]
pub struct Style {
styles: Styles,
child: WidgetInstance,
mounted_child: Option<ManagedWidget>,
child: ChildWidget,
}
impl Style {
/// Returns a new widget that applies `styles` to `child` and any children
/// it may have.
pub fn new(styles: impl Into<Styles>, child: impl Widget) -> Self {
pub fn new(styles: impl Into<Styles>, child: impl MakeWidget) -> Self {
Self {
styles: styles.into(),
child: WidgetInstance::new(child),
mounted_child: None,
child: ChildWidget::new(child),
}
}
}
@ -29,25 +27,11 @@ impl Style {
impl Widget for Style {
fn mounted(&mut self, context: &mut EventContext<'_, '_>) {
context.attach_styles(self.styles.clone());
self.mounted_child = Some(context.push_child(self.child.clone()));
}
fn unmounted(&mut self, context: &mut EventContext<'_, '_>) {
let child = self
.mounted_child
.take()
.expect("unmounted without being mounted");
context.remove_child(&child);
}
fn redraw(&mut self, context: &mut GraphicsContext<'_, '_, '_, '_, '_>) {
context
.for_other(
self.mounted_child
.as_ref()
.expect("measuring without being mounted"),
)
.redraw();
let child = self.child.mounted(&mut context.as_event_context());
context.for_other(&child).redraw();
}
fn measure(
@ -55,12 +39,7 @@ impl Widget for Style {
available_space: Size<ConstraintLimit>,
context: &mut GraphicsContext<'_, '_, '_, '_, '_>,
) -> Size<UPx> {
context
.for_other(
self.mounted_child
.as_ref()
.expect("measuring without being mounted"),
)
.measure(available_space)
let child = self.child.mounted(&mut context.as_event_context());
context.for_other(&child).measure(available_space)
}
}

View file

@ -16,7 +16,7 @@ use kludgine::app::winit::event::{
use kludgine::app::winit::keyboard::KeyCode;
use kludgine::app::WindowBehavior as _;
use kludgine::figures::units::Px;
use kludgine::figures::Point;
use kludgine::figures::{IntoSigned, Point, Rect, Size};
use kludgine::render::Drawing;
use kludgine::Kludgine;
@ -26,7 +26,7 @@ use crate::tree::Tree;
use crate::utils::ModifiersExt;
use crate::widget::{EventHandling, ManagedWidget, Widget, WidgetInstance, HANDLED, IGNORED};
use crate::window::sealed::WindowCommand;
use crate::Run;
use crate::{ConstraintLimit, Run};
/// A currently running Gooey window.
pub type RunningWindow<'window> = kludgine::app::Window<'window, WindowCommand>;
@ -198,11 +198,24 @@ where
graphics.reset_text_attributes();
self.root.tree.reset_render_order();
let graphics = self.contents.new_frame(graphics);
GraphicsContext {
let mut context = GraphicsContext {
widget: WidgetContext::new(&self.root, &self.redraw_status, &mut window),
graphics: Exclusive::Owned(Graphics::new(graphics)),
};
let window_size = context.graphics.size();
let actual_size = context.measure(Size::new(
ConstraintLimit::ClippedAfter(window_size.width),
ConstraintLimit::ClippedAfter(window_size.height),
));
let render_size = actual_size.min(window_size);
if render_size.width < window_size.width || render_size.height < window_size.height {
context
.clipped_to(Rect::from(render_size.into_signed()))
.redraw();
} else {
context.redraw();
}
.redraw();
}
fn render<'pass>(