Compare commits

..
64 Commits
Author SHA1 Message Date
Squid f3ba9e1aeb Added terminal search function, case (in)sensetive match, regex
Moorly CI / windows-build (push) Successful in 3m40s
Moorly CI / linux-build (push) Successful in 4m17s
2026-11-17 22:33:51 +01:00
Squid f6a2f65cd4 Added search in settings
Moorly CI / windows-build (push) Successful in 3m28s
Moorly CI / linux-build (push) Successful in 4m11s
2026-11-17 22:18:17 +01:00
Squid 438f202dfe Added right click menu for tabs
Moorly CI / windows-build (push) Successful in 3m27s
Moorly CI / linux-build (push) Successful in 4m10s
2026-11-17 22:10:52 +01:00
Squid ee01826fb9 Added scrollback history setting to terminals
Moorly CI / windows-build (push) Successful in 3m46s
Moorly CI / linux-build (push) Successful in 4m11s
2026-11-17 21:59:13 +01:00
Squid 2d54d74c69 Removed console window for windows release build
Moorly CI / windows-build (push) Successful in 3m30s
Moorly CI / linux-build (push) Successful in 4m8s
2026-11-17 21:07:41 +01:00
Squid fca5bb4e93 Fixed folder picker appearing behind profile window
Moorly CI / windows-build (push) Successful in 3m43s
Moorly CI / linux-build (push) Successful in 4m12s
2026-11-17 21:02:58 +01:00
Squid ce917ced9f Fixed session end buttons
Moorly CI / windows-build (push) Successful in 3m30s
Moorly CI / linux-build (push) Successful in 4m15s
2026-11-17 20:56:40 +01:00
Squid a85c57c8e7 Better mouse cursors selection on tabs and tab close areas
Moorly CI / windows-build (push) Successful in 3m27s
Moorly CI / linux-build (push) Successful in 4m10s
2026-11-17 20:44:05 +01:00
Squid 403cdf8174 Fixed mirrored crosshair color picker
Moorly CI / linux-build (push) Successful in 5m4s
Moorly CI / windows-build (push) Successful in 6m14s
2026-11-17 20:33:25 +01:00
Squid 66bafe0524 Updated the logos to look correct
Moorly CI / linux-build (push) Successful in 6m23s
Moorly CI / windows-build (push) Successful in 6m27s
2026-11-15 19:25:06 +01:00
Squid cb512d743b Added program icons
Moorly CI / linux-build (push) Successful in 4m21s
Moorly CI / windows-build (push) Successful in 4m25s
2026-11-12 22:18:18 +01:00
Squid 4494dee4a8 Added program icons (png + ico)
Moorly CI / windows-build (push) Successful in 3m17s
Moorly CI / linux-build (push) Successful in 4m7s
2026-11-12 21:36:07 +01:00
Squid adac2b9a68 Corrected righy click options so shift+right click always works
Moorly CI / windows-build (push) Successful in 3m1s
Moorly CI / linux-build (push) Successful in 4m5s
2026-11-12 21:03:58 +01:00
Squid 1b73c313b2 Added shift+right click to get a context menu in terminals
Moorly CI / windows-build (push) Successful in 2m59s
Moorly CI / linux-build (push) Successful in 4m5s
2026-11-12 20:29:09 +01:00
Squid b5713819fe Added ctrl+shift+m to hide the windows
Moorly CI / windows-build (push) Successful in 3m5s
Moorly CI / linux-build (push) Successful in 4m5s
2026-11-12 20:22:38 +01:00
Squid 4dc4401871 Added single-instance, where second instance raises the current running instance instead of creating a second conflicting instance
Moorly CI / windows-build (push) Successful in 3m2s
Moorly CI / linux-build (push) Successful in 4m7s
2026-11-12 20:07:56 +01:00
Squid 6425cfaacf Changed command palette to have exit/quit as command, and the fuzzy matching ranks matching text, so quit makes the command higher then quick terminal
Moorly CI / windows-build (push) Successful in 3m6s
Moorly CI / linux-build (push) Successful in 4m16s
2026-11-12 19:52:09 +01:00
Squid 5b2e2c0d1f Added right-clik copy/paste selection in terminals
Moorly CI / windows-build (push) Successful in 3m18s
Moorly CI / linux-build (push) Successful in 4m15s
2026-11-12 19:44:53 +01:00
Squid 64a152133e Moved the add/remove autostart button position
Moorly CI / windows-build (push) Successful in 3m18s
Moorly CI / linux-build (push) Successful in 4m14s
2026-11-12 19:30:48 +01:00
Squid af4f4c889f Added autostart option for the program
Moorly CI / windows-build (push) Successful in 3m2s
Moorly CI / linux-build (push) Successful in 4m14s
2026-11-12 19:28:52 +01:00
Squid 8e17b4a707 Fixed so you can select and copy text in terminal
Moorly CI / windows-build (push) Successful in 2m59s
Moorly CI / linux-build (push) Successful in 4m4s
2026-11-12 19:21:55 +01:00
Squid 9319d54620 Added support of autostarting profiles, quick terminal, quick powershell(windows)
Moorly CI / windows-build (push) Successful in 3m26s
Moorly CI / linux-build (push) Successful in 4m9s
2026-11-12 19:11:44 +01:00
Squid c998122587 Fixed so command palette regains focus when opening from hidden window state
Moorly CI / windows-build (push) Successful in 3m54s
Moorly CI / linux-build (push) Successful in 4m10s
2026-11-09 22:40:40 +01:00
Squid 4140d5a07c Added a setting for Minimize to tray
Moorly CI / windows-build (push) Successful in 3m36s
Moorly CI / linux-build (push) Successful in 4m11s
2026-11-08 21:43:40 +01:00
Squid e7afad602b Fixed button wrapping in settings -> shortcuts
Moorly CI / windows-build (push) Successful in 3m29s
Moorly CI / linux-build (push) Successful in 4m11s
2026-11-08 21:16:51 +01:00
Squid e0de7a43f0 Added fuzzy matching on profile path also
Moorly CI / windows-build (push) Successful in 3m23s
Moorly CI / linux-build (push) Successful in 4m11s
2026-11-08 21:09:42 +01:00
Squid 485cbf4c18 updated shortcut functions on wayland/kde to stop showing shortcuts setting window on every launch
Moorly CI / windows-build (push) Successful in 3m55s
Moorly CI / linux-build (push) Successful in 4m15s
2026-11-08 21:04:33 +01:00
Squid abbca0e411 Added tray function for windows and linux(kde/gnome). Global shortcut to show/hide program windows
Moorly CI / windows-build (push) Successful in 3m54s
Moorly CI / linux-build (push) Successful in 4m12s
2026-11-08 20:37:19 +01:00
Squid 0fe753f16e Added global hotkeys for windows, gnome and windows 10/11
Moorly CI / windows-build (push) Successful in 3m36s
Moorly CI / linux-build (push) Successful in 4m1s
2026-11-08 18:00:23 +01:00
Squid c05dc3f9f5 Added support for powershell on windows and linux, information if powershell is not installed and prevents running that profile
Moorly CI / windows-build (push) Successful in 3m20s
Moorly CI / linux-build (push) Successful in 3m43s
2026-11-08 17:14:23 +01:00
Squid 7260e2411f Added start path for powershell profile
Moorly CI / windows-build (push) Successful in 3m29s
Moorly CI / linux-build (push) Successful in 3m38s
2026-11-08 16:57:39 +01:00
Squid 317b773a18 Added terminal support for windows 10/11
Moorly CI / windows-build (push) Successful in 3m34s
Moorly CI / linux-build (push) Successful in 3m46s
2026-11-08 16:55:03 +01:00
Squid 6915fc2857 Corrected display error on color picker in windows
Moorly CI / windows-build (push) Successful in 3m7s
Moorly CI / linux-build (push) Successful in 3m42s
2026-11-08 16:35:11 +01:00
Squid 0c9946d2b4 Added working terminal interface for linux
Moorly CI / linux-build (push) Successful in 3m43s
Moorly CI / windows-build (push) Successful in 3m51s
2026-11-08 15:43:59 +01:00
Squid 6f5a115cff Fine tuned some dialogs, added some more color settings, enabled drag and drop for profiles and folders in settings
Moorly CI / windows-build (push) Successful in 2m49s
Moorly CI / linux-build (push) Successful in 3m34s
2026-11-08 14:30:13 +01:00
Squid 9fd5287ec7 Changed settings object widths to a more dynamic sizing
Moorly CI / windows-build (push) Successful in 2m53s
Moorly CI / linux-build (push) Successful in 3m35s
2026-11-08 13:11:42 +01:00
Squid a73668c4be Added custom border color
Moorly CI / windows-build (push) Successful in 2m47s
Moorly CI / linux-build (push) Successful in 3m33s
2026-11-08 13:06:43 +01:00
Squid 758486084e Added typography settings, enbeded JetBrains Mono font And Inter font into build
Moorly CI / windows-build (push) Successful in 2m45s
Moorly CI / linux-build (push) Successful in 3m35s
2026-11-08 13:02:23 +01:00
Squid df19d1dd5d Added shortcut into command palette command listings if there is a set shortcut for a specific command
Moorly CI / windows-build (push) Successful in 2m52s
Moorly CI / linux-build (push) Successful in 3m32s
2026-11-08 12:11:21 +01:00
Squid 2106c88868 Unified label sizes
Moorly CI / windows-build (push) Successful in 2m50s
Moorly CI / linux-build (push) Successful in 3m34s
2026-11-08 12:07:35 +01:00
Squid e8d6575ab3 Added + menu for opening terminal or ssh, shortcuts for the command. Command palette functionallity to type quick terminal/ssh
Moorly CI / windows-build (push) Successful in 2m51s
Moorly CI / linux-build (push) Successful in 3m38s
2026-11-08 11:52:19 +01:00
Squid c963558fff Updated how folders are created and can be created in current selected folder or use a droplist to select target for new folder
Moorly CI / windows-build (push) Successful in 2m46s
Moorly CI / linux-build (push) Successful in 3m34s
2026-11-08 11:22:59 +01:00
Squid db6f03c3b2 Updated folder structures to use UUID v4 for parent folder structure instead on folder name
Moorly CI / windows-build (push) Successful in 2m53s
Moorly CI / linux-build (push) Successful in 3m33s
2026-11-08 10:57:40 +01:00
Squid 2ec496691c Fixed folder moving in profiles, also show/hiding folders also hides sub folders
Moorly CI / windows-build (push) Successful in 2m49s
Moorly CI / linux-build (push) Successful in 3m34s
2026-11-07 23:48:35 +01:00
Squid 46b35567c5 Added abillity to edit profiles, Also color choice on the profile icon
Moorly CI / windows-build (push) Successful in 2m49s
Moorly CI / linux-build (push) Successful in 3m33s
2026-11-07 23:09:05 +01:00
Squid dadf0d5b4d Added a couple of commands to the palette functions.
Moorly CI / windows-build (push) Successful in 3m7s
Moorly CI / linux-build (push) Successful in 3m35s
2026-11-07 22:31:09 +01:00
Squid e4f6afada9 Added a dummy command palette function
Moorly CI / windows-build (push) Successful in 2m53s
Moorly CI / linux-build (push) Successful in 3m32s
2026-11-07 21:36:15 +01:00
Squid b1e5dd8432 Removed buttons from start tab. Added cogwheel to settings button and menu
Moorly CI / windows-build (push) Successful in 2m47s
Moorly CI / linux-build (push) Successful in 3m34s
2026-11-07 20:48:06 +01:00
Squid eef4a7a34e Added delete/restore for profiles and folders
Moorly CI / windows-build (push) Successful in 2m58s
Moorly CI / linux-build (push) Successful in 3m36s
2026-11-07 20:34:40 +01:00
Squid 02b8ce7ebd Added folder handling in profiles
Moorly CI / windows-build (push) Successful in 2m48s
Moorly CI / linux-build (push) Successful in 3m32s
2026-11-07 19:19:04 +01:00
Squid 0d48e332a9 Added error handling for missing theme files. Added debug config file usage in a debug build
Moorly CI / windows-build (push) Successful in 3m6s
Moorly CI / linux-build (push) Successful in 3m35s
2026-11-07 18:25:40 +01:00
Squid 348b47d9c6 Added reordering tabs, move tabs to new windows, to other windows
Moorly CI / windows-build (push) Successful in 2m48s
Moorly CI / linux-build (push) Successful in 3m31s
2026-11-06 23:30:51 +01:00
Squid c2f9580eea Added scrollable view in the theme customization
Moorly CI / windows-build (push) Successful in 2m50s
Moorly CI / linux-build (push) Successful in 3m32s
2026-11-06 22:53:18 +01:00
Squid 891bb85d92 Added a toaster system, and custom theme coloring for toasters
Moorly CI / windows-build (push) Successful in 2m47s
Moorly CI / linux-build (push) Successful in 3m32s
2026-11-06 22:39:33 +01:00
Squid 8d9f4584dd Added a default restore button for shortcuts
Moorly CI / windows-build (push) Successful in 2m47s
Moorly CI / linux-build (push) Successful in 3m28s
2026-11-06 22:16:45 +01:00
Squid 2e1248d7df Updated the config handling, all in one TOML
Moorly CI / windows-build (push) Successful in 3m5s
Moorly CI / linux-build (push) Successful in 3m35s
2026-11-06 22:14:33 +01:00
Squid 188e4f64d4 Added theme management, custom theme colors
Moorly CI / windows-build (push) Successful in 3m4s
Moorly CI / linux-build (push) Successful in 3m36s
2026-11-06 21:58:06 +01:00
Squid da752bcfd7 Redesigned the tabs and its colors, sizes and positions
Moorly CI / linux-build (push) Successful in 3m30s
Moorly CI / windows-build (push) Successful in 6m57s
2026-11-06 20:15:07 +01:00
Squid 0f442e84e5 Added setting for fade in/out settings tabs
Moorly CI / linux-build (push) Successful in 3m28s
Moorly CI / windows-build (push) Successful in 3m30s
2026-11-04 22:10:46 +01:00
Squid 2deea1d69f Added a start tab, and a setting to enable/disable it to show at startup
Moorly CI / windows-build (push) Successful in 2m40s
Moorly CI / linux-build (push) Successful in 3m23s
2026-11-04 21:30:42 +01:00
Squid e1d234144f Replaced < with a glyph on submenues in the hamburger menu
Moorly CI / windows-build (push) Successful in 2m45s
Moorly CI / linux-build (push) Successful in 3m23s
2026-11-04 21:04:37 +01:00
Squid 1caf2924c5 Added artifact upload
Moorly CI / windows-build (push) Successful in 2m47s
Moorly CI / linux-build (push) Successful in 3m25s
2026-11-04 19:48:34 +01:00
Squid 9d3accc5d5 Linux gitea runner builder
Moorly CI / windows-build (push) Successful in 3m21s
Moorly CI / linux-build (push) Successful in 3m46s
2026-11-04 19:40:51 +01:00
Squid 920cb7cc38 Gitea runner config
Moorly CI / windows-build (push) Successful in 7m41s
2026-11-03 22:16:33 +01:00
148 changed files with 59016 additions and 620 deletions

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
name: Moorly CI
on:
push:
branches:
- dev
workflow_dispatch:
jobs:
windows-build:
runs-on: windows-x64
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Build Moorly
shell: powershell
run: cargo build --release
- name: Upload Windows build
uses: actions/upload-artifact@v4
with:
name: moorly-windows
path: target/release/moorly.exe
if-no-files-found: error
retention-days: 14
linux-build:
runs-on: linux-x64
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Build Moorly
run: cargo build --release
- name: Upload Linux build
uses: actions/upload-artifact@v4
with:
name: moorly-linux
path: target/release/moorly
if-no-files-found: error
retention-days: 14
Generated
+679 -60
View File
File diff suppressed because it is too large. Load diff
+38 -1
View File
@@ -4,7 +4,44 @@ version = "0.1.0"
edition = "2024"
[dependencies]
iced = "0.14.0"
iced = { version = "0.14.0", features = ["tokio", "advanced"] }
iced_aw = { path = "vendor/iced_aw", default-features = false, features = ["color_picker"] }
instance-handoff = "=0.1.0-alpha.2"
num-format = "0.4"
png = "0.18"
regex = "1"
russh = "0.65.0"
russh-sftp = "3.0.1"
serde = { version = "1.0.229", features = ["derive"] }
sys-locale = "0.3"
tokio = { version = "1.54.1", features = ["full"] }
toml = "0.8"
ttf-parser = "0.25"
uuid = { version = "1.29.0", features = ["v4"] }
vt100 = "0.18.1"
[target.'cfg(unix)'.dependencies]
nix = { version = "0.31.3", features = ["term", "process", "signal", "fs"] }
[target.'cfg(any(target_os = "linux", target_os = "windows"))'.dependencies]
global-hotkey = "0.9.0"
[target.'cfg(target_os = "linux")'.dependencies]
ashpd = { version = "0.14.0", features = ["global_shortcuts"] }
tray-icon = { version = "0.26.1", default-features = false, features = ["ksni"] }
[target.'cfg(windows)'.dependencies]
tray-icon = { version = "0.26.1", default-features = false }
windows-sys = { version = "0.61.2", features = [
"Win32_Foundation",
"Win32_Security",
"Win32_System_Console",
"Win32_System_Pipes",
"Win32_System_Threading",
] }
[build-dependencies]
winresource = "0.1"
[dev-dependencies]
iced_test = "0.14"
+1 -1
View File
@@ -1,3 +1,3 @@
# Moorly
A cross-platform SSH and terminal client for Linux and Windows, featuring SSH password and key authentication (local key files and SSH agents), interactive and non-interactive command execution, SFTP file transfers, and native PowerShell support on Windows.
A cross-platform SSH and terminal client for Linux and Windows, featuring SSH password and key authentication (local key files and SSH agents), interactive and non-interactive command execution, SFTP file transfers, and native PowerShell support on Linux and Windows.
+10
View File
@@ -0,0 +1,10 @@
[Desktop Entry]
Type=Application
Name=Moorly
Comment=SSH and terminal client
Exec=moorly
Icon=dev.moorly.Moorly
Terminal=false
Categories=Network;Utility;TerminalEmulator;
StartupNotify=true
StartupWMClass=Moorly
Binary file not shown.
+93
View File
@@ -0,0 +1,93 @@
Copyright 2020 The Inter Project Authors (https://github.com/rsms/inter)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+93
View File
@@ -0,0 +1,93 @@
Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 300 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 300 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 143 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

+15
View File
@@ -0,0 +1,15 @@
fn main() {
println!("cargo:rerun-if-changed=assets/icons/ico/moorly.ico");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut resource = winresource::WindowsResource::new();
resource.set_icon("assets/icons/ico/moorly.ico");
resource.set("ProductName", "Moorly");
resource.set("FileDescription", "Moorly");
resource
.compile()
.expect("failed to embed the Windows icon resource");
}
+123
View File
@@ -0,0 +1,123 @@
//! Login autostart integration.
//!
//! Linux uses an XDG autostart entry, Windows a script in `shell:startup`.
//! Both use a stable file name and only ever touch that one file.
/// Stable name of our XDG autostart entry.
#[cfg(target_os = "linux")]
pub const LINUX_FILE: &str = "dev.moorly.Moorly.desktop";
/// Stable name of our Windows startup script.
#[cfg(windows)]
pub const WINDOWS_FILE: &str = "Moorly.cmd";
#[cfg(target_os = "linux")]
fn entry_path() -> Option<std::path::PathBuf> {
let config = std::env::var_os("XDG_CONFIG_HOME")
.map(std::path::PathBuf::from)
.or_else(|| {
std::env::var_os("HOME").map(|home| std::path::PathBuf::from(home).join(".config"))
})?;
Some(config.join("autostart").join(LINUX_FILE))
}
#[cfg(windows)]
fn entry_path() -> Option<std::path::PathBuf> {
let appdata = std::env::var_os("APPDATA").map(std::path::PathBuf::from)?;
Some(
appdata
.join("Microsoft")
.join("Windows")
.join("Start Menu")
.join("Programs")
.join("Startup")
.join(WINDOWS_FILE),
)
}
#[cfg(not(any(target_os = "linux", windows)))]
fn entry_path() -> Option<std::path::PathBuf> {
None
}
/// Whether our autostart entry exists.
pub fn enabled() -> bool {
entry_path().is_some_and(|path| path.is_file())
}
/// Creates or refreshes our autostart entry.
pub fn enable() -> Result<(), String> {
let path = entry_path()
.ok_or_else(|| "Autostart at login is only supported on Linux and Windows.".to_owned())?;
let executable = std::env::current_exe()
.map_err(|error| format!("Could not find the Moorly executable: {error}"))?;
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)
.map_err(|error| format!("Could not create the autostart folder: {error}"))?;
}
std::fs::write(&path, entry_contents(&executable))
.map_err(|error| format!("Could not write the autostart entry: {error}"))?;
#[cfg(target_os = "linux")]
crate::icons::refresh_linux_caches();
Ok(())
}
/// Removes our autostart entry, leaving every other entry untouched.
pub fn disable() -> Result<(), String> {
let Some(path) = entry_path() else {
return Ok(());
};
match std::fs::remove_file(&path) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(format!("Could not remove the autostart entry: {error}")),
}
}
#[cfg(target_os = "linux")]
fn entry_contents(executable: &std::path::Path) -> String {
let executable = executable.display().to_string();
let executable = executable.replace('\\', "\\\\").replace('"', "\\\"");
format!(
"[Desktop Entry]\n\
Type=Application\n\
Name=Moorly\n\
Comment=SSH and terminal client\n\
Exec=\"{executable}\"\n\
Icon=dev.moorly.Moorly\n\
Terminal=false\n\
Categories=Network;Utility;TerminalEmulator;\n\
StartupNotify=true\n\
StartupWMClass=Moorly\n\
X-Moorly-Generated=true\n"
)
}
#[cfg(windows)]
fn entry_contents(executable: &std::path::Path) -> String {
format!("@echo off\r\nstart \"\" \"{}\"\r\n", executable.display())
}
#[cfg(not(any(target_os = "linux", windows)))]
fn entry_contents(_executable: &std::path::Path) -> String {
String::new()
}
#[cfg(all(test, target_os = "linux"))]
mod tests {
#[test]
fn entry_is_marked_as_ours() {
let entry = super::entry_contents(std::path::Path::new("/usr/bin/moorly"));
assert!(entry.contains("Exec=\"/usr/bin/moorly\""));
assert!(entry.contains("Icon=dev.moorly.Moorly"));
assert!(entry.contains("X-Moorly-Generated=true"));
}
}
+908
View File
@@ -0,0 +1,908 @@
//! System-wide keyboard shortcuts.
//!
//! `global-hotkey` covers Windows and Linux X11. Linux Wayland uses the
//! XDG GlobalShortcuts portal through `ashpd`; it never grabs input directly.
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, RwLock};
use iced::Subscription;
use iced::futures::StreamExt;
use iced::futures::stream::{self, BoxStream};
use tokio::sync::broadcast;
#[cfg(any(target_os = "linux", target_os = "windows"))]
use global_hotkey::hotkey::HotKey;
#[cfg(any(target_os = "linux", target_os = "windows"))]
use global_hotkey::{GlobalHotKeyEvent, GlobalHotKeyManager, HotKeyState};
/// Stable desktop identity used when registering with the portal.
#[cfg(target_os = "linux")]
pub const APP_ID: &str = "dev.moorly.Moorly";
/// Actions exposed as global shortcuts. The IDs are persisted by desktop
/// environments, so they must not change.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Action {
ToggleWindowVisibility,
OpenCommandPalette,
}
impl Action {
pub const ALL: [Self; 2] = [Self::ToggleWindowVisibility, Self::OpenCommandPalette];
pub fn id(self) -> &'static str {
match self {
Self::ToggleWindowVisibility => "toggle_window_visibility",
Self::OpenCommandPalette => "open_command_palette",
}
}
pub fn description(self) -> &'static str {
match self {
Self::ToggleWindowVisibility => "Show or hide Moorly",
Self::OpenCommandPalette => "Open the Moorly command palette",
}
}
#[cfg(target_os = "linux")]
pub fn default_trigger(self) -> &'static str {
match self {
Self::ToggleWindowVisibility => "Ctrl+Space",
Self::OpenCommandPalette => "Ctrl+Shift+Space",
}
}
#[cfg(target_os = "linux")]
pub fn from_id(id: &str) -> Option<Self> {
Self::ALL.into_iter().find(|action| action.id() == id)
}
}
/// The backend selected for the current session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Backend {
/// Native implementation from `global-hotkey` (Windows / X11).
Native,
/// XDG GlobalShortcuts portal (Wayland).
Portal,
/// No safe implementation is available in this session.
Unsupported,
}
/// Result of trying to register one action.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Status {
Registered,
Disabled,
Unavailable(String),
}
/// Events delivered to the Iced application loop.
#[derive(Debug, Clone)]
pub enum Event {
Activated(Action),
Status {
action: Action,
status: Status,
},
/// The portal reports a new trigger description after the user changed a
/// shortcut in the desktop environment.
#[allow(dead_code)] // Only constructed by the Linux portal backend.
ShortcutChanged {
action: Action,
trigger: Option<String>,
},
/// The selected backend could not be used at all.
BackendUnavailable(String),
}
/// One action and the preferred trigger configured by Moorly.
#[derive(Debug, Clone)]
pub struct Binding {
pub action: Action,
pub trigger: Option<String>,
}
#[derive(Clone)]
struct Shared {
events: broadcast::Sender<Event>,
statuses: Arc<Mutex<HashMap<Action, Status>>>,
revision: Arc<AtomicU64>,
}
impl Shared {
fn send(&self, event: Event) {
let _ = self.events.send(event);
}
fn set_status(&self, action: Action, status: Status) {
let changed = {
let mut statuses = self.statuses.lock().unwrap();
if statuses.get(&action) == Some(&status) {
false
} else {
statuses.insert(action, status.clone());
true
}
};
if changed {
self.revision.fetch_add(1, Ordering::SeqCst);
self.send(Event::Status { action, status });
}
}
fn backend_unavailable(&self, reason: String) {
{
let mut statuses = self.statuses.lock().unwrap();
for action in Action::ALL {
statuses.insert(action, Status::Unavailable(reason.clone()));
}
}
self.revision.fetch_add(1, Ordering::SeqCst);
self.send(Event::BackendUnavailable(reason));
}
fn status_events(&self) -> Vec<Event> {
let statuses = self.statuses.lock().unwrap();
Action::ALL
.into_iter()
.filter_map(|action| {
statuses.get(&action).map(|status| Event::Status {
action,
status: status.clone(),
})
})
.collect()
}
}
struct Service {
backend: Backend,
shared: Shared,
#[cfg(any(target_os = "linux", target_os = "windows"))]
native: Option<Mutex<Native>>,
#[cfg(target_os = "linux")]
portal: Option<PortalHandle>,
}
static SERVICE: OnceLock<Service> = OnceLock::new();
/// Starts the service once. Later calls only return the selected backend.
pub fn start(bindings: Vec<Binding>) -> Backend {
if let Some(service) = SERVICE.get() {
return service.backend;
}
let (events, _) = broadcast::channel(64);
let shared = Shared {
events,
statuses: Arc::new(Mutex::new(HashMap::new())),
revision: Arc::new(AtomicU64::new(0)),
};
let mut backend = detect_backend();
#[cfg(any(target_os = "linux", target_os = "windows"))]
let mut native = None;
#[cfg(target_os = "linux")]
let mut portal = None;
match backend {
Backend::Native => {
#[cfg(any(target_os = "linux", target_os = "windows"))]
match Native::new(shared.clone()) {
Ok(mut manager) => {
manager.apply(&shared, &bindings);
native = Some(Mutex::new(manager));
}
Err(reason) => {
shared.backend_unavailable(reason);
backend = Backend::Unsupported;
}
}
#[cfg(not(any(target_os = "linux", target_os = "windows")))]
{
shared.backend_unavailable(
"Native global shortcuts are not available on this platform.".to_owned(),
);
backend = Backend::Unsupported;
}
}
Backend::Portal => {
#[cfg(target_os = "linux")]
{
// Preferred triggers are only suggestions to the portal; the
// desktop environment owns the persisted binding. Use the
// documented defaults instead of Moorly's local settings so
// restarting never rewrites a user's portal configuration.
let bindings = bindings
.into_iter()
.map(|binding| Binding {
action: binding.action,
trigger: binding
.trigger
.map(|_| binding.action.default_trigger().to_owned()),
})
.collect();
match start_portal(shared.clone(), bindings) {
Some(handle) => portal = Some(handle),
None => {
shared.backend_unavailable(
"Could not start the XDG GlobalShortcuts portal worker.".to_owned(),
);
backend = Backend::Unsupported;
}
}
}
#[cfg(not(target_os = "linux"))]
{
shared.backend_unavailable(
"The XDG GlobalShortcuts portal is only available on Linux.".to_owned(),
);
backend = Backend::Unsupported;
}
}
Backend::Unsupported => {
shared.backend_unavailable(unsupported_reason());
}
}
let service = Service {
backend,
shared,
#[cfg(any(target_os = "linux", target_os = "windows"))]
native,
#[cfg(target_os = "linux")]
portal,
};
let _ = SERVICE.set(service);
backend
}
pub fn backend() -> Backend {
SERVICE
.get()
.map(|service| service.backend)
.unwrap_or(Backend::Unsupported)
}
/// Changes whenever a registration status changes. Used as subscription data
/// so Iced re-evaluates dependent subscriptions.
pub fn revision() -> u64 {
SERVICE
.get()
.map(|service| service.shared.revision.load(Ordering::SeqCst))
.unwrap_or(0)
}
pub fn is_registered(action: Action) -> bool {
SERVICE
.get()
.and_then(|service| service.shared.statuses.lock().ok()?.get(&action).cloned())
.is_some_and(|status| status == Status::Registered)
}
/// Applies new triggers to a Moorly-managed backend. Portal shortcuts are
/// managed by the desktop environment and are intentionally left untouched.
pub fn set_bindings(bindings: Vec<Binding>) {
let Some(service) = SERVICE.get() else {
return;
};
#[cfg(any(target_os = "linux", target_os = "windows"))]
if let Some(native) = &service.native
&& let Ok(mut manager) = native.lock()
{
manager.apply(&service.shared, &bindings);
}
#[cfg(target_os = "linux")]
let _ = (&service.portal, bindings);
#[cfg(not(target_os = "linux"))]
let _ = (service, bindings);
}
/// Releases registrations before the process exits.
pub fn shutdown() {
let Some(service) = SERVICE.get() else {
return;
};
#[cfg(any(target_os = "linux", target_os = "windows"))]
if let Some(native) = &service.native
&& let Ok(mut manager) = native.lock()
{
manager.shutdown();
}
#[cfg(target_os = "linux")]
if let Some(portal) = &service.portal {
portal.shutdown();
}
}
pub fn subscription() -> Subscription<Event> {
Subscription::run(event_stream)
}
fn event_stream() -> BoxStream<'static, Event> {
let Some(service) = SERVICE.get() else {
return stream::pending().boxed();
};
// Subscribe before taking the snapshot so no status can fall between the
// two. Duplicates are harmless and the app deduplicates notifications.
let receiver = service.shared.events.subscribe();
let snapshot = service.shared.status_events();
stream::iter(snapshot)
.chain(stream::unfold(receiver, |mut receiver| async move {
loop {
match receiver.recv().await {
Ok(event) => return Some((event, receiver)),
Err(broadcast::error::RecvError::Lagged(_)) => continue,
Err(broadcast::error::RecvError::Closed) => return None,
}
}
}))
.boxed()
}
fn detect_backend() -> Backend {
#[cfg(target_os = "windows")]
{
Backend::Native
}
#[cfg(target_os = "linux")]
{
if is_wayland_session() {
Backend::Portal
} else if std::env::var_os("DISPLAY").is_some() {
Backend::Native
} else {
Backend::Unsupported
}
}
#[cfg(not(any(target_os = "linux", target_os = "windows")))]
{
Backend::Unsupported
}
}
#[cfg(target_os = "linux")]
pub(crate) fn is_wayland_session() -> bool {
std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE")
.is_ok_and(|session| session.eq_ignore_ascii_case("wayland"))
}
fn unsupported_reason() -> String {
#[cfg(target_os = "linux")]
{
"No display server was detected. Global shortcuts are unavailable.".to_owned()
}
#[cfg(not(target_os = "linux"))]
{
"Global shortcuts are not supported on this platform.".to_owned()
}
}
/// Makes the application discoverable by the portal on systems where Moorly
/// was not installed through a package manager. Existing entries are never
/// overwritten.
#[cfg(target_os = "linux")]
fn ensure_desktop_entry() {
let Some(data_dir) = std::env::var_os("XDG_DATA_HOME")
.map(std::path::PathBuf::from)
.or_else(|| {
std::env::var_os("HOME").map(|home| std::path::PathBuf::from(home).join(".local/share"))
})
else {
return;
};
let applications = data_dir.join("applications");
let path = applications.join(format!("{APP_ID}.desktop"));
let existing = std::fs::read_to_string(&path).ok();
if let Some(existing) = &existing
&& !existing.contains("X-Moorly-Generated=true")
{
// A packaged entry (or the user's own entry) is authoritative.
return;
}
let Ok(executable) = std::env::current_exe() else {
return;
};
let executable = executable.display().to_string();
let executable = executable.replace('\\', "\\\\").replace('"', "\\\"");
let entry = format!(
"[Desktop Entry]\n\
Type=Application\n\
Name=Moorly\n\
Comment=SSH and terminal client\n\
Exec=\"{executable}\"\n\
Icon=dev.moorly.Moorly\n\
Terminal=false\n\
Categories=Network;Utility;TerminalEmulator;\n\
StartupNotify=true\n\
StartupWMClass=Moorly\n\
X-Moorly-Generated=true\n"
);
if existing.as_deref() == Some(entry.as_str()) {
return;
}
if std::fs::create_dir_all(&applications).is_ok() && std::fs::write(path, entry).is_ok() {
crate::icons::refresh_linux_caches();
}
}
/// XKB keysym name used by the XDG shortcuts specification.
#[cfg(target_os = "linux")]
fn portal_trigger(trigger: &str) -> Option<String> {
let mut parts = trigger
.split('+')
.map(str::trim)
.filter(|part| !part.is_empty())
.collect::<Vec<_>>();
let key = parts.pop()?;
let key = match key.to_ascii_lowercase().as_str() {
"space" => "space".to_owned(),
"enter" | "return" => "Return".to_owned(),
"escape" | "esc" => "Escape".to_owned(),
"tab" => "Tab".to_owned(),
"," => "comma".to_owned(),
"." => "period".to_owned(),
";" => "semicolon".to_owned(),
"'" => "apostrophe".to_owned(),
"/" => "slash".to_owned(),
"\\" => "backslash".to_owned(),
"[" => "bracketleft".to_owned(),
"]" => "bracketright".to_owned(),
"-" => "minus".to_owned(),
"=" => "equal".to_owned(),
"`" => "grave".to_owned(),
key if key.chars().count() == 1 && key.chars().all(|c| c.is_ascii_alphanumeric()) => {
key.to_ascii_lowercase()
}
_ => return None,
};
let mut output = Vec::new();
for modifier in parts {
output.push(match modifier.to_ascii_lowercase().as_str() {
"ctrl" | "control" => "CTRL".to_owned(),
"shift" => "SHIFT".to_owned(),
"alt" => "ALT".to_owned(),
"super" | "meta" | "win" => "LOGO".to_owned(),
_ => return None,
});
}
output.push(key);
Some(output.join("+"))
}
#[cfg(any(target_os = "linux", target_os = "windows"))]
struct Native {
manager: GlobalHotKeyManager,
registered: HashMap<Action, HotKey>,
ids: Arc<RwLock<HashMap<u32, Action>>>,
stop: Arc<AtomicBool>,
thread: Option<std::thread::JoinHandle<()>>,
}
// The manager is only accessed through the Mutex above. Windows requires the
// manager to be created on the same thread as the Win32 event loop (Iced's
// main thread), but registration is safe to call through its window handle.
#[cfg(any(target_os = "linux", target_os = "windows"))]
unsafe impl Send for Native {}
#[cfg(any(target_os = "linux", target_os = "windows"))]
unsafe impl Sync for Native {}
#[cfg(any(target_os = "linux", target_os = "windows"))]
impl Native {
fn new(shared: Shared) -> Result<Self, String> {
let manager = GlobalHotKeyManager::new()
.map_err(|error| format!("Could not start global hotkeys: {error}"))?;
let ids = Arc::new(RwLock::new(HashMap::new()));
let stop = Arc::new(AtomicBool::new(false));
let receiver = GlobalHotKeyEvent::receiver().clone();
let event_ids = ids.clone();
let events = shared.events.clone();
let thread_stop = stop.clone();
let thread = std::thread::Builder::new()
.name("moorly-global-hotkeys".to_owned())
.spawn(move || {
while !thread_stop.load(Ordering::Relaxed) {
let Ok(event) = receiver.recv_timeout(std::time::Duration::from_millis(250))
else {
continue;
};
if event.state != HotKeyState::Pressed {
continue;
}
let action = event_ids
.read()
.ok()
.and_then(|ids| ids.get(&event.id).copied());
if let Some(action) = action {
let _ = events.send(Event::Activated(action));
}
}
})
.map_err(|error| format!("Could not start the global hotkey listener: {error}"))?;
Ok(Self {
manager,
registered: HashMap::new(),
ids,
stop,
thread: Some(thread),
})
}
fn apply(&mut self, shared: &Shared, bindings: &[Binding]) {
for (_, hotkey) in self.registered.drain() {
let _ = self.manager.unregister(hotkey);
}
if let Ok(mut ids) = self.ids.write() {
ids.clear();
}
for binding in bindings {
let Some(trigger) = binding
.trigger
.as_deref()
.filter(|trigger| !trigger.is_empty())
else {
shared.set_status(binding.action, Status::Disabled);
continue;
};
let hotkey = match trigger.parse::<HotKey>() {
Ok(hotkey) => hotkey,
Err(error) => {
shared.set_status(
binding.action,
Status::Unavailable(format!("\"{trigger}\" is not supported: {error}")),
);
continue;
}
};
match self.manager.register(hotkey) {
Ok(()) => {
if let Ok(mut ids) = self.ids.write() {
ids.insert(hotkey.id(), binding.action);
}
self.registered.insert(binding.action, hotkey);
shared.set_status(binding.action, Status::Registered);
}
Err(error) => {
shared.set_status(
binding.action,
Status::Unavailable(format!(
"\"{trigger}\" could not be registered: {error}"
)),
);
}
}
}
}
fn shutdown(&mut self) {
self.stop.store(true, Ordering::Relaxed);
for (_, hotkey) in self.registered.drain() {
let _ = self.manager.unregister(hotkey);
}
if let Ok(mut ids) = self.ids.write() {
ids.clear();
}
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
#[cfg(target_os = "linux")]
enum PortalCommand {
Shutdown,
}
#[cfg(target_os = "linux")]
struct PortalHandle {
commands: tokio::sync::mpsc::UnboundedSender<PortalCommand>,
done: Mutex<std::sync::mpsc::Receiver<()>>,
}
#[cfg(target_os = "linux")]
impl PortalHandle {
fn shutdown(&self) {
// Wait briefly for the session to close. Never block the GUI for long:
// the worker may be waiting on a portal confirmation dialog.
let _ = self.commands.send(PortalCommand::Shutdown);
if let Ok(done) = self.done.lock() {
let _ = done.recv_timeout(std::time::Duration::from_millis(500));
}
}
}
#[cfg(target_os = "linux")]
fn start_portal(shared: Shared, bindings: Vec<Binding>) -> Option<PortalHandle> {
let (commands, receiver) = tokio::sync::mpsc::unbounded_channel();
let (done, done_receiver) = std::sync::mpsc::channel();
std::thread::Builder::new()
.name("moorly-portal-shortcuts".to_owned())
.spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build();
match runtime {
Ok(runtime) => {
runtime.block_on(portal_main(shared, bindings, receiver));
}
Err(error) => {
shared.backend_unavailable(format!(
"Could not start the portal shortcut worker: {error}"
));
}
}
let _ = done.send(());
})
.ok()?;
Some(PortalHandle {
commands,
done: Mutex::new(done_receiver),
})
}
#[cfg(target_os = "linux")]
async fn portal_main(
shared: Shared,
bindings: Vec<Binding>,
mut commands: tokio::sync::mpsc::UnboundedReceiver<PortalCommand>,
) {
if let Err(reason) = run_portal(&shared, &bindings, &mut commands).await {
shared.backend_unavailable(reason);
}
}
#[cfg(target_os = "linux")]
async fn run_portal(
shared: &Shared,
bindings: &[Binding],
commands: &mut tokio::sync::mpsc::UnboundedReceiver<PortalCommand>,
) -> Result<(), String> {
use ashpd::desktop::Session;
use ashpd::desktop::global_shortcuts::{GlobalShortcuts, ListShortcutsOptions, NewShortcut};
let connection = ashpd::zbus::Connection::session()
.await
.map_err(|error| format!("Could not connect to the session bus: {error}"))?;
if let Ok(app_id) = ashpd::AppID::try_from(APP_ID) {
// Host (non-Flatpak) applications need this so the portal can attach
// permissions to a stable application ID. It must use the same
// connection as the portal calls, because the registry maps the
// caller's bus connection to the app ID.
if !ashpd::is_sandboxed() {
ensure_desktop_entry();
}
// Older portal versions may not implement the registry. The portal's
// fallback identity still works, but cannot be pinned to our app ID.
let _ = ashpd::register_host_app_with_connection(connection.clone(), app_id).await;
}
let proxy = GlobalShortcuts::with_connection(connection)
.await
.map_err(|error| format!("XDG GlobalShortcuts portal is unavailable: {error}"))?;
let session: Session<GlobalShortcuts> = proxy
.create_session(Default::default())
.await
.map_err(|error| format!("Could not create a global shortcuts session: {error}"))?;
let mut activated = Box::pin(
proxy
.receive_activated()
.await
.map_err(|error| format!("Could not listen for shortcut activations: {error}"))?,
);
let mut changed = Box::pin(
proxy
.receive_shortcuts_changed()
.await
.map_err(|error| format!("Could not listen for desktop shortcut changes: {error}"))?,
);
let requested = bindings
.iter()
.filter_map(|binding| {
let trigger = binding.trigger.as_deref()?;
let trigger = portal_trigger(trigger)?;
Some(
NewShortcut::new(binding.action.id(), binding.action.description())
.preferred_trigger(Some(trigger.as_str())),
)
})
.collect::<Vec<_>>();
// KDE 6.3+ restores persisted shortcuts when the session is created.
// Ask for them first so a normal restart does not call BindShortcuts,
// which unconditionally opens the KDE shortcut configuration window.
let listed = proxy
.list_shortcuts(&session, ListShortcutsOptions::default())
.await
.ok()
.and_then(|request| request.response().ok())
.map(|response| response.shortcuts().to_vec())
.unwrap_or_default();
let known = bindings.iter().any(|binding| {
binding.trigger.is_some()
&& listed
.iter()
.any(|shortcut| shortcut.id() == binding.action.id())
});
let shortcuts = if requested.is_empty() || known {
listed
} else {
// First launch (or a portal that does not restore actions on session
// creation). This is the only call that may open a configuration UI.
let request = proxy
.bind_shortcuts(&session, &requested, None, Default::default())
.await
.map_err(|error| {
format!("The desktop environment rejected global shortcuts: {error}")
})?;
let response = request.response().map_err(|error| {
format!("The desktop environment rejected global shortcuts: {error}")
})?;
response.shortcuts().to_vec()
};
apply_portal_shortcuts(
shared,
bindings,
&shortcuts,
"The shortcut is not configured in the desktop environment.",
);
loop {
tokio::select! {
Some(event) = activated.next() => {
if let Some(action) = Action::from_id(event.shortcut_id()) {
shared.send(Event::Activated(action));
}
}
Some(event) = changed.next() => {
apply_portal_changes(shared, bindings, event.shortcuts());
}
Some(command) = commands.recv() => {
if matches!(command, PortalCommand::Shutdown) {
let _ = session.close().await;
return Ok(());
}
}
else => return Ok(()),
}
}
}
#[cfg(target_os = "linux")]
fn apply_portal_changes(
shared: &Shared,
bindings: &[Binding],
shortcuts: &[ashpd::desktop::global_shortcuts::Shortcut],
) {
apply_portal_shortcuts(
shared,
bindings,
shortcuts,
"The shortcut was removed in the desktop settings.",
);
}
#[cfg(target_os = "linux")]
fn apply_portal_shortcuts(
shared: &Shared,
bindings: &[Binding],
shortcuts: &[ashpd::desktop::global_shortcuts::Shortcut],
missing: &str,
) {
let known = shortcuts
.iter()
.map(|shortcut| (shortcut.id(), shortcut))
.collect::<HashMap<_, _>>();
for binding in bindings {
if binding.trigger.is_none() {
shared.set_status(binding.action, Status::Disabled);
continue;
}
match known.get(binding.action.id()) {
Some(shortcut) if shortcut.trigger_description().is_empty() => {
// The action exists but the user removed its key binding.
shared.set_status(binding.action, Status::Disabled);
}
Some(shortcut) => {
shared.set_status(binding.action, Status::Registered);
shared.send(Event::ShortcutChanged {
action: binding.action,
trigger: Some(shortcut.trigger_description().to_owned()),
});
}
None => shared.set_status(binding.action, Status::Unavailable(missing.to_owned())),
}
}
}
#[cfg(test)]
mod tests {
use super::{Action, portal_trigger};
#[test]
fn action_ids_and_defaults_are_stable() {
assert_eq!(
Action::ToggleWindowVisibility.id(),
"toggle_window_visibility"
);
assert_eq!(Action::OpenCommandPalette.id(), "open_command_palette");
assert_eq!(
Action::ToggleWindowVisibility.default_trigger(),
"Ctrl+Space"
);
assert_eq!(
Action::OpenCommandPalette.default_trigger(),
"Ctrl+Shift+Space"
);
assert_eq!(
Action::from_id("open_command_palette"),
Some(Action::OpenCommandPalette)
);
assert_eq!(Action::from_id("unknown"), None);
}
#[test]
fn portal_triggers_use_xkb_names() {
assert_eq!(portal_trigger("Ctrl+Space").as_deref(), Some("CTRL+space"));
assert_eq!(
portal_trigger("Ctrl+Shift+Space").as_deref(),
Some("CTRL+SHIFT+space")
);
assert_eq!(portal_trigger("Alt+,").as_deref(), Some("ALT+comma"));
assert_eq!(portal_trigger("Ctrl+NotAKey"), None);
}
}
+248
View File
@@ -0,0 +1,248 @@
//! Embedded application icon resources.
//!
//! The same PNGs feed the window icon, the system tray and the Linux hicolor
//! icon theme, so the binary never depends on an external image file.
use serde::{Deserialize, Serialize};
/// Color application logo, also used by the Linux desktop entry and tray.
pub const APP_ICON_PNG: &[u8] = include_bytes!("../assets/icons/color/moorly_logo_256x256.png");
/// Monochrome tray icon.
pub const TRAY_MONOCHROME_PNG: &[u8] =
include_bytes!("../assets/icons/monochrome/moorly_logo_monochrome_256x256.png");
/// Selected icon variant for the system tray.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TrayIconStyle {
#[default]
Color,
Monochrome,
}
impl TrayIconStyle {
pub const ALL: [Self; 2] = [Self::Color, Self::Monochrome];
pub fn label(self) -> &'static str {
match self {
Self::Color => "Color",
Self::Monochrome => "Monochrome",
}
}
fn png(self) -> &'static [u8] {
match self {
Self::Color => APP_ICON_PNG,
Self::Monochrome => TRAY_MONOCHROME_PNG,
}
}
}
/// Decoded RGBA icon for the system tray.
#[cfg(any(target_os = "linux", target_os = "windows"))]
pub fn tray_icon(style: TrayIconStyle) -> Result<tray_icon::Icon, String> {
let (rgba, width, height) = decode_rgba(style.png())?;
tray_icon::Icon::from_rgba(rgba, width, height)
.map_err(|error| format!("Could not create the system tray icon: {error}"))
}
/// Window and taskbar icon, decoded once per window from the embedded logo.
pub fn window_icon() -> Option<iced::window::Icon> {
let (rgba, width, height) = decode_rgba(APP_ICON_PNG).ok()?;
iced::window::icon::from_rgba(rgba, width, height).ok()
}
/// Makes the logo available under the XDG hicolor icon theme so the desktop
/// entry can resolve `Icon=dev.moorly.Moorly` from any working directory.
#[cfg(target_os = "linux")]
pub fn install_linux_icon() {
let Some(data_dir) = linux_data_dir() else {
return;
};
install_linux_icon_in(&data_dir);
// The icon may already exist from an older build, so always invalidate the
// icon and desktop caches instead of only doing it when the file changes.
refresh_linux_caches_in(&data_dir);
}
/// Refreshes the icon and desktop caches after a generated desktop entry
/// changed, without requiring a Plasma restart.
#[cfg(target_os = "linux")]
pub fn refresh_linux_caches() {
if let Some(data_dir) = linux_data_dir() {
refresh_linux_caches_in(&data_dir);
}
}
#[cfg(target_os = "linux")]
fn linux_data_dir() -> Option<std::path::PathBuf> {
std::env::var_os("XDG_DATA_HOME")
.map(std::path::PathBuf::from)
.or_else(|| {
std::env::var_os("HOME").map(|home| std::path::PathBuf::from(home).join(".local/share"))
})
}
#[cfg(target_os = "linux")]
fn install_linux_icon_in(data_dir: &std::path::Path) {
let path = data_dir
.join("icons")
.join("hicolor")
.join("256x256")
.join("apps")
.join(format!("{}.png", crate::hotkeys::APP_ID));
// Repair an icon left behind by an older build instead of keeping a stale
// monochrome or otherwise wrong image.
if std::fs::read(&path).is_ok_and(|current| current == APP_ICON_PNG) {
return;
}
if let Some(parent) = path.parent()
&& std::fs::create_dir_all(parent).is_ok()
{
let _ = std::fs::write(path, APP_ICON_PNG);
}
}
#[cfg(target_os = "linux")]
fn refresh_linux_caches_in(data_dir: &std::path::Path) {
let hicolor = data_dir.join("icons").join("hicolor");
if hicolor.is_dir() {
// xdg-icon-resource uses the same trick to make icon loaders notice
// directory changes.
let dummy = hicolor.join(".xdg-icon-resource-dummy");
let _ = std::fs::write(&dummy, []);
let _ = std::fs::remove_file(dummy);
if hicolor.join("icon-theme.cache").is_file() {
let _ = spawn_cache_command(
"gtk-update-icon-cache",
&[
std::ffi::OsStr::new("-f"),
std::ffi::OsStr::new("-t"),
std::ffi::OsStr::new("-q"),
hicolor.as_os_str(),
],
);
}
}
if std::env::var_os("KDE_FULL_SESSION").is_some()
|| std::env::var("XDG_CURRENT_DESKTOP").is_ok_and(|desktop| desktop.contains("KDE"))
{
let rebuild =
spawn_cache_command("kbuildsycoca6", &[std::ffi::OsStr::new("--noincremental")]);
if rebuild.is_err() {
let _ =
spawn_cache_command("kbuildsycoca5", &[std::ffi::OsStr::new("--noincremental")]);
}
}
}
#[cfg(target_os = "linux")]
fn spawn_cache_command(
program: &str,
args: &[&std::ffi::OsStr],
) -> std::io::Result<std::process::Child> {
std::process::Command::new(program)
.args(args)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
}
fn decode_rgba(bytes: &[u8]) -> Result<(Vec<u8>, u32, u32), String> {
let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = decoder
.read_info()
.map_err(|error| format!("Could not read the icon: {error}"))?;
let mut buffer = vec![
0;
reader
.output_buffer_size()
.ok_or_else(|| "The icon dimensions are invalid.".to_owned())?
];
let info = reader
.next_frame(&mut buffer)
.map_err(|error| format!("Could not decode the icon: {error}"))?;
buffer.truncate(info.buffer_size());
let rgba = match info.color_type {
png::ColorType::Rgba => buffer,
png::ColorType::Rgb => buffer
.chunks_exact(3)
.flat_map(|pixel| [pixel[0], pixel[1], pixel[2], u8::MAX])
.collect(),
png::ColorType::Grayscale => buffer
.into_iter()
.flat_map(|value| [value, value, value, u8::MAX])
.collect(),
png::ColorType::GrayscaleAlpha => buffer
.chunks_exact(2)
.flat_map(|pixel| [pixel[0], pixel[0], pixel[0], pixel[1]])
.collect(),
png::ColorType::Indexed => {
return Err("The icon could not be expanded to RGBA.".to_owned());
}
};
Ok((rgba, info.width, info.height))
}
#[cfg(test)]
mod tests {
use super::{TrayIconStyle, decode_rgba};
#[test]
fn embedded_tray_icons_decode_to_rgba() {
for style in TrayIconStyle::ALL {
let (rgba, width, height) = decode_rgba(style.png()).unwrap();
assert_eq!((width, height), (256, 256));
assert_eq!(rgba.len(), 256 * 256 * 4);
}
assert_eq!(TrayIconStyle::Color.png(), super::APP_ICON_PNG);
assert_eq!(TrayIconStyle::Monochrome.png(), super::TRAY_MONOCHROME_PNG);
}
#[test]
fn window_icon_is_always_the_color_logo() {
let (rgba, size) = super::window_icon().unwrap().into_raw();
let (expected, width, height) = decode_rgba(super::APP_ICON_PNG).unwrap();
assert_eq!(rgba, expected);
assert_eq!(size, iced::Size::new(width, height));
}
#[cfg(target_os = "linux")]
#[test]
fn linux_icon_is_installed_under_hicolor() {
let data = std::env::temp_dir().join(format!("moorly-icon-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&data);
super::install_linux_icon_in(&data);
let icon = data
.join("icons/hicolor/256x256/apps")
.join(format!("{}.png", crate::hotkeys::APP_ID));
assert!(icon.is_file());
assert_eq!(std::fs::read(&icon).unwrap(), super::APP_ICON_PNG);
// An older build may have left the wrong variant in place.
std::fs::write(&icon, super::TRAY_MONOCHROME_PNG).unwrap();
super::install_linux_icon_in(&data);
assert_eq!(std::fs::read(icon).unwrap(), super::APP_ICON_PNG);
let _ = std::fs::remove_dir_all(data);
}
}
+15042 -497
View File
File diff suppressed because it is too large. Load diff
+495
View File
@@ -0,0 +1,495 @@
//! Reusable in-app notification manager and toast rendering.
//!
//! The manager owns notification state independently from the widgets that
//! render it, so it can later be shared by more than one window.
use std::time::Duration;
use iced::time::Instant;
use iced::widget::{button, column, container, opaque, responsive, row, scrollable, text};
use iced::{Alignment, Border, Color, Element, Length, Shadow, Theme, Vector};
/// Default lifetime of a timed notification.
pub const DEFAULT_DURATION: Duration = Duration::from_secs(5);
const FADE_IN: Duration = Duration::from_millis(160);
const FADE_OUT: Duration = Duration::from_millis(140);
const MAX_WIDTH: f32 = 340.0;
const MARGIN: f32 = 16.0;
const SPACING: f32 = 8.0;
/// Colors used to render toasts. The defaults follow the active iced theme;
/// a theme can override every field.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ToastColors {
pub background: Color,
pub text: Color,
pub title: Color,
pub border: Color,
pub info: Color,
pub success: Color,
pub warning: Color,
pub error: Color,
pub dismiss: Color,
}
impl ToastColors {
pub fn default_for(theme: &Theme) -> Self {
let palette = theme.extended_palette();
Self {
background: mix(
palette.background.weak.color,
palette.primary.base.color,
0.06,
),
text: palette.background.weak.text,
title: palette.background.weak.text,
border: palette.background.strong.color,
info: palette.primary.base.color,
success: palette.success.base.color,
warning: palette.warning.base.color,
error: palette.danger.base.color,
dismiss: palette.background.weak.text,
}
}
pub fn as_array(self) -> [Color; 9] {
[
self.background,
self.text,
self.title,
self.border,
self.info,
self.success,
self.warning,
self.error,
self.dismiss,
]
}
pub fn from_array(colors: [Color; 9]) -> Self {
Self {
background: colors[0],
text: colors[1],
title: colors[2],
border: colors[3],
info: colors[4],
success: colors[5],
warning: colors[6],
error: colors[7],
dismiss: colors[8],
}
}
}
/// Unique identifier for a notification within a manager.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NotificationId(u64);
/// The four supported notification severities.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotificationKind {
Info,
Success,
Warning,
Error,
}
impl NotificationKind {
fn icon(self) -> &'static str {
match self {
Self::Info => "ℹ",
Self::Success => "✓",
Self::Warning => "⚠",
Self::Error => "✕",
}
}
fn accent(self, colors: ToastColors) -> Color {
match self {
Self::Info => colors.info,
Self::Success => colors.success,
Self::Warning => colors.warning,
Self::Error => colors.error,
}
}
}
/// How long a notification stays visible.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotificationLifetime {
Timed(Duration),
Persistent,
}
impl Default for NotificationLifetime {
fn default() -> Self {
Self::Timed(DEFAULT_DURATION)
}
}
/// A single notification. Create it with [`Notification::new`] and configure
/// it with the builder methods before handing it to a manager.
#[derive(Debug, Clone)]
pub struct Notification {
id: NotificationId,
kind: NotificationKind,
title: Option<String>,
message: String,
lifetime: NotificationLifetime,
born: Instant,
closing: Option<Instant>,
}
impl Notification {
pub fn new(kind: NotificationKind, message: impl Into<String>) -> Self {
Self {
id: NotificationId(0),
kind,
title: None,
message: message.into(),
lifetime: NotificationLifetime::default(),
born: Instant::now(),
closing: None,
}
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn persistent(mut self) -> Self {
self.lifetime = NotificationLifetime::Persistent;
self
}
pub fn timed(mut self, duration: Duration) -> Self {
self.lifetime = NotificationLifetime::Timed(duration);
self
}
fn expires_at(&self) -> Option<Instant> {
match self.lifetime {
NotificationLifetime::Timed(duration) => Some(self.born + duration),
NotificationLifetime::Persistent => None,
}
}
fn opacity(&self, now: Instant) -> f32 {
let fade_in = (now.saturating_duration_since(self.born).as_secs_f32()
/ FADE_IN.as_secs_f32())
.clamp(0.0, 1.0);
let fade_out = self
.closing
.map(|at| {
1.0 - (now.saturating_duration_since(at).as_secs_f32() / FADE_OUT.as_secs_f32())
.clamp(0.0, 1.0)
})
.unwrap_or(1.0);
fade_in.min(fade_out)
}
fn is_finished(&self, now: Instant) -> bool {
self.closing
.is_some_and(|at| now.saturating_duration_since(at) >= FADE_OUT)
}
}
/// Owns all live notifications. New entries are inserted at the top.
#[derive(Debug)]
pub struct NotificationManager {
next_id: u64,
notifications: Vec<Notification>,
}
impl Default for NotificationManager {
fn default() -> Self {
Self {
next_id: 1,
notifications: Vec::new(),
}
}
}
impl NotificationManager {
pub fn add(&mut self, notification: Notification) -> NotificationId {
self.add_at(Instant::now(), notification)
}
fn add_at(&mut self, now: Instant, mut notification: Notification) -> NotificationId {
let id = NotificationId(self.next_id);
self.next_id = self.next_id.saturating_add(1);
notification.id = id;
notification.born = now;
notification.closing = None;
self.notifications.insert(0, notification);
id
}
/// Starts dismissing a notification; it is removed after the fade-out.
pub fn dismiss(&mut self, id: NotificationId) {
self.dismiss_at(id, Instant::now());
}
fn dismiss_at(&mut self, id: NotificationId, now: Instant) {
if let Some(notification) = self
.notifications
.iter_mut()
.find(|notification| notification.id == id)
&& notification.closing.is_none()
{
notification.closing = Some(now);
}
}
/// Expires due timed notifications and removes finished fade-outs.
pub fn remove_expired(&mut self, now: Instant) {
for notification in &mut self.notifications {
if notification.closing.is_none()
&& notification.expires_at().is_some_and(|at| now >= at)
{
notification.closing = Some(now);
}
}
self.notifications
.retain(|notification| !notification.is_finished(now));
}
#[allow(dead_code)] // Public manager API for future call sites.
pub fn clear(&mut self) {
self.notifications.clear();
}
pub fn is_empty(&self) -> bool {
self.notifications.is_empty()
}
#[allow(dead_code)] // Public manager API for future call sites.
pub fn len(&self) -> usize {
self.notifications.len()
}
/// Whether another timed notification still needs an expiry timer.
pub fn has_timed(&self) -> bool {
self.notifications.iter().any(|notification| {
notification.closing.is_none()
&& matches!(notification.lifetime, NotificationLifetime::Timed(_))
})
}
/// Whether any notification is fading in or out and needs frame updates.
pub fn is_animating(&self, now: Instant) -> bool {
self.notifications.iter().any(|notification| {
notification.closing.is_some()
|| now.saturating_duration_since(notification.born) < FADE_IN
})
}
/// Renders the toast stack in the bottom-right corner.
pub fn view(&self, now: Instant, colors: Option<ToastColors>) -> Element<'_, Message> {
responsive(move |size| {
let mut list = column![].spacing(SPACING).width(Length::Fill);
for notification in &self.notifications {
let opacity = notification.opacity(now);
if opacity > 0.0 {
list = list.push(toast(notification, opacity, colors));
}
}
let width = (size.width - MARGIN * 2.0).clamp(220.0, MAX_WIDTH);
let max_height = (size.height * 0.6).clamp(160.0, 480.0);
let stack = container(scrollable(list).width(Length::Fill))
.width(Length::Fixed(width))
.max_height(max_height);
container(opaque(stack))
.width(Length::Fill)
.height(Length::Fill)
.align_x(Alignment::End)
.align_y(Alignment::End)
.padding(MARGIN)
.into()
})
.into()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Message {
Dismiss(NotificationId),
}
fn toast(
notification: &Notification,
opacity: f32,
colors: Option<ToastColors>,
) -> Element<'_, Message> {
let kind = notification.kind;
let mut body = column![].spacing(2).width(Length::Fill);
if let Some(title) = &notification.title {
let title = container(text(title).size(14).width(Length::Fill)).style(move |theme| {
let colors = colors.unwrap_or_else(|| ToastColors::default_for(theme));
container::Style {
text_color: Some(colors.title.scale_alpha(opacity)),
..container::Style::default()
}
});
body = body.push(title);
}
body = body.push(text(&notification.message).size(13).width(Length::Fill));
let icon = container(text(kind.icon()).size(16)).style(move |theme| {
let colors = colors.unwrap_or_else(|| ToastColors::default_for(theme));
container::Style {
text_color: Some(kind.accent(colors).scale_alpha(opacity)),
..container::Style::default()
}
});
let dismiss = button(text("✕").size(14))
.on_press(Message::Dismiss(notification.id))
.padding([2, 6])
.style(move |theme, status| dismiss_style(theme, status, opacity, colors));
container(
row![icon, body, dismiss]
.spacing(8)
.align_y(Alignment::Start),
)
.width(Length::Fill)
.padding(10)
.style(move |theme| {
panel_style(
colors.unwrap_or_else(|| ToastColors::default_for(theme)),
opacity,
)
})
.into()
}
fn dismiss_style(
theme: &Theme,
status: button::Status,
opacity: f32,
colors: Option<ToastColors>,
) -> button::Style {
let colors = colors.unwrap_or_else(|| ToastColors::default_for(theme));
let mut style = button::text(theme, status);
style.text_color = colors.dismiss.scale_alpha(opacity);
style
}
fn panel_style(colors: ToastColors, opacity: f32) -> container::Style {
container::Style {
background: Some(colors.background.scale_alpha(opacity).into()),
text_color: Some(colors.text.scale_alpha(opacity)),
border: Border {
color: colors.border.scale_alpha(opacity * 0.7),
width: 1.0,
radius: 6.0.into(),
},
shadow: Shadow {
color: Color::BLACK.scale_alpha(0.18 * opacity),
offset: Vector::new(0.0, 2.0),
blur_radius: 8.0,
},
..container::Style::default()
}
}
fn mix(left: Color, right: Color, amount: f32) -> Color {
Color {
r: left.r + (right.r - left.r) * amount,
g: left.g + (right.g - left.g) * amount,
b: left.b + (right.b - left.b) * amount,
a: left.a + (right.a - left.a) * amount,
}
}
#[cfg(test)]
mod tests {
use super::{
DEFAULT_DURATION, Notification, NotificationKind, NotificationLifetime, NotificationManager,
};
use iced::time::{Duration, Instant};
#[test]
fn new_notifications_are_unique_and_stack_newest_first() {
let mut manager = NotificationManager::default();
let now = Instant::now();
let first = manager.add_at(now, Notification::new(NotificationKind::Info, "first"));
let second = manager.add_at(now, Notification::new(NotificationKind::Error, "second"));
assert_ne!(first, second);
assert_eq!(manager.len(), 2);
assert_eq!(manager.notifications[0].id, second);
assert_eq!(manager.notifications[1].id, first);
}
#[test]
fn timed_notifications_expire_but_persistent_ones_do_not() {
let mut manager = NotificationManager::default();
let now = Instant::now();
let timed = manager.add_at(
now,
Notification::new(NotificationKind::Success, "timed").timed(Duration::from_secs(2)),
);
let persistent = manager.add_at(
now,
Notification::new(NotificationKind::Warning, "persistent").persistent(),
);
manager.remove_expired(now + Duration::from_secs(1));
assert_eq!(manager.len(), 2);
assert!(manager.notifications.iter().any(|n| n.id == timed));
assert!(manager.notifications.iter().any(|n| n.id == persistent));
// Expiry starts a fade-out, then the entry is removed.
manager.remove_expired(now + Duration::from_secs(2));
assert_eq!(manager.len(), 2);
manager.remove_expired(now + Duration::from_secs(3));
assert!(manager.notifications.iter().all(|n| n.id != timed));
assert!(manager.notifications.iter().any(|n| n.id == persistent));
}
#[test]
fn dismissing_starts_the_fade_out_and_clear_removes_everything() {
let mut manager = NotificationManager::default();
let now = Instant::now();
let id = manager.add_at(now, Notification::new(NotificationKind::Info, "hello"));
manager.dismiss_at(id, now);
assert_eq!(manager.len(), 1);
manager.remove_expired(now + Duration::from_secs(1));
assert!(manager.is_empty());
manager.add_at(now, Notification::new(NotificationKind::Info, "one"));
manager.add_at(now, Notification::new(NotificationKind::Info, "two"));
manager.clear();
assert!(manager.is_empty());
}
#[test]
fn default_lifetime_is_five_seconds() {
let notification = Notification::new(NotificationKind::Info, "hello");
assert_eq!(
notification.lifetime,
NotificationLifetime::Timed(DEFAULT_DURATION)
);
}
}
+87
View File
@@ -0,0 +1,87 @@
//! Single-instance election and activation hand-off.
//!
//! `instance-handoff` takes a per-user lock before any window, tray or hotkey
//! exists. Later launches hand over their request and exit; the owner keeps a
//! local IPC listener alive for its lifetime. The OS releases the lock when
//! the owner exits or crashes, so a stale lock cannot block a future launch.
use std::sync::Mutex;
use iced::futures::{SinkExt, Stream};
use iced::{Subscription, stream};
use instance_handoff::{AppId, Builder, Owner, Request, Started, State};
use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
const APP_ID: AppId = AppId::windowed("dev.moorly.Moorly");
static OWNER: Mutex<Option<Owner>> = Mutex::new(None);
static EVENTS: Mutex<Option<UnboundedReceiver<()>>> = Mutex::new(None);
/// Elects the primary instance. Returns `false` when this launch handed its
/// activation request to the already-running instance and should exit.
pub fn acquire() -> bool {
let state = crate::config_path()
.and_then(|path| path.parent().map(|dir| State::dir(dir.to_path_buf())))
.unwrap_or(State::none());
match Builder::new(APP_ID, state).start(&()) {
Started::Owner(claim) => {
let (sender, receiver) = unbounded_channel();
if let Ok(mut events) = EVENTS.lock() {
*events = Some(receiver);
}
let owner = claim.serve(move |_request: Request<()>| sender.send(()).is_ok());
if let Ok(mut slot) = OWNER.lock() {
*slot = Some(owner);
}
true
}
Started::HandedOff(_) => false,
Started::Alone(reason) => {
eprintln!("Moorly could not become the single instance: {reason}");
false
}
}
}
/// Activation requests from later launches, delivered into the iced update
/// loop without blocking the GUI thread.
pub fn subscription() -> Subscription<crate::Message> {
Subscription::run(events)
}
fn events() -> impl Stream<Item = crate::Message> {
stream::channel(
8,
|mut output: iced::futures::channel::mpsc::Sender<crate::Message>| async move {
let receiver = EVENTS.lock().ok().and_then(|mut slot| slot.take());
let Some(mut receiver) = receiver else {
return;
};
while receiver.recv().await.is_some() {
if output
.send(crate::Message::SecondInstanceActivated)
.await
.is_err()
{
break;
}
}
},
)
}
/// Stops the IPC listener and gives up the lock before the process exits.
pub fn shutdown() {
if let Ok(mut slot) = OWNER.lock()
&& let Some(owner) = slot.take()
{
owner.release();
}
}
+1541 -3
View File
File diff suppressed because it is too large. Load diff
+162 -58
View File
@@ -5,14 +5,49 @@
//! changes while the app is running).
use std::env;
use std::fs;
use std::path::PathBuf;
use std::sync::{OnceLock, RwLock};
use iced::border::Radius;
use iced::widget::{button, container, text_input};
use iced::{Border, Color, Theme};
/// Accent red used for destructive/close affordances in both themes.
pub const DANGER: Color = Color::from_rgb8(0xff, 0x3b, 0x30);
/// Accent blue used for the active tab outline.
pub const ACTIVE_TAB: Color = Color::from_rgb8(0x60, 0x82, 0xB6);
/// Highlight for the selected settings section.
pub const SETTINGS_ACTIVE: Color = Color::from_rgb8(0x5D, 0x3F, 0xD3);
/// Border for the collapsible advanced-settings area.
/// Tab bar surfaces: the active tab merges with the content area below.
pub const TAB_ACTIVE_BG: Color = Color::from_rgb8(0x19, 0x19, 0x19);
pub const TAB_INACTIVE_BG: Color = Color::from_rgb8(0x13, 0x13, 0x13);
/// Text and icons drawn on the dark tab bar.
pub const TAB_TEXT: Color = Color::from_rgb8(0xe6, 0xe6, 0xe6);
/// Blue used for folders that only exist at runtime because a profile refers
/// to a path missing from `folders.toml`.
pub const UNTRACKED_FOLDER: Color = Color::from_rgb8(0x4a, 0x90, 0xd9);
/// Name color for profiles marked hidden.
pub const HIDDEN_PROFILE: Color = Color::from_rgb8(0x80, 0x80, 0x80);
/// Border color shared by every styled frame and control.
static BORDER_COLOR: OnceLock<RwLock<Color>> = OnceLock::new();
pub fn set_border_color(color: Color) {
let lock = BORDER_COLOR.get_or_init(|| RwLock::new(Color::WHITE));
if let Ok(mut current) = lock.write() {
*current = color;
}
}
pub fn border_color() -> Color {
BORDER_COLOR
.get_or_init(|| RwLock::new(Color::WHITE))
.read()
.map(|color| *color)
.unwrap_or(Color::WHITE)
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Preference {
@@ -41,7 +76,7 @@ impl Preference {
}
}
fn as_str(self) -> &'static str {
pub fn as_str(self) -> &'static str {
match self {
Self::System => "system",
Self::Light => "light",
@@ -49,7 +84,7 @@ impl Preference {
}
}
fn parse(value: &str) -> Option<Self> {
pub fn parse(value: &str) -> Option<Self> {
Self::ALL.into_iter().find(|pref| pref.as_str() == value)
}
}
@@ -60,29 +95,7 @@ impl std::fmt::Display for Preference {
}
}
/// Loads the persisted preference, falling back to `System`.
pub fn load() -> Preference {
config_path()
.and_then(|path| fs::read_to_string(path).ok())
.and_then(|value| Preference::parse(value.trim()))
.unwrap_or_default()
}
/// Persists the preference. Failures are ignored so theme selection never
/// blocks the UI; the in-memory choice still applies for this session.
pub fn save(preference: Preference) {
let Some(path) = config_path() else {
return;
};
if let Some(parent) = path.parent() {
let _ = fs::create_dir_all(parent);
}
let _ = fs::write(path, preference.as_str());
}
fn config_path() -> Option<PathBuf> {
pub(crate) fn config_path() -> Option<PathBuf> {
let base = if cfg!(windows) {
env::var_os("APPDATA").map(PathBuf::from)
} else {
@@ -91,46 +104,107 @@ fn config_path() -> Option<PathBuf> {
.or_else(|| env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))
}?;
Some(base.join("moorly").join("theme"))
// Debug builds get their own folder so manual testing never touches the
// profiles, themes, or settings used by a release build. Filenames stay
// the same so individual files can be copied between the two.
let folder = if cfg!(debug_assertions) {
"moorly_debug"
} else {
"moorly"
};
Some(base.join(folder).join("config.toml"))
}
/// Style for the top menubar.
pub fn menubar(theme: &Theme) -> container::Style {
let palette = theme.extended_palette();
pub fn menubar(_theme: &Theme, background: Color) -> container::Style {
container::Style {
background: Some(palette.background.weak.color.into()),
background: Some(background.into()),
..container::Style::default()
}
}
/// Style for buttons that sit directly on the dark menubar.
pub fn menubar_button(theme: &Theme, status: button::Status, text_color: Color) -> button::Style {
let mut style = button::text(theme, status);
style.text_color = if matches!(status, button::Status::Disabled) {
text_color.scale_alpha(0.4)
} else {
text_color
};
style
}
/// Style for dropdown menus and dialogs: a raised panel with a themed border.
pub fn menu(theme: &Theme) -> container::Style {
container::Style {
background: Some(theme.extended_palette().background.weak.color.into()),
border: Border {
color: palette.background.strong.color,
color: border_color(),
width: 1.0,
radius: 0.0.into(),
radius: 6.0.into(),
},
..container::Style::default()
}
}
/// Style for dropdown menu panels.
pub fn menu(theme: &Theme) -> container::Style {
let mut style = container::rounded_box(theme);
style.background = Some(theme.extended_palette().background.weak.color.into());
style
}
/// Style for a tab in the menubar; active tabs sit on the base surface.
pub fn tab(theme: &Theme, active: bool) -> container::Style {
let palette = theme.extended_palette();
/// Style for a tab in the menubar; active tabs sit on the content surface.
/// The active outline is drawn separately so it has no bottom edge.
pub fn tab(_theme: &Theme, active: bool, active_bg: Color, inactive_bg: Color) -> container::Style {
container::Style {
background: active.then(|| palette.background.base.color.into()),
background: Some(if active {
active_bg.into()
} else {
inactive_bg.into()
}),
border: Border {
color: palette.background.strong.color,
width: if active { 1.0 } else { 0.0 },
radius: 3.0.into(),
color: Color::TRANSPARENT,
width: 0.0,
radius: Radius {
top_left: 3.0,
top_right: 3.0,
bottom_right: 0.0,
bottom_left: 0.0,
},
},
..container::Style::default()
}
}
/// Style for the active tab's thin top/left/right outline.
pub fn tab_outline(_theme: &Theme, color: Color) -> container::Style {
container::Style {
background: Some(color.into()),
..container::Style::default()
}
}
/// Rounded frame around the advanced-settings area.
pub fn advanced_frame(_theme: &Theme) -> container::Style {
container::Style {
border: Border {
color: border_color(),
width: 1.0,
radius: 6.0.into(),
},
..container::Style::default()
}
}
/// Style for the selected settings section in the settings menu.
pub fn settings_active(_theme: &Theme, _status: button::Status, accent: Color) -> button::Style {
button::Style {
background: Some(accent.into()),
text_color: Color::WHITE,
border: Border {
color: accent,
width: 1.0,
radius: 4.0.into(),
},
..button::Style::default()
}
}
/// Style for the currently selected option in a group of choice buttons.
pub fn selected_option(theme: &Theme, _status: button::Status) -> button::Style {
let palette = theme.extended_palette();
@@ -150,11 +224,9 @@ pub fn selected_option(theme: &Theme, _status: button::Status) -> button::Style
/// Style for an unselected choice button: outlined so it reads as a button
/// rather than a plain text label.
pub fn outlined_option(theme: &Theme, status: button::Status) -> button::Style {
let palette = theme.extended_palette();
button::Style {
border: Border {
color: palette.background.strong.color,
color: border_color(),
width: 1.0,
radius: 4.0.into(),
},
@@ -227,8 +299,7 @@ pub fn selectable_row(theme: &Theme, status: button::Status, selected: bool) ->
let mut style = button::text(theme, status);
if matches!(status, button::Status::Hovered) {
style.background =
Some(theme.extended_palette().background.weak.color.into());
style.background = Some(theme.extended_palette().background.weak.color.into());
}
style
@@ -237,18 +308,17 @@ pub fn selectable_row(theme: &Theme, status: button::Status, selected: bool) ->
/// Style for filter/text fields: a thicker outline while focused.
pub fn filter_field(theme: &Theme, status: text_input::Status) -> text_input::Style {
let palette = theme.extended_palette();
let mut style = text_input::default(theme, status);
style.border = if matches!(status, text_input::Status::Focused { .. }) {
Border {
color: palette.primary.strong.color,
color: border_color(),
width: 2.0,
radius: 4.0.into(),
}
} else {
Border {
color: palette.background.strong.color,
color: border_color(),
width: 1.0,
radius: 4.0.into(),
}
@@ -257,6 +327,25 @@ pub fn filter_field(theme: &Theme, status: text_input::Status) -> text_input::St
style
}
/// Style for the unsaved-changes bar at the bottom of the settings frame.
pub fn settings_bar(theme: &Theme) -> container::Style {
let palette = theme.extended_palette();
container::Style {
background: Some(palette.background.weak.color.into()),
border: Border {
color: border_color(),
width: 1.0,
radius: Radius {
top_left: 6.0,
top_right: 6.0,
..Radius::default()
},
},
..container::Style::default()
}
}
/// Style for the settings window frame.
pub fn settings_frame(theme: &Theme) -> container::Style {
let palette = theme.extended_palette();
@@ -264,7 +353,7 @@ pub fn settings_frame(theme: &Theme) -> container::Style {
container::Style {
background: Some(palette.background.base.color.into()),
border: Border {
color: palette.background.strong.color,
color: border_color(),
width: 1.0,
radius: 6.0.into(),
},
@@ -274,7 +363,7 @@ pub fn settings_frame(theme: &Theme) -> container::Style {
#[cfg(test)]
mod tests {
use super::Preference;
use super::{Preference, Theme};
#[test]
fn preference_round_trips_through_text() {
@@ -283,4 +372,19 @@ mod tests {
}
assert_eq!(Preference::parse("unknown"), None);
}
#[test]
fn active_tabs_are_visually_distinct() {
let theme = Theme::Light;
let active = super::tab(&theme, true, super::TAB_ACTIVE_BG, super::TAB_INACTIVE_BG);
let inactive = super::tab(&theme, false, super::TAB_ACTIVE_BG, super::TAB_INACTIVE_BG);
assert_ne!(active.background, inactive.background);
assert_eq!(active.border.width, 0.0);
assert_eq!(inactive.border.width, 0.0);
assert_eq!(
super::tab_outline(&theme, super::ACTIVE_TAB).background,
Some(super::ACTIVE_TAB.into())
);
}
}
+194
View File
@@ -0,0 +1,194 @@
//! System tray icon and context menu.
//!
//! Linux uses the StatusNotifierItem (KSNI) backend, which talks to the
//! desktop panel over D-Bus and needs no GTK event loop. Windows uses the
//! native notification-area backend. Both come from the `tray-icon` crate.
use std::sync::OnceLock;
use iced::Subscription;
use iced::futures::StreamExt;
use iced::futures::stream::{self, BoxStream};
use tokio::sync::broadcast;
use crate::icons::{self, TrayIconStyle};
/// Events delivered to the Iced application loop.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
/// Left click on the icon, or the Show/Hide menu entry.
Toggle,
Quit,
}
static EVENTS: OnceLock<broadcast::Sender<Event>> = OnceLock::new();
const TOGGLE_ID: &str = "moorly.tray.toggle";
const QUIT_ID: &str = "moorly.tray.quit";
/// Creates the tray icon once. Subsequent calls are a no-op.
pub fn start(style: TrayIconStyle) -> Result<(), String> {
imp::start(style)
}
/// Replaces the icon of the existing tray instance.
pub fn set_icon(style: TrayIconStyle) -> Result<(), String> {
imp::set_icon(style)
}
/// Releases the tray icon and its menu. Safe to call more than once.
pub fn shutdown() {
imp::shutdown();
}
/// Updates the Show/Hide menu entry to match the main window state.
pub fn set_window_visible(visible: bool) {
imp::set_window_visible(visible);
}
pub fn subscription() -> Subscription<Event> {
Subscription::run(event_stream)
}
fn event_stream() -> BoxStream<'static, Event> {
let Some(events) = EVENTS.get() else {
return stream::pending().boxed();
};
let receiver = events.subscribe();
stream::unfold(receiver, |mut receiver| async move {
loop {
match receiver.recv().await {
Ok(event) => return Some((event, receiver)),
Err(broadcast::error::RecvError::Lagged(_)) => continue,
Err(broadcast::error::RecvError::Closed) => return None,
}
}
})
.boxed()
}
#[cfg(any(target_os = "linux", target_os = "windows"))]
mod imp {
use std::cell::RefCell;
use tray_icon::menu::{Menu, MenuEvent, MenuItem, PredefinedMenuItem};
use tray_icon::{MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
use super::{EVENTS, Event, QUIT_ID, TOGGLE_ID, TrayIconStyle, broadcast, icons};
thread_local! {
// `TrayIcon` is not `Send`; it is created and dropped on the main
// thread that also runs the Iced/winit event loop.
static TRAY: RefCell<Option<TrayIcon>> = const { RefCell::new(None) };
static TOGGLE_ITEM: RefCell<Option<MenuItem>> = const { RefCell::new(None) };
}
pub(super) fn start(style: TrayIconStyle) -> Result<(), String> {
if EVENTS.get().is_some() {
return Ok(());
}
let icon = icons::tray_icon(style)?;
let (sender, _) = broadcast::channel(16);
// The window starts visible, so the entry starts as "Hide Moorly".
let toggle = MenuItem::with_id(TOGGLE_ID, "Hide Moorly", true, None);
let separator = PredefinedMenuItem::separator();
let quit = MenuItem::with_id(QUIT_ID, "Quit Moorly", true, None);
let menu = Menu::with_items(&[&toggle, &separator, &quit])
.map_err(|error| format!("Could not build the tray menu: {error}"))?;
let tray = TrayIconBuilder::new()
.with_tooltip("Moorly")
.with_menu(Box::new(menu))
// Left click toggles the window; right click opens the menu.
// These flags are honoured by Windows. KSNI hosts decide for
// themselves and send us the left-click activation event.
.with_menu_on_left_click(false)
.with_menu_on_right_click(true)
.with_icon(icon)
.build()
.map_err(|error| format!("Could not create the system tray icon: {error}"))?;
let _ = EVENTS.set(sender.clone());
let tray_sender = sender.clone();
TrayIconEvent::set_event_handler(Some(move |event| {
if let TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Up,
..
} = event
{
let _ = tray_sender.send(Event::Toggle);
}
}));
MenuEvent::set_event_handler(Some(move |event: MenuEvent| {
let event = match event.id().as_ref() {
TOGGLE_ID => Event::Toggle,
QUIT_ID => Event::Quit,
_ => return,
};
let _ = sender.send(event);
}));
// Store after the handlers are installed so no early event is lost.
TOGGLE_ITEM.with(|slot| *slot.borrow_mut() = Some(toggle));
TRAY.with(|slot| *slot.borrow_mut() = Some(tray));
Ok(())
}
pub(super) fn set_icon(style: TrayIconStyle) -> Result<(), String> {
let icon = icons::tray_icon(style)?;
TRAY.with(|slot| {
let tray = slot.borrow();
let Some(tray) = tray.as_ref() else {
return Err("The system tray is not available.".to_owned());
};
tray.set_icon(Some(icon))
.map_err(|error| format!("Could not update the system tray icon: {error}"))
})
}
pub(super) fn shutdown() {
TOGGLE_ITEM.with(|slot| slot.borrow_mut().take());
TRAY.with(|tray| {
if let Some(tray) = tray.borrow_mut().take() {
drop(tray);
}
});
}
pub(super) fn set_window_visible(visible: bool) {
TOGGLE_ITEM.with(|slot| {
if let Some(item) = slot.borrow().as_ref() {
item.set_text(if visible {
"Hide Moorly"
} else {
"Show Moorly"
});
}
});
}
}
#[cfg(not(any(target_os = "linux", target_os = "windows")))]
mod imp {
use super::TrayIconStyle;
pub(super) fn start(_style: TrayIconStyle) -> Result<(), String> {
Err("System tray integration is only implemented on Linux and Windows.".to_owned())
}
pub(super) fn set_icon(_style: TrayIconStyle) -> Result<(), String> {
Err("System tray integration is only implemented on Linux and Windows.".to_owned())
}
pub(super) fn shutdown() {}
pub(super) fn set_window_visible(_visible: bool) {}
}
Generated Vendored
+4529
View File
File diff suppressed because it is too large. Load diff
+150
View File
@@ -0,0 +1,150 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
rust-version = "1.88"
name = "iced_aw"
version = "0.14.1"
authors = [
"Kaiden42 <gitlab@tinysn.com>",
"Andrew Wheeler <genusistimelord@gmail.com>",
]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Additional widgets for the Iced GUI library"
homepage = "https://iced.rs"
readme = "README.md"
keywords = [
"gui",
"graphics",
"interface",
"widgets",
"iced",
]
categories = ["gui"]
license = "MIT"
repository = "https://github.com/iced-rs/iced_aw"
[features]
badge = []
card = []
color_picker = ["iced_widget/canvas"]
context_menu = []
custom_layout = []
date_picker = ["chrono"]
debug_log = ["log"]
default = ["full"]
drop_down = []
full = [
"badge",
"card",
"number_input",
"date_picker",
"color_picker",
"tab_bar",
"tabs",
"time_picker",
"slide_bar",
"wrap",
"selection_list",
"quad",
"context_menu",
"spinner",
"drop_down",
"menu",
"sidebar",
"labeled_frame",
"custom_layout",
]
labeled_frame = []
menu = []
number_input = [
"num-format",
"num-traits",
"typed_input",
]
quad = []
selection_list = []
sidebar = []
slide_bar = []
spinner = []
tab_bar = []
tabs = ["tab_bar"]
time_picker = [
"chrono",
"iced_widget/canvas",
]
typed_input = []
wrap = []
[lib]
name = "iced_aw"
# rlib only. The upstream cdylib type makes Cargo link iced_aw.dll on Windows
# GNU, where MinGW ld fails with "export ordinal too large".
crate-type = [
"rlib",
]
path = "src/lib.rs"
[dependencies.cfg-if]
version = "1.0"
[dependencies.chrono]
version = "0.4.44"
features = ["wasmbind"]
optional = true
[dependencies.iced_core]
version = "0.14.0"
[dependencies.iced_fonts]
version = "0.3.0"
features = ["advanced_text"]
[dependencies.iced_widget]
version = "0.14.2"
[dependencies.log]
version = "0.4"
optional = true
[dependencies.num-format]
version = "0.4.4"
optional = true
[dependencies.num-traits]
version = "0.2.19"
optional = true
[dependencies.web-time]
version = "1.1.0"
[dev-dependencies.env_logger]
version = "0.11.10"
[dev-dependencies.getrandom]
version = "0.4.2"
features = ["wasm_js"]
[dev-dependencies.iced]
version = "0.14.0"
features = ["advanced"]
[dev-dependencies.iced_test]
version = "0.14"
[dev-dependencies.rand]
version = "0.10.1"
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Kaiden42
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.
+173
View File
@@ -0,0 +1,173 @@
# Iced - Additional Widgets
[![Documentation](https://docs.rs/iced_aw/badge.svg)](https://docs.rs/iced_aw)
[![Crates.io](https://img.shields.io/crates/v/iced_aw.svg)](https://crates.io/crates/iced_aw)
[![License](https://img.shields.io/crates/l/iced_aw.svg)](https://github.com/iced-rs/iced/blob/master/LICENSE)
[![Discord Server](https://img.shields.io/discord/628993209984614400?label=&labelColor=6A7EC2&logo=discord&logoColor=ffffff&color=7389D8)](https://discord.gg/3xZJ65GAhd)
This crate contains additional widgets for the GUI library [Iced](https://github.com/hecrj/iced).
Every widget is hidden by a feature gate. This allows you to cherry pick the widgets you actually need.
## Usage
Include `iced_aw` as a dependency in your `Cargo.toml`:
```toml
[dependencies]
iced = "0.14.0"
iced_aw = { version = "0.14.0", features = ["full"] }
```
## Versioning
| `iced` version | `iced_aw` version |
| -------------- | ----------------- |
| 0.13 | 0.12 |
| 0.14 | 0.13, 0.14 |
## Widgets
### Badge
<div align="center">
![Badge showcase](./images/showcase/badge.png)
</div>
Please take a look into our examples on how to use badges.
Enable this widget with the feature `badge`.
### Card
<div align="center">
![Card showcase](./images/showcase/card.png)
</div>
Please take a look into our examples on how to use cards.
Enable this widget with the feature `card`.
### Color Picker
<div align="center">
![Color Picker showcase](./images/showcase/color_picker.png)
</div>
Please take a look into our examples on how to use color pickers.
Enable this widget with the feature `color_picker`.
### Date Picker
<div align="center">
![Date Picker showcase](./images/showcase/date_picker.png)
</div>
Please take a look into our examples on how to use date pickers.
Enable this widget with the feature `date_picker`.
### NumberInput
Just like TextInput, but only for numbers.
<div align="center">
![NumberInput showcase](./images/showcase/number_input.png)
</div>
Please take a look into our examples on how to use number inputs.
Enable this widget with the feature `number_input`.
*This widget does currently not support web*
### SelectionList
A selection space to show any options passed in.
<div align="center">
![SelectionList showcase](./images/showcase/selection_list.gif)
</div>
Enable this widget with the feature `selection_list`.
### TabBar and Tabs
<div align="center">
![Tabs showcase](./images/showcase/tabs_example.gif)
</div>
Please take a look into our examples on how to use TabBars and Tabs.
Enable TabBars with the feature `tab_bar` and Tabs with `tabs`.
### Time Picker
<div align="center">
![Modal showcase](./images/showcase/time_picker.png)
</div>
Please take a look into our examples on how to use time pickers.
Enable this widget with the feature `time_picker`.
### Menu
<div align="center">
![Menu showcase](./images/showcase/menu.gif)
</div>
Please take a look into our examples on how to use menus.
Enable this widget with the feature `menu`.
You might also want to enable the feature `quad` for drawing separators.
### Slide Bar
Please take a look into our examples on how to use slidebars.
Enable this widget with the feature `slide_bar`.
### Context Menu
See the example [here](./examples/context_menu.rs)
### Drop Down Menu
See the example [here](./examples/drop_down.rs)
### Sidebar
<div align="center">
![Modal showcase](./images/showcase/sidebar.png)
</div>
Please take a look into our examples on how to use Sidebar.
Enable Sidebar with the feature `sidebar`.
Also included in this feature, are two widgets `sidebar::column::FlushColumn` and `sidebar::row::FlushRow` that flushes the end/start element to the opposite direction to the alignment of the container.
### Color palette
This crate adds a predefined color palette based on the [CSS color palette](https://www.w3schools.com/cssref/css_colors.asp).
### LabeledFrame
A frame with a title.
<div align="center">
![LabeledFrame showcase](./images/showcase/labeled_frame.png)
</div>
BIN
View File
Binary file not shown.
+22
View File
@@ -0,0 +1,22 @@
//! `iced_aw_core`.
#[cfg(feature = "date_picker")]
pub mod date;
#[cfg(feature = "time_picker")]
pub mod clock;
#[cfg(feature = "color_picker")]
pub mod color;
pub mod overlay;
pub mod renderer;
#[cfg(feature = "time_picker")]
pub mod time;
#[cfg(feature = "drop_down")]
pub mod offset;
#[cfg(feature = "drop_down")]
pub mod alignment;
+26
View File
@@ -0,0 +1,26 @@
//! Alignment enum, similar to an anchor
/// ```text
/// +-----------+-----------+-----------+
/// | TopStart | Top | TopEnd |
/// +-----------+-----------+-----------+
/// | Start | | End |
/// +-----------+-----------+-----------+
/// |BottomStart| Bottom | BottomEnd |
/// +-----------+-----------+-----------+
/// ```
#[allow(missing_docs)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Alignment {
TopStart,
Top,
TopEnd,
End,
BottomEnd,
Bottom,
BottomStart,
Start,
}
+367
View File
@@ -0,0 +1,367 @@
//! Helper functions for calculating the clock
use iced_core::Point;
use std::fmt::Display;
/// The size of the period on the clock based on the clock's size.
pub const PERIOD_PERCENTAGE: f32 = 0.1;
/// The radius of the hour on the clock based on the clock's size.
pub const HOUR_RADIUS_PERCENTAGE: f32 = 0.4;
/// The radius of the minute on the clock based on the clock's size.
pub const MINUTE_RADIUS_PERCENTAGE: f32 = 0.65;
/// The radius of the second on the clock based on the clock's size.
pub const SECOND_RADIUS_PERCENTAGE: f32 = 0.9;
/// The radius of the hour without the seconds on the clock based on the
/// clock's size.
pub const HOUR_RADIUS_PERCENTAGE_NO_SECONDS: f32 = 0.5;
/// The radius of the minute without the seconds on the clock based on the
/// clock's size.
pub const MINUTE_RADIUS_PERCENTAGE_NO_SECONDS: f32 = 0.9;
/// The current period of the clock.
#[derive(Clone, Debug)]
pub enum Period {
/// Ante meridiem: Before noon.
AM,
/// Post meridiem: After noon.
PM,
}
impl Display for Period {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::AM => "AM",
Self::PM => "PM",
}
)
}
}
/// The radius nearest to the cursor position.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NearestRadius {
/// Nothing is near to the cursor position.
None,
/// Period is the nearest radius to the cursor position.
Period,
/// Hour is the nearest radius to the cursor position.
Hour,
/// Minute is the nearest radius to the cursor position.
Minute,
/// Second is the nearest radius to the cursor position.
Second,
}
/// Distributes the amount of points on a circle with the given radius around the
/// center.
#[must_use]
pub fn circle_points(distance_radius: f32, center: Point, amount: u16) -> Vec<Point> {
let part = std::f32::consts::TAU / f32::from(amount);
let rotation =
|(x, y): (f32, f32), t: f32| (x * t.cos() - y * t.sin(), x * t.sin() + y * t.cos());
let points: Vec<(f32, f32)> = (0..amount).fold(Vec::new(), |mut v, i| {
v.push(rotation((0.0, -distance_radius), part * f32::from(i)));
v
});
let points: Vec<Point> = points
.iter()
.map(|p| Point::new(p.0 + center.x, p.1 + center.y))
.collect();
points
}
/// # Panics
/// Determines the nearest point with the smallest distance to the cursor
/// position. The index of the point is returned.
/// Will panic if distance vec can not compare a and b
#[must_use]
pub fn nearest_point(points: &[Point], cursor_position: Point) -> usize {
let mut distance_vec: Vec<(usize, f32)> = points
.iter()
.enumerate()
.map(|(i, p)| (i, p.distance(cursor_position)))
.collect();
distance_vec.sort_by(|a, b| a.1.partial_cmp(&b.1).expect("Should be comparable"));
distance_vec[0].0
}
/// # Panics
/// Determining the nearest radius to the position of the cursor position based
/// on the distance to the center.
/// Will panic if distance vec can not compare a and b
#[must_use]
pub fn nearest_radius(
radii: &[(f32, NearestRadius)],
cursor_position: Point,
center: Point,
) -> NearestRadius {
let distance = cursor_position.distance(center);
let mut distance_vec: Vec<(f32, &NearestRadius)> = radii
.iter()
.map(|(r, n)| ((r - distance).abs(), n))
.collect();
distance_vec.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("Should be comparable"));
distance_vec[0].1.clone()
}
#[cfg(test)]
mod tests {
use iced_core::{Point, Vector};
use super::{NearestRadius, circle_points, nearest_point, nearest_radius};
#[test]
fn circle_points_test() {
let points = circle_points(10.0, Point::new(0.0, 0.0), 10);
let expected = vec![
Point { x: 0.0, y: -10.0 },
Point {
x: 5.877_852_4,
y: -8.09017,
},
Point {
x: 9.510_566,
y: -3.090_169_7,
},
Point {
x: 9.510_565,
y: 3.090_170_4,
},
Point {
x: 5.877_852,
y: 8.090_171,
},
Point {
x: -0.000_000_874_227_8,
y: 10.0,
},
Point {
x: -5.877_853_4,
y: 8.09017,
},
Point {
x: -9.510_565,
y: 3.090_170_9,
},
Point {
x: -9.510_565,
y: -3.090_171_3,
},
Point {
x: -5.877_849_6,
y: -8.090_173,
},
];
assert_eq!(points, expected);
}
#[test]
fn nearest_radius_test() {
let radii = vec![
(10.0, NearestRadius::Period),
(20.0, NearestRadius::Hour),
(30.0, NearestRadius::Minute),
(40.0, NearestRadius::Second),
];
let center = Point::new(0.0, 0.0);
let cursor_position = Point::new(5.0, 0.0);
let result = nearest_radius(&radii, cursor_position, center);
assert_eq!(result, NearestRadius::Period);
let cursor_position = Point::new(16.0, 0.0);
let result = nearest_radius(&radii, cursor_position, center);
assert_eq!(result, NearestRadius::Hour);
let cursor_position = Point::new(26.0, 0.0);
let result = nearest_radius(&radii, cursor_position, center);
assert_eq!(result, NearestRadius::Minute);
let cursor_position = Point::new(36.0, 0.0);
let result = nearest_radius(&radii, cursor_position, center);
assert_eq!(result, NearestRadius::Second);
}
#[test]
fn nearest_point_test() {
let points = circle_points(10.0, Point::new(0.0, 0.0), 10);
let mut index = 5;
let cursor_position = points[index] + Vector::new(1.0, -1.0);
let mut result = nearest_point(&points, cursor_position);
assert_eq!(index, result);
index = 0;
let cursor_position = points[index] + Vector::new(-1.0, 1.0);
result = nearest_point(&points, cursor_position);
assert_eq!(index, result);
}
#[test]
fn period_display_am() {
use super::Period;
let period = Period::AM;
assert_eq!(format!("{period}"), "AM");
}
#[test]
fn period_display_pm() {
use super::Period;
let period = Period::PM;
assert_eq!(format!("{period}"), "PM");
}
#[test]
fn circle_points_with_offset_center() {
let points = circle_points(5.0, Point::new(10.0, 20.0), 4);
assert_eq!(points.len(), 4);
// Top point should be at (10, 15) - center.y - radius
assert!((points[0].x - 10.0).abs() < 0.001);
assert!((points[0].y - 15.0).abs() < 0.001);
}
#[test]
fn circle_points_single_point() {
let points = circle_points(10.0, Point::new(0.0, 0.0), 1);
assert_eq!(points.len(), 1);
// Single point should be at top (0, -10)
assert!((points[0].x - 0.0).abs() < 0.001);
assert!((points[0].y - (-10.0)).abs() < 0.001);
}
#[test]
fn circle_points_twelve_points() {
let points = circle_points(10.0, Point::new(0.0, 0.0), 12);
assert_eq!(points.len(), 12);
// 12 points should be evenly distributed (like clock hours)
// First point should be at top
assert!((points[0].x - 0.0).abs() < 0.001);
assert!((points[0].y - (-10.0)).abs() < 0.001);
}
#[test]
fn nearest_point_single_point() {
let points = vec![Point::new(5.0, 5.0)];
let cursor = Point::new(100.0, 100.0);
let result = nearest_point(&points, cursor);
assert_eq!(result, 0);
}
#[test]
fn nearest_point_exact_match() {
let points = circle_points(10.0, Point::new(0.0, 0.0), 8);
// Cursor exactly on point 3
let cursor = points[3];
let result = nearest_point(&points, cursor);
assert_eq!(result, 3);
}
#[test]
fn nearest_radius_at_exact_radius() {
let radii = vec![
(10.0, NearestRadius::Period),
(20.0, NearestRadius::Hour),
(30.0, NearestRadius::Minute),
];
let center = Point::new(0.0, 0.0);
// Cursor exactly at radius 20
let cursor = Point::new(20.0, 0.0);
let result = nearest_radius(&radii, cursor, center);
assert_eq!(result, NearestRadius::Hour);
}
#[test]
fn nearest_radius_at_center() {
let radii = vec![
(10.0, NearestRadius::Period),
(20.0, NearestRadius::Hour),
(30.0, NearestRadius::Minute),
];
let center = Point::new(0.0, 0.0);
// Cursor at center
let cursor = Point::new(0.0, 0.0);
let result = nearest_radius(&radii, cursor, center);
// Should pick the smallest radius (Period at 10.0)
assert_eq!(result, NearestRadius::Period);
}
#[test]
fn nearest_radius_beyond_largest() {
let radii = vec![
(10.0, NearestRadius::Period),
(20.0, NearestRadius::Hour),
(30.0, NearestRadius::Minute),
];
let center = Point::new(0.0, 0.0);
// Cursor far beyond all radii
let cursor = Point::new(100.0, 0.0);
let result = nearest_radius(&radii, cursor, center);
// Should still pick the closest (Minute at 30.0)
assert_eq!(result, NearestRadius::Minute);
}
#[test]
fn nearest_radius_with_offset_center() {
let radii = vec![(5.0, NearestRadius::Period), (15.0, NearestRadius::Hour)];
let center = Point::new(50.0, 50.0);
let cursor = Point::new(62.0, 50.0);
// Distance from center is 12, closer to Hour (15) than Period (5)
// |5 - 12| = 7, |15 - 12| = 3, so Hour is closer
let result = nearest_radius(&radii, cursor, center);
assert_eq!(result, NearestRadius::Hour);
}
#[test]
fn nearest_radius_none_variant() {
let radii = vec![(10.0, NearestRadius::None), (20.0, NearestRadius::Hour)];
let center = Point::new(0.0, 0.0);
let cursor = Point::new(11.0, 0.0);
let result = nearest_radius(&radii, cursor, center);
// Should pick None as it's closer to radius 10
assert_eq!(result, NearestRadius::None);
}
#[test]
fn circle_points_large_amount() {
let points = circle_points(10.0, Point::new(0.0, 0.0), 60);
assert_eq!(points.len(), 60);
// All points should be approximately 10.0 away from center
let center = Point::new(0.0, 0.0);
for point in points {
let distance = point.distance(center);
assert!((distance - 10.0).abs() < 0.001);
}
}
#[test]
fn constants_are_defined() {
use super::*;
// Just verify the constants are accessible and have expected values
assert_eq!(PERIOD_PERCENTAGE, 0.1);
assert_eq!(HOUR_RADIUS_PERCENTAGE, 0.4);
assert_eq!(MINUTE_RADIUS_PERCENTAGE, 0.65);
assert_eq!(SECOND_RADIUS_PERCENTAGE, 0.9);
assert_eq!(HOUR_RADIUS_PERCENTAGE_NO_SECONDS, 0.5);
assert_eq!(MINUTE_RADIUS_PERCENTAGE_NO_SECONDS, 0.9);
}
}
+339
View File
@@ -0,0 +1,339 @@
//! Helper functions and structs for picking dates.
use iced_core::Color;
/// A color in the HSV color space.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Hsv {
/// HSV hue.
pub(crate) hue: u16,
/// HSV Saturation.
pub(crate) saturation: f32,
/// HSV value.
pub(crate) value: f32,
}
impl Hsv {
/// Creates a [`Hsv`] from its HSV components.
#[must_use]
pub const fn from_hsv(hue: u16, saturation: f32, value: f32) -> Self {
Self {
hue,
saturation,
value,
}
}
}
/// Creates a string of hexadecimal characters.
pub trait HexString {
/// Turns self into a string of hexadecimal characters.
fn as_hex_string(&self) -> String;
}
impl HexString for Color {
fn as_hex_string(&self) -> String {
format!(
"#{:02X?}{:02X?}{:02X?}{:02X?}",
(self.r * 255.0) as u8,
(self.g * 255.0) as u8,
(self.b * 255.0) as u8,
(self.a * 255.0) as u8,
)
}
}
impl From<Color> for Hsv {
// https://de.wikipedia.org/wiki/HSV-Farbraum#Umrechnung_RGB_in_HSV/HSL
fn from(color: Color) -> Self {
let max = color.r.max(color.g.max(color.b));
let min = color.r.min(color.g.min(color.b));
let hue = if (max - min).abs() < f32::EPSILON {
0.0
} else if (max - color.r).abs() < f32::EPSILON {
60.0 * (0.0 + (color.g - color.b) / (max - min))
} else if (max - color.g).abs() < f32::EPSILON {
60.0 * (2.0 + (color.b - color.r) / (max - min))
} else {
60.0 * (4.0 + (color.r - color.g) / (max - min))
};
let hue = if hue < 0.0 { hue + 360.0 } else { hue } as u16 % 360;
let saturation = if max == 0.0 { 0.0 } else { (max - min) / max };
let value = max;
Self {
hue,
saturation,
value,
}
}
}
impl From<Hsv> for Color {
fn from(hsv: Hsv) -> Self {
// https://de.wikipedia.org/wiki/HSV-Farbraum#Umrechnung_HSV_in_RGB
let h_i = (f32::from(hsv.hue) / 60.0).floor();
let f = (f32::from(hsv.hue) / 60.0) - h_i;
let p = hsv.value * (1.0 - hsv.saturation);
let q = hsv.value * (1.0 - hsv.saturation * f);
let t = hsv.value * (1.0 - hsv.saturation * (1.0 - f));
let h_i = h_i as u8;
let (red, green, blue) = match h_i {
1 => (q, hsv.value, p),
2 => (p, hsv.value, t),
3 => (p, q, hsv.value),
4 => (t, p, hsv.value),
5 => (hsv.value, p, q),
_ => (hsv.value, t, p),
};
Self::from_rgb(red, green, blue)
}
}
#[cfg(test)]
mod tests {
use iced_core::Color;
use super::Hsv;
#[allow(clippy::cognitive_complexity)]
#[test]
fn rgb_to_hsv() {
// https://de.wikipedia.org/wiki/HSV-Farbraum#Transformation_von_HSV/HSL_und_RGB
let red_rgb = Color::from_rgb(1.0, 0.0, 0.0);
let red_hsv = Hsv::from_hsv(0, 1.0, 1.0);
assert_eq!(red_hsv, red_rgb.into());
let orange_rgb = Color::from_rgb(1.0, 0.5, 0.0);
let orange_hsv = Hsv::from_hsv(30, 1.0, 1.0);
assert_eq!(orange_hsv, orange_rgb.into());
let yellow_rgb = Color::from_rgb(1.0, 1.0, 0.0);
let yellow_hsv = Hsv::from_hsv(60, 1.0, 1.0);
assert_eq!(yellow_hsv, yellow_rgb.into());
let dark_green_rgb = Color::from_rgb(0.0, 0.5, 0.0);
let dark_green_hsv = Hsv::from_hsv(120, 1.0, 0.5);
assert_eq!(dark_green_hsv, dark_green_rgb.into());
let violett_rgb = Color::from_rgb(0.5, 0.0, 1.0);
let violett_hsv = Hsv::from_hsv(270, 1.0, 1.0);
assert_eq!(violett_hsv, violett_rgb.into());
let black_rgb = Color::from_rgb(0.0, 0.0, 0.0);
let black_hsv = Hsv::from_hsv(0, 0.0, 0.0);
assert_eq!(black_hsv, black_rgb.into());
let blue_rgb = Color::from_rgb(0.0, 0.0, 1.0);
let blue_hsv = Hsv::from_hsv(240, 1.0, 1.0);
assert_eq!(blue_hsv, blue_rgb.into());
let brown_rgb = Color::from_rgb(0.36, 0.18, 0.09);
let brown_hsv = Hsv::from_hsv(20, 0.75, 0.36);
assert_eq!(brown_hsv, brown_rgb.into());
let white_rgb = Color::from_rgb(1.0, 1.0, 1.0);
let white_hsv = Hsv::from_hsv(0, 0.0, 1.0);
assert_eq!(white_hsv, white_rgb.into());
let green_rgb = Color::from_rgb(0.0, 1.0, 0.0);
let green_hsv = Hsv::from_hsv(120, 1.0, 1.0);
assert_eq!(green_hsv, green_rgb.into());
let cyan_rgb = Color::from_rgb(0.0, 1.0, 1.0);
let cyan_hsv = Hsv::from_hsv(180, 1.0, 1.0);
assert_eq!(cyan_hsv, cyan_rgb.into());
let magenta_rgb = Color::from_rgb(1.0, 0.0, 1.0);
let magenta_hsv = Hsv::from_hsv(300, 1.0, 1.0);
assert_eq!(magenta_hsv, magenta_rgb.into());
let blue_green_rgb = Color::from_rgb(0.0, 1.0, 0.5);
let blue_green_hsv = Hsv::from_hsv(150, 1.0, 1.0);
assert_eq!(blue_green_hsv, blue_green_rgb.into());
let green_blue_rgb = Color::from_rgb(0.0, 0.5, 1.0);
let green_blue_hsv = Hsv::from_hsv(210, 1.0, 1.0);
assert_eq!(green_blue_hsv, green_blue_rgb.into());
let green_yellow_rgb = Color::from_rgb(0.5, 1.0, 0.0);
let green_yellow_hsv = Hsv::from_hsv(90, 1.0, 1.0);
assert_eq!(green_yellow_hsv, green_yellow_rgb.into());
let blue_red_rgb = Color::from_rgb(1.0, 0.0, 0.5);
let blue_red_hsv = Hsv::from_hsv(330, 1.0, 1.0);
assert_eq!(blue_red_hsv, blue_red_rgb.into());
let zinnober_rgb = Color::from_rgb(1.0, 0.25, 0.0);
let zinnober_hsv = Hsv::from_hsv(15, 1.0, 1.0);
assert_eq!(zinnober_hsv, zinnober_rgb.into());
let indigo_rgb = Color::from_rgb(0.25, 0.0, 1.0);
let indigo_hsv = Hsv::from_hsv(255, 1.0, 1.0);
assert_eq!(indigo_hsv, indigo_rgb.into());
let light_blue_green_rgb = Color::from_rgb(0.0, 1.0, 0.25);
let light_blue_green_hsv = Hsv::from_hsv(135, 1.0, 1.0);
assert_eq!(light_blue_green_hsv, light_blue_green_rgb.into());
let blue_cyan_rgb = Color::from_rgb(0.0, 0.75, 1.0);
let blue_cyan_hsv = Hsv::from_hsv(195, 1.0, 1.0);
assert_eq!(blue_cyan_hsv, blue_cyan_rgb.into());
let light_green_yellow_rgb = Color::from_rgb(0.75, 1.0, 0.0);
let light_green_yellow_hsv = Hsv::from_hsv(75, 1.0, 1.0);
assert_eq!(light_green_yellow_hsv, light_green_yellow_rgb.into());
let red_magenta_rgb = Color::from_rgb(1.0, 0.0, 0.75);
let red_magenta_hsv = Hsv::from_hsv(315, 1.0, 1.0);
assert_eq!(red_magenta_hsv, red_magenta_rgb.into());
let safran_rgb = Color::from_rgb(1.0, 0.75, 0.0);
let safran_hsv = Hsv::from_hsv(45, 1.0, 1.0);
assert_eq!(safran_hsv, safran_rgb.into());
let blue_magenta_rgb = Color::from_rgb(0.75, 0.0, 1.0);
let blue_magenta_hsv = Hsv::from_hsv(285, 1.0, 1.0);
assert_eq!(blue_magenta_hsv, blue_magenta_rgb.into());
let green_cyan_rgb = Color::from_rgb(0.0, 1.0, 0.75);
let green_cyan_hsv = Hsv::from_hsv(165, 1.0, 1.0);
assert_eq!(green_cyan_hsv, green_cyan_rgb.into());
let light_green_blue_rgb = Color::from_rgb(0.0, 0.25, 1.0);
let light_green_blue_hsv = Hsv::from_hsv(225, 1.0, 1.0);
assert_eq!(light_green_blue_hsv, light_green_blue_rgb.into());
let lime_rgb = Color::from_rgb(0.25, 1.0, 0.0);
let lime_hsv = Hsv::from_hsv(105, 1.0, 1.0);
assert_eq!(lime_hsv, lime_rgb.into());
let light_blue_red_rgb = Color::from_rgb(1.0, 0.0, 0.25);
let light_blue_red_hsv = Hsv::from_hsv(345, 1.0, 1.0);
assert_eq!(light_blue_red_hsv, light_blue_red_rgb.into());
}
#[allow(clippy::cognitive_complexity)]
#[test]
fn hsv_to_rgb() {
// https://de.wikipedia.org/wiki/HSV-Farbraum#Transformation_von_HSV/HSL_und_RGB
let red_hsv = Hsv::from_hsv(0, 1.0, 1.0);
let red_rgb = Color::from_rgb(1.0, 0.0, 0.0);
assert_eq!(red_rgb, red_hsv.into());
let orange_hsv = Hsv::from_hsv(30, 1.0, 1.0);
let orange_rgb = Color::from_rgb(1.0, 0.5, 0.0);
assert_eq!(orange_rgb, orange_hsv.into());
let yellow_hsv = Hsv::from_hsv(60, 1.0, 1.0);
let yellow_rgb = Color::from_rgb(1.0, 1.0, 0.0);
assert_eq!(yellow_rgb, yellow_hsv.into());
let dark_green_hsv = Hsv::from_hsv(120, 1.0, 0.5);
let dark_green_rgb = Color::from_rgb(0.0, 0.5, 0.0);
assert_eq!(dark_green_rgb, dark_green_hsv.into());
let violett_hsv = Hsv::from_hsv(270, 1.0, 1.0);
let violett_rgb = Color::from_rgb(0.5, 0.0, 1.0);
assert_eq!(violett_rgb, violett_hsv.into());
let black_hsv = Hsv::from_hsv(0, 0.0, 0.0);
let black_rgb = Color::from_rgb(0.0, 0.0, 0.0);
assert_eq!(black_rgb, black_hsv.into());
let blue_hsv = Hsv::from_hsv(240, 1.0, 1.0);
let blue_rgb = Color::from_rgb(0.0, 0.0, 1.0);
assert_eq!(blue_rgb, blue_hsv.into());
let brown_hsv = Hsv::from_hsv(20, 0.75, 0.36);
let brown_rgb = Color::from_rgb(0.36, 0.18, 0.09);
assert_eq!(brown_rgb, brown_hsv.into());
let white_hsv = Hsv::from_hsv(0, 0.0, 1.0);
let white_rgb = Color::from_rgb(1.0, 1.0, 1.0);
assert_eq!(white_rgb, white_hsv.into());
let green_hsv = Hsv::from_hsv(120, 1.0, 1.0);
let green_rgb = Color::from_rgb(0.0, 1.0, 0.0);
assert_eq!(green_rgb, green_hsv.into());
let cyan_hsv = Hsv::from_hsv(180, 1.0, 1.0);
let cyan_rgb = Color::from_rgb(0.0, 1.0, 1.0);
assert_eq!(cyan_rgb, cyan_hsv.into());
let magenta_hsv = Hsv::from_hsv(300, 1.0, 1.0);
let magenta_rgb = Color::from_rgb(1.0, 0.0, 1.0);
assert_eq!(magenta_rgb, magenta_hsv.into());
let blue_green_hsv = Hsv::from_hsv(150, 1.0, 1.0);
let blue_green_rgb = Color::from_rgb(0.0, 1.0, 0.5);
assert_eq!(blue_green_rgb, blue_green_hsv.into());
let green_blue_hsv = Hsv::from_hsv(210, 1.0, 1.0);
let green_blue_rgb = Color::from_rgb(0.0, 0.5, 1.0);
assert_eq!(green_blue_rgb, green_blue_hsv.into());
let green_yellow_hsv = Hsv::from_hsv(90, 1.0, 1.0);
let green_yellow_rgb = Color::from_rgb(0.5, 1.0, 0.0);
assert_eq!(green_yellow_rgb, green_yellow_hsv.into());
let blue_red_hsv = Hsv::from_hsv(330, 1.0, 1.0);
let blue_red_rgb = Color::from_rgb(1.0, 0.0, 0.5);
assert_eq!(blue_red_rgb, blue_red_hsv.into());
let zinnober_hsv = Hsv::from_hsv(15, 1.0, 1.0);
let zinnober_rgb = Color::from_rgb(1.0, 0.25, 0.0);
assert_eq!(zinnober_rgb, zinnober_hsv.into());
let indigo_hsv = Hsv::from_hsv(255, 1.0, 1.0);
let indigo_rgb = Color::from_rgb(0.25, 0.0, 1.0);
assert_eq!(indigo_rgb, indigo_hsv.into());
let light_blue_green_hsv = Hsv::from_hsv(135, 1.0, 1.0);
let light_blue_green_rgb = Color::from_rgb(0.0, 1.0, 0.25);
assert_eq!(light_blue_green_rgb, light_blue_green_hsv.into());
let blue_cyan_hsv = Hsv::from_hsv(195, 1.0, 1.0);
let blue_cyan_rgb = Color::from_rgb(0.0, 0.75, 1.0);
assert_eq!(blue_cyan_rgb, blue_cyan_hsv.into());
let light_green_yellow_hsv = Hsv::from_hsv(75, 1.0, 1.0);
let light_green_yellow_rgb = Color::from_rgb(0.75, 1.0, 0.0);
assert_eq!(light_green_yellow_rgb, light_green_yellow_hsv.into());
let red_magenta_hsv = Hsv::from_hsv(315, 1.0, 1.0);
let red_magenta_rgb = Color::from_rgb(1.0, 0.0, 0.75);
assert_eq!(red_magenta_rgb, red_magenta_hsv.into());
let safran_hsv = Hsv::from_hsv(45, 1.0, 1.0);
let safran_rgb = Color::from_rgb(1.0, 0.75, 0.0);
assert_eq!(safran_rgb, safran_hsv.into());
let blue_magenta_hsv = Hsv::from_hsv(285, 1.0, 1.0);
let blue_magenta_rgb = Color::from_rgb(0.75, 0.0, 1.0);
assert_eq!(blue_magenta_rgb, blue_magenta_hsv.into());
let green_cyan_hsv = Hsv::from_hsv(165, 1.0, 1.0);
let green_cyan_rgb = Color::from_rgb(0.0, 1.0, 0.75);
assert_eq!(green_cyan_rgb, green_cyan_hsv.into());
let light_green_blue_hsv = Hsv::from_hsv(225, 1.0, 1.0);
let light_green_blue_rgb = Color::from_rgb(0.0, 0.25, 1.0);
assert_eq!(light_green_blue_rgb, light_green_blue_hsv.into());
let lime_hsv = Hsv::from_hsv(105, 1.0, 1.0);
let lime_rgb = Color::from_rgb(0.25, 1.0, 0.0);
assert_eq!(lime_rgb, lime_hsv.into());
let light_blue_red_hsv = Hsv::from_hsv(345, 1.0, 1.0);
let light_blue_red_rgb = Color::from_rgb(1.0, 0.0, 0.25);
assert_eq!(light_blue_red_rgb, light_blue_red_hsv.into());
}
}
+682
View File
@@ -0,0 +1,682 @@
//! Helper functions for calculating dates
use chrono::{Datelike, Duration, Local, NaiveDate};
use std::fmt::Display;
use std::sync::LazyLock;
/// The date value
#[derive(Clone, Copy, Debug)]
pub struct Date {
/// The year value of the date.
pub year: i32,
/// The month value of the date (1 - 12).
pub month: u32,
/// The day value of the date (1 - 31).
pub day: u32,
}
impl Default for Date {
fn default() -> Self {
Self {
year: 2024,
month: 1,
day: 1,
}
}
}
impl Date {
/// Creates a new date from the current timestamp.
#[must_use]
pub fn today() -> Self {
let today = Local::now().naive_local().date();
today.into()
}
/// Creates a new date.
#[must_use]
pub const fn from_ymd(year: i32, month: u32, day: u32) -> Self {
Self { year, month, day }
}
}
impl Display for Date {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
}
}
impl From<Date> for NaiveDate {
fn from(date: Date) -> Self {
Self::from_ymd_opt(date.year, date.month, date.day)
.expect("Year, Month or Day doesnt Exist")
}
}
impl From<NaiveDate> for Date {
fn from(date: NaiveDate) -> Self {
Self::from_ymd(date.year(), date.month(), date.day())
}
}
/// # Panics
/// Creates a date with the previous month based on the given date.
/// panics if year, month or day doesnt exist.
#[must_use]
pub fn pred_month(date: NaiveDate) -> NaiveDate {
let (year, month) = if date.month() == 1 {
(date.year() - 1, 12)
} else {
(date.year(), date.month() - 1)
};
let day = date.day().min(num_days_of_month(year, month));
NaiveDate::from_ymd_opt(year, month, day).expect("Year, Month or Day doesnt Exist")
}
/// # Panics
/// Creates a date with the next month based on given date.
/// panics if year, month or day doesnt exist.
#[must_use]
pub fn succ_month(date: NaiveDate) -> NaiveDate {
let (year, month) = if date.month() == 12 {
(date.year() + 1, 1)
} else {
(date.year(), date.month() + 1)
};
let day = date.day().min(num_days_of_month(year, month));
NaiveDate::from_ymd_opt(year, month, day).expect("Year, Month or Day doesnt Exist")
}
/// # Panics
/// Creates a date with the previous year based on the given date.
// panics if year, month or day doesnt exist.
#[must_use]
pub fn pred_year(date: NaiveDate) -> NaiveDate {
let year = date.year() - 1;
let day = date.day().min(num_days_of_month(year, date.month()));
NaiveDate::from_ymd_opt(year, date.month(), day).expect("Year, Month or Day doesnt Exist")
}
/// # Panics
/// Creates a date with the next year based on the given date.
// panics if year, month or day doesnt exist.
#[must_use]
pub fn succ_year(date: NaiveDate) -> NaiveDate {
let year = date.year() + 1;
let day = date.day().min(num_days_of_month(year, date.month()));
NaiveDate::from_ymd_opt(year, date.month(), day).expect("Year, Month or Day doesnt Exist")
}
/// Calculates a date with the previous week based on the given date.
#[must_use]
pub fn pred_week(date: NaiveDate) -> NaiveDate {
date - Duration::days(7)
}
/// Calculates a date with the next week based on the given date.
#[must_use]
pub fn succ_week(date: NaiveDate) -> NaiveDate {
date + Duration::days(7)
}
/// Calculates a date with the previous day based on the given date.
#[must_use]
pub fn pred_day(date: NaiveDate) -> NaiveDate {
date - Duration::days(1)
}
/// Calculates a date with the next day based on the given date.
#[must_use]
pub fn succ_day(date: NaiveDate) -> NaiveDate {
date + Duration::days(1)
}
/// Specifies if the calculated day lays in the previous, same or next month of
/// the date.
#[derive(Debug, PartialEq, Eq)]
pub enum IsInMonth {
/// The day lays in the previous month.
Previous,
/// The day lays in the same month.
Same,
/// The day lays in the next month.
Next,
}
/// # Panics
/// Calculates the day number at the given position in the calendar table based
/// on the given year and month.
/// panics if year, month or day does not exist.
#[must_use]
pub fn position_to_day(x: usize, y: usize, year: i32, month: u32) -> (usize, IsInMonth) {
let (x, y) = (x as isize, y as isize);
let first_day =
NaiveDate::from_ymd_opt(year, month, 1).expect("Year, Month or Day doesnt Exist");
let day_of_week = first_day.weekday().num_days_from_monday() as isize;
let day_of_week = if day_of_week == 0 { 7 } else { day_of_week };
let day = (x + 7 * y) + 1 - day_of_week;
if day < 1 {
let last_month = first_day.pred_opt().unwrap_or_default();
(
(num_days_of_month(last_month.year(), last_month.month()) as isize + day) as usize,
IsInMonth::Previous,
)
} else if day > num_days_of_month(year, month) as isize {
(
(day - num_days_of_month(year, month) as isize) as usize,
IsInMonth::Next,
)
} else {
(day as usize, IsInMonth::Same)
}
}
/// Checks if the given year is a leap year.
const fn is_leap_year(year: i32) -> bool {
let mod4 = year % 4 == 0;
let mod100 = year % 100 == 0;
let mod400 = year % 400 == 0;
mod4 && (!mod100 || mod400)
}
/// Gets the number of days the given month in the year has.
const fn num_days_of_month(year: i32, month: u32) -> u32 {
match month {
4 | 6 | 9 | 11 => 30,
2 => {
if is_leap_year(year) {
29
} else {
28
}
}
_ => 31,
}
}
/// Gets the string representation of the date of the given month and date.
#[must_use]
pub fn date_as_string(date: NaiveDate) -> String {
date.format("%Y %B").to_string()
}
/// Gets the length of the longest month name.
pub static MAX_MONTH_STR_LEN: LazyLock<usize> = LazyLock::new(|| {
let months = [
NaiveDate::from_ymd_opt(0, 1, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 2, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 3, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 4, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 5, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 6, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 7, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 8, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 9, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 10, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 11, 1).expect("Year, Month or Day doesnt Exist"),
NaiveDate::from_ymd_opt(0, 12, 1).expect("Year, Month or Day doesnt Exist"),
];
months
.iter()
.map(|m| {
let d = date_as_string(*m);
let (_, s) = d.split_once(' ').expect("Date must contain space");
s.len()
})
.max()
.expect("There should be a maximum element")
});
/// Gets the labels of the weekdays containing the first two characters of
/// the weekdays.
pub static WEEKDAY_LABELS: LazyLock<Vec<String>> = LazyLock::new(|| {
let days = [
// Monday
NaiveDate::from_ymd_opt(2020, 6, 1).expect("Year, Month or Day doesnt Exist"),
// Tuesday
NaiveDate::from_ymd_opt(2020, 6, 2).expect("Year, Month or Day doesnt Exist"),
// Wednesday
NaiveDate::from_ymd_opt(2020, 6, 3).expect("Year, Month or Day doesnt Exist"),
// Thursday
NaiveDate::from_ymd_opt(2020, 6, 4).expect("Year, Month or Day doesnt Exist"),
// Friday
NaiveDate::from_ymd_opt(2020, 6, 5).expect("Year, Month or Day doesnt Exist"),
// Saturday
NaiveDate::from_ymd_opt(2020, 6, 6).expect("Year, Month or Day doesnt Exist"),
// Sunday
NaiveDate::from_ymd_opt(2020, 6, 7).expect("Year, Month or Day doesnt Exist"),
];
days.iter()
.map(|d| d.format("%a").to_string())
.map(|s| s[0..2].to_owned())
.collect()
});
#[cfg(test)]
mod tests {
use chrono::{Datelike, NaiveDate};
use super::{
IsInMonth, is_leap_year, num_days_of_month, position_to_day, pred_month, pred_year,
succ_month, succ_year,
};
#[test]
fn pred_month_test() {
let date = NaiveDate::from_ymd_opt(2020, 5, 6).expect("Year, Month or Day doesnt Exist");
let result = pred_month(date);
let expected =
NaiveDate::from_ymd_opt(2020, 4, 6).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2020, 1, 24).expect("Year, Month or Day doesnt Exist");
let result = pred_month(date);
let expected =
NaiveDate::from_ymd_opt(2019, 12, 24).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2020, 3, 31).expect("Year, Month or Day doesnt Exist");
let result = pred_month(date);
let expected =
NaiveDate::from_ymd_opt(2020, 2, 29).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
}
#[test]
fn succ_month_test() {
let date = NaiveDate::from_ymd_opt(2020, 5, 6).expect("Year, Month or Day doesnt Exist");
let result = succ_month(date);
let expected =
NaiveDate::from_ymd_opt(2020, 6, 6).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2019, 12, 24).expect("Year, Month or Day doesnt Exist");
let result = succ_month(date);
let expected =
NaiveDate::from_ymd_opt(2020, 1, 24).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2020, 1, 31).expect("Year, Month or Day doesnt Exist");
let result = succ_month(date);
let expected =
NaiveDate::from_ymd_opt(2020, 2, 29).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
}
#[test]
fn pred_year_test() {
let date = NaiveDate::from_ymd_opt(2020, 5, 6).expect("Year, Month or Day doesnt Exist");
let result = pred_year(date);
let expected =
NaiveDate::from_ymd_opt(2019, 5, 6).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2020, 2, 29).expect("Year, Month or Day doesnt Exist");
let result = pred_year(date);
let expected =
NaiveDate::from_ymd_opt(2019, 2, 28).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2021, 2, 28).expect("Year, Month or Day doesnt Exist");
let result = pred_year(date);
let expected =
NaiveDate::from_ymd_opt(2020, 2, 28).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
}
#[test]
fn succ_year_test() {
let date = NaiveDate::from_ymd_opt(2020, 5, 6).expect("Year, Month or Day doesnt Exist");
let result = succ_year(date);
let expected =
NaiveDate::from_ymd_opt(2021, 5, 6).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2020, 2, 29).expect("Year, Month or Day doesnt Exist");
let result = succ_year(date);
let expected =
NaiveDate::from_ymd_opt(2021, 2, 28).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
let date = NaiveDate::from_ymd_opt(2019, 2, 28).expect("Year, Month or Day doesnt Exist");
let result = succ_year(date);
let expected =
NaiveDate::from_ymd_opt(2020, 2, 28).expect("Year, Month or Day doesnt Exist");
assert_eq!(result, expected);
}
#[allow(clippy::shadow_unrelated)]
#[test]
fn position_to_day_test() {
let (day, is_in_month) = position_to_day(0, 0, 2020, 12);
assert_eq!(day, 30);
assert_eq!(is_in_month, IsInMonth::Previous);
let (day, is_in_month) = position_to_day(1, 0, 2020, 12);
assert_eq!(day, 1);
assert_eq!(is_in_month, IsInMonth::Same);
let (day, is_in_month) = position_to_day(3, 4, 2020, 12);
assert_eq!(day, 31);
assert_eq!(is_in_month, IsInMonth::Same);
let (day, is_in_month) = position_to_day(6, 5, 2020, 12);
assert_eq!(day, 10);
assert_eq!(is_in_month, IsInMonth::Next);
let (day, is_in_month) = position_to_day(0, 0, 2020, 11);
assert_eq!(day, 26);
assert_eq!(is_in_month, IsInMonth::Previous);
let (day, is_in_month) = position_to_day(6, 0, 2020, 11);
assert_eq!(day, 1);
assert_eq!(is_in_month, IsInMonth::Same);
let (day, is_in_month) = position_to_day(0, 5, 2020, 11);
assert_eq!(day, 30);
assert_eq!(is_in_month, IsInMonth::Same);
let (day, is_in_month) = position_to_day(6, 5, 2020, 11);
assert_eq!(day, 6);
assert_eq!(is_in_month, IsInMonth::Next);
let (day, is_in_month) = position_to_day(0, 0, 2021, 2);
assert_eq!(day, 25);
assert_eq!(is_in_month, IsInMonth::Previous);
let (day, is_in_month) = position_to_day(0, 1, 2021, 2);
assert_eq!(day, 1);
assert_eq!(is_in_month, IsInMonth::Same);
let (day, is_in_month) = position_to_day(6, 4, 2021, 2);
assert_eq!(day, 28);
assert_eq!(is_in_month, IsInMonth::Same);
let (day, is_in_month) = position_to_day(0, 5, 2021, 2);
assert_eq!(day, 1);
assert_eq!(is_in_month, IsInMonth::Next);
}
#[test]
fn is_leap_year_test() {
assert!(is_leap_year(2020));
assert!(!is_leap_year(2019));
assert!(!is_leap_year(2021));
assert!(is_leap_year(2000));
assert!(!is_leap_year(1000));
}
#[test]
fn num_days_of_month_test() {
assert_eq!(num_days_of_month(2020, 1), 31);
assert_eq!(num_days_of_month(2020, 2), 29);
assert_eq!(num_days_of_month(2019, 2), 28);
assert_eq!(num_days_of_month(2020, 3), 31);
assert_eq!(num_days_of_month(2020, 4), 30);
assert_eq!(num_days_of_month(2020, 5), 31);
assert_eq!(num_days_of_month(2020, 6), 30);
assert_eq!(num_days_of_month(2020, 7), 31);
assert_eq!(num_days_of_month(2020, 8), 31);
assert_eq!(num_days_of_month(2020, 9), 30);
assert_eq!(num_days_of_month(2020, 10), 31);
assert_eq!(num_days_of_month(2020, 11), 30);
assert_eq!(num_days_of_month(2020, 12), 31);
}
#[test]
fn date_default() {
use super::Date;
let date = Date::default();
assert_eq!(date.year, 2024);
assert_eq!(date.month, 1);
assert_eq!(date.day, 1);
}
#[test]
fn date_from_ymd() {
use super::Date;
let date = Date::from_ymd(2023, 12, 25);
assert_eq!(date.year, 2023);
assert_eq!(date.month, 12);
assert_eq!(date.day, 25);
}
#[test]
fn date_display() {
use super::Date;
let date = Date::from_ymd(2023, 3, 5);
assert_eq!(format!("{date}"), "2023-03-05");
let date = Date::from_ymd(2023, 12, 31);
assert_eq!(format!("{date}"), "2023-12-31");
let date = Date::from_ymd(1999, 1, 1);
assert_eq!(format!("{date}"), "1999-01-01");
}
#[test]
fn date_to_naive_date() {
use super::Date;
let date = Date::from_ymd(2023, 6, 15);
let naive: NaiveDate = date.into();
assert_eq!(naive.year(), 2023);
assert_eq!(naive.month(), 6);
assert_eq!(naive.day(), 15);
}
#[test]
fn naive_date_to_date() {
use super::Date;
let naive =
NaiveDate::from_ymd_opt(2023, 6, 15).expect("naive_date_to_date should not be none");
let date: Date = naive.into();
assert_eq!(date.year, 2023);
assert_eq!(date.month, 6);
assert_eq!(date.day, 15);
}
#[test]
fn pred_week_test() {
use super::pred_week;
let date = NaiveDate::from_ymd_opt(2020, 5, 15).expect("pred_week_test should not be none");
let result = pred_week(date);
let expected =
NaiveDate::from_ymd_opt(2020, 5, 8).expect("pred_week_test should not be none");
assert_eq!(result, expected);
}
#[test]
fn pred_week_crosses_month() {
use super::pred_week;
let date = NaiveDate::from_ymd_opt(2020, 5, 5)
.expect("pred_week_crosses_month should not be none");
let result = pred_week(date);
let expected = NaiveDate::from_ymd_opt(2020, 4, 28)
.expect("pred_week_crosses_month should not be none");
assert_eq!(result, expected);
}
#[test]
fn succ_week_test() {
use super::succ_week;
let date = NaiveDate::from_ymd_opt(2020, 5, 15).expect("succ_week_test should not be none");
let result = succ_week(date);
let expected =
NaiveDate::from_ymd_opt(2020, 5, 22).expect("succ_week_test should not be none");
assert_eq!(result, expected);
}
#[test]
fn succ_week_crosses_month() {
use super::succ_week;
let date = NaiveDate::from_ymd_opt(2020, 5, 28)
.expect("succ_week_crosses_month should not be none");
let result = succ_week(date);
let expected = NaiveDate::from_ymd_opt(2020, 6, 4)
.expect("succ_week_crosses_month should not be none");
assert_eq!(result, expected);
}
#[test]
fn pred_day_test() {
use super::pred_day;
let date = NaiveDate::from_ymd_opt(2020, 5, 15).expect("pred_day_test should not be none");
let result = pred_day(date);
let expected =
NaiveDate::from_ymd_opt(2020, 5, 14).expect("pred_day_test should not be none");
assert_eq!(result, expected);
}
#[test]
fn pred_day_crosses_month() {
use super::pred_day;
let date =
NaiveDate::from_ymd_opt(2020, 5, 1).expect("pred_day_crosses_month should not be none");
let result = pred_day(date);
let expected = NaiveDate::from_ymd_opt(2020, 4, 30)
.expect("pred_day_crosses_month should not be none");
assert_eq!(result, expected);
}
#[test]
fn succ_day_test() {
use super::succ_day;
let date = NaiveDate::from_ymd_opt(2020, 5, 15).expect("succ_day_test should not be none");
let result = succ_day(date);
let expected =
NaiveDate::from_ymd_opt(2020, 5, 16).expect("succ_day_test should not be none");
assert_eq!(result, expected);
}
#[test]
fn succ_day_crosses_month() {
use super::succ_day;
let date = NaiveDate::from_ymd_opt(2020, 5, 31)
.expect("succ_day_crosses_month should not be none");
let result = succ_day(date);
let expected =
NaiveDate::from_ymd_opt(2020, 6, 1).expect("succ_day_crosses_month should not be none");
assert_eq!(result, expected);
}
#[test]
fn date_as_string_test() {
use super::date_as_string;
let date =
NaiveDate::from_ymd_opt(2023, 1, 15).expect("date_as_string_test should not be none");
let result = date_as_string(date);
assert!(result.starts_with("2023"));
assert!(result.contains("January") || result.contains("Jan"));
}
#[test]
fn is_leap_year_century_rules() {
// Century years divisible by 400 are leap years
assert!(is_leap_year(2000));
assert!(is_leap_year(2400));
// Century years not divisible by 400 are not leap years
assert!(!is_leap_year(1900));
assert!(!is_leap_year(2100));
assert!(!is_leap_year(2200));
assert!(!is_leap_year(2300));
}
#[test]
fn is_leap_year_edge_cases() {
// Regular leap years
assert!(is_leap_year(2024));
assert!(is_leap_year(2028));
// Regular non-leap years
assert!(!is_leap_year(2023));
assert!(!is_leap_year(2025));
assert!(!is_leap_year(2026));
assert!(!is_leap_year(2027));
}
#[test]
fn max_month_str_len_is_defined() {
use super::MAX_MONTH_STR_LEN;
// Just verify it's accessible and has a reasonable value
assert!(*MAX_MONTH_STR_LEN > 0);
assert!(*MAX_MONTH_STR_LEN <= 20); // No month name should be longer than 20 chars
}
#[test]
fn weekday_labels_has_seven_days() {
use super::WEEKDAY_LABELS;
assert_eq!(WEEKDAY_LABELS.len(), 7);
// Each label should be exactly 2 characters
for label in WEEKDAY_LABELS.iter() {
assert_eq!(label.len(), 2);
}
}
#[test]
fn pred_month_february_to_january() {
let date = NaiveDate::from_ymd_opt(2020, 2, 15)
.expect("pred_month_february_to_january should not be none");
let result = pred_month(date);
let expected = NaiveDate::from_ymd_opt(2020, 1, 15)
.expect("pred_month_february_to_january should not be none");
assert_eq!(result, expected);
}
#[test]
fn succ_month_november_to_december() {
let date = NaiveDate::from_ymd_opt(2020, 11, 15)
.expect("succ_month_november_to_december should not be none");
let result = succ_month(date);
let expected = NaiveDate::from_ymd_opt(2020, 12, 15)
.expect("succ_month_november_to_december should not be none");
assert_eq!(result, expected);
}
#[test]
fn num_days_february_leap_vs_non_leap() {
// Leap year
assert_eq!(num_days_of_month(2020, 2), 29);
assert_eq!(num_days_of_month(2024, 2), 29);
// Non-leap year
assert_eq!(num_days_of_month(2019, 2), 28);
assert_eq!(num_days_of_month(2021, 2), 28);
assert_eq!(num_days_of_month(2022, 2), 28);
assert_eq!(num_days_of_month(2023, 2), 28);
}
#[test]
fn date_copy_trait() {
use super::Date;
let date1 = Date::from_ymd(2023, 6, 15);
let date2 = date1; // Copy
// Both should be usable
assert_eq!(date1.year, 2023);
assert_eq!(date2.year, 2023);
}
#[test]
fn date_clone_trait() {
use super::Date;
let date1 = Date::from_ymd(2023, 6, 15);
let date2 = date1;
assert_eq!(date1.year, date2.year);
assert_eq!(date1.month, date2.month);
assert_eq!(date1.day, date2.day);
}
}
+134
View File
@@ -0,0 +1,134 @@
//! Offset struct
use iced_core::Point;
/// Represents an offset in a two-dimensional space.
#[derive(Copy, Clone, Debug)]
pub struct Offset {
/// Offset on the x-axis
pub x: f32,
/// Offset on the y-axis
pub y: f32,
}
impl Offset {
/// Construct a new [`Offset`]
#[must_use]
pub fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
}
impl From<f32> for Offset {
fn from(float: f32) -> Self {
Self { x: float, y: float }
}
}
impl From<[f32; 2]> for Offset {
fn from(array: [f32; 2]) -> Self {
Self {
x: array[0],
y: array[1],
}
}
}
impl From<Offset> for Point {
fn from(offset: Offset) -> Self {
Self::new(offset.x, offset.y)
}
}
impl From<&Offset> for Point {
fn from(offset: &Offset) -> Self {
Self::new(offset.x, offset.y)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_creates_offset() {
let offset = Offset::new(10.0, 20.0);
assert_eq!(offset.x, 10.0);
assert_eq!(offset.y, 20.0);
}
#[test]
fn new_handles_negative_values() {
let offset = Offset::new(-5.0, -15.0);
assert_eq!(offset.x, -5.0);
assert_eq!(offset.y, -15.0);
}
#[test]
fn new_handles_zero() {
let offset = Offset::new(0.0, 0.0);
assert_eq!(offset.x, 0.0);
assert_eq!(offset.y, 0.0);
}
#[test]
fn from_f32_creates_offset_with_same_values() {
let offset = Offset::from(5.0);
assert_eq!(offset.x, 5.0);
assert_eq!(offset.y, 5.0);
}
#[test]
fn from_f32_handles_negative() {
let offset = Offset::from(-3.5);
assert_eq!(offset.x, -3.5);
assert_eq!(offset.y, -3.5);
}
#[test]
fn from_array_creates_offset() {
let offset = Offset::from([12.0, 34.0]);
assert_eq!(offset.x, 12.0);
assert_eq!(offset.y, 34.0);
}
#[test]
fn from_array_handles_different_signs() {
let offset = Offset::from([-7.5, 8.5]);
assert_eq!(offset.x, -7.5);
assert_eq!(offset.y, 8.5);
}
#[test]
fn offset_to_point_conversion() {
let offset = Offset::new(15.0, 25.0);
let point: Point = offset.into();
assert_eq!(point.x, 15.0);
assert_eq!(point.y, 25.0);
}
#[test]
fn offset_ref_to_point_conversion() {
let offset = Offset::new(15.0, 25.0);
let point: Point = (&offset).into();
assert_eq!(point.x, 15.0);
assert_eq!(point.y, 25.0);
}
#[test]
fn offset_is_copy() {
let offset1 = Offset::new(1.0, 2.0);
let offset2 = offset1;
// Both should be usable since Offset implements Copy
assert_eq!(offset1.x, 1.0);
assert_eq!(offset2.x, 1.0);
}
#[test]
fn offset_is_clone() {
let offset1 = Offset::new(3.0, 4.0);
let offset2 = offset1;
assert_eq!(offset1.x, offset2.x);
assert_eq!(offset1.y, offset2.y);
}
}
+214
View File
@@ -0,0 +1,214 @@
//! Helper functions for overlays
use iced_core::{Point, Size, layout};
/// Trait containing functions for positioning of nodes.
pub trait Position {
/// Centers this node around the given position. If the node is over the
/// specified bounds it's bouncing back to be fully visible on screen.
fn center_and_bounce(&mut self, position: Point, bounds: Size);
}
impl Position for layout::Node {
fn center_and_bounce(&mut self, position: Point, bounds: Size) {
let size = self.size();
self.move_to_mut(Point::new(
(position.x - (size.width / 2.0)).max(0.0),
(position.y - (size.height / 2.0)).max(0.0),
));
let new_self_bounds = self.bounds();
self.move_to_mut(Point::new(
if new_self_bounds.x + new_self_bounds.width > bounds.width {
(new_self_bounds.x - (new_self_bounds.width - (bounds.width - new_self_bounds.x)))
.max(0.0)
} else {
new_self_bounds.x
},
if new_self_bounds.y + new_self_bounds.height > bounds.height {
(new_self_bounds.y - (new_self_bounds.height - (bounds.height - new_self_bounds.y)))
.max(0.0)
} else {
new_self_bounds.y
},
));
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::layout::Node;
#[test]
fn center_within_bounds() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(200.0, 150.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Node should be centered at position: x = 200 - 50 = 150, y = 150 - 25 = 125
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 150.0);
assert_eq!(node_bounds.y, 125.0);
}
#[test]
fn bounce_right_edge() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(380.0, 150.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Node would center at x = 380 - 50 = 330, which extends to 430
// This exceeds bounds.width (400), so should bounce back to x = 300
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 300.0);
assert_eq!(node_bounds.y, 125.0);
}
#[test]
fn bounce_bottom_edge() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(200.0, 285.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Node would center at y = 285 - 25 = 260, which extends to 310
// This exceeds bounds.height (300), so should bounce back to y = 250
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 150.0);
assert_eq!(node_bounds.y, 250.0);
}
#[test]
fn bounce_right_and_bottom() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(380.0, 285.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Should bounce back on both axes
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 300.0);
assert_eq!(node_bounds.y, 250.0);
}
#[test]
fn position_at_origin() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(0.0, 0.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Centering at origin would give negative position, but it's clamped to 0
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 0.0);
assert_eq!(node_bounds.y, 0.0);
}
#[test]
fn position_near_top_left() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(10.0, 10.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Would center at negative position, clamped to 0
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 0.0);
assert_eq!(node_bounds.y, 0.0);
}
#[test]
fn exact_fit_at_corner() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(350.0, 275.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Node centers at (300, 250) and fits exactly within bounds
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 300.0);
assert_eq!(node_bounds.y, 250.0);
}
#[test]
fn small_node_centered() {
let mut node = Node::new(Size::new(20.0, 10.0));
let position = Point::new(200.0, 150.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Small node should center perfectly
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 190.0);
assert_eq!(node_bounds.y, 145.0);
}
#[test]
fn node_larger_than_bounds() {
let mut node = Node::new(Size::new(500.0, 400.0));
let position = Point::new(200.0, 150.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Node is larger than bounds, should position at (0, 0) as best effort
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 0.0);
assert_eq!(node_bounds.y, 0.0);
}
#[test]
fn node_width_equals_bounds_width() {
let mut node = Node::new(Size::new(400.0, 50.0));
let position = Point::new(200.0, 150.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Node width equals bounds, should position at x = 0
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 0.0);
assert_eq!(node_bounds.y, 125.0);
}
#[test]
fn node_height_equals_bounds_height() {
let mut node = Node::new(Size::new(100.0, 300.0));
let position = Point::new(200.0, 150.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Node height equals bounds, should position at y = 0
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 150.0);
assert_eq!(node_bounds.y, 0.0);
}
#[test]
fn position_at_exact_bounds() {
let mut node = Node::new(Size::new(100.0, 50.0));
let position = Point::new(400.0, 300.0);
let bounds = Size::new(400.0, 300.0);
node.center_and_bounce(position, bounds);
// Position at bounds edge, should bounce back
let node_bounds = node.bounds();
assert_eq!(node_bounds.x, 300.0);
assert_eq!(node_bounds.y, 250.0);
}
}
+20
View File
@@ -0,0 +1,20 @@
//! Helper struct for drawing
use iced_core::{Layout, Point, Rectangle};
/// Collection of all necessary data to draw a widget.
#[derive(Debug)]
pub struct DrawEnvironment<'a, Defaults, Style, Focus> {
/// The defaults of the renderer.
pub defaults: &'a Defaults,
/// The layout of the widget.
pub layout: Layout<'a>,
/// The position of the cursor.
pub cursor_position: Point,
/// The style of the widget.
pub style_sheet: &'a Style,
/// The viewport of the renderer.
pub viewport: Option<&'a Rectangle>,
/// The focus to an input element on the widget.
pub focus: Focus,
}
+683
View File
@@ -0,0 +1,683 @@
//! Use a time picker as an input element for picking times.
//!
//! *This API requires the following crate features to be activated: `time_picker`*
use chrono::{Local, Timelike};
use std::fmt::Display;
/// The time value
#[derive(Clone, Copy, Debug)]
pub enum Time {
/// The time value containing hour, minute and period.
Hm {
/// The hour value.
hour: u32,
/// The minute value.
minute: u32,
/// The current period of the time.
period: Period,
},
/// The time value containing hour, minute, second and period.
Hms {
/// The hour value.
hour: u32,
/// The minute value.
minute: u32,
/// The second value.
second: u32,
/// The current period of the time.
period: Period,
},
}
impl Default for Time {
fn default() -> Self {
Self::Hm {
hour: 1,
minute: 0,
period: Period::Am,
}
}
}
impl Time {
/// Creates a new time (hours, minutes) from the current timestamp.
#[must_use]
pub fn now_hm(use_24h: bool) -> Self {
let now = Local::now().naive_local().time();
let (hour, period) = if use_24h {
(now.hour(), Period::H24)
} else {
let (period, hour12) = now.hour12();
(hour12, if period { Period::Pm } else { Period::Am })
};
Self::Hm {
hour,
minute: now.minute(),
period,
}
}
/// Creates a new time (hours, minutes, seconds) from the current timestamp.
#[must_use]
pub fn now_hms(use_24h: bool) -> Self {
let now = Local::now().naive_local().time();
let (hour, period) = if use_24h {
(now.hour(), Period::H24)
} else {
let (period, hour12) = now.hour12();
(hour12, if period { Period::Pm } else { Period::Am })
};
Self::Hms {
hour,
minute: now.minute(),
second: now.second(),
period,
}
}
/// The default time `00:00` with the given period.
#[must_use]
pub const fn default_hm(period: Period) -> Self {
Self::Hm {
hour: 0,
minute: 0,
period,
}
}
/// The default time `00:00:00` with the given period.
#[must_use]
pub const fn default_hms(period: Period) -> Self {
Self::Hms {
hour: 0,
minute: 0,
second: 0,
period,
}
}
}
impl Display for Time {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Hm {
hour,
minute,
period,
} => {
write!(f, "{hour:02}:{minute:02}{period}")
}
Self::Hms {
hour,
minute,
second,
period,
} => {
write!(f, "{hour:02}:{minute:02}:{second:02}{period}")
}
}
}
}
/// The current period of the clock
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Period {
/// No period - using 24 hour format.
H24,
/// Ante meridiem: Before noon.
Am,
/// Post meridiem: After noon.
Pm,
}
impl Display for Period {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Self::H24 => "",
Self::Am => " AM",
Self::Pm => " PM",
}
)
}
}
impl From<Time> for chrono::NaiveTime {
fn from(time: Time) -> Self {
let (h, m, s, p) = match time {
Time::Hm {
hour,
minute,
period,
} => (hour, minute, 0, period),
Time::Hms {
hour,
minute,
second,
period,
} => (hour, minute, second, period),
};
let h = if h == 12 && p != Period::H24 { 0 } else { h };
let h = match p {
Period::H24 | Period::Am => h,
Period::Pm => (h + 12) % 24,
};
Self::from_hms_opt(h, m, s).expect("Time Conversion failed. H, M, or S was too large.")
}
}
impl From<chrono::NaiveTime> for Time {
fn from(time: chrono::NaiveTime) -> Self {
Self::Hms {
hour: time.hour(),
minute: time.minute(),
second: time.second(),
period: Period::H24,
}
}
}
#[cfg(test)]
mod tests {
use chrono::NaiveTime;
use super::{Period, Time};
#[test]
fn time_to_naive() {
let time = Time::Hms {
hour: 8,
minute: 52,
second: 17,
period: Period::H24,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(8, 52, 17).expect("Time Conversion failed")
);
let time = Time::Hms {
hour: 23,
minute: 48,
second: 39,
period: Period::H24,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(23, 48, 39).expect("Time Conversion failed")
);
let time = Time::Hms {
hour: 8,
minute: 52,
second: 17,
period: Period::Am,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(8, 52, 17).expect("Time Conversion failed")
);
let time = Time::Hms {
hour: 8,
minute: 52,
second: 17,
period: Period::Pm,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(20, 52, 17).expect("Time Conversion failed")
);
let time = Time::Hms {
hour: 12,
minute: 52,
second: 17,
period: Period::Am,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(0, 52, 17).expect("Time Conversion failed")
);
let time = Time::Hms {
hour: 12,
minute: 52,
second: 17,
period: Period::Pm,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(12, 52, 17).expect("Time Conversion failed")
);
let time = Time::Hm {
hour: 17,
minute: 52,
period: Period::H24,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(17, 52, 0).expect("Time Conversion failed")
);
}
#[test]
fn time_default() {
let time = Time::default();
match time {
Time::Hm {
hour,
minute,
period,
} => {
assert_eq!(hour, 1);
assert_eq!(minute, 0);
assert_eq!(period, Period::Am);
}
#[allow(clippy::panic)]
Time::Hms { .. } => panic!("Expected Time::Hm variant"),
}
}
#[test]
fn time_default_hm_am() {
let time = Time::default_hm(Period::Am);
match time {
Time::Hm {
hour,
minute,
period,
} => {
assert_eq!(hour, 0);
assert_eq!(minute, 0);
assert_eq!(period, Period::Am);
}
#[allow(clippy::panic)]
Time::Hms { .. } => panic!("Expected Time::Hm variant"),
}
}
#[test]
fn time_default_hm_pm() {
let time = Time::default_hm(Period::Pm);
match time {
Time::Hm {
hour,
minute,
period,
} => {
assert_eq!(hour, 0);
assert_eq!(minute, 0);
assert_eq!(period, Period::Pm);
}
#[allow(clippy::panic)]
Time::Hms { .. } => panic!("Expected Time::Hm variant"),
}
}
#[test]
fn time_default_hm_h24() {
let time = Time::default_hm(Period::H24);
match time {
Time::Hm {
hour,
minute,
period,
} => {
assert_eq!(hour, 0);
assert_eq!(minute, 0);
assert_eq!(period, Period::H24);
}
#[allow(clippy::panic)]
Time::Hms { .. } => panic!("Expected Time::Hm variant"),
}
}
#[test]
fn time_default_hms_am() {
let time = Time::default_hms(Period::Am);
match time {
Time::Hms {
hour,
minute,
second,
period,
} => {
assert_eq!(hour, 0);
assert_eq!(minute, 0);
assert_eq!(second, 0);
assert_eq!(period, Period::Am);
}
#[allow(clippy::panic)]
Time::Hm { .. } => panic!("Expected Time::Hms variant"),
}
}
#[test]
fn time_default_hms_pm() {
let time = Time::default_hms(Period::Pm);
match time {
Time::Hms {
hour,
minute,
second,
period,
} => {
assert_eq!(hour, 0);
assert_eq!(minute, 0);
assert_eq!(second, 0);
assert_eq!(period, Period::Pm);
}
#[allow(clippy::panic)]
Time::Hm { .. } => panic!("Expected Time::Hms variant"),
}
}
#[test]
fn time_default_hms_h24() {
let time = Time::default_hms(Period::H24);
match time {
Time::Hms {
hour,
minute,
second,
period,
} => {
assert_eq!(hour, 0);
assert_eq!(minute, 0);
assert_eq!(second, 0);
assert_eq!(period, Period::H24);
}
#[allow(clippy::panic)]
Time::Hm { .. } => panic!("Expected Time::Hms variant"),
}
}
#[test]
fn time_hm_display_h24() {
let time = Time::Hm {
hour: 14,
minute: 30,
period: Period::H24,
};
assert_eq!(format!("{time}"), "14:30");
}
#[test]
fn time_hm_display_am() {
let time = Time::Hm {
hour: 9,
minute: 15,
period: Period::Am,
};
assert_eq!(format!("{time}"), "09:15 AM");
}
#[test]
fn time_hm_display_pm() {
let time = Time::Hm {
hour: 3,
minute: 45,
period: Period::Pm,
};
assert_eq!(format!("{time}"), "03:45 PM");
}
#[test]
fn time_hms_display_h24() {
let time = Time::Hms {
hour: 23,
minute: 59,
second: 59,
period: Period::H24,
};
assert_eq!(format!("{time}"), "23:59:59");
}
#[test]
fn time_hms_display_am() {
let time = Time::Hms {
hour: 6,
minute: 30,
second: 45,
period: Period::Am,
};
assert_eq!(format!("{time}"), "06:30:45 AM");
}
#[test]
fn time_hms_display_pm() {
let time = Time::Hms {
hour: 11,
minute: 22,
second: 33,
period: Period::Pm,
};
assert_eq!(format!("{time}"), "11:22:33 PM");
}
#[test]
fn period_display_h24() {
assert_eq!(format!("{}", Period::H24), "");
}
#[test]
fn period_display_am() {
assert_eq!(format!("{}", Period::Am), " AM");
}
#[test]
fn period_display_pm() {
assert_eq!(format!("{}", Period::Pm), " PM");
}
#[test]
fn naive_time_to_time() {
let naive =
NaiveTime::from_hms_opt(14, 30, 45).expect("naive_time_to_time should not be none");
let time: Time = naive.into();
match time {
Time::Hms {
hour,
minute,
second,
period,
} => {
assert_eq!(hour, 14);
assert_eq!(minute, 30);
assert_eq!(second, 45);
assert_eq!(period, Period::H24);
}
#[allow(clippy::panic)]
Time::Hm { .. } => panic!("Expected Time::Hms variant"),
}
}
#[test]
fn naive_time_midnight_to_time() {
let naive = NaiveTime::from_hms_opt(0, 0, 0)
.expect("naive_time_midnight_to_time should not be none");
let time: Time = naive.into();
match time {
Time::Hms {
hour,
minute,
second,
period,
} => {
assert_eq!(hour, 0);
assert_eq!(minute, 0);
assert_eq!(second, 0);
assert_eq!(period, Period::H24);
}
#[allow(clippy::panic)]
Time::Hm { .. } => panic!("Expected Time::Hms variant"),
}
}
#[test]
fn time_hm_midnight_am_to_naive() {
let time = Time::Hm {
hour: 12,
minute: 0,
period: Period::Am,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(0, 0, 0)
.expect("time_hm_midnight_am_to_naive Should not be none")
);
}
#[test]
fn time_hm_noon_pm_to_naive() {
let time = Time::Hm {
hour: 12,
minute: 0,
period: Period::Pm,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(12, 0, 0).expect("time_hm_noon_pm_to_naive Should not be none")
);
}
#[test]
fn time_hm_one_am_to_naive() {
let time = Time::Hm {
hour: 1,
minute: 30,
period: Period::Am,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(1, 30, 0).expect("time_hm_one_am_to_naive Should not be none")
);
}
#[test]
fn time_hm_eleven_pm_to_naive() {
let time = Time::Hm {
hour: 11,
minute: 45,
period: Period::Pm,
};
let naive: NaiveTime = time.into();
assert_eq!(
naive,
NaiveTime::from_hms_opt(23, 45, 0)
.expect("time_hm_eleven_pm_to_naive Should not be none")
);
}
#[test]
fn time_copy_trait() {
let time1 = Time::Hm {
hour: 10,
minute: 30,
period: Period::Am,
};
let time2 = time1; // Copy
// Both should be usable
match time1 {
Time::Hm { hour, .. } => assert_eq!(hour, 10),
#[allow(clippy::panic)]
Time::Hms { .. } => panic!("Expected Time::Hm"),
}
match time2 {
Time::Hm { hour, .. } => assert_eq!(hour, 10),
#[allow(clippy::panic)]
Time::Hms { .. } => panic!("Expected Time::Hm"),
}
}
#[test]
fn time_clone_trait() {
let time1 = Time::Hms {
hour: 15,
minute: 45,
second: 30,
period: Period::H24,
};
let time2 = time1;
match (time1, time2) {
(
Time::Hms {
hour: h1,
minute: m1,
second: s1,
period: p1,
},
Time::Hms {
hour: h2,
minute: m2,
second: s2,
period: p2,
},
) => {
assert_eq!(h1, h2);
assert_eq!(m1, m2);
assert_eq!(s1, s2);
assert_eq!(p1, p2);
}
#[allow(clippy::panic)]
_ => panic!("Expected Time::Hms for both"),
}
}
#[test]
fn period_copy_trait() {
let p1 = Period::Am;
let p2 = p1; // Copy
assert_eq!(p1, Period::Am);
assert_eq!(p2, Period::Am);
}
#[test]
fn period_clone_trait() {
let p1 = Period::Pm;
let p2 = p1;
assert_eq!(p1, p2);
}
#[test]
fn period_equality() {
assert_eq!(Period::Am, Period::Am);
assert_eq!(Period::Pm, Period::Pm);
assert_eq!(Period::H24, Period::H24);
assert_ne!(Period::Am, Period::Pm);
assert_ne!(Period::Am, Period::H24);
assert_ne!(Period::Pm, Period::H24);
}
}
+178
View File
@@ -0,0 +1,178 @@
//! Additional widget for the Iced GUI library.
//!
//! # Examples
//!
//! * `badge` (Author: Kaiden42 <gitlab@tinysn.com>)
//! * `card` (Author: Kaiden42 <gitlab@tinysn.com>)
//! * `color_picker` (Author: Kaiden42 <gitlab@tinysn.com>)
//! * `context_menu` (Author: wiiznokes <wiiznokes2@gmail.com>)
//! * `date_picker` (Author: Kaiden42 <gitlab@tinysn.com>)
//! * `drop_down` (Author: wiiznokes <wiiznokes2@gmail.com>)
//! * `menu`
//! * `number_input` (Author: leang27 <52003343+leang27@users.noreply.github.com>)
//! * `selection_list` (Author: Héctor Ramón Jiménez <hector0193@gmail.com> and Andrew Wheeler <genusistimelord@gmail.com>)
//! * `side_bar` (Author: Kaiden42 <gitlab@tinysn.com> and Rizzen Yazston)
//! * `slide_bar` (Author: Andrew Wheeler <genusistimelord@gmail.com>)
//! * `spinner` (Author: Iohann Rabeson <irabeson42@gmail.com>)
//! * `tab_bar` (Author: Kaiden42 <gitlab@tinysn.com>)
//! * `tabs` (Author: Kaiden42 <gitlab@tinysn.com>)
//! * `time_picker` (Author: Kaiden42 <gitlab@tinysn.com>)
//! * `typed_input` (Author: Ultraxime <36888699+Ultraxime@users.noreply.github.com>)
//! * `widget_id_return` (Author: Andrew Wheeler <genusistimelord@gmail.com>)
//! * `wrap` (Author: owntime <yrainbxqc@gmail.com>)
//! * `labeled_frame` (Author: JL710)
#![deny(missing_docs)]
#![deny(unused_results)]
#![forbid(unsafe_code)]
#![warn(
clippy::pedantic,
clippy::nursery,
// Restriction lints
clippy::clone_on_ref_ptr,
clippy::create_dir,
clippy::dbg_macro,
clippy::decimal_literal_representation,
clippy::exit,
clippy::float_cmp_const,
clippy::get_unwrap,
clippy::let_underscore_must_use,
clippy::map_err_ignore,
clippy::mem_forget,
clippy::missing_docs_in_private_items,
clippy::multiple_inherent_impl,
clippy::panic,
clippy::panic_in_result_fn,
clippy::print_stderr,
clippy::print_stdout,
clippy::rest_pat_in_fully_bound_structs,
clippy::str_to_string,
clippy::todo,
clippy::unimplemented,
clippy::unneeded_field_pattern,
clippy::unwrap_in_result,
clippy::unwrap_used,
clippy::use_debug,
)]
#![allow(
clippy::suboptimal_flops,
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_possible_wrap,
clippy::module_name_repetitions,
clippy::borrowed_box,
clippy::missing_const_for_fn,
clippy::too_many_lines,
clippy::cast_precision_loss,
clippy::missing_docs_in_private_items,
clippy::unit_arg,
clippy::trivially_copy_pass_by_ref,
clippy::let_unit_value,
clippy::float_cmp
)]
pub mod widget;
#[deprecated(since = "0.9.4", note = "use `widget` instead")]
pub use widget as widgets;
pub mod core;
pub mod style;
pub use iced_fonts;
/// Exports for all platforms that are not WASM32.
mod platform {
#[allow(unused_imports)]
pub use crate::style;
pub use crate::widget::helpers;
#[doc(no_inline)]
#[cfg(feature = "badge")]
pub use {crate::widget::badge, badge::Badge};
#[doc(no_inline)]
#[cfg(feature = "card")]
pub use {crate::widget::card, card::Card};
#[doc(no_inline)]
#[cfg(feature = "color_picker")]
pub use {crate::widget::color_picker, color_picker::ColorPicker};
#[doc(no_inline)]
#[cfg(feature = "date_picker")]
pub use {crate::widget::date_picker, date_picker::DatePicker};
#[doc(no_inline)]
#[cfg(feature = "tab_bar")]
pub use {
crate::widget::tab_bar,
tab_bar::{TabBar, TabLabel},
};
#[doc(no_inline)]
#[cfg(feature = "tabs")]
pub use {
crate::widget::tabs,
tabs::{TabBarPosition, Tabs},
};
#[doc(no_inline)]
#[cfg(feature = "time_picker")]
pub use {crate::widget::time_picker, time_picker::TimePicker};
#[doc(no_inline)]
#[cfg(feature = "wrap")]
pub use {crate::widget::wrap, wrap::Wrap, wrap::direction};
#[doc(no_inline)]
#[cfg(feature = "number_input")]
pub use {crate::widget::number_input, number_input::NumberInput};
#[doc(no_inline)]
#[cfg(feature = "typed_input")]
pub use {crate::widget::typed_input, typed_input::TypedInput};
#[doc(no_inline)]
#[cfg(feature = "selection_list")]
pub use {crate::widget::selection_list, selection_list::SelectionList};
#[doc(no_inline)]
#[cfg(feature = "menu")]
pub use {crate::widget::menu, menu::Menu, menu::MenuBar};
#[doc(no_inline)]
#[cfg(feature = "quad")]
pub use {crate::widget::quad, quad::Quad};
#[doc(no_inline)]
#[cfg(feature = "spinner")]
pub use {crate::widget::spinner, spinner::Spinner};
#[doc(no_inline)]
#[cfg(feature = "slide_bar")]
pub use crate::widget::SlideBar;
#[doc(no_inline)]
#[cfg(feature = "context_menu")]
pub use {crate::widget::context_menu, context_menu::ContextMenu};
#[doc(no_inline)]
#[cfg(feature = "drop_down")]
pub use {crate::widget::drop_down, drop_down::DropDown};
#[doc(no_inline)]
#[cfg(feature = "sidebar")]
pub use crate::widget::sidebar;
}
#[doc(no_inline)]
pub use platform::*;
use iced_core::Font;
use iced_fonts::generate_icon_functions;
/// Embedded font file. There a handfull of glyphs so no need to worry.
pub const ICED_AW_FONT_BYTES: &[u8] = include_bytes!("../font.ttf");
/// Font type to use in text widgets.
pub const ICED_AW_FONT: Font = Font::with_name("iced_aw");
// The icon macro resolves this path from the workspace root.
generate_icon_functions!("vendor/iced_aw/font.ttf", iced_aw_font, ICED_AW_FONT);
+40
View File
@@ -0,0 +1,40 @@
//! The appearance of the widget
pub mod colors;
pub mod status;
pub mod style_state;
pub use status::{Status, StyleFn};
#[cfg(feature = "badge")]
pub mod badge;
#[cfg(feature = "card")]
pub mod card;
#[cfg(feature = "color_picker")]
pub mod color_picker;
#[cfg(feature = "date_picker")]
pub mod date_picker;
#[cfg(feature = "tab_bar")]
pub mod tab_bar;
#[cfg(feature = "time_picker")]
pub mod time_picker;
#[cfg(feature = "number_input")]
pub mod number_input;
#[cfg(feature = "selection_list")]
pub mod selection_list;
#[cfg(feature = "menu")]
pub mod menu_bar;
#[cfg(feature = "context_menu")]
pub mod context_menu;
#[cfg(feature = "sidebar")]
pub mod sidebar;
+475
View File
@@ -0,0 +1,475 @@
//! Use a badge for color highlighting important information.
//!
//! *This API requires the following crate features to be activated: badge*
use super::{Status, StyleFn, colors};
use iced_core::{Background, Color, Theme, theme::palette};
/// The style of a [`Badge`](crate::widget::badge::Badge).
#[derive(Clone, Copy, Debug)]
pub struct Style {
/// The background of the [`Badge`](crate::widget::badge::Badge).
pub background: Background,
/// The border radius of the [`Badge`](crate::widget::badge::Badge).
/// If no radius is specified the default one will be used.
pub border_radius: Option<f32>,
/// The border with of the [`Badge`](crate::widget::badge::Badge).
pub border_width: f32,
/// The border color of the [`Badge`](crate::widget::badge::Badge).
pub border_color: Option<Color>,
/// The default text color of the [`Badge`](crate::widget::badge::Badge).
pub text_color: Color,
}
/// The Catalog of a [`Badge`](crate::widget::badge::Badge).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl std::default::Default for Style {
fn default() -> Self {
Self {
background: Background::Color([0.87, 0.87, 0.87].into()),
border_radius: None,
border_width: 1.0,
border_color: Some([0.8, 0.8, 0.8].into()),
text_color: Color::BLACK,
}
}
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn primary(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let base = styled(palette.primary.strong);
match status {
Status::Hovered => Style {
background: Background::Color(palette.primary.base.color),
..base
},
Status::Disabled => disabled(base),
_ => base,
}
}
/// The secondary theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn secondary(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let base = styled(palette.secondary.strong);
match status {
Status::Hovered => Style {
background: Background::Color(palette.primary.base.color),
..base
},
Status::Disabled => disabled(base),
_ => base,
}
}
/// The success theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn success(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let base = styled(palette.success.strong);
match status {
Status::Hovered => Style {
background: Background::Color(palette.primary.base.color),
..base
},
Status::Disabled => disabled(base),
_ => base,
}
}
/// The danger theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn danger(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let base = styled(palette.danger.strong);
match status {
Status::Hovered => Style {
background: Background::Color(palette.primary.base.color),
..base
},
Status::Disabled => disabled(base),
_ => base,
}
}
/// The warning theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn warning(_theme: &Theme, status: Status) -> Style {
let base = from_color(colors::WARNING, colors::BLACK);
match status {
Status::Disabled => disabled(base),
_ => base,
}
}
/// The info theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn info(_theme: &Theme, status: Status) -> Style {
let base = from_color(colors::INFO, colors::BLACK);
match status {
Status::Disabled => disabled(base),
_ => base,
}
}
/// The light theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn light(_theme: &Theme, status: Status) -> Style {
let base = from_color(colors::LIGHT, colors::BLACK);
match status {
Status::Disabled => disabled(base),
_ => base,
}
}
/// The dark theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn dark(_theme: &Theme, status: Status) -> Style {
let base = from_color(colors::DARK, colors::WHITE);
match status {
Status::Disabled => disabled(base),
_ => base,
}
}
/// The white theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn white(_theme: &Theme, status: Status) -> Style {
let base = from_color(colors::WHITE, colors::BLACK);
match status {
Status::Disabled => disabled(base),
_ => base,
}
}
fn from_color(color: Color, text_color: Color) -> Style {
Style {
background: Background::Color(color),
border_color: Some(color),
text_color,
..Style::default()
}
}
fn styled(pair: palette::Pair) -> Style {
Style {
background: Background::Color(pair.color),
border_color: Some(pair.color),
text_color: pair.text,
..Style::default()
}
}
fn disabled(style: Style) -> Style {
Style {
background: style.background.scale_alpha(0.5),
text_color: style.text_color.scale_alpha(0.5),
..style
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Color, Theme};
#[test]
fn style_default() {
let style = Style::default();
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_radius.is_none());
assert_eq!(style.border_width, 1.0);
assert!(style.border_color.is_some());
assert_eq!(style.text_color, Color::BLACK);
}
#[test]
fn from_color_creates_style() {
let color = Color::from_rgb(1.0, 0.0, 0.0);
let text = Color::WHITE;
let style = from_color(color, text);
assert_eq!(style.background, Background::Color(color));
assert_eq!(style.border_color, Some(color));
assert_eq!(style.text_color, text);
assert_eq!(style.border_width, 1.0);
assert!(style.border_radius.is_none());
}
#[test]
fn disabled_scales_alpha() {
let base = Style {
background: Background::Color(Color::from_rgb(1.0, 0.0, 0.0)),
border_radius: Some(5.0),
border_width: 2.0,
border_color: Some(Color::from_rgb(0.5, 0.5, 0.5)),
text_color: Color::WHITE,
};
let disabled_style = disabled(base);
// Background and text color should have scaled alpha
assert!(matches!(disabled_style.background, Background::Color(_)));
assert_eq!(disabled_style.border_radius, Some(5.0));
assert_eq!(disabled_style.border_width, 2.0);
assert_eq!(
disabled_style.border_color,
Some(Color::from_rgb(0.5, 0.5, 0.5))
);
}
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn secondary_theme_active() {
let theme = Theme::TokyoNight;
let style = secondary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn secondary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = secondary(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn secondary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = secondary(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn success_theme_active() {
let theme = Theme::TokyoNight;
let style = success(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn success_theme_hovered() {
let theme = Theme::TokyoNight;
let style = success(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn success_theme_disabled() {
let theme = Theme::TokyoNight;
let style = success(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn danger_theme_active() {
let theme = Theme::TokyoNight;
let style = danger(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn danger_theme_hovered() {
let theme = Theme::TokyoNight;
let style = danger(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn danger_theme_disabled() {
let theme = Theme::TokyoNight;
let style = danger(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn warning_theme_active() {
let theme = Theme::TokyoNight;
let style = warning(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
assert_eq!(style.text_color, colors::BLACK);
}
#[test]
fn warning_theme_disabled() {
let theme = Theme::TokyoNight;
let style = warning(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn info_theme_active() {
let theme = Theme::TokyoNight;
let style = info(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
assert_eq!(style.text_color, colors::BLACK);
}
#[test]
fn info_theme_disabled() {
let theme = Theme::TokyoNight;
let style = info(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn light_theme_active() {
let theme = Theme::TokyoNight;
let style = light(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
assert_eq!(style.text_color, colors::BLACK);
}
#[test]
fn light_theme_disabled() {
let theme = Theme::TokyoNight;
let style = light(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn dark_theme_active() {
let theme = Theme::TokyoNight;
let style = dark(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
assert_eq!(style.text_color, colors::WHITE);
}
#[test]
fn dark_theme_disabled() {
let theme = Theme::TokyoNight;
let style = dark(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn white_theme_active() {
let theme = Theme::TokyoNight;
let style = white(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
assert_eq!(style.text_color, colors::BLACK);
}
#[test]
fn white_theme_disabled() {
let theme = Theme::TokyoNight;
let style = white(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(style.border_color.is_some());
}
}
+348
View File
@@ -0,0 +1,348 @@
//! Displays a [`Card`](crate::widget::Card).
//!
//! *This API requires the following crate features to be activated: card*
use super::{Status, StyleFn, colors};
use iced_core::{Background, Color, Theme};
/// The appearance of a [`Card`](crate::widget::card::Card).
#[derive(Clone, Copy, Debug)]
pub struct Style {
/// The background of the [`Card`](crate::widget::card::Card).
pub background: Background,
/// The border radius of the [`Card`](crate::widget::card::Card).
pub border_radius: f32,
/// The border width of the [`Card`](crate::widget::card::Card).
pub border_width: f32,
/// The border color of the [`Card`](crate::widget::card::Card).
pub border_color: Color,
/// The background of the head of the [`Card`](crate::widget::card::Card).
pub head_background: Background,
/// The text color of the head of the [`Card`](crate::widget::card::Card).
pub head_text_color: Color,
/// The background of the body of the [`Card`](crate::widget::card::Card).
pub body_background: Background,
/// The text color of the body of the [`Card`](crate::widget::card::Card).
pub body_text_color: Color,
/// The background of the foot of the [`Card`](crate::widget::card::Card).
pub foot_background: Background,
/// The text color of the foot of the [`Card`](crate::widget::card::Card).
pub foot_text_color: Color,
/// The color of the close icon of the [`Card`](crate::widget::card::Card).
pub close_color: Color,
}
/// The appearance of a [`Card`](crate::widget::card::Card).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Default for Style {
fn default() -> Self {
Self {
background: Color::WHITE.into(),
border_radius: 10.0,
border_width: 1.0,
border_color: [0.87, 0.87, 0.87].into(),
head_background: Background::Color([0.87, 0.87, 0.87].into()),
head_text_color: Color::BLACK,
body_background: Color::TRANSPARENT.into(),
body_text_color: Color::BLACK,
foot_background: Color::TRANSPARENT.into(),
foot_text_color: Color::BLACK,
close_color: Color::BLACK,
}
}
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn primary(theme: &Theme, _status: Status) -> Style {
backing_with_text(theme, colors::PRIMARY, colors::WHITE)
}
/// The secondary theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn secondary(theme: &Theme, _status: Status) -> Style {
backing_with_text(theme, colors::SECONDARY, colors::WHITE)
}
/// The success theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn success(theme: &Theme, _status: Status) -> Style {
backing_with_text(theme, colors::SUCCESS, colors::WHITE)
}
/// The danger theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn danger(theme: &Theme, _status: Status) -> Style {
backing_with_text(theme, colors::DANGER, colors::WHITE)
}
/// The warning theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn warning(theme: &Theme, _status: Status) -> Style {
backing_only(theme, colors::WARNING)
}
/// The info theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn info(theme: &Theme, _status: Status) -> Style {
backing_only(theme, colors::INFO)
}
/// The light theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn light(theme: &Theme, _status: Status) -> Style {
backing_only(theme, colors::LIGHT)
}
/// The dark theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn dark(theme: &Theme, _status: Status) -> Style {
backing_with_text(theme, colors::DARK, colors::WHITE)
}
/// The white theme of a [`Card`](crate::widget::card::Card).
#[must_use]
pub fn white(theme: &Theme, _status: Status) -> Style {
backing_only(theme, colors::WHITE)
}
fn backing_with_text(theme: &Theme, color: Color, text_color: Color) -> Style {
let palette = theme.extended_palette();
let foreground = theme.palette();
Style {
border_color: color,
head_background: color.into(),
head_text_color: text_color,
close_color: text_color,
background: palette.background.base.color.into(),
body_text_color: foreground.text,
foot_text_color: foreground.text,
..Style::default()
}
}
fn backing_only(theme: &Theme, color: Color) -> Style {
let palette = theme.extended_palette();
let foreground = theme.palette();
Style {
border_color: color,
head_background: color.into(),
background: palette.background.base.color.into(),
body_text_color: foreground.text,
foot_text_color: foreground.text,
..Style::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Color, Theme};
#[test]
fn style_default() {
let style = Style::default();
assert_eq!(style.background, Background::Color(Color::WHITE));
assert_eq!(style.border_radius, 10.0);
assert_eq!(style.border_width, 1.0);
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.head_text_color, Color::BLACK);
assert_eq!(style.body_background, Background::Color(Color::TRANSPARENT));
assert_eq!(style.body_text_color, Color::BLACK);
assert_eq!(style.foot_background, Background::Color(Color::TRANSPARENT));
assert_eq!(style.foot_text_color, Color::BLACK);
assert_eq!(style.close_color, Color::BLACK);
}
#[test]
fn backing_with_text_creates_style() {
let theme = Theme::TokyoNight;
let color = Color::from_rgb(1.0, 0.0, 0.0);
let text = Color::WHITE;
let style = backing_with_text(&theme, color, text);
assert_eq!(style.border_color, color);
assert_eq!(style.head_background, Background::Color(color));
assert_eq!(style.head_text_color, text);
assert_eq!(style.close_color, text);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.body_background, Background::Color(_)));
assert!(matches!(style.foot_background, Background::Color(_)));
}
#[test]
fn backing_only_creates_style() {
let theme = Theme::TokyoNight;
let color = Color::from_rgb(0.0, 1.0, 0.0);
let style = backing_only(&theme, color);
assert_eq!(style.border_color, color);
assert_eq!(style.head_background, Background::Color(color));
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.body_background, Background::Color(_)));
assert!(matches!(style.foot_background, Background::Color(_)));
}
#[test]
fn primary_theme() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.head_text_color, colors::WHITE);
assert_eq!(style.close_color, colors::WHITE);
}
#[test]
fn secondary_theme() {
let theme = Theme::TokyoNight;
let style = secondary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.head_text_color, colors::WHITE);
assert_eq!(style.close_color, colors::WHITE);
}
#[test]
fn success_theme() {
let theme = Theme::TokyoNight;
let style = success(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.head_text_color, colors::WHITE);
assert_eq!(style.close_color, colors::WHITE);
}
#[test]
fn danger_theme() {
let theme = Theme::TokyoNight;
let style = danger(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.head_text_color, colors::WHITE);
assert_eq!(style.close_color, colors::WHITE);
}
#[test]
fn warning_theme() {
let theme = Theme::TokyoNight;
let style = warning(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.border_color, colors::WARNING);
}
#[test]
fn info_theme() {
let theme = Theme::TokyoNight;
let style = info(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.border_color, colors::INFO);
}
#[test]
fn light_theme() {
let theme = Theme::TokyoNight;
let style = light(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.border_color, colors::LIGHT);
}
#[test]
fn dark_theme() {
let theme = Theme::TokyoNight;
let style = dark(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.head_text_color, colors::WHITE);
assert_eq!(style.close_color, colors::WHITE);
assert_eq!(style.border_color, colors::DARK);
}
#[test]
fn white_theme() {
let theme = Theme::TokyoNight;
let style = white(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
assert_eq!(style.border_color, colors::WHITE);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
}
#[test]
fn primary_theme_with_hovered_status() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
}
#[test]
fn primary_theme_with_disabled_status() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.head_background, Background::Color(_)));
}
}
+192
View File
@@ -0,0 +1,192 @@
//! Use a color picker as an input element for picking colors.
//!
//! *This API requires the following crate features to be activated: `color_picker`*
use super::{Status, StyleFn};
use iced_core::{Background, Color, Theme};
/// The appearance of a [`ColorPicker`](crate::widget::ColorPicker).
#[derive(Clone, Copy, Debug)]
pub struct Style {
/// The background of the [`ColorPicker`](crate::widget::ColorPicker).
pub background: Background,
/// The border radius of the [`ColorPicker`](crate::widget::ColorPicker).
pub border_radius: f32,
/// The border with of the [`ColorPicker`](crate::widget::ColorPicker).
pub border_width: f32,
/// The border color of the [`ColorPicker`](crate::widget::ColorPicker).
pub border_color: Color,
/// The border radius of the bars of the [`ColorPicker`](crate::widget::ColorPicker).
pub bar_border_radius: f32,
/// The border width of the bars of the [`ColorPicker`](crate::widget::ColorPicker).
pub bar_border_width: f32,
/// The border color of the bars of the [`ColorPicker`](crate::widget::ColorPicker).
pub bar_border_color: Color,
}
/// The Catalog of a [`ColorPicker`](crate::widget::ColorPicker).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn primary(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let foreground = theme.palette();
let base = Style {
background: palette.background.base.color.into(),
border_radius: 15.0,
border_width: 1.0,
border_color: foreground.text,
bar_border_radius: 5.0,
bar_border_width: 1.0,
bar_border_color: foreground.text,
};
match status {
Status::Focused => Style {
border_color: palette.background.strong.color,
bar_border_color: palette.background.strong.color,
..base
},
_ => base,
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Theme};
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
assert_eq!(style.bar_border_radius, 5.0);
assert_eq!(style.bar_border_width, 1.0);
}
#[test]
fn primary_theme_focused() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Focused);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
assert_eq!(style.bar_border_radius, 5.0);
assert_eq!(style.bar_border_width, 1.0);
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn focused_changes_border_colors() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let focused_style = primary(&theme, Status::Focused);
// Border colors should be different when focused
assert_ne!(base_style.border_color, focused_style.border_color);
assert_ne!(base_style.bar_border_color, focused_style.bar_border_color);
// Other properties should remain the same
assert_eq!(base_style.background, focused_style.background);
assert_eq!(base_style.border_radius, focused_style.border_radius);
assert_eq!(base_style.border_width, focused_style.border_width);
assert_eq!(
base_style.bar_border_radius,
focused_style.bar_border_radius
);
assert_eq!(base_style.bar_border_width, focused_style.bar_border_width);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
assert_eq!(style.bar_border_radius, 5.0);
assert_eq!(style.bar_border_width, 1.0);
}
#[test]
fn catalog_style_focused() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Focused);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
}
#[test]
fn style_fields_are_valid() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
// Verify all fields have valid values
assert!(style.border_radius > 0.0);
assert!(style.border_width > 0.0);
assert!(style.bar_border_radius > 0.0);
assert!(style.bar_border_width > 0.0);
}
}
+662
View File
@@ -0,0 +1,662 @@
//! Predefined color palette based on the CSS color palette
//!
//!
//! Thanks to:
//! * [W3 Schools](https://www.w3schools.com/cssref/css_colors.asp)
//! * [Corecoding](https://corecoding.com/utilities/rgb-or-hex-to-float.php)
use iced_core::Color;
/// Primary <span style="color:dodgerblue">Color</span>.
pub const PRIMARY: Color = DODGER_BLUE;
/// Secondary <span style="color:dimgray">Color</span>.
pub const SECONDARY: Color = DIM_GRAY;
/// Success <span style="color:limeGreen">Color</span>.
pub const SUCCESS: Color = LIME_GREEN;
/// Danger <span style="color:red">Color</span>.
pub const DANGER: Color = RED;
/// Warning <span style="color:gold">Color</span>.
pub const WARNING: Color = GOLD;
/// Info <span style="color:skyBlue">Color</span>.
pub const INFO: Color = SKY_BLUE;
/// Light <span style="color:ghostWhite">Color</span>.
pub const LIGHT: Color = GHOST_WHITE;
/// Dark <span style="color:rgb(0.204, 0.227, 0.251)">Color</span>.
pub const DARK: Color = Color::from_rgb(0.204, 0.227, 0.251);
/// Alice Blue <span style="color:aliceBlue">Color</span>.
pub const ALICE_BLUE: Color = Color::from_rgb(0.941, 0.973, 1.0);
/// Antique White <span style="color:antiqueWhite">Color</span>.
pub const ANTIQUE_WHITE: Color = Color::from_rgb(0.98, 0.922, 0.843);
/// Aqua <span style="color:aqua">Color</span>.
pub const AQUA: Color = Color::from_rgb(0.0, 1.0, 1.0);
/// Aquamarine <span style="color:aquamarine">Color</span>.
pub const AQUAMARINE: Color = Color::from_rgb(0.498, 1.0, 0.831);
/// Azure <span style="color:azure">Color</span>.
pub const AZURE: Color = Color::from_rgb(0.941, 1.0, 1.0);
/// Beige <span style="color:beige">Color</span>.
pub const BEIGE: Color = Color::from_rgb(0.961, 0.961, 0.863);
/// Bisque <span style="color:bisque">Color</span>.
pub const BISQUE: Color = Color::from_rgb(1.0, 0.894, 0.769);
/// Black <span style="color:black">Color</span>.
pub const BLACK: Color = Color::BLACK;
/// Blanched Almond <span style="color:blanchedAlmond">Color</span>.
pub const BLANCHED_ALMOND: Color = Color::from_rgb(1.0, 0.922, 0.804);
/// Blue <span style="color:blue">Color</span>.
pub const BLUE: Color = Color::from_rgb(0.0, 0.0, 1.0);
/// Blue Violet <span style="color:blueViolet">Color</span>.
pub const BLUE_VIOLET: Color = Color::from_rgb(0.541, 0.169, 0.886);
/// Brown <span style="color:brown">Color</span>.
pub const BROWN: Color = Color::from_rgb(0.647, 0.165, 0.165);
/// Burly Wood <span style="color:burlyWood">Color</span>.
pub const BURLY_WOOD: Color = Color::from_rgb(0.871, 0.722, 0.529);
/// Cadet Blue <span style="color:cadetBlue">Color</span>.
pub const CADET_BLUE: Color = Color::from_rgb(0.373, 0.62, 0.627);
/// Chartreuse <span style="color:chartreuse">Color</span>.
pub const CHARTREUSE: Color = Color::from_rgb(0.498, 1.0, 0.0);
/// Chocolate <span style="color:chocolate">Color</span>.
pub const CHOCOLATE: Color = Color::from_rgb(0.824, 0.412, 0.118);
/// Coral <span style="color:coral">Color</span>.
pub const CORAL: Color = Color::from_rgb(1.0, 0.498, 0.314);
/// Cornflower Blue <span style="color:cornflowerBlue">Color</span>.
pub const CORNFLOWER_BLUE: Color = Color::from_rgb(0.392, 0.584, 0.929);
/// Cornsilk <span style="color:cornsilk">Color</span>.
pub const CORNSILK: Color = Color::from_rgb(1.0, 0.973, 0.863);
/// Crimson <span style="color:crimson">Color</span>.
pub const CRIMSON: Color = Color::from_rgb(0.863, 0.078, 0.235);
/// Cyan <span style="color:cyan">Color</span>.
pub const CYAN: Color = Color::from_rgb(0.0, 1.0, 1.0);
/// Dark Blue <span style="color:darkBlue">Color</span>.
pub const DARK_BLUE: Color = Color::from_rgb(0.0, 0.0, 0.545);
/// Dark Cyan <span style="color:darkCyan">Color</span>.
pub const DARK_CYAN: Color = Color::from_rgb(0.0, 0.545, 0.545);
/// Dark Golden Rod <span style="color:darkGoldenRod">Color</span>.
pub const DARK_GOLDEN_ROD: Color = Color::from_rgb(0.722, 0.525, 0.043);
/// Dark Gray <span style="color:darkGray">Color</span>.
pub const DARK_GRAY: Color = Color::from_rgb(0.663, 0.663, 0.663);
/// Dark Grey <span style="color:darkGrey">Color</span>.
pub const DARK_GREY: Color = DARK_GRAY;
/// Dark Green <span style="color:darkGreen">Color</span>.
pub const DARK_GREEN: Color = Color::from_rgb(0.0, 0.392, 0.0);
/// Dark Khaki <span style="color:darkKhaki">Color</span>.
pub const DARK_KHAKI: Color = Color::from_rgb(0.741, 0.718, 0.42);
/// Dark Magenta <span style="color:darkMagenta">Color</span>.
pub const DARK_MAGENTA: Color = Color::from_rgb(0.545, 0.0, 0.545);
/// Dark Olive Green <span style="color:darkOliveGreen">Color</span>.
pub const DARK_OLIVE_GREEN: Color = Color::from_rgb(0.333, 0.42, 0.184);
/// Dark Orange <span style="color:darkOrange">Color</span>.
pub const DARK_ORANGE: Color = Color::from_rgb(1.0, 0.549, 0.0);
/// Dark Orchid <span style="color:darkOrchid">Color</span>.
pub const DARK_ORCHID: Color = Color::from_rgb(0.6, 0.196, 0.8);
/// Dark Red <span style="color:darkRed">Color</span>.
pub const DARK_RED: Color = Color::from_rgb(0.545, 0.0, 0.0);
/// Dark Salmon <span style="color:darkSalmon">Color</span>.
pub const DARK_SALMON: Color = Color::from_rgb(0.914, 0.588, 0.478);
/// Dark Sea Green <span style="color:darkSeaGreen">Color</span>.
pub const DARK_SEA_GREEN: Color = Color::from_rgb(0.561, 0.737, 0.561);
/// Dark Slate Blue <span style="color:darkSlateBlue">Color</span>.
pub const DARK_SLATE_BLUE: Color = Color::from_rgb(0.282, 0.239, 0.545);
/// Dark Slate Gray <span style="color:darkSlateGray">Color</span>.
pub const DARK_SLATE_GRAY: Color = Color::from_rgb(0.184, 0.31, 0.31);
/// Dark Slate Grey <span style="color:darkSlateGrey">Color</span>.
pub const DARK_SLATE_GREY: Color = DARK_SLATE_GRAY;
/// Dark Turquoise <span style="color:darkTurquoise">Color</span>.
pub const DARK_TURQUOISE: Color = Color::from_rgb(0.0, 0.808, 0.82);
/// Dark Violet <span style="color:darkViolet">Color</span>.
pub const DARK_VIOLET: Color = Color::from_rgb(0.58, 0.0, 0.827);
/// Deep Pink <span style="color:deepPink">Color</span>.
pub const DEEP_PINK: Color = Color::from_rgb(1.0, 0.078, 0.576);
/// Deep Sky Blue <span style="color:deepSkyBlue">Color</span>.
pub const DEEP_SKY_BLUE: Color = Color::from_rgb(0.0, 0.749, 1.0);
/// Dim Gray <span style="color:dimgray">Color</span>.
pub const DIM_GRAY: Color = Color::from_rgb(0.412, 0.412, 0.412);
/// Dim Grey <span style="color:dimgrey">Color</span>.
pub const DIM_GREY: Color = DIM_GRAY;
/// Dodger Blue <span style="color:dodgerBlue">Color</span>.
pub const DODGER_BLUE: Color = Color::from_rgb(0.118, 0.565, 1.0);
/// Fire Brick <span style="color:fireBrick">Color</span>.
pub const FIRE_BRICK: Color = Color::from_rgb(0.698, 0.133, 0.133);
/// Floral White <span style="color:floralWhite">Color</span>.
pub const FLORAL_WHITE: Color = Color::from_rgb(1.0, 0.98, 0.941);
/// Forest Green <span style="color:forestGreen">Color</span>.
pub const FOREST_GREEN: Color = Color::from_rgb(0.133, 0.545, 0.133);
/// Fuchsia <span style="color:fuchsia">Color</span>.
pub const FUCHSIA: Color = Color::from_rgb(1.0, 0.0, 1.0);
/// Gainsboro <span style="color:gainsboro">Color</span>.
pub const GAINSBORO: Color = Color::from_rgb(0.863, 0.863, 0.863);
/// Ghost White <span style="color:ghostWhite">Color</span>.
pub const GHOST_WHITE: Color = Color::from_rgb(0.973, 0.973, 1.0);
/// Gold <span style="color:gold">Color</span>.
pub const GOLD: Color = Color::from_rgb(1.0, 0.843, 0.0);
/// Golden Rod <span style="color:goldenRod">Color</span>.
pub const GOLDEN_ROD: Color = Color::from_rgb(0.855, 0.647, 0.125);
/// Gray <span style="color:gray">Color</span>.
pub const GRAY: Color = Color::from_rgb(0.502, 0.502, 0.502);
/// Grey <span style="color:grey">Color</span>.
pub const GREY: Color = GRAY;
/// Green <span style="color:green">Color</span>.
pub const GREEN: Color = Color::from_rgb(0.0, 0.502, 0.0);
/// Green Yellow <span style="color:greenYellow">Color</span>.
pub const GREEN_YELLOW: Color = Color::from_rgb(0.678, 1.0, 0.184);
/// Honey Dew <span style="color:honeyDew">Color</span>.
pub const HONEY_DEW: Color = Color::from_rgb(0.941, 1.0, 0.941);
/// Hot Pink <span style="color:hotPink">Color</span>.
pub const HOT_PINK: Color = Color::from_rgb(1.0, 0.412, 0.706);
/// Indian Red <span style="color:indianRed">Color</span>.
pub const INDIAN_RED: Color = Color::from_rgb(0.804, 0.361, 0.361);
/// Indigo <span style="color:indigo">Color</span>.
pub const INDIGO: Color = Color::from_rgb(0.294, 0.0, 0.51);
/// Ivory <span style="color:ivory">Color</span>.
pub const IVORY: Color = Color::from_rgb(1.0, 1.0, 0.941);
/// Khaki <span style="color:khaki">Color</span>.
pub const KHAKI: Color = Color::from_rgb(0.941, 0.902, 0.549);
/// Lavender <span style="color:lavender">Color</span>.
pub const LAVENDER: Color = Color::from_rgb(0.902, 0.902, 0.98);
/// Lavender Blush <span style="color:lavenderBlush">Color</span>.
pub const LAVENDER_BLUSH: Color = Color::from_rgb(1.0, 0.941, 0.961);
/// Lawn Green <span style="color:lawnGreen">Color</span>.
pub const LAWN_GREEN: Color = Color::from_rgb(0.486, 0.988, 0.0);
/// Lemon Chiffon <span style="color:lemonChiffon">Color</span>.
pub const LEMON_CHIFFON: Color = Color::from_rgb(1.0, 0.98, 0.804);
/// Light Blue <span style="color:lightBlue">Color</span>.
pub const LIGHT_BLUE: Color = Color::from_rgb(0.678, 0.847, 0.902);
/// Light Coral <span style="color:lightCoral">Color</span>.
pub const LIGHT_CORAL: Color = Color::from_rgb(0.941, 0.502, 0.502);
/// Light Cyan <span style="color:lightCyan">Color</span>.
pub const LIGHT_CYAN: Color = Color::from_rgb(0.878, 1.0, 1.0);
/// Light Golden Rod Yellow <span style="color:lightGoldenRodYellow">Color</span>.
pub const LIGHT_GOLDEN_ROD_YELLOW: Color = Color::from_rgb(0.98, 0.98, 0.824);
/// Light Gray <span style="color:lightGray">Color</span>.
pub const LIGHT_GRAY: Color = Color::from_rgb(0.827, 0.827, 0.827);
/// Light Grey <span style="color:lightGrey">Color</span>.
pub const LIGHT_GREY: Color = LIGHT_GRAY;
/// Light Green <span style="color:lightGreen">Color</span>.
pub const LIGHT_GREEN: Color = Color::from_rgb(0.565, 0.933, 0.565);
/// Light Pink <span style="color:lightPink">Color</span>.
pub const LIGHT_PINK: Color = Color::from_rgb(1.0, 0.714, 0.757);
/// Light Salmon <span style="color:lightSalmon">Color</span>.
pub const LIGHT_SALMON: Color = Color::from_rgb(1.0, 0.627, 0.478);
/// Light Sea Green <span style="color:lightSeaGreen">Color</span>.
pub const LIGHT_SEA_GREEN: Color = Color::from_rgb(0.125, 0.698, 0.667);
/// Light Sky Blue <span style="color:lightSkyBlue">Color</span>.
pub const LIGHT_SKY_BLUE: Color = Color::from_rgb(0.529, 0.808, 0.98);
/// Light Slate Gray <span style="color:lightSlateGray">Color</span>.
pub const LIGHT_SLATE_GRAY: Color = Color::from_rgb(0.467, 0.533, 0.6);
/// Light Slate Grey <span style="color:lightSlateGrey">Color</span>.
pub const LIGHT_SLATE_GREY: Color = LIGHT_SLATE_GRAY;
/// Light Steel Blue <span style="color:lightSteelBlue">Color</span>.
pub const LIGHT_STEEL_BLUE: Color = Color::from_rgb(0.69, 0.769, 0.871);
/// Light Yellow <span style="color:lightYellow">Color</span>.
pub const LIGHT_YELLOW: Color = Color::from_rgb(1.0, 1.0, 0.878);
/// Lime <span style="color:lime">Color</span>.
pub const LIME: Color = Color::from_rgb(0.0, 1.0, 0.0);
/// Lime Green <span style="color:limeGreen">Color</span>.
pub const LIME_GREEN: Color = Color::from_rgb(0.196, 0.804, 0.196);
/// Linen <span style="color:linen">Color</span>.
pub const LINEN: Color = Color::from_rgb(0.98, 0.941, 0.902);
/// Magenta <span style="color:magenta">Color</span>.
pub const MAGENTA: Color = Color::from_rgb(1.0, 0.0, 1.0);
/// Maroon <span style="color:maroon">Color</span>.
pub const MAROON: Color = Color::from_rgb(0.502, 0.0, 0.0);
/// Medium Aqua Marine <span style="color:mediumAquaMarine">Color</span>.
pub const MEDIUM_AQUA_MARINE: Color = Color::from_rgb(0.4, 0.804, 0.667);
/// Medium Blue <span style="color:mediumBlue">Color</span>.
pub const MEDIUM_BLUE: Color = Color::from_rgb(0.0, 0.0, 0.804);
/// Medium Orchid <span style="color:mediumOrchid">Color</span>.
pub const MEDIUM_ORCHID: Color = Color::from_rgb(0.729, 0.333, 0.827);
/// Medium Purple <span style="color:mediumPurple">Color</span>.
pub const MEDIUM_PURPLE: Color = Color::from_rgb(0.576, 0.439, 0.859);
/// Medium Sea Green <span style="color:mediumSeaGreen">Color</span>.
pub const MEDIUM_SEA_GREEN: Color = Color::from_rgb(0.235, 0.702, 0.443);
/// Medium Slate Blue <span style="color:mediumSlateBlue">Color</span>.
pub const MEDIUM_SLATE_BLUE: Color = Color::from_rgb(0.482, 0.408, 0.933);
/// Medium Spring Green <span style="color:mediumSpringGreen">Color</span>.
pub const MEDIUM_SPRING_GREEN: Color = Color::from_rgb(0.0, 0.98, 0.604);
/// Medium Turquoise <span style="color:mediumTurquoise">Color</span>.
pub const MEDIUM_TURQUOISE: Color = Color::from_rgb(0.282, 0.82, 0.8);
/// Medium Violet Red <span style="color:mediumVioletRed">Color</span>.
pub const MEDIUM_VIOLET_RED: Color = Color::from_rgb(0.78, 0.082, 0.522);
/// Midnight Blue <span style="color:midnightBlue">Color</span>.
pub const MIDNIGHT_BLUE: Color = Color::from_rgb(0.098, 0.098, 0.439);
/// Mint Cream <span style="color:mintCream">Color</span>.
pub const MINT_CREAM: Color = Color::from_rgb(0.961, 1.0, 0.98);
/// Misty Rose <span style="color:mistyRose">Color</span>.
pub const MISTY_ROSE: Color = Color::from_rgb(1.0, 0.894, 0.882);
/// Moccasin <span style="color:moccasin">Color</span>.
pub const MOCCASIN: Color = Color::from_rgb(1.0, 0.894, 0.71);
/// Navajo White <span style="color:navajo_white">Color</span>.
pub const NAVAJO_WHITE: Color = Color::from_rgb(1.0, 0.871, 0.678);
/// Navy <span style="color:navy">Color</span>.
pub const NAVY: Color = Color::from_rgb(0.0, 0.0, 0.502);
/// Old Lace <span style="color:oldLace">Color</span>.
pub const OLD_LACE: Color = Color::from_rgb(0.992, 0.961, 0.902);
/// Olive <span style="color:olive">Color</span>.
pub const OLIVE: Color = Color::from_rgb(0.502, 0.502, 0.0);
/// Olive Drab <span style="color:oliveDrab">Color</span>.
pub const OLIVE_DRAB: Color = Color::from_rgb(0.42, 0.557, 0.137);
/// Orange <span style="color:orange">Color</span>.
pub const ORANGE: Color = Color::from_rgb(1.0, 0.647, 0.0);
/// Orange Red <span style="color:orangeRed">Color</span>.
pub const ORANGE_RED: Color = Color::from_rgb(1.0, 0.271, 0.0);
/// Orchid <span style="color:orchid">Color</span>.
pub const ORCHID: Color = Color::from_rgb(0.855, 0.439, 0.839);
/// Pale Golden Rod <span style="color:paleGoldenRod">Color</span>.
pub const PALE_GOLDEN_ROD: Color = Color::from_rgb(0.933, 0.91, 0.667);
/// Pale Green <span style="color:paleGreen">Color</span>.
pub const PALE_GREEN: Color = Color::from_rgb(0.596, 0.984, 0.596);
/// Pale Turquoise <span style="color:paleTurquoise">Color</span>.
pub const PALE_TURQUOISE: Color = Color::from_rgb(0.686, 0.933, 0.933);
/// Pale Violet Red <span style="color:paleVioletRed">Color</span>.
pub const PALE_VIOLET_RED: Color = Color::from_rgb(0.859, 0.439, 0.576);
/// Papaya Whip <span style="color:papayaWhip">Color</span>.
pub const PAPAYA_WHIP: Color = Color::from_rgb(1.0, 0.937, 0.835);
/// Peach Puff <span style="color:peachPuff">Color</span>.
pub const PEACH_PUFF: Color = Color::from_rgb(1.0, 0.855, 0.725);
/// Peru <span style="color:peru">Color</span>.
pub const PERU: Color = Color::from_rgb(0.804, 0.522, 0.247);
/// Pink <span style="color:pink">Color</span>.
pub const PINK: Color = Color::from_rgb(1.0, 0.753, 0.796);
/// Plum <span style="color:plum">Color</span>.
pub const PLUM: Color = Color::from_rgb(0.867, 0.627, 0.867);
/// Powder Blue <span style="color:powderBlue">Color</span>.
pub const POWDER_BLUE: Color = Color::from_rgb(0.69, 0.878, 0.902);
/// Purple <span style="color:purple">Color</span>.
pub const PURPLE: Color = Color::from_rgb(0.502, 0.0, 0.502);
/// Rebecca Purple <span style="color:rebeccaPurple">Color</span>.
pub const REBECCA_PURPLE: Color = Color::from_rgb(0.4, 0.2, 0.6);
/// Red <span style="color:red">Color</span>.
pub const RED: Color = Color::from_rgb(1.0, 0.0, 0.0);
/// Rosy Brown <span style="color:rosyBrown">Color</span>.
pub const ROSY_BROWN: Color = Color::from_rgb(0.737, 0.561, 0.561);
/// Royal Blue <span style="color:royalBlue">Color</span>.
pub const ROYAL_BLUE: Color = Color::from_rgb(0.255, 0.412, 0.882);
/// Saddle Brown <span style="color:saddleBrown">Color</span>.
pub const SADDLE_BROWN: Color = Color::from_rgb(0.545, 0.271, 0.075);
/// Salmon <span style="color:salmon">Color</span>.
pub const SALMON: Color = Color::from_rgb(0.98, 0.502, 0.447);
/// Sandy Brown <span style="color:sandyBrown">Color</span>.
pub const SANDY_BROWN: Color = Color::from_rgb(0.957, 0.643, 0.376);
/// Sea Green <span style="color:seaGreen">Color</span>.
pub const SEA_GREEN: Color = Color::from_rgb(0.18, 0.545, 0.341);
/// Sea Shell <span style="color:seaShell">Color</span>.
pub const SEA_SHELL: Color = Color::from_rgb(1.0, 0.961, 0.933);
/// Sienna <span style="color:sienna">Color</span>.
pub const SIENNA: Color = Color::from_rgb(0.627, 0.322, 0.176);
/// Silver <span style="color:silver">Color</span>.
pub const SILVER: Color = Color::from_rgb(0.753, 0.753, 0.753);
/// Sky Blue <span style="color:skyBlue">Color</span>.
pub const SKY_BLUE: Color = Color::from_rgb(0.529, 0.808, 0.922);
/// Slate Blue <span style="color:slateBlue">Color</span>.
pub const SLATE_BLUE: Color = Color::from_rgb(0.416, 0.353, 0.804);
/// Slate Gray <span style="color:slateGray">Color</span>.
pub const SLATE_GRAY: Color = Color::from_rgb(0.439, 0.502, 0.565);
/// Slate Grey <span style="color:slateGrey">Color</span>.
pub const SLATE_GREY: Color = SLATE_GRAY;
/// Snow <span style="color:snow">Color</span>.
pub const SNOW: Color = Color::from_rgb(1.0, 0.98, 0.98);
/// Spring Green <span style="color:springGreen">Color</span>.
pub const SPRING_GREEN: Color = Color::from_rgb(0.0, 1.0, 0.498);
/// Steel Blue <span style="color:steelBlue">Color</span>.
pub const STEEL_BLUE: Color = Color::from_rgb(0.275, 0.51, 0.706);
/// Tan <span style="color:tan">Color</span>.
pub const TAN: Color = Color::from_rgb(0.824, 0.706, 0.549);
/// Teal <span style="color:teal">Color</span>.
pub const TEAL: Color = Color::from_rgb(0.0, 0.502, 0.502);
/// Thistle <span style="color:thistle">Color</span>.
pub const THISTLE: Color = Color::from_rgb(0.847, 0.749, 0.847);
/// Tomato <span style="color:tomato">Color</span>.
pub const TOMATO: Color = Color::from_rgb(1.0, 0.388, 0.278);
/// Turquoise <span style="color:turquoise">Color</span>.
pub const TURQUOISE: Color = Color::from_rgb(0.251, 0.878, 0.816);
/// Violet <span style="color:violet">Color</span>.
pub const VIOLET: Color = Color::from_rgb(0.933, 0.51, 0.933);
/// Wheat <span style="color:wheat">Color</span>.
pub const WHEAT: Color = Color::from_rgb(0.961, 0.871, 0.702);
/// White <span style="color:white">Color</span>.
pub const WHITE: Color = Color::WHITE;
/// White Smoke <span style="color:whiteSmoke">Color</span>.
pub const WHITE_SMOKE: Color = Color::WHITE;
/// Yellow <span style="color:yellow">Color</span>.
pub const YELLOW: Color = Color::from_rgb(1.0, 1.0, 0.0);
/// Yellow Green <span style="color:yellowGreen">Color</span>.
pub const YELLOW_GREEN: Color = Color::from_rgb(0.604, 0.804, 0.196);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn semantic_colors_are_defined() {
// Verify semantic colors point to the correct values
assert_eq!(PRIMARY, DODGER_BLUE);
assert_eq!(SECONDARY, DIM_GRAY);
assert_eq!(SUCCESS, LIME_GREEN);
assert_eq!(DANGER, RED);
assert_eq!(WARNING, GOLD);
assert_eq!(INFO, SKY_BLUE);
assert_eq!(LIGHT, GHOST_WHITE);
}
#[test]
fn dark_color_is_custom() {
// DARK is a custom color, not an alias
assert_eq!(DARK, Color::from_rgb(0.204, 0.227, 0.251));
}
#[test]
fn black_and_white_constants() {
assert_eq!(BLACK, Color::BLACK);
assert_eq!(WHITE, Color::WHITE);
assert_eq!(WHITE_SMOKE, Color::WHITE);
}
#[test]
fn gray_grey_aliases_match() {
// American/British spelling aliases should be equal
assert_eq!(GRAY, GREY);
assert_eq!(DARK_GRAY, DARK_GREY);
assert_eq!(DIM_GRAY, DIM_GREY);
assert_eq!(LIGHT_GRAY, LIGHT_GREY);
assert_eq!(SLATE_GRAY, SLATE_GREY);
assert_eq!(DARK_SLATE_GRAY, DARK_SLATE_GREY);
assert_eq!(LIGHT_SLATE_GRAY, LIGHT_SLATE_GREY);
}
#[test]
fn primary_colors_are_valid() {
// Test basic RGB colors
assert_eq!(RED, Color::from_rgb(1.0, 0.0, 0.0));
assert_eq!(GREEN, Color::from_rgb(0.0, 0.502, 0.0));
assert_eq!(BLUE, Color::from_rgb(0.0, 0.0, 1.0));
}
#[test]
fn cyan_magenta_yellow_are_valid() {
assert_eq!(CYAN, Color::from_rgb(0.0, 1.0, 1.0));
assert_eq!(MAGENTA, Color::from_rgb(1.0, 0.0, 1.0));
assert_eq!(YELLOW, Color::from_rgb(1.0, 1.0, 0.0));
}
#[test]
fn aqua_equals_cyan() {
assert_eq!(AQUA, CYAN);
}
#[test]
fn fuchsia_equals_magenta() {
assert_eq!(FUCHSIA, MAGENTA);
}
#[test]
fn color_values_are_in_valid_range() {
// Sample various colors to ensure RGB values are between 0.0 and 1.0
let sample_colors = [
ALICE_BLUE,
ANTIQUE_WHITE,
CORAL,
CRIMSON,
DARK_GOLDEN_ROD,
DEEP_PINK,
DODGER_BLUE,
FOREST_GREEN,
GOLD,
INDIAN_RED,
LAVENDER,
LIME_GREEN,
MEDIUM_PURPLE,
NAVY,
ORANGE,
PALE_GREEN,
PURPLE,
ROSY_BROWN,
SALMON,
SLATE_BLUE,
TOMATO,
TURQUOISE,
VIOLET,
];
for color in &sample_colors {
assert!(
color.r >= 0.0 && color.r <= 1.0,
"Red component out of range"
);
assert!(
color.g >= 0.0 && color.g <= 1.0,
"Green component out of range"
);
assert!(
color.b >= 0.0 && color.b <= 1.0,
"Blue component out of range"
);
}
}
#[test]
fn specific_colors_have_correct_values() {
// Test a few specific colors to ensure accuracy
assert_eq!(GOLD, Color::from_rgb(1.0, 0.843, 0.0));
assert_eq!(LIME_GREEN, Color::from_rgb(0.196, 0.804, 0.196));
assert_eq!(SKY_BLUE, Color::from_rgb(0.529, 0.808, 0.922));
assert_eq!(DODGER_BLUE, Color::from_rgb(0.118, 0.565, 1.0));
assert_eq!(GHOST_WHITE, Color::from_rgb(0.973, 0.973, 1.0));
assert_eq!(DIM_GRAY, Color::from_rgb(0.412, 0.412, 0.412));
}
#[test]
fn dark_colors_are_darker() {
// Verify dark variants have lower RGB values than their base colors
const {
assert!(DARK_BLUE.r <= BLUE.r);
assert!(DARK_BLUE.g <= BLUE.g);
assert!(DARK_BLUE.b <= BLUE.b);
assert!(DARK_GREEN.r <= GREEN.r);
assert!(DARK_GREEN.g <= GREEN.g);
assert!(DARK_GREEN.b <= GREEN.b);
assert!(DARK_RED.r <= RED.r);
assert!(DARK_RED.g <= RED.g);
assert!(DARK_RED.b <= RED.b);
}
}
#[test]
fn light_colors_are_lighter() {
// Verify some light variants are generally lighter (higher average RGB brightness)
// Note: Not all CSS "light" colors are consistently lighter than their base
let light_blue_avg = (LIGHT_BLUE.r + LIGHT_BLUE.g + LIGHT_BLUE.b) / 3.0;
let blue_avg = (BLUE.r + BLUE.g + BLUE.b) / 3.0;
assert!(light_blue_avg > blue_avg);
let light_green_avg = (LIGHT_GREEN.r + LIGHT_GREEN.g + LIGHT_GREEN.b) / 3.0;
let green_avg = (GREEN.r + GREEN.g + GREEN.b) / 3.0;
assert!(light_green_avg > green_avg);
const {
// Light Gray should be lighter than Gray in all components (grayscale)
assert!(LIGHT_GRAY.r >= GRAY.r);
assert!(LIGHT_GRAY.g >= GRAY.g);
assert!(LIGHT_GRAY.b >= GRAY.b);
}
}
#[test]
fn brown_shades_exist() {
// Test various brown colors
assert_eq!(BROWN, Color::from_rgb(0.647, 0.165, 0.165));
assert_eq!(SADDLE_BROWN, Color::from_rgb(0.545, 0.271, 0.075));
assert_eq!(SANDY_BROWN, Color::from_rgb(0.957, 0.643, 0.376));
assert_eq!(ROSY_BROWN, Color::from_rgb(0.737, 0.561, 0.561));
}
#[test]
fn purple_shades_exist() {
// Test various purple colors
assert_eq!(PURPLE, Color::from_rgb(0.502, 0.0, 0.502));
assert_eq!(REBECCA_PURPLE, Color::from_rgb(0.4, 0.2, 0.6));
assert_eq!(MEDIUM_PURPLE, Color::from_rgb(0.576, 0.439, 0.859));
}
#[test]
fn orange_shades_exist() {
// Test various orange colors
assert_eq!(ORANGE, Color::from_rgb(1.0, 0.647, 0.0));
assert_eq!(DARK_ORANGE, Color::from_rgb(1.0, 0.549, 0.0));
assert_eq!(ORANGE_RED, Color::from_rgb(1.0, 0.271, 0.0));
}
}
+176
View File
@@ -0,0 +1,176 @@
//! Use a badge for color highlighting important information.
//!
//! *This API requires the following crate features to be activated: badge*
use super::{Status, StyleFn};
use iced_core::{Background, Color, Theme};
/// The style of a [`ContextMenu`](crate::widget::ContextMenu).
#[derive(Clone, Copy, Debug)]
pub struct Style {
/// The background of the [`ContextMenu`](crate::widget::ContextMenu).
///
/// This is used to color the backdrop of the modal.
pub background: Background,
}
impl Default for Style {
fn default() -> Self {
Self {
background: Background::Color([0.87, 0.87, 0.87, 0.30].into()),
}
}
}
/// The Catalog of a [`ContextMenu`](crate::widget::ContextMenu).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`ContextMenu`](crate::widget::ContextMenu).
#[must_use]
pub fn primary(theme: &Theme, _status: Status) -> Style {
let palette = theme.extended_palette();
Style {
background: Background::Color(Color {
a: 0f32,
..palette.background.base.color
}),
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Theme};
#[test]
fn style_default() {
let style = Style::default();
assert!(matches!(style.background, Background::Color(_)));
// Verify the default has a semi-transparent background
if let Background::Color(color) = style.background {
assert_eq!(color.a, 0.30);
}
}
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
}
#[test]
fn primary_theme_focused() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Focused);
assert!(matches!(style.background, Background::Color(_)));
}
#[test]
fn primary_theme_has_transparent_background() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
// The primary theme should create a transparent background
#[allow(clippy::panic)]
if let Background::Color(color) = style.background {
assert_eq!(
color.a, 0.0,
"Primary theme should have fully transparent background"
);
} else {
panic!("Expected Background::Color");
}
}
#[test]
fn status_does_not_affect_style() {
let theme = Theme::TokyoNight;
let active_style = primary(&theme, Status::Active);
let hovered_style = primary(&theme, Status::Hovered);
let disabled_style = primary(&theme, Status::Disabled);
let focused_style = primary(&theme, Status::Focused);
// All statuses should produce the same style
assert_eq!(
format!("{:?}", active_style.background),
format!("{:?}", hovered_style.background)
);
assert_eq!(
format!("{:?}", active_style.background),
format!("{:?}", disabled_style.background)
);
assert_eq!(
format!("{:?}", active_style.background),
format!("{:?}", focused_style.background)
);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
}
#[test]
fn catalog_style_with_different_statuses() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let active_style = theme.style(&class, Status::Active);
let hovered_style = theme.style(&class, Status::Hovered);
let disabled_style = theme.style(&class, Status::Disabled);
assert!(matches!(active_style.background, Background::Color(_)));
assert!(matches!(hovered_style.background, Background::Color(_)));
assert!(matches!(disabled_style.background, Background::Color(_)));
}
}
+271
View File
@@ -0,0 +1,271 @@
//! Use a date picker as an input element for picking dates.
//!
//! *This API requires the following crate features to be activated: `date_picker`*
use super::{Status, StyleFn};
use iced_core::{Background, Color, Theme};
/// The appearance of a [`DatePicker`](crate::widget::DatePicker).
#[derive(Clone, Copy, Debug)]
pub struct Style {
/// The background of the [`DatePicker`](crate::widget::DatePicker).
pub background: Background,
/// The border radius of the [`DatePicker`](crate::widget::DatePicker).
pub border_radius: f32,
/// The border with of the [`DatePicker`](crate::widget::DatePicker).
pub border_width: f32,
/// The border color of the [`DatePicker`](crate::widget::DatePicker).
pub border_color: Color,
/// The text color of the [`DatePicker`](crate::widget::DatePicker).
pub text_color: Color,
/// The attenuated color of the days which are not in the selected month
/// of the [`DatePicker`](crate::widget::DatePicker).
pub text_attenuated_color: Color,
/// The background of the days in the calender of the
/// [`DatePicker`](crate::widget::DatePicker).
pub day_background: Background,
}
/// The Catalog of a [`DatePicker`](crate::widget::DatePicker).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn primary(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let foreground = theme.palette();
let base = Style {
background: palette.background.base.color.into(),
border_radius: 15.0,
border_width: 1.0,
border_color: foreground.text,
text_color: foreground.text,
text_attenuated_color: Color {
a: foreground.text.a * 0.5,
..foreground.text
},
day_background: palette.background.base.color.into(),
};
match status {
Status::Selected => Style {
day_background: palette.primary.strong.color.into(),
text_color: palette.primary.strong.text,
..base
},
Status::Hovered => Style {
day_background: palette.primary.weak.color.into(),
text_color: palette.primary.weak.text,
..base
},
Status::Focused => Style {
border_color: Color::from_rgb(0.5, 0.5, 0.5),
..base
},
_ => base,
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Theme};
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
assert!(matches!(style.day_background, Background::Color(_)));
}
#[test]
fn primary_theme_selected() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Selected);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.day_background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert!(matches!(style.day_background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_focused() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Focused);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_color, Color::from_rgb(0.5, 0.5, 0.5));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn selected_changes_day_background_and_text() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let selected_style = primary(&theme, Status::Selected);
// Day background and text color should be different when selected
assert_ne!(
format!("{:?}", base_style.day_background),
format!("{:?}", selected_style.day_background)
);
assert_ne!(base_style.text_color, selected_style.text_color);
// Other properties should remain the same
assert_eq!(base_style.background, selected_style.background);
assert_eq!(base_style.border_radius, selected_style.border_radius);
assert_eq!(base_style.border_width, selected_style.border_width);
assert_eq!(base_style.border_color, selected_style.border_color);
}
#[test]
fn hovered_changes_day_background_and_text() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let hovered_style = primary(&theme, Status::Hovered);
// Day background and text color should be different when hovered
assert_ne!(
format!("{:?}", base_style.day_background),
format!("{:?}", hovered_style.day_background)
);
assert_ne!(base_style.text_color, hovered_style.text_color);
// Other properties should remain the same
assert_eq!(base_style.background, hovered_style.background);
assert_eq!(base_style.border_radius, hovered_style.border_radius);
assert_eq!(base_style.border_width, hovered_style.border_width);
assert_eq!(base_style.border_color, hovered_style.border_color);
}
#[test]
fn focused_changes_border_color() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let focused_style = primary(&theme, Status::Focused);
// Border color should be different when focused
assert_ne!(base_style.border_color, focused_style.border_color);
assert_eq!(focused_style.border_color, Color::from_rgb(0.5, 0.5, 0.5));
// Other properties should remain the same
assert_eq!(base_style.background, focused_style.background);
assert_eq!(base_style.border_radius, focused_style.border_radius);
assert_eq!(base_style.border_width, focused_style.border_width);
assert_eq!(base_style.text_color, focused_style.text_color);
assert_eq!(
format!("{:?}", base_style.day_background),
format!("{:?}", focused_style.day_background)
);
}
#[test]
fn text_attenuated_color_has_reduced_alpha() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
// Attenuated color should have half the alpha
assert!(
style.text_attenuated_color.a <= style.text_color.a,
"Attenuated color should have reduced alpha"
);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_radius, 15.0);
assert_eq!(style.border_width, 1.0);
}
#[test]
fn catalog_style_with_different_statuses() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let active_style = theme.style(&class, Status::Active);
let selected_style = theme.style(&class, Status::Selected);
let hovered_style = theme.style(&class, Status::Hovered);
let focused_style = theme.style(&class, Status::Focused);
assert!(matches!(active_style.background, Background::Color(_)));
assert!(matches!(selected_style.background, Background::Color(_)));
assert!(matches!(hovered_style.background, Background::Color(_)));
assert!(matches!(focused_style.background, Background::Color(_)));
}
#[test]
fn style_fields_are_valid() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
// Verify all fields have valid values
assert!(style.border_radius > 0.0);
assert!(style.border_width > 0.0);
assert!(style.text_attenuated_color.a >= 0.0);
assert!(style.text_attenuated_color.a <= 1.0);
}
}
+301
View File
@@ -0,0 +1,301 @@
//! Change the appearance of menu bars and their menus.
use super::{Status, StyleFn};
use iced_core::{Background, Border, Color, Shadow, Theme, Vector};
/// The appearance of a menu bar and its menus.
#[derive(Debug, Clone, Copy)]
pub struct Style {
/// The background of the menu bar.
pub bar_background: Background,
/// The border of the menu bar.
pub bar_border: Border,
/// The shadow of the menu bar.
pub bar_shadow: Shadow,
/// The background of the menus.
pub menu_background: Background,
/// The border of the menus.
pub menu_border: Border,
/// The shadow of the menus
pub menu_shadow: Shadow,
/// The backgraound of the path
pub path: Background,
/// The border of the path
pub path_border: Border,
}
impl std::default::Default for Style {
fn default() -> Self {
Self {
bar_background: Color::from([0.85; 3]).into(),
bar_border: Border {
radius: 8.0.into(),
..Default::default()
},
bar_shadow: Shadow::default(),
menu_background: Color::from([0.85; 3]).into(),
menu_border: Border {
radius: 8.0.into(),
..Default::default()
},
menu_shadow: Shadow {
color: Color::from([0.0, 0.0, 0.0, 0.5]),
offset: Vector::ZERO,
blur_radius: 10.0,
},
path: Color::from([0.3; 3]).into(),
path_border: Border {
radius: 6.0.into(),
..Default::default()
},
}
}
}
/// The Catalog of a [`Menu`](crate::widget::menu::Menu).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`Menu`](crate::widget::menu::Menu).
#[must_use]
pub fn primary(theme: &Theme, _status: Status) -> Style {
let palette = theme.extended_palette();
Style {
bar_background: palette.background.base.color.into(),
menu_background: palette.background.base.color.into(),
path: palette.primary.weak.color.into(),
..Default::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Theme};
#[test]
fn style_default() {
let style = Style::default();
// Verify bar properties
assert!(matches!(style.bar_background, Background::Color(_)));
assert_eq!(style.bar_border.radius.top_left, 8.0);
assert_eq!(style.bar_border.radius.top_right, 8.0);
assert_eq!(style.bar_border.radius.bottom_left, 8.0);
assert_eq!(style.bar_border.radius.bottom_right, 8.0);
// Verify menu properties
assert!(matches!(style.menu_background, Background::Color(_)));
assert_eq!(style.menu_border.radius.top_left, 8.0);
assert_eq!(style.menu_shadow.blur_radius, 10.0);
// Verify path properties
assert!(matches!(style.path, Background::Color(_)));
assert_eq!(style.path_border.radius.top_left, 6.0);
}
#[test]
fn default_shadow_has_blur() {
let style = Style::default();
// Menu shadow should have blur
assert_eq!(style.menu_shadow.blur_radius, 10.0);
assert_eq!(style.menu_shadow.offset, Vector::ZERO);
// Verify shadow color has transparency
if let Background::Color(color) = style.bar_background {
// Just verify it exists
let _ = color;
}
}
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.bar_background, Background::Color(_)));
assert!(matches!(style.menu_background, Background::Color(_)));
assert!(matches!(style.path, Background::Color(_)));
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.bar_background, Background::Color(_)));
assert!(matches!(style.menu_background, Background::Color(_)));
assert!(matches!(style.path, Background::Color(_)));
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.bar_background, Background::Color(_)));
assert!(matches!(style.menu_background, Background::Color(_)));
assert!(matches!(style.path, Background::Color(_)));
}
#[test]
fn primary_theme_focused() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Focused);
assert!(matches!(style.bar_background, Background::Color(_)));
assert!(matches!(style.menu_background, Background::Color(_)));
assert!(matches!(style.path, Background::Color(_)));
}
#[test]
fn primary_uses_default_borders_and_shadows() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
let default_style = Style::default();
// Primary theme should use default borders
assert_eq!(style.bar_border.radius, default_style.bar_border.radius);
assert_eq!(style.menu_border.radius, default_style.menu_border.radius);
assert_eq!(style.path_border.radius, default_style.path_border.radius);
// Primary theme should use default shadows
assert_eq!(
style.bar_shadow.blur_radius,
default_style.bar_shadow.blur_radius
);
assert_eq!(
style.menu_shadow.blur_radius,
default_style.menu_shadow.blur_radius
);
}
#[test]
fn status_does_not_affect_style() {
let theme = Theme::TokyoNight;
let active_style = primary(&theme, Status::Active);
let hovered_style = primary(&theme, Status::Hovered);
let disabled_style = primary(&theme, Status::Disabled);
// All statuses should produce the same style
assert_eq!(
format!("{:?}", active_style.bar_background),
format!("{:?}", hovered_style.bar_background)
);
assert_eq!(
format!("{:?}", active_style.bar_background),
format!("{:?}", disabled_style.bar_background)
);
assert_eq!(
format!("{:?}", active_style.menu_background),
format!("{:?}", hovered_style.menu_background)
);
assert_eq!(
format!("{:?}", active_style.path),
format!("{:?}", hovered_style.path)
);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.bar_background, Background::Color(_)));
assert!(matches!(style.menu_background, Background::Color(_)));
assert!(matches!(style.path, Background::Color(_)));
}
#[test]
fn catalog_style_with_different_statuses() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let active_style = theme.style(&class, Status::Active);
let hovered_style = theme.style(&class, Status::Hovered);
let disabled_style = theme.style(&class, Status::Disabled);
assert!(matches!(active_style.bar_background, Background::Color(_)));
assert!(matches!(hovered_style.bar_background, Background::Color(_)));
assert!(matches!(
disabled_style.bar_background,
Background::Color(_)
));
}
#[test]
fn default_border_radii_are_consistent() {
let style = Style::default();
// Bar border should have uniform radius
assert_eq!(
style.bar_border.radius.top_left,
style.bar_border.radius.top_right
);
assert_eq!(
style.bar_border.radius.bottom_left,
style.bar_border.radius.bottom_right
);
// Menu border should have uniform radius
assert_eq!(
style.menu_border.radius.top_left,
style.menu_border.radius.top_right
);
assert_eq!(
style.menu_border.radius.bottom_left,
style.menu_border.radius.bottom_right
);
// Path border should have uniform radius
assert_eq!(
style.path_border.radius.top_left,
style.path_border.radius.top_right
);
assert_eq!(
style.path_border.radius.bottom_left,
style.path_border.radius.bottom_right
);
}
#[test]
fn all_backgrounds_are_colors() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
// All backgrounds should be Color variants
assert!(matches!(style.bar_background, Background::Color(_)));
assert!(matches!(style.menu_background, Background::Color(_)));
assert!(matches!(style.path, Background::Color(_)));
}
}
+275
View File
@@ -0,0 +1,275 @@
//! Display fields that can only be filled with numeric type.
//!
//! *This API requires the following crate features to be activated: `number_input`*
use super::{Status, StyleFn};
use iced_core::{Background, Color, Theme};
use iced_widget::{container, text, text_input};
/// The appearance of a [`NumberInput`](crate::widget::number_input::NumberInput).
#[derive(Clone, Copy, Debug)]
pub struct Style {
/// The background of the [`NumberInput`](crate::widget::number_input::NumberInput).
pub button_background: Option<Background>,
/// The Color of the arrows of [`NumberInput`](crate::widget::number_input::NumberInput).
pub icon_color: Color,
}
impl Default for Style {
fn default() -> Self {
Self {
button_background: None,
icon_color: Color::BLACK,
}
}
}
/// The Catalog of a [`NumberInput`](crate::widget::number_input::NumberInput).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The Extended Catalog of a [`NumberInput`](crate::widget::number_input::NumberInput).
pub trait ExtendedCatalog:
text_input::Catalog + container::Catalog + text::Catalog + self::Catalog
{
/// The default class produced by the [`Catalog`].
#[must_use]
fn default_input<'a>() -> <Self as text_input::Catalog>::Class<'a> {
<Self as text_input::Catalog>::default()
}
/// The [`Style`] of a class with the given status.
fn style(&self, class: &<Self as self::Catalog>::Class<'_>, status: Status) -> Style;
}
impl ExtendedCatalog for Theme {
fn style(&self, class: &<Self as self::Catalog>::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`Badge`](crate::widget::badge::Badge).
#[must_use]
pub fn primary(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let base = Style {
button_background: Some(palette.primary.strong.color.into()),
icon_color: palette.primary.strong.text,
};
match status {
Status::Disabled => Style {
button_background: base.button_background.map(|bg| match bg {
Background::Color(color) => Background::Color(Color {
a: color.a * 0.5,
..color
}),
Background::Gradient(grad) => Background::Gradient(grad),
}),
icon_color: Color {
a: base.icon_color.a * 0.5,
..base.icon_color
},
},
_ => base,
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::Theme;
#[test]
fn style_default() {
let style = Style::default();
assert!(style.button_background.is_none());
assert_eq!(style.icon_color, Color::BLACK);
}
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(style.button_background.is_some());
#[allow(clippy::panic)]
if let Some(Background::Color(_)) = style.button_background {
// Background is a color
} else {
panic!("Expected button_background to be Some(Background::Color)");
}
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(style.button_background.is_some());
}
#[test]
fn primary_theme_focused() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Focused);
assert!(style.button_background.is_some());
}
#[test]
fn primary_theme_selected() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Selected);
assert!(style.button_background.is_some());
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(style.button_background.is_some());
}
#[test]
fn disabled_reduces_alpha() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let disabled_style = primary(&theme, Status::Disabled);
// Icon color alpha should be reduced
assert!(
disabled_style.icon_color.a <= base_style.icon_color.a,
"Disabled icon color should have reduced alpha"
);
// Button background alpha should be reduced for Color backgrounds
if let (Some(Background::Color(base_color)), Some(Background::Color(disabled_color))) = (
base_style.button_background,
disabled_style.button_background,
) {
assert!(
disabled_color.a <= base_color.a,
"Disabled button background should have reduced alpha"
);
}
}
#[test]
fn disabled_has_half_alpha() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let disabled_style = primary(&theme, Status::Disabled);
// Icon color should have approximately half the alpha
let expected_icon_alpha = base_style.icon_color.a * 0.5;
assert!(
(disabled_style.icon_color.a - expected_icon_alpha).abs() < 0.01,
"Disabled icon alpha should be approximately half"
);
}
#[test]
fn non_disabled_statuses_use_base_style() {
let theme = Theme::TokyoNight;
let active_style = primary(&theme, Status::Active);
let hovered_style = primary(&theme, Status::Hovered);
let focused_style = primary(&theme, Status::Focused);
// All non-disabled statuses should have the same style
assert_eq!(
format!("{:?}", active_style.button_background),
format!("{:?}", hovered_style.button_background)
);
assert_eq!(
format!("{:?}", active_style.button_background),
format!("{:?}", focused_style.button_background)
);
assert_eq!(active_style.icon_color, hovered_style.icon_color);
assert_eq!(active_style.icon_color, focused_style.icon_color);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = <Theme as Catalog>::style(&theme, &class, Status::Active);
assert!(style.button_background.is_some());
}
#[test]
fn catalog_style_with_different_statuses() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let active_style = <Theme as Catalog>::style(&theme, &class, Status::Active);
let hovered_style = <Theme as Catalog>::style(&theme, &class, Status::Hovered);
let disabled_style = <Theme as Catalog>::style(&theme, &class, Status::Disabled);
assert!(active_style.button_background.is_some());
assert!(hovered_style.button_background.is_some());
assert!(disabled_style.button_background.is_some());
}
#[test]
fn extended_catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = <Theme as ExtendedCatalog>::style(&theme, &class, Status::Active);
assert!(style.button_background.is_some());
}
#[test]
fn extended_catalog_default_input() {
let _class = <Theme as ExtendedCatalog>::default_input();
}
#[test]
fn disabled_preserves_gradient_backgrounds() {
// Create a style with a gradient background
let gradient = iced_core::Gradient::Linear(iced_core::gradient::Linear {
angle: 0.0.into(),
stops: [None; 8],
});
let style_with_gradient = Style {
button_background: Some(Background::Gradient(gradient)),
icon_color: Color::WHITE,
};
// If we had a disabled version, it should preserve the gradient
// This tests that gradients are handled in the match statement
#[allow(clippy::panic)]
if let Some(Background::Color(_)) = style_with_gradient.button_background {
panic!("Expected gradient to be preserved");
}
}
}
+256
View File
@@ -0,0 +1,256 @@
//! Selection List
//!
//! *This API requires the following crate features to be activated: `selection_list`*
use super::{Status, StyleFn};
use iced_core::{Background, Color, Theme};
/// The appearance of a menu.
#[derive(Debug, Clone, Copy)]
pub struct Style {
/// The List Label Text Color
pub text_color: Color,
/// The background
pub background: Background,
/// The container Border width
pub border_width: f32,
/// The container Border color
pub border_color: Color,
}
/// The Catalog of a [`Badge`](crate::widget::selection_list::SelectionList).
pub trait Catalog {
///Style for the trait to use.
type Class<'a>;
/// The default class produced by the [`Catalog`].
fn default<'a>() -> Self::Class<'a>;
/// The [`Style`] of a class with the given status.
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style;
}
impl Catalog for Theme {
type Class<'a> = StyleFn<'a, Self, Style>;
fn default<'a>() -> Self::Class<'a> {
Box::new(primary)
}
fn style(&self, class: &Self::Class<'_>, status: Status) -> Style {
class(self, status)
}
}
/// The primary theme of a [`Badge`](crate::widget::selection_list::SelectionList).
#[must_use]
pub fn primary(theme: &Theme, status: Status) -> Style {
let palette = theme.extended_palette();
let base = Style {
text_color: palette.background.base.text,
background: palette.background.base.color.into(),
border_width: 1.0,
border_color: palette.background.weak.color,
};
match status {
Status::Hovered => Style {
text_color: palette.primary.base.text,
background: palette.primary.base.color.into(),
..base
},
Status::Selected => Style {
text_color: palette.primary.strong.text,
background: palette.primary.strong.color.into(),
..base
},
_ => base,
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_core::{Background, Theme};
#[test]
fn primary_theme_active() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_hovered() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Hovered);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_selected() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Selected);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_disabled() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Disabled);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_width, 1.0);
}
#[test]
fn primary_theme_focused() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Focused);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_width, 1.0);
}
#[test]
fn hovered_changes_text_and_background() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let hovered_style = primary(&theme, Status::Hovered);
// Text color and background should be different when hovered
assert_ne!(base_style.text_color, hovered_style.text_color);
assert_ne!(
format!("{:?}", base_style.background),
format!("{:?}", hovered_style.background)
);
// Border properties should remain the same
assert_eq!(base_style.border_width, hovered_style.border_width);
assert_eq!(base_style.border_color, hovered_style.border_color);
}
#[test]
fn selected_changes_text_and_background() {
let theme = Theme::TokyoNight;
let base_style = primary(&theme, Status::Active);
let selected_style = primary(&theme, Status::Selected);
// Text color and background should be different when selected
assert_ne!(base_style.text_color, selected_style.text_color);
assert_ne!(
format!("{:?}", base_style.background),
format!("{:?}", selected_style.background)
);
// Border properties should remain the same
assert_eq!(base_style.border_width, selected_style.border_width);
assert_eq!(base_style.border_color, selected_style.border_color);
}
#[test]
fn selected_and_hovered_have_different_styles() {
let theme = Theme::TokyoNight;
let hovered_style = primary(&theme, Status::Hovered);
let selected_style = primary(&theme, Status::Selected);
// Selected and hovered should use different colors
assert_ne!(hovered_style.text_color, selected_style.text_color);
assert_ne!(
format!("{:?}", hovered_style.background),
format!("{:?}", selected_style.background)
);
}
#[test]
fn non_interactive_statuses_use_base_style() {
let theme = Theme::TokyoNight;
let active_style = primary(&theme, Status::Active);
let disabled_style = primary(&theme, Status::Disabled);
let focused_style = primary(&theme, Status::Focused);
// Non-interactive statuses should have the same style
assert_eq!(active_style.text_color, disabled_style.text_color);
assert_eq!(active_style.text_color, focused_style.text_color);
assert_eq!(
format!("{:?}", active_style.background),
format!("{:?}", disabled_style.background)
);
assert_eq!(
format!("{:?}", active_style.background),
format!("{:?}", focused_style.background)
);
}
#[test]
fn catalog_default_class() {
let _class = <Theme as Catalog>::default();
}
#[test]
fn catalog_style() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let style = theme.style(&class, Status::Active);
assert!(matches!(style.background, Background::Color(_)));
assert_eq!(style.border_width, 1.0);
}
#[test]
fn catalog_style_with_different_statuses() {
let theme = Theme::TokyoNight;
let class = <Theme as Catalog>::default();
let active_style = theme.style(&class, Status::Active);
let hovered_style = theme.style(&class, Status::Hovered);
let selected_style = theme.style(&class, Status::Selected);
assert!(matches!(active_style.background, Background::Color(_)));
assert!(matches!(hovered_style.background, Background::Color(_)));
assert!(matches!(selected_style.background, Background::Color(_)));
}
#[test]
fn border_width_is_consistent() {
let theme = Theme::TokyoNight;
// All statuses should have the same border width
let active = primary(&theme, Status::Active);
let hovered = primary(&theme, Status::Hovered);
let selected = primary(&theme, Status::Selected);
assert_eq!(active.border_width, 1.0);
assert_eq!(hovered.border_width, 1.0);
assert_eq!(selected.border_width, 1.0);
}
#[test]
fn border_color_is_consistent() {
let theme = Theme::TokyoNight;
// All statuses should have the same border color
let active = primary(&theme, Status::Active);
let hovered = primary(&theme, Status::Hovered);
let selected = primary(&theme, Status::Selected);
assert_eq!(active.border_color, hovered.border_color);
assert_eq!(active.border_color, selected.border_color);
}
#[test]
fn style_fields_are_valid() {
let theme = Theme::TokyoNight;
let style = primary(&theme, Status::Active);
// Verify all fields have valid values
assert!(style.border_width > 0.0);
}
}
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff. Show more