├── .gitignore
├── .travis.yml
├── Cargo.toml
├── ELM_LICENSE.md
├── README.md
├── assets
└── NotoSans
│ ├── LICENSE-2.0.txt
│ ├── NotoSans-Bold.ttf
│ ├── NotoSans-BoldItalic.ttf
│ ├── NotoSans-Italic.ttf
│ └── NotoSans-Regular.ttf
├── examples
└── graphics.rs
└── src
├── color.rs
├── element.rs
├── form.rs
├── lib.rs
├── text.rs
├── transform_2d.rs
└── utils.rs
/.gitignore:
--------------------------------------------------------------------------------
1 | # RUST STUFF
2 |
3 | # Compiled files
4 | *.o
5 | *.so
6 | *.rlib
7 | *.dll
8 |
9 | # Executables
10 | *.exe
11 |
12 | # Generated by Cargo
13 | /target/
14 | Cargo.lock
15 |
16 |
17 |
18 | # MAC STUFF
19 |
20 | .DS_Store
21 | .AppleDouble
22 | .LSOverride
23 |
24 | # Icon must end with two \r
25 | Icon
26 |
27 | # Thumbnails
28 | ._*
29 |
30 | # Files that might appear on external disk
31 | .Spotlight-V100
32 | .Trashes
33 |
34 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: false
2 | language: rust
3 | os:
4 | - linux
5 | env:
6 | global:
7 | - secure: W/pxVmgtzNXIQNPOm9lsIjSr2nEHGVD8uOGV0be4kdz0bUXCjFDe1j45VVDnXPoJZDrnv7TO0etn3yT7hpuiZGAT40Ovn7LVq7gqtTAoP2U7vbURN55g0MU9dSIAOUdfclAMZez9HgOHWC0P3Tg6bNkNrW5B5wwpmaFVyYwiQkE=
8 | - secure: qlflwsinhvNorlh6l4Hl3tQDytF/LTzlUmw3hA4yj7pwEFUP4BORTvNIlJa+DCft4P4aEU0pgCsC8eb+MQ+q1WOQr2e+EfE+KT/FS9pT6RvqyYUs4QaEznbJkHxMjzkU2N5jf6RGssIEx3ieXD1y+LETxk+KIBFY8DN+wmMYjas=
9 | addons:
10 | apt:
11 | packages:
12 | - libxxf86vm-dev
13 | - libosmesa6-dev
14 | script:
15 | - cargo build --verbose
16 | - cargo test --verbose
17 | - cargo doc --verbose
18 | after_success: |
19 | [ $TRAVIS_BRANCH = master ] &&
20 | [ $TRAVIS_PULL_REQUEST = false ] &&
21 | cargo doc &&
22 | echo "" > target/doc/index.html &&
23 | sudo pip install ghp-import &&
24 | ghp-import -n target/doc &&
25 | git push -fq https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages
26 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "elmesque"
3 | version = "0.12.0"
4 | authors = ["mitchmindtree "]
5 | description = "An attempt at porting Elm's incredibly useful, purely functional std graphics modules."
6 | readme = "README.md"
7 | keywords = ["elm", "graphics", "2d", "ui", "shape"]
8 | license = "MIT"
9 | repository = "https://github.com/mitchmindtree/elmesque.git"
10 | homepage = "https://github.com/mitchmindtree/elmesque"
11 |
12 |
13 | [dependencies]
14 | num = "0.1.27"
15 | piston2d-graphics = "0.13.0"
16 | rand = "0.3.12"
17 | rustc-serialize = "0.3.16"
18 | vecmath = "0.2.0"
19 |
20 | [dev-dependencies]
21 | find_folder = "0.3.0"
22 | piston = "0.16.0"
23 | piston_window = "0.33.0"
24 |
--------------------------------------------------------------------------------
/ELM_LICENSE.md:
--------------------------------------------------------------------------------
1 | Copyright (c) 2013-2015, Evan Czaplicki
2 |
3 | All rights reserved.
4 |
5 | Redistribution and use in source and binary forms, with or without
6 | modification, are permitted provided that the following conditions are met:
7 |
8 | * Redistributions of source code must retain the above copyright
9 | notice, this list of conditions and the following disclaimer.
10 |
11 | * Redistributions in binary form must reproduce the above
12 | copyright notice, this list of conditions and the following
13 | disclaimer in the documentation and/or other materials provided
14 | with the distribution.
15 |
16 | * Neither the name of Evan Czaplicki nor the names of other
17 | contributors may be used to endorse or promote products derived
18 | from this software without specific prior written permission.
19 |
20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # elmesque [](https://travis-ci.org/mitchmindtree/elmesque)
2 |
3 | This crate is an attempt at porting Elm's incredibly useful, purely functional std graphics modules. Its useful for all kinds of 2D freeform graphics and UI design.
4 |
5 | See [the docs](http://mitchmindtree.github.io/elmesque) or checkout [the example](https://github.com/mitchmindtree/elmesque/blob/master/examples/graphics.rs).
6 |
7 | Visit [elm-lang.org](http://elm-lang.org/) to learn more about Elm.
8 |
9 |
10 | All credit and thanks goes to Evan Czaplicki for all algorithms included within.
11 |
12 | Ported to Rust by Mitchell Nordine.
13 |
14 |
15 |
16 | Usage
17 | -----
18 |
19 | Add elmesque to your cargo dependencies like so.
20 |
21 | ```toml
22 | [dependencies]
23 | elmesque = "*"
24 | ```
25 |
26 |
--------------------------------------------------------------------------------
/assets/NotoSans/LICENSE-2.0.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/assets/NotoSans/NotoSans-Bold.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mitchmindtree/elmesque/aef4ec6b478b21b369061dcaaa4485ec4262670b/assets/NotoSans/NotoSans-Bold.ttf
--------------------------------------------------------------------------------
/assets/NotoSans/NotoSans-BoldItalic.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mitchmindtree/elmesque/aef4ec6b478b21b369061dcaaa4485ec4262670b/assets/NotoSans/NotoSans-BoldItalic.ttf
--------------------------------------------------------------------------------
/assets/NotoSans/NotoSans-Italic.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mitchmindtree/elmesque/aef4ec6b478b21b369061dcaaa4485ec4262670b/assets/NotoSans/NotoSans-Italic.ttf
--------------------------------------------------------------------------------
/assets/NotoSans/NotoSans-Regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mitchmindtree/elmesque/aef4ec6b478b21b369061dcaaa4485ec4262670b/assets/NotoSans/NotoSans-Regular.ttf
--------------------------------------------------------------------------------
/examples/graphics.rs:
--------------------------------------------------------------------------------
1 | extern crate elmesque;
2 | extern crate find_folder;
3 | extern crate graphics;
4 | extern crate num;
5 | extern crate piston;
6 | extern crate piston_window;
7 |
8 | use elmesque::{Form, Renderer};
9 | use piston::input::UpdateEvent;
10 | use piston::window::WindowSettings;
11 | use piston_window::{PistonWindow, Glyphs};
12 |
13 | fn main() {
14 |
15 | // Construct the window.
16 | let window: PistonWindow =
17 | WindowSettings::new("Elmesque", [1180, 580])
18 | .exit_on_esc(true)
19 | .samples(4)
20 | .vsync(true)
21 | .build()
22 | .unwrap();
23 |
24 | // Construct the GlyphCache.
25 | let mut glyph_cache = {
26 | let assets = find_folder::Search::ParentsThenKids(3, 3).for_folder("assets").unwrap();
27 | let font_path = assets.join("NotoSans/NotoSans-Regular.ttf");
28 | Glyphs::new(&font_path, window.factory.borrow().clone()).unwrap()
29 | };
30 |
31 | // We'll use this to animate our graphics.
32 | let mut secs = 0.0;
33 |
34 | // Poll events from the window.
35 | for event in window {
36 | event.draw_2d(|context, g| {
37 | let view_dim = context.get_view_size();
38 | let (w, h) = (view_dim[0], view_dim[1]);
39 |
40 | // Construct the elmesque Renderer with our graphics backend and glyph cache.
41 | let mut renderer = Renderer::new(context, g).character_cache(&mut glyph_cache);
42 |
43 | // Construct some freeform graphics aka a `Form`.
44 | let form = elmesque_demo_form(secs);
45 |
46 | // Convert the form to an `Element` for rendering.
47 | let a = elmesque::form::collage(w as i32, h as i32, vec![form])
48 | //.crop((secs / 2.0).sin() * (w / 2.0), (secs / 3.0).sin() * (h / 2.0), 400.0, 400.0)
49 | .clear(elmesque::color::black());
50 |
51 | a.draw(&mut renderer);
52 | });
53 | event.update(|args| secs += args.dt);
54 | }
55 |
56 | }
57 |
58 |
59 | /// Demo of grouping multiple forms into a new single form, transformable at any stage.
60 | pub fn elmesque_demo_form(secs: f64) -> Form {
61 | use elmesque::color::{blue, dark_blue, light_blue, dark_purple, white};
62 | use elmesque::form::{circle, group, ngon, oval, point_path, rect, solid, text, traced};
63 | use elmesque::text::Text;
64 | use elmesque::utils::{degrees};
65 | use num::Float;
66 |
67 | // Time to get creative!
68 | group(vec![
69 |
70 | rect(60.0, 40.0).filled(blue())
71 | .shift(secs.sin() * 50.0, secs.cos() * 50.0)
72 | .alpha(((secs * 200.0).cos() * 0.5 + 0.5) as f32)
73 | .rotate(-secs),
74 |
75 | rect(100.0, 10.0).filled(dark_blue())
76 | .shift((secs * 5.0).sin() * 200.0, (secs * 5.0).cos() * 200.0)
77 | .alpha(((secs * 2.0).cos() * 0.5 + 0.5) as f32)
78 | .rotate(-(secs * 5.0)),
79 |
80 | rect(10.0, 300.0).filled(blue())
81 | .alpha(((secs * 3.0).sin() * 0.25 + 0.75) as f32)
82 | .rotate(-(secs * 1.5)),
83 |
84 | rect(5.0, (secs * 0.1).sin() * 600.0 + 300.0).filled(light_blue())
85 | .alpha(((secs).cos() * 0.25 + 0.75) as f32)
86 | .rotate(secs * 0.75),
87 |
88 | rect(3.0, 2000.0).filled(dark_blue())
89 | .alpha(((secs * 100.0).cos() * 0.5 + 0.25) as f32)
90 | .rotate(-(secs * 0.5)),
91 |
92 | oval(3.0, 2000.0 * (secs * 60.0).sin()).filled(light_blue())
93 | .alpha(((secs * 100.0).cos() * 0.5 + 0.25) as f32)
94 | .rotate(-(secs * 0.6)),
95 |
96 | rect(10.0, 750.0).filled(blue())
97 | .alpha(((secs * 2.0).cos() * 0.5 + 0.25) as f32)
98 | .rotate(-(secs * 1.85)),
99 |
100 | circle((secs * 0.5).sin() * 1500.0).outlined(solid(dark_purple()))
101 | .alpha(((secs * 0.2).sin() * 0.25 + 0.35) as f32)
102 | .rotate(-(secs * 0.5)),
103 |
104 | ngon(12, (secs * 0.1).cos() * 100.0 + 300.0).filled(blue())
105 | .alpha((0.25 * secs.cos()) as f32)
106 | .rotate(secs * 0.5),
107 |
108 | ngon(9, (secs * 0.1).cos() * 200.0 + 250.0).outlined(solid(dark_blue()))
109 | .alpha(((0.33 * secs).sin() + 0.15) as f32)
110 | .rotate(secs * 0.2),
111 |
112 | rect(300.0, 20.0).filled(light_blue())
113 | .shift((secs * 1.5).cos() * 250.0, (secs * 1.5).sin() * 250.0)
114 | .alpha(((secs * 4.5).cos() * 0.25 + 0.35) as f32)
115 | .rotate(secs * 1.5 + degrees(90.0)),
116 |
117 | traced(
118 | solid(light_blue()),
119 | point_path(vec![(-500.0, 100.0), (0.0, 250.0 * secs.sin()), (500.0, 100.0)])
120 | ).alpha(((secs * 0.2).sin() * 0.25 + 0.35) as f32),
121 |
122 | traced(
123 | solid(blue()),
124 | point_path(vec![(-500.0, 0.0), (0.0, 0.0), (500.0, 0.0)])
125 | ).alpha(((secs * 4.5).cos() * 0.25 + 0.35) as f32),
126 |
127 | traced(
128 | solid(dark_blue()),
129 | point_path(vec![(-500.0, -100.0), (0.0, -250.0 * secs.sin()), (500.0, -100.0)])
130 | ).alpha(((secs * 0.15).cos() * 0.25 + 0.35) as f32),
131 |
132 | text(Text::from_string("elmesque".to_string()).color(white())),
133 |
134 | ]).rotate(degrees(secs.sin() * 360.0))
135 | .scale((secs * 0.05).cos() * 0.2 + 0.9)
136 |
137 | }
138 |
139 |
--------------------------------------------------------------------------------
/src/color.rs:
--------------------------------------------------------------------------------
1 | //!
2 | //! A library providing simple `Color` and `Gradient` types along with useful transformations and
3 | //! presets.
4 | //!
5 | //!
6 | //! Inspiration taken from [elm-lang's color module]
7 | //! (https://github.com/elm-lang/core/blob/62b22218c42fb8ccc996c86bea450a14991ab815/src/Color.elm)
8 | //!
9 | //!
10 | //! Module for working with colors. Includes [RGB](https://en.wikipedia.org/wiki/RGB_color_model)
11 | //! and [HSL](http://en.wikipedia.org/wiki/HSL_and_HSV) creation, gradients and built-in names.
12 | //!
13 |
14 | use rustc_serialize::hex::ToHex;
15 | use std::ascii::AsciiExt;
16 | use std::f32::consts::PI;
17 | use utils::{clampf32, degrees, fmod, min, max, turns};
18 |
19 |
20 | /// Color supporting RGB and HSL variants.
21 | #[derive(PartialEq, Copy, Clone, Debug, RustcEncodable, RustcDecodable)]
22 | pub enum Color {
23 | /// Red, Green, Blue, Alpha - All values' scales represented between 0.0 and 1.0.
24 | Rgba(f32, f32, f32, f32),
25 | /// Hue, Saturation, Lightness, Alpha - all valuess scales represented between 0.0 and 1.0.
26 | Hsla(f32, f32, f32, f32),
27 | }
28 |
29 | /// Regional spelling alias.
30 | pub type Colour = Color;
31 |
32 |
33 | /// Create RGB colors with an alpha component for transparency.
34 | /// The alpha component is specified with numbers between 0 and 1.
35 | #[inline]
36 | pub fn rgba(r: f32, g: f32, b: f32, a: f32) -> Color {
37 | Color::Rgba(r, g, b, a)
38 | }
39 |
40 |
41 | /// Create RGB colors from numbers between 0.0 and 1.0.
42 | #[inline]
43 | pub fn rgb(r: f32, g: f32, b: f32) -> Color {
44 | Color::Rgba(r, g, b, 1.0)
45 | }
46 |
47 |
48 | /// Create RGB colors from numbers between 0 and 255 inclusive.
49 | /// The alpha component is specified with numbers between 0 and 1.
50 | #[inline]
51 | pub fn rgba_bytes(r: u8, g: u8, b: u8, a: f32) -> Color {
52 | Color::Rgba(r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, a)
53 | }
54 |
55 |
56 | /// Create RGB colors from numbers between 0 and 255 inclusive.
57 | #[inline]
58 | pub fn rgb_bytes(r: u8, g: u8, b: u8) -> Color {
59 | rgba_bytes(r, g, b, 1.0)
60 | }
61 |
62 |
63 | /// Create [HSL colors](http://en.wikipedia.org/wiki/HSL_and_HSV) with an alpha component for
64 | /// transparency.
65 | #[inline]
66 | pub fn hsla(hue: f32, saturation: f32, lightness: f32, alpha: f32) -> Color {
67 | Color::Hsla(hue - turns((hue / (2.0 * PI)).floor()), saturation, lightness, alpha)
68 | }
69 |
70 |
71 | /// Create [HSL colors](http://en.wikipedia.org/wiki/HSL_and_HSV). This gives you access to colors
72 | /// more like a color wheel, where all hues are arranged in a circle that you specify with radians.
73 | ///
74 | /// red = hsl(degrees(0.0) , 1.0 , 0.5)
75 | /// green = hsl(degrees(120.0) , 1.0 , 0.5)
76 | /// blue = hsl(degrees(240.0) , 1.0 , 0.5)
77 | /// pastel_red = hsl(degrees(0.0) , 0.7 , 0.7)
78 | ///
79 | /// To cycle through all colors, just cycle through degrees. The saturation level is how vibrant
80 | /// the color is, like a dial between grey and bright colors. The lightness level is a dial between
81 | /// white and black.
82 | #[inline]
83 | pub fn hsl(hue: f32, saturation: f32, lightness: f32) -> Color {
84 | hsla(hue, saturation, lightness, 1.0)
85 | }
86 |
87 |
88 | /// Produce a gray based on the input. 0.0 is white, 1.0 is black.
89 | pub fn grayscale(p: f32) -> Color {
90 | Color::Hsla(0.0, 0.0, 1.0-p, 1.0)
91 | }
92 | /// Produce a gray based on the input. 0.0 is white, 1.0 is black.
93 | pub fn greyscale(p: f32) -> Color {
94 | Color::Hsla(0.0, 0.0, 1.0-p, 1.0)
95 | }
96 |
97 |
98 | /// Construct a random color.
99 | pub fn random() -> Color {
100 | rgb(::rand::random(), ::rand::random(), ::rand::random())
101 | }
102 |
103 |
104 | impl Color {
105 |
106 | /// Produce a complementary color. The two colors will accent each other. This is the same as
107 | /// rotating the hue by 180 degrees.
108 | pub fn complement(self) -> Color {
109 | match self {
110 | Color::Hsla(h, s, l, a) => hsla(h + degrees(180.0), s, l, a),
111 | Color::Rgba(r, g, b, a) => {
112 | let (h, s, l) = rgb_to_hsl(r, g, b);
113 | hsla(h + degrees(180.0), s, l, a)
114 | },
115 | }
116 | }
117 |
118 | /// Calculate and return the luminance of the Color.
119 | pub fn luminance(&self) -> f32 {
120 | match *self {
121 | Color::Rgba(r, g, b, _) => (r + g + b) / 3.0,
122 | Color::Hsla(_, _, l, _) => l,
123 | }
124 | }
125 |
126 | /// Return either black or white, depending which contrasts the Color the most. This will be
127 | /// useful for determining a readable color for text on any given background Color.
128 | pub fn plain_contrast(self) -> Color {
129 | if self.luminance() > 0.5 { black() } else { white() }
130 | }
131 |
132 | /// Extract the components of a color in the HSL format.
133 | pub fn to_hsl(self) -> Hsla {
134 | match self {
135 | Color::Hsla(h, s, l, a) => Hsla(h, s, l, a),
136 | Color::Rgba(r, g, b, a) => {
137 | let (h, s, l) = rgb_to_hsl(r, g, b);
138 | Hsla(h, s, l, a)
139 | },
140 | }
141 | }
142 |
143 | /// Extract the components of a color in the RGB format.
144 | pub fn to_rgb(self) -> Rgba {
145 | match self {
146 | Color::Rgba(r, g, b, a) => Rgba(r, g, b, a),
147 | Color::Hsla(h, s, l, a) => {
148 | let (r, g, b) = hsl_to_rgb(h, s, l);
149 | Rgba(r, g, b, a)
150 | },
151 | }
152 | }
153 |
154 | /// Extract the components of a color in the RGB format within a fixed-size array.
155 | pub fn to_fsa(self) -> [f32; 4] {
156 | let Rgba(r, g, b, a) = self.to_rgb();
157 | [r, g, b, a]
158 | }
159 |
160 | /// Same as `to_fsa`, except r, g, b and a are represented in byte form.
161 | pub fn to_byte_fsa(self) -> [u8; 4] {
162 | let Rgba(r, g, b, a) = self.to_rgb();
163 | [f32_to_byte(r), f32_to_byte(g), f32_to_byte(b), f32_to_byte(a)]
164 | }
165 |
166 | /// Return the hex representation of this color in the format #RRGGBBAA
167 | /// e.g. `Color(1.0, 0.0, 5.0, 1.0) == "#FF0080FF"`
168 | pub fn to_hex(self) -> String {
169 | let vals = self.to_byte_fsa();
170 | let hex = vals.to_hex().to_ascii_uppercase();
171 | format!("#{}", &hex)
172 | }
173 |
174 | /// Return the same color but with the given luminance.
175 | pub fn with_luminance(self, l: f32) -> Color {
176 | let Hsla(h, s, _, a) = self.to_hsl();
177 | Color::Hsla(h, s, l, a)
178 | }
179 |
180 | /// Return the same color but with the alpha multiplied by the given alpha.
181 | pub fn alpha(self, alpha: f32) -> Color {
182 | match self {
183 | Color::Rgba(r, g, b, a) => Color::Rgba(r, g, b, a * alpha),
184 | Color::Hsla(h, s, l, a) => Color::Hsla(h, s, l, a * alpha),
185 | }
186 | }
187 |
188 | /// Return the same color but with the given alpha.
189 | pub fn with_alpha(self, a: f32) -> Color {
190 | match self {
191 | Color::Rgba(r, g, b, _) => Color::Rgba(r, g, b, a),
192 | Color::Hsla(h, s, l, _) => Color::Hsla(h, s, l, a),
193 | }
194 | }
195 |
196 | /// Return a highlighted version of the current Color.
197 | pub fn highlighted(self) -> Color {
198 | let luminance = self.luminance();
199 | let Rgba(r, g, b, a) = self.to_rgb();
200 | let (r, g, b) = {
201 | if luminance > 0.8 { (r - 0.2, g - 0.2, b - 0.2) }
202 | else if luminance < 0.2 { (r + 0.2, g + 0.2, b + 0.2) }
203 | else {
204 | (clampf32((1.0 - r) * 0.5 * r + r),
205 | clampf32((1.0 - g) * 0.1 * g + g),
206 | clampf32((1.0 - b) * 0.1 * b + b))
207 | }
208 | };
209 | let a = clampf32((1.0 - a) * 0.5 + a);
210 | rgba(r, g, b, a)
211 | }
212 |
213 | /// Return a clicked version of the current Color.
214 | pub fn clicked(&self) -> Color {
215 | let luminance = self.luminance();
216 | let Rgba(r, g, b, a) = self.to_rgb();
217 | let (r, g, b) = {
218 | if luminance > 0.8 { (r , g - 0.2, b - 0.2) }
219 | else if luminance < 0.2 { (r + 0.4, g + 0.2, b + 0.2) }
220 | else {
221 | (clampf32((1.0 - r) * 0.75 + r),
222 | clampf32((1.0 - g) * 0.25 + g),
223 | clampf32((1.0 - b) * 0.25 + b))
224 | }
225 | };
226 | let a = clampf32((1.0 - a) * 0.75 + a);
227 | rgba(r, g, b, a)
228 | }
229 |
230 | /// Return the Color's invert.
231 | pub fn invert(self) -> Color {
232 | let Rgba(r, g, b, a) = self.to_rgb();
233 | rgba((r - 1.0).abs(), (g - 1.0).abs(), (b - 1.0).abs(), a)
234 | }
235 |
236 | /// Return the red value.
237 | pub fn red(&self) -> f32 {
238 | let Rgba(r, _, _, _) = self.to_rgb();
239 | r
240 | }
241 |
242 | /// Return the green value.
243 | pub fn green(&self) -> f32 {
244 | let Rgba(_, g, _, _) = self.to_rgb();
245 | g
246 | }
247 |
248 | /// Return the blue value.
249 | pub fn blue(&self) -> f32 {
250 | let Rgba(_, _, b, _) = self.to_rgb();
251 | b
252 | }
253 |
254 | /// Set the red value.
255 | pub fn set_red(&mut self, r: f32) {
256 | let Rgba(_, g, b, a) = self.to_rgb();
257 | *self = rgba(r, g, b, a);
258 | }
259 |
260 | /// Set the green value.
261 | pub fn set_green(&mut self, g: f32) {
262 | let Rgba(r, _, b, a) = self.to_rgb();
263 | *self = rgba(r, g, b, a);
264 | }
265 |
266 | /// Set the blue value.
267 | pub fn set_blue(&mut self, b: f32) {
268 | let Rgba(r, g, _, a) = self.to_rgb();
269 | *self = rgba(r, g, b, a);
270 | }
271 |
272 | }
273 |
274 |
275 | /// The parts of HSL along with an alpha for transparency.
276 | #[derive(Copy, Clone, Debug)]
277 | pub struct Hsla(pub f32, pub f32, pub f32, pub f32);
278 |
279 |
280 | /// The parts of RGB along with an alpha for transparency.
281 | #[derive(Copy, Clone, Debug)]
282 | pub struct Rgba(pub f32, pub f32, pub f32, pub f32);
283 |
284 |
285 | /// Convert an f32 color to a byte.
286 | #[inline]
287 | pub fn f32_to_byte(c: f32) -> u8 { (c * 255.0) as u8 }
288 |
289 |
290 | /// Pure function for converting rgb to hsl.
291 | pub fn rgb_to_hsl(r: f32, g: f32, b: f32) -> (f32, f32, f32) {
292 | let c_max = max(max(r, g), b);
293 | let c_min = min(min(r, g), b);
294 | let c = c_max - c_min;
295 |
296 | let hue = if c == 0.0 {
297 | // If there's no difference in the channels we have grayscale, so the hue is undefined.
298 | 0.0
299 | } else {
300 | degrees(60.0) * if c_max == r { fmod(((g - b) / c), 6) }
301 | else if c_max == g { ((b - r) / c) + 2.0 }
302 | else { ((r - g) / c) + 4.0 }
303 | };
304 |
305 | let lightness = (c_max + c_min) / 2.0;
306 | let saturation = if lightness == 0.0 { 0.0 }
307 | else { c / (1.0 - (2.0 * lightness - 1.0).abs()) };
308 | (hue, saturation, lightness)
309 | }
310 |
311 |
312 | /// Pure function for converting hsl to rgb.
313 | pub fn hsl_to_rgb(hue: f32, saturation: f32, lightness: f32) -> (f32, f32, f32) {
314 | let chroma = (1.0 - (2.0 * lightness - 1.0).abs()) * saturation;
315 | let hue = hue / degrees(60.0);
316 | let x = chroma * (1.0 - (fmod(hue, 2) - 1.0).abs());
317 | let (r, g, b) = match hue {
318 | hue if hue < 0.0 => (0.0, 0.0, 0.0),
319 | hue if hue < 1.0 => (chroma, x, 0.0),
320 | hue if hue < 2.0 => (x, chroma, 0.0),
321 | hue if hue < 3.0 => (0.0, chroma, x),
322 | hue if hue < 4.0 => (0.0, x, chroma),
323 | hue if hue < 5.0 => (x, 0.0, chroma),
324 | hue if hue < 6.0 => (chroma, 0.0, x),
325 | _ => (0.0, 0.0, 0.0),
326 | };
327 | let m = lightness - chroma / 2.0;
328 | (r + m, g + m, b + m)
329 | }
330 |
331 |
332 | /// Linear or Radial Gradient.
333 | #[derive(Clone, Debug)]
334 | pub enum Gradient {
335 | /// Takes a start and end point and then a series of color stops that indicate how to
336 | /// interpolate between the start and end points.
337 | Linear((f64, f64), (f64, f64), Vec<(f64, Color)>),
338 | /// First takes a start point and inner radius. Then takes an end point and outer radius.
339 | /// It then takes a series of color stops that indicate how to interpolate between the
340 | /// inner and outer circles.
341 | Radial((f64, f64), f64, (f64, f64), f64, Vec<(f64, Color)>),
342 | }
343 |
344 |
345 | /// Create a linear gradient.
346 | pub fn linear(start: (f64, f64), end: (f64, f64), colors: Vec<(f64, Color)>) -> Gradient {
347 | Gradient::Linear(start, end, colors)
348 | }
349 |
350 |
351 | /// Create a radial gradient.
352 | pub fn radial(start: (f64, f64), start_r: f64,
353 | end: (f64, f64), end_r: f64,
354 | colors: Vec<(f64, Color)>) -> Gradient {
355 | Gradient::Radial(start, start_r, end, end_r, colors)
356 | }
357 |
358 |
359 | /// Built-in colors.
360 | ///
361 | /// These colors come from the
362 | /// [Tango palette](http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines) which provides
363 | /// aesthetically reasonable defaults for colors. Each color also comes with a light and dark
364 | /// version.
365 |
366 | /// Scarlet Red - Light - #EF2929
367 | pub fn light_red() -> Color { rgb_bytes(239 , 41 , 41 ) }
368 | /// Scarlet Red - Regular - #CC0000
369 | pub fn red() -> Color { rgb_bytes(204 , 0 , 0 ) }
370 | /// Scarlet Red - Dark - #A30000
371 | pub fn dark_red() -> Color { rgb_bytes(164 , 0 , 0 ) }
372 |
373 | /// Orange - Light - #FCAF3E
374 | pub fn light_orange() -> Color { rgb_bytes(252 , 175 , 62 ) }
375 | /// Orange - Regular - #F57900
376 | pub fn orange() -> Color { rgb_bytes(245 , 121 , 0 ) }
377 | /// Orange - Dark - #CE5C00
378 | pub fn dark_orange() -> Color { rgb_bytes(206 , 92 , 0 ) }
379 |
380 | /// Butter - Light - #FCE94F
381 | pub fn light_yellow() -> Color { rgb_bytes(255 , 233 , 79 ) }
382 | /// Butter - Regular - #EDD400
383 | pub fn yellow() -> Color { rgb_bytes(237 , 212 , 0 ) }
384 | /// Butter - Dark - #C4A000
385 | pub fn dark_yellow() -> Color { rgb_bytes(196 , 160 , 0 ) }
386 |
387 | /// Chameleon - Light - #8AE234
388 | pub fn light_green() -> Color { rgb_bytes(138 , 226 , 52 ) }
389 | /// Chameleon - Regular - #73D216
390 | pub fn green() -> Color { rgb_bytes(115 , 210 , 22 ) }
391 | /// Chameleon - Dark - #4E9A06
392 | pub fn dark_green() -> Color { rgb_bytes(78 , 154 , 6 ) }
393 |
394 | /// Sky Blue - Light - #729FCF
395 | pub fn light_blue() -> Color { rgb_bytes(114 , 159 , 207) }
396 | /// Sky Blue - Regular - #3465A4
397 | pub fn blue() -> Color { rgb_bytes(52 , 101 , 164) }
398 | /// Sky Blue - Dark - #204A87
399 | pub fn dark_blue() -> Color { rgb_bytes(32 , 74 , 135) }
400 |
401 | /// Plum - Light - #AD7FA8
402 | pub fn light_purple() -> Color { rgb_bytes(173 , 127 , 168) }
403 | /// Plum - Regular - #75507B
404 | pub fn purple() -> Color { rgb_bytes(117 , 80 , 123) }
405 | /// Plum - Dark - #5C3566
406 | pub fn dark_purple() -> Color { rgb_bytes(92 , 53 , 102) }
407 |
408 | /// Chocolate - Light - #E9B96E
409 | pub fn light_brown() -> Color { rgb_bytes(233 , 185 , 110) }
410 | /// Chocolate - Regular - #C17D11
411 | pub fn brown() -> Color { rgb_bytes(193 , 125 , 17 ) }
412 | /// Chocolate - Dark - #8F5902
413 | pub fn dark_brown() -> Color { rgb_bytes(143 , 89 , 2 ) }
414 |
415 | /// Straight Black.
416 | pub fn black() -> Color { rgb_bytes(0 , 0 , 0 ) }
417 | /// Straight White.
418 | pub fn white() -> Color { rgb_bytes(255 , 255 , 255) }
419 |
420 | /// Alluminium - Light
421 | pub fn light_gray() -> Color { rgb_bytes(238 , 238 , 236) }
422 | /// Alluminium - Regular
423 | pub fn gray() -> Color { rgb_bytes(211 , 215 , 207) }
424 | /// Alluminium - Dark
425 | pub fn dark_gray() -> Color { rgb_bytes(186 , 189 , 182) }
426 |
427 | /// Aluminium - Light - #EEEEEC
428 | pub fn light_grey() -> Color { rgb_bytes(238 , 238 , 236) }
429 | /// Aluminium - Regular - #D3D7CF
430 | pub fn grey() -> Color { rgb_bytes(211 , 215 , 207) }
431 | /// Aluminium - Dark - #BABDB6
432 | pub fn dark_grey() -> Color { rgb_bytes(186 , 189 , 182) }
433 |
434 | /// Charcoal - Light - #888A85
435 | pub fn light_charcoal() -> Color { rgb_bytes(136 , 138 , 133) }
436 | /// Charcoal - Regular - #555753
437 | pub fn charcoal() -> Color { rgb_bytes(85 , 87 , 83 ) }
438 | /// Charcoal - Dark - #2E3436
439 | pub fn dark_charcoal() -> Color { rgb_bytes(46 , 52 , 54 ) }
440 |
441 |
442 |
443 | /// Types that can be colored.
444 | pub trait Colorable: Sized {
445 |
446 | /// Set the color of the widget.
447 | fn color(self, color: Color) -> Self;
448 |
449 | /// Set the color of the widget from rgba values.
450 | fn rgba(self, r: f32, g: f32, b: f32, a: f32) -> Self {
451 | self.color(rgba(r, g, b, a))
452 | }
453 |
454 | /// Set the color of the widget from rgb values.
455 | fn rgb(self, r: f32, g: f32, b: f32) -> Self {
456 | self.color(rgb(r, g, b))
457 | }
458 |
459 | /// Set the color of the widget from hsla values.
460 | fn hsla(self, h: f32, s: f32, l: f32, a: f32) -> Self {
461 | self.color(hsla(h, s, l, a))
462 | }
463 |
464 | /// Set the color of the widget from hsl values.
465 | fn hsl(self, h: f32, s: f32, l: f32) -> Self {
466 | self.color(hsl(h, s, l))
467 | }
468 |
469 | }
470 |
471 |
--------------------------------------------------------------------------------
/src/element.rs:
--------------------------------------------------------------------------------
1 | //!
2 | //! Ported from [elm-lang's `Graphics.Element` module]
3 | //! (https://github.com/elm-lang/core/blob/1.1.1/src/Graphics/Element.elm)
4 | //!
5 | //!
6 | //! Graphical elements that snap together to build complex widgets and layouts.
7 | //!
8 | //! Each element is a rectangle with a known width and height, making them easy to combine and
9 | //! position.
10 | //!
11 | //!
12 | //! # Images
13 | //!
14 | //! image, fitted_image, cropped_image, tiled_image
15 | //!
16 | //!
17 | //! # Styling
18 | //!
19 | //! width, height, size, color, opacity
20 | //!
21 | //!
22 | //! # Inspection
23 | //!
24 | //! width_of, height_of, size_of
25 | //!
26 | //!
27 | //! # Layout
28 | //!
29 | //! flow, up, down, left, right, inward, outward
30 | //!
31 | //! ## Layout Aliases
32 | //!
33 | //! There are some convenience functions for working with `flow` in specific cases:
34 | //!
35 | //! layers, above, below, beside
36 | //!
37 | //!
38 | //! # Positioning
39 | //! empty, spacer, container
40 | //!
41 | //! ## Specific Positions
42 | //!
43 | //! To create a `Position` you can use any of the built-in positions which cover nine common
44 | //! positions:
45 | //!
46 | //! middle, mid_top, mid_bottom, mid_left, mid_right, top_left, top_right, bottom_left,
47 | //! bottom_right
48 | //!
49 | //! If you need more precision, you can create custom positions:
50 | //!
51 | //! absolute, relative, middle_at, mid_top_at, mid_bottom_at, mid_left_at, mid_right_at,
52 | //! top_left_at, top_right_at, bottom_left_at, bottom_right_at
53 | //!
54 |
55 | use color::Color;
56 | use form::{self, Form};
57 | use graphics::character::CharacterCache;
58 | use graphics::{Context, Graphics, Transformed};
59 | use self::Three::{P, Z, N};
60 | use std::path::PathBuf;
61 | use transform_2d;
62 |
63 |
64 | /// An Element's Properties.
65 | #[derive(Clone, Debug)]
66 | pub struct Properties {
67 | pub width: i32,
68 | pub height: i32,
69 | pub opacity: f32,
70 | pub crop: Option<(f64, f64, f64, f64)>,
71 | pub color: Option,
72 | }
73 |
74 |
75 | /// Graphical elements that snap together to build complex widgets and layouts.
76 | ///
77 | /// Each element is a rectangle with a known width and height, making them easy to combine and
78 | /// position.
79 | #[derive(Clone, Debug)]
80 | pub struct Element {
81 | pub props: Properties,
82 | pub element: Prim,
83 | }
84 |
85 |
86 | impl Element {
87 |
88 | /// Create an `Element` with a given width.
89 | #[inline]
90 | pub fn width(self, new_width: i32) -> Element {
91 | let Element { props, element } = self;
92 | let new_props = match element {
93 | Prim::Image(_, w, h, _) | Prim::Collage(w, h, _) => {
94 | Properties {
95 | height: (h as f32 / w as f32 * new_width as f32).round() as i32,
96 | ..props
97 | }
98 | },
99 | _ => props,
100 | };
101 | Element { props: new_props, element: element }
102 | }
103 |
104 | /// Create an `Element` with a given height.
105 | #[inline]
106 | pub fn height(self, new_height: i32) -> Element {
107 | let Element { props, element } = self;
108 | let new_props = match element {
109 | Prim::Image(_, w, h, _) | Prim::Collage(w, h, _) => {
110 | Properties {
111 | width: (w as f32 / h as f32 * new_height as f32).round() as i32,
112 | ..props
113 | }
114 | },
115 | _ => props,
116 | };
117 | Element { props: new_props, element: element }
118 | }
119 |
120 | /// Create an `Element` with a given size.
121 | #[inline]
122 | pub fn size(self, new_w: i32, new_h: i32) -> Element {
123 | self.height(new_h).width(new_w)
124 | }
125 |
126 | /// Create an `Element` with a given opacity.
127 | #[inline]
128 | pub fn opacity(mut self, opacity: f32) -> Element {
129 | self.props.opacity = opacity;
130 | self
131 | }
132 |
133 | /// Create an `Element with a given background color.
134 | #[inline]
135 | pub fn color(mut self, color: Color) -> Element {
136 | self.props.color = Some(color);
137 | self
138 | }
139 |
140 | /// Crops an `Element` with the given rectangle.
141 | #[inline]
142 | pub fn crop(self, x: f64, y: f64, w: f64, h: f64) -> Element {
143 | let Element { props, element } = self;
144 | let new_props = Properties { crop: Some((x, y, w, h)), ..props };
145 | Element { props: new_props, element: element }
146 | }
147 |
148 | /// Put an element in a container. This lets you position the element really easily, and there are
149 | /// tons of ways to set the `Position`.
150 | #[inline]
151 | pub fn container(self, w: i32, h: i32, pos: Position) -> Element {
152 | new_element(w, h, Prim::Container(pos, Box::new(self)))
153 | }
154 |
155 | /// Put an element in a cleared wrapper. The color provided will be the color that clears the
156 | /// screen before rendering the contained element.
157 | #[inline]
158 | pub fn clear(self, color: Color) -> Element {
159 | new_element(self.get_width(), self.get_height(),
160 | Prim::Cleared(color, Box::new(self)))
161 | }
162 |
163 | /// Stack elements vertically. To put `a` above `b` you would say: `a.above(b)`
164 | #[inline]
165 | pub fn above(self, other: Element) -> Element {
166 | new_element(::std::cmp::max(self.get_width(), other.get_width()),
167 | self.get_height() + other.get_height(),
168 | Prim::Flow(down(), vec![self, other]))
169 | }
170 |
171 | /// Stack elements vertically. To put `a` below `b` you would say: `a.below(b)`
172 | #[inline]
173 | pub fn below(self, other: Element) -> Element {
174 | other.above(self)
175 | }
176 |
177 | /// Put elements beside each other horizontally. To put `b` to the right of `a` you would say:
178 | /// `a.beside(b)`
179 | #[inline]
180 | pub fn beside(self, other: Element) -> Element {
181 | new_element(self.get_width() + other.get_width(),
182 | ::std::cmp::max(self.get_height(), other.get_height()),
183 | Prim::Flow(right(), vec![self, other]))
184 | }
185 |
186 | /// Return the width of the Element.
187 | pub fn get_width(&self) -> i32 { self.props.width }
188 |
189 | /// Return the height of the Element.
190 | pub fn get_height(&self) -> i32 { self.props.height }
191 |
192 | /// Return the size of the Element's bounding rectangle.
193 | pub fn get_size(&self) -> (i32, i32) { (self.props.width, self.props.height) }
194 |
195 | /// Draw the form with some given graphics backend.
196 | #[inline]
197 | pub fn draw<'a, C, G>(&self, renderer: &mut Renderer<'a, C, G>)
198 | where
199 | C: CharacterCache,
200 | G: Graphics,
201 | {
202 | let Renderer {
203 | context,
204 | ref mut backend,
205 | ref mut maybe_character_cache,
206 | } = *renderer;
207 | let view_size = context.get_view_size();
208 | let context = context.trans(view_size[0] / 2.0, view_size[1] / 2.0).scale(1.0, -1.0);
209 | draw_element(self, 1.0, *backend, maybe_character_cache, context);
210 | }
211 |
212 | /// Return whether or not a point is over the element.
213 | pub fn is_over(&self, x: i32, y: i32) -> bool {
214 | unimplemented!();
215 | }
216 |
217 | }
218 |
219 | /// Return the size of the Element.
220 | pub fn size_of(e: &Element) -> (i32, i32) {
221 | (e.props.width, e.props.height)
222 | }
223 |
224 |
225 | /// Construct a new Element from width, height and some Prim.
226 | /// Iterates the global GUID counter by one and returns that as the Element id.
227 | #[inline]
228 | pub fn new_element(w: i32, h: i32, element: Prim) -> Element {
229 | Element {
230 | props: Properties {
231 | width: w,
232 | height: h,
233 | opacity: 1.0,
234 | color: None,
235 | crop: None,
236 | },
237 | element: element,
238 | }
239 | }
240 |
241 |
242 | /// Create an empty box. this is useful for getting your spacing right and making borders.
243 | pub fn spacer(w: i32, h: i32) -> Element {
244 | new_element(w, h, Prim::Spacer)
245 | }
246 |
247 |
248 | /// An Element that takes up no space. Good for things that appear conditionally.
249 | pub fn empty() -> Element {
250 | spacer(0, 0)
251 | }
252 |
253 |
254 | /// The various kinds of Elements.
255 | #[derive(Clone, Debug)]
256 | pub enum Prim {
257 | Image(ImageStyle, i32, i32, PathBuf),
258 | Container(Position, Box),
259 | Flow(Direction, Vec),
260 | Collage(i32, i32, Vec