Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
70e53c1246 | ||
|
|
b2ae30bab4 | ||
|
|
2538e41f00 | ||
|
|
3eb7cddb6c | ||
|
|
2813ae0eff | ||
|
|
1b1ffc4435 | ||
|
|
cf9fabb052 | ||
|
|
43fe73bf09 | ||
|
|
d291e36b3f | ||
|
|
fe37c15f95 | ||
|
|
d4f62da6f5 | ||
|
|
1edefd9cad | ||
|
|
90ffa7df27 | ||
|
|
d69e941ec1 | ||
|
|
5e5e8876f6 | ||
|
|
886d595f91 | ||
|
|
e04237b928 | ||
|
|
ef84c519a2 | ||
|
|
1e647c7036 | ||
|
|
56f6b1668d | ||
|
|
4c49407849 | ||
|
|
07d8066d90 | ||
|
|
ee2646f091 | ||
|
|
89eafe5bc7 | ||
|
|
bd9106c5ee | ||
|
|
2e49b98b82 | ||
|
|
12ea4e7f60 | ||
|
|
91fdfcd2b6 | ||
|
|
2c8b27bb5a | ||
|
|
f6cebdeba4 | ||
|
|
3b9aed089c | ||
|
|
20e08f74ee | ||
|
|
89c5aeb01d | ||
|
|
f1811475cd | ||
|
|
f25909b7f8 | ||
|
|
6690cda29f | ||
|
|
76e9d267df | ||
|
|
50ac4a89f5 | ||
|
|
376a6f215b | ||
|
|
24ec63a178 | ||
|
|
2f61da8690 | ||
|
|
48985c470a | ||
|
|
1a62696662 | ||
|
|
becd676352 | ||
|
|
f546cfa194 | ||
|
|
319bcdd355 | ||
|
|
300711affe | ||
|
|
c380d20794 | ||
|
|
833f289cd0 | ||
|
|
0577c023b8 | ||
|
|
460b63555a | ||
|
|
aec80d1afd | ||
|
|
0a5c4a386a | ||
|
|
8877674f43 | ||
|
|
d6b53be516 | ||
|
|
cf37611243 | ||
|
|
5191952155 | ||
|
|
193f1d59fa | ||
|
|
809af580a9 | ||
|
|
2ba19f9e64 | ||
|
|
9233128b7c | ||
|
|
b51fc8a1b0 | ||
|
|
0de3da162b | ||
|
|
510ad34183 | ||
|
|
c676c0223b | ||
|
|
29252cbbc6 | ||
|
|
c695288d1e | ||
|
|
c02937d8b6 | ||
|
|
b9ff6725cd | ||
|
|
3572d22ba8 | ||
|
|
50e2ab25a5 | ||
|
|
a1e36d9ac5 | ||
|
|
1ae11bab29 | ||
|
|
4e9f0e566f | ||
|
|
4ca4fa307a | ||
|
|
f2999fb53f | ||
|
|
b94e80c346 | ||
|
|
c5cc36b7cf | ||
|
|
14388085cb | ||
|
|
9908392af1 | ||
|
|
d10883169f | ||
|
|
d419946959 | ||
|
|
6679418696 | ||
|
|
61ad3e4d94 | ||
|
|
89d96e28ac | ||
|
|
b53a909e1c | ||
|
|
4053bb8973 | ||
|
|
5555c3c787 | ||
|
|
3b4c9267bb | ||
|
|
2bad68a8cf | ||
|
|
d41e338dfb | ||
|
|
46a1c9e701 | ||
|
|
bbfdb56d70 | ||
|
|
3dd09ca589 | ||
|
|
2d1d9d45d3 | ||
|
|
640165d8cc | ||
|
|
70bc9238c5 | ||
|
|
fa759c304a | ||
|
|
6deffa91bb | ||
|
|
1cadf43d49 | ||
|
|
560f92a64e | ||
|
|
2f9534f75f | ||
|
|
4bc58623b7 | ||
|
|
eec74ca750 | ||
|
|
2bb0a2f29f | ||
|
|
e9decaa594 | ||
|
|
c10e312b51 | ||
|
|
6e3bd0c4a8 | ||
|
|
9c3bfb627e | ||
|
|
a7011558b0 | ||
|
|
92acc7c356 | ||
|
|
e81a51416e | ||
|
|
19df29d7e0 | ||
|
|
461b34e5cb | ||
|
|
bb6c540441 | ||
|
|
ec2cfff9c4 | ||
|
|
18c93ec538 | ||
|
|
ea2fd4b701 | ||
|
|
37fcb7390b | ||
|
|
c5d7faceba | ||
|
|
ee4fe479d0 | ||
|
|
0896290411 | ||
|
|
0d8facbb01 | ||
|
|
a8c5c59b22 | ||
|
|
b72c8e9cd9 | ||
|
|
e63a28abb7 | ||
|
|
11fd9a79c3 | ||
|
|
4e48df376b | ||
|
|
fbc1f058ad | ||
|
|
840c8496ab | ||
|
|
0b5a6f6538 | ||
|
|
7845d64313 | ||
|
|
9329a1ebd8 | ||
|
|
b6bff9e9df | ||
|
|
095c2c9aef | ||
|
|
22893fd681 | ||
|
|
beb6cb2f08 | ||
|
|
5cc4a6e740 | ||
|
|
a4f661ffa7 | ||
|
|
339b069354 | ||
|
|
ca0e646564 | ||
|
|
9116399ddd | ||
|
|
c135f37b45 | ||
|
|
f6bc4c6bbb | ||
|
|
14ca00a866 | ||
|
|
f33bc883e3 | ||
|
|
cee182df50 | ||
|
|
354558e592 | ||
|
|
9ea990d3c6 | ||
|
|
fa9716bc64 | ||
|
|
6f474a9a77 | ||
|
|
e84ebf36dc | ||
|
|
f351d183d3 | ||
|
|
52f4ae3cbf | ||
|
|
a2bc6190ce | ||
|
|
a52bc3f126 | ||
|
|
1b8c041151 | ||
|
|
331cc930ca | ||
|
|
a5a7a6937c | ||
|
|
a1b1bb01ff | ||
|
|
7e74b2e3ac | ||
|
|
5c50e294ff | ||
|
|
7bfd708399 | ||
|
|
bdcf83d1c2 | ||
|
|
bc16514f05 | ||
|
|
734a7bf04a | ||
|
|
a3d4709472 | ||
|
|
0cee090fa2 | ||
|
|
9ac29b2a94 | ||
|
|
14a1611e9e | ||
|
|
e426e1f884 | ||
|
|
b87bcd8cc9 | ||
|
|
a293b5914a | ||
|
|
247a56edf5 | ||
|
|
bf0a3617a6 | ||
|
|
dea9378d8d | ||
|
|
0a4e0829b9 | ||
|
|
9d2dd4ec37 | ||
|
|
247286fc5e |
+15
@@ -0,0 +1,15 @@
|
|||||||
|
image: archlinux
|
||||||
|
packages:
|
||||||
|
- rust
|
||||||
|
- libpulse
|
||||||
|
- alsa-lib
|
||||||
|
- fontconfig
|
||||||
|
sources:
|
||||||
|
- https://git.sr.ht/~kennylevinsen/wldash
|
||||||
|
tasks:
|
||||||
|
- rustfmt-check: |
|
||||||
|
cd wldash
|
||||||
|
cargo fmt -- --check
|
||||||
|
- build: |
|
||||||
|
cd wldash
|
||||||
|
cargo build
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# These are supported funding model platforms
|
||||||
|
|
||||||
|
liberapay: kennylevinsen
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
/target
|
||||||
|
**/*.rs.bk
|
||||||
Generated
+1229
File diff suppressed because it is too large
Load Diff
+50
@@ -0,0 +1,50 @@
|
|||||||
|
[package]
|
||||||
|
name = "wldash"
|
||||||
|
version = "0.3.0"
|
||||||
|
authors = ["Kenny Levinsen <kl@kl.wtf>"]
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
lto = "fat"
|
||||||
|
panic = "abort"
|
||||||
|
opt-level = "z"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["alsa-widget", "pulseaudio-widget", "yaml-cfg", "json-cfg"]
|
||||||
|
damage_debug = []
|
||||||
|
|
||||||
|
yaml-cfg = ["serde_yaml"]
|
||||||
|
json-cfg = ["serde_json"]
|
||||||
|
|
||||||
|
alsa-widget = ["alsa"]
|
||||||
|
pulseaudio-widget = ["libpulse-binding"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
byteorder = "1.4"
|
||||||
|
bitflags = "1.3"
|
||||||
|
dlib = "0.5"
|
||||||
|
rusttype = "^0.9"
|
||||||
|
chrono = "0.4"
|
||||||
|
nix = "0.26"
|
||||||
|
memmap = "0.7"
|
||||||
|
os_pipe = "1.1"
|
||||||
|
wayland-client = { version = "0.29"}
|
||||||
|
wayland-protocols = { version = "0.29", features = ["client", "unstable_protocols"] }
|
||||||
|
dbus = "0.6"
|
||||||
|
fuzzy-matcher = "0.3"
|
||||||
|
lazy_static = "1.4"
|
||||||
|
rcalc_lib = "1.0"
|
||||||
|
rust-ini = "0.18"
|
||||||
|
shlex = "1.1"
|
||||||
|
timerfd = "1.4.0"
|
||||||
|
walkdir = "2.3"
|
||||||
|
itertools = "0.10"
|
||||||
|
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
serde_json = { version = "1.0", optional = true }
|
||||||
|
serde_yaml = { version = "0.9", optional = true }
|
||||||
|
|
||||||
|
libpulse-binding = { version = "2.26", optional = true }
|
||||||
|
alsa = { version = "0.7.0", optional = true }
|
||||||
|
fontconfig = "0.6.0"
|
||||||
|
unicode-segmentation = "1.10.0"
|
||||||
@@ -0,0 +1,674 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
# wldash
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
A dashboard/launcher/control-panel thing for Wayland. Requires wlr-layer-shell-unstable-v1.
|
||||||
|
|
||||||
|
Consider this alpha-quality: While it works, *everything* is subject to change with a moments notice. You may end up pulling in the latest changes, and *poof*, wldash suddenly turns into an artisan espresso machine.
|
||||||
|
|
||||||
|
## How to use
|
||||||
|
|
||||||
|
1. Checkout: `git clone https://github.com/kennylevinsen/wldash`
|
||||||
|
2. Build: `cargo build --release`
|
||||||
|
3. Put somewhere: `cp target/release/wldash /usr/local/bin/wldash`
|
||||||
|
4. Run: `wldash`
|
||||||
|
|
||||||
|
To see the default configuration, run `wldash print-config`. To configure, place a file in `$XDG_CONFIG_HOME/wldash/config.yaml` (or if `XDG_CONFIG_HOME` is not set, `~/.config/wldash/config.yaml`). JSON is also currently supported.
|
||||||
|
|
||||||
|
Notable settings: `outptuMode` can be `active` or `all`, `scale` can be set to `2` to half the buffer size, and the widgets (and their layout) can be configured.
|
||||||
|
|
||||||
|
For more info, look in `src/config.rs`.
|
||||||
|
|
||||||
|
## System dependencies
|
||||||
|
|
||||||
|
`dbus`. See https://github.com/diwic/dbus-rs#requirements.
|
||||||
|
|
||||||
|
## How to use launcher
|
||||||
|
|
||||||
|
The launcher for wldash is built-in, based on https://github.com/kennylevinsen/dot-desktop. Pluggable systems may come back in the future.
|
||||||
|
|
||||||
|
The environment variables `XDG_DATA_DIRS` and `XDG_DATA_HOME` are read to find the many `applications` folders that contain `desktop` files.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
### Date and time
|
||||||
|
|
||||||
|
In nice, big letters!
|
||||||
|
|
||||||
|
### 3 month calendar
|
||||||
|
|
||||||
|
Scroll or click on the months to navigate.
|
||||||
|
|
||||||
|
### Battery level
|
||||||
|
|
||||||
|
Over upower, only visible if upower battery is detected
|
||||||
|
|
||||||
|
### Audio volume
|
||||||
|
|
||||||
|
Over pulseaudio, only visible if pulseaudio connection is successful. Scroll to adjust volume, right-click to toggle mute.
|
||||||
|
|
||||||
|
### Backlight control
|
||||||
|
|
||||||
|
Using backlight sys file, only visible of backlight is detected. Scroll to adjust, right-click to toggle between the extreme values.
|
||||||
|
|
||||||
|
### Launcher
|
||||||
|
|
||||||
|
Loads desktop files from the usual locations.
|
||||||
|
|
||||||
|
The launcher also accepts prefix operators to change its mode:
|
||||||
|
|
||||||
|
- `!`: Arbitrary command
|
||||||
|
- `=`: Calculator based on rcalc_lib. See https://docs.rs/rcalc_lib/0.9.3/rcalc_lib/
|
||||||
|
|
||||||
|
## Notable missing features:
|
||||||
|
|
||||||
|
- Scaling of any kind - all sizes are currently hardcoded in pixels
|
||||||
|
- Configurability
|
||||||
|
- Cleanup and reorganization
|
||||||
|
- Proper line editor for the launcher
|
||||||
|
|
||||||
|
## How to discuss
|
||||||
|
|
||||||
|
Go to #kennylevinsen @ irc.libera.chat to discuss, or use [~kennylevinsen/public-inbox@lists.sr.ht](https://lists.sr.ht/~kennylevinsen/public-inbox).
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 130 KiB |
+55
@@ -0,0 +1,55 @@
|
|||||||
|
{
|
||||||
|
"widget": {
|
||||||
|
"margin": {
|
||||||
|
"margins": [20,20,20,20],
|
||||||
|
"widget": {
|
||||||
|
"verticalLayout": [{
|
||||||
|
"horizontalLayout": [{
|
||||||
|
"margin": {
|
||||||
|
"margins": [0,88,0,32],
|
||||||
|
"widget": {
|
||||||
|
"verticalLayout": [
|
||||||
|
{"date": {"font_size": 64.0}},
|
||||||
|
{"clock": {"font_size": 256.0}}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},{
|
||||||
|
"verticalLayout": [{
|
||||||
|
"margin": {
|
||||||
|
"margins": [0,0,0,8],
|
||||||
|
"widget": {"battery": {"font_size": 24.0,"length": 600}}
|
||||||
|
}
|
||||||
|
},{
|
||||||
|
"margin": {
|
||||||
|
"margins": [0,0,0,8],
|
||||||
|
"widget": {"backlight": {"device": "intel_backlight", "font_size": 24.0,"length": 600}}
|
||||||
|
}
|
||||||
|
},{
|
||||||
|
"margin": {
|
||||||
|
"margins": [0,0,0,8],
|
||||||
|
"widget": {"pulseAudio": {"font_size": 24.0,"length": 600}}
|
||||||
|
}
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
]},
|
||||||
|
{"calendar": {"font_size": 16.0,"sections": 3}},
|
||||||
|
{"launcher": {
|
||||||
|
"font_size": 32.0,
|
||||||
|
"length": 1200,
|
||||||
|
"app_opener": "swaymsg exec -- ",
|
||||||
|
"term_opener": "foot --",
|
||||||
|
"url_opener": "xdg-open "
|
||||||
|
}}
|
||||||
|
]}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"outputMode": "active",
|
||||||
|
"scale": 1,
|
||||||
|
"background": {
|
||||||
|
"red": 0,
|
||||||
|
"green": 0,
|
||||||
|
"blue": 0,
|
||||||
|
"opacity": 0.9
|
||||||
|
}
|
||||||
|
}
|
||||||
+50
@@ -0,0 +1,50 @@
|
|||||||
|
outputMode: active
|
||||||
|
scale: 1
|
||||||
|
background:
|
||||||
|
red: 0.0
|
||||||
|
green: 0.0
|
||||||
|
blue: 0.0
|
||||||
|
opacity: 0.9
|
||||||
|
widget:
|
||||||
|
margin:
|
||||||
|
margins: [20, 20, 20, 20]
|
||||||
|
widget:
|
||||||
|
verticalLayout:
|
||||||
|
- horizontalLayout:
|
||||||
|
- margin:
|
||||||
|
margins: [0, 88, 0, 32]
|
||||||
|
widget:
|
||||||
|
verticalLayout:
|
||||||
|
- date:
|
||||||
|
font_size: 64.0
|
||||||
|
- clock:
|
||||||
|
font_size: 256.0
|
||||||
|
- verticalLayout:
|
||||||
|
- margin:
|
||||||
|
margins: [0, 0, 0, 8]
|
||||||
|
widget:
|
||||||
|
battery:
|
||||||
|
font_size: 24.0
|
||||||
|
length: 600
|
||||||
|
- margin:
|
||||||
|
margins: [0, 0, 0, 8]
|
||||||
|
widget:
|
||||||
|
backlight:
|
||||||
|
device: "intel_backlight"
|
||||||
|
font_size: 24.0
|
||||||
|
length: 600
|
||||||
|
- margin:
|
||||||
|
margins: [0, 0, 0, 8]
|
||||||
|
widget:
|
||||||
|
pulseAudio:
|
||||||
|
font_size: 24.0
|
||||||
|
length: 600
|
||||||
|
- calendar:
|
||||||
|
font_size: 16.0
|
||||||
|
sections: 3
|
||||||
|
- launcher:
|
||||||
|
font_size: 32.0
|
||||||
|
length: 1200
|
||||||
|
app_opener: "swaymsg exec --"
|
||||||
|
term_opener: "foot --"
|
||||||
|
url_opener: "xdg-open "
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 201 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 781 KiB |
-102
@@ -1,102 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<title>wldash</title>
|
|
||||||
<meta http-equiv="refresh" content="0; URL=https://kl.wtf/projects/wldash">
|
|
||||||
<link rel="canonical" href="https://kl.wtf/projects/wldash">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
||||||
<style>
|
|
||||||
body {
|
|
||||||
display: grid;
|
|
||||||
justify-items: center;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
h1 {
|
|
||||||
font-size: 3em;
|
|
||||||
text-align: center;
|
|
||||||
font-family: monospace;
|
|
||||||
}
|
|
||||||
h2 {
|
|
||||||
text-align: center;
|
|
||||||
font-family: monospace;
|
|
||||||
}
|
|
||||||
h3 {
|
|
||||||
font-family: monospace;
|
|
||||||
}
|
|
||||||
header {
|
|
||||||
width: 100%;
|
|
||||||
max-width: 720px;
|
|
||||||
}
|
|
||||||
section {
|
|
||||||
width: 100%;
|
|
||||||
max-width: 720px;
|
|
||||||
}
|
|
||||||
a {
|
|
||||||
text-decoration: unset;
|
|
||||||
color: rgb(100, 100, 100);
|
|
||||||
}
|
|
||||||
li {
|
|
||||||
list-style-type: '— ';
|
|
||||||
}
|
|
||||||
p {
|
|
||||||
margin-bottom: 2em;
|
|
||||||
}
|
|
||||||
img {
|
|
||||||
width: 100%;
|
|
||||||
border-radius: 10px;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<header>
|
|
||||||
<h1>wldash</h1>
|
|
||||||
<h2>wayland launcher/dashboard</h2>
|
|
||||||
</header>
|
|
||||||
<section>
|
|
||||||
<img src="images/wldash.jpg" alt="screenshot of wldash" />
|
|
||||||
<p>
|
|
||||||
<a href="https://github.com/kennylevinsen/wldash"><code>wldash</code></a> is a convenient dashboard and launcher for Wayland (requires wlr-layer-shell-unstable-v1 support), allowing easy access to things like date and time, backlight and volume control.
|
|
||||||
</p>
|
|
||||||
<h3>How to get wldash</h3>
|
|
||||||
<ul>
|
|
||||||
<li><a href="https://github.com/kennylevinsen/wldash/releases">Download the latest release from GitHub</a></li>
|
|
||||||
<li>To build:
|
|
||||||
<pre><code>
|
|
||||||
git clone https://github.com/kennylevinsen/wldash
|
|
||||||
cd wldash
|
|
||||||
cargo build --release
|
|
||||||
cp ./target/release/wldash /usr/local/bin/
|
|
||||||
wldash
|
|
||||||
</code></pre>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
<h3>Usage</h3>
|
|
||||||
<p>
|
|
||||||
Run <code>wldash print-config</code> to see the current configuration. Use that as template to write a new one to <code>~/.config/wldash/config.json</code>. The widgets, their size and layout can be configured as well.
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
To make wldash toggle itself every time it is started, instantiate with <code>wldash start-or-kill</code>.
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
To run arbitrary command, type <code>!</code>. To use built-in calculator, type <code>=</code>.
|
|
||||||
</p>
|
|
||||||
<p>
|
|
||||||
Hint: Try to scroll, left-click and right-click on things.
|
|
||||||
</p>
|
|
||||||
<h3>Links</h3>
|
|
||||||
<p>
|
|
||||||
<ul>
|
|
||||||
<li>Github link: <a href="https://github.com/kennylevinsen/wldash">https://github.com/kennylevinsen/wldash</a></li>
|
|
||||||
<li>IRC: #wldash @ irc.freenode.net</li>
|
|
||||||
</ul>
|
|
||||||
</p>
|
|
||||||
<h3>Donate</h3>
|
|
||||||
<ul>
|
|
||||||
<li><a href="https://en.liberapay.com/kennylevinsen/">LiberaPay</a></li>
|
|
||||||
</ul>
|
|
||||||
<p>
|
|
||||||
<a href="https://kl.wtf/">© 2019, Kenny Levinsen</a>
|
|
||||||
</p>
|
|
||||||
</section>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
+600
@@ -0,0 +1,600 @@
|
|||||||
|
use std::collections::VecDeque;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::sync::mpsc::Sender;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use chrono::{Duration, Local, NaiveDateTime};
|
||||||
|
|
||||||
|
use crate::keyboard::{keysyms, map_keyboard, Event as KbEvent, KeyState, ModifiersState};
|
||||||
|
|
||||||
|
use wayland_client::protocol::{wl_compositor, wl_output, wl_pointer, wl_seat, wl_shm, wl_surface};
|
||||||
|
use wayland_client::{Display, EventQueue, GlobalEvent, GlobalManager, Main};
|
||||||
|
use wayland_protocols::wlr::unstable::layer_shell::v1::client::{
|
||||||
|
zwlr_layer_shell_v1, zwlr_layer_surface_v1,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::buffer::Buffer;
|
||||||
|
use crate::color::Color;
|
||||||
|
use crate::widget::{DrawContext, WaitContext, Widget};
|
||||||
|
|
||||||
|
use crate::cmd::Cmd;
|
||||||
|
use crate::doublemempool::DoubleMemPool;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum OutputMode {
|
||||||
|
Active,
|
||||||
|
All,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct AppInner {
|
||||||
|
compositor: Option<Main<wl_compositor::WlCompositor>>,
|
||||||
|
surfaces: Vec<Main<wl_surface::WlSurface>>,
|
||||||
|
shell_surfaces: Vec<Main<zwlr_layer_surface_v1::ZwlrLayerSurfaceV1>>,
|
||||||
|
configured_surfaces: Arc<Mutex<usize>>,
|
||||||
|
outputs: Vec<(u32, Main<wl_output::WlOutput>)>,
|
||||||
|
shell: Option<Main<zwlr_layer_shell_v1::ZwlrLayerShellV1>>,
|
||||||
|
draw_tx: Sender<Cmd>,
|
||||||
|
output_mode: OutputMode,
|
||||||
|
visible: bool,
|
||||||
|
scale: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppInner {
|
||||||
|
fn new(tx: Sender<Cmd>, output_mode: OutputMode, scale: u32) -> AppInner {
|
||||||
|
AppInner {
|
||||||
|
compositor: None,
|
||||||
|
surfaces: Vec::new(),
|
||||||
|
shell_surfaces: Vec::new(),
|
||||||
|
configured_surfaces: Arc::new(Mutex::new(0)),
|
||||||
|
outputs: Vec::new(),
|
||||||
|
shell: None,
|
||||||
|
draw_tx: tx,
|
||||||
|
output_mode,
|
||||||
|
visible: true,
|
||||||
|
scale,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_shell_surface(
|
||||||
|
compositor: &wl_compositor::WlCompositor,
|
||||||
|
shell: &zwlr_layer_shell_v1::ZwlrLayerShellV1,
|
||||||
|
scale: u32,
|
||||||
|
configured_surfaces: Arc<Mutex<usize>>,
|
||||||
|
tx: Sender<Cmd>,
|
||||||
|
output: Option<&wl_output::WlOutput>,
|
||||||
|
) -> (
|
||||||
|
Main<wl_surface::WlSurface>,
|
||||||
|
Main<zwlr_layer_surface_v1::ZwlrLayerSurfaceV1>,
|
||||||
|
) {
|
||||||
|
let surface = compositor.create_surface();
|
||||||
|
|
||||||
|
let this_is_stupid = AtomicBool::new(false);
|
||||||
|
|
||||||
|
let shell_surface = shell.get_layer_surface(
|
||||||
|
&surface,
|
||||||
|
output,
|
||||||
|
zwlr_layer_shell_v1::Layer::Overlay,
|
||||||
|
"".to_string(),
|
||||||
|
);
|
||||||
|
shell_surface.quick_assign(move |layer, event, _| match event {
|
||||||
|
zwlr_layer_surface_v1::Event::Configure { serial, .. } => {
|
||||||
|
if this_is_stupid
|
||||||
|
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
|
||||||
|
.is_ok()
|
||||||
|
{
|
||||||
|
*(configured_surfaces.lock().unwrap()) += 1;
|
||||||
|
layer.ack_configure(serial);
|
||||||
|
tx.send(Cmd::ForceDraw).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => unreachable!(),
|
||||||
|
});
|
||||||
|
|
||||||
|
shell_surface.set_keyboard_interactivity(zwlr_layer_surface_v1::KeyboardInteractivity::Exclusive);
|
||||||
|
shell_surface.set_size(1, 1);
|
||||||
|
surface.set_buffer_scale(scale as i32);
|
||||||
|
surface.commit();
|
||||||
|
(surface, shell_surface)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn outputs_changed(&mut self) {
|
||||||
|
let shell = match self.shell {
|
||||||
|
Some(ref shell) => shell.to_owned(),
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
let compositor = match self.compositor {
|
||||||
|
Some(ref c) => c.to_owned(),
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
|
||||||
|
for shell_surface in self.shell_surfaces.iter() {
|
||||||
|
shell_surface.destroy();
|
||||||
|
}
|
||||||
|
for surface in self.surfaces.iter() {
|
||||||
|
surface.destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
self.configured_surfaces = Arc::new(Mutex::new(0));
|
||||||
|
|
||||||
|
if !self.visible {
|
||||||
|
self.surfaces = Vec::new();
|
||||||
|
self.shell_surfaces = Vec::new();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
match self.output_mode {
|
||||||
|
OutputMode::Active => {
|
||||||
|
if !self.shell_surfaces.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (surface, shell_surface) = AppInner::add_shell_surface(
|
||||||
|
&compositor,
|
||||||
|
&shell,
|
||||||
|
self.scale,
|
||||||
|
self.configured_surfaces.clone(),
|
||||||
|
self.draw_tx.clone(),
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
self.surfaces = vec![surface];
|
||||||
|
self.shell_surfaces = vec![shell_surface];
|
||||||
|
}
|
||||||
|
OutputMode::All => {
|
||||||
|
let mut surfaces = Vec::new();
|
||||||
|
let mut shell_surfaces = Vec::new();
|
||||||
|
for output in self.outputs.iter() {
|
||||||
|
let (surface, shell_surface) = AppInner::add_shell_surface(
|
||||||
|
&compositor,
|
||||||
|
&shell,
|
||||||
|
self.scale,
|
||||||
|
self.configured_surfaces.clone(),
|
||||||
|
self.draw_tx.clone(),
|
||||||
|
Some(&output.1),
|
||||||
|
);
|
||||||
|
surfaces.push(surface);
|
||||||
|
shell_surfaces.push(shell_surface);
|
||||||
|
}
|
||||||
|
self.surfaces = surfaces;
|
||||||
|
self.shell_surfaces = shell_surfaces;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.draw_tx.send(Cmd::ForceDraw).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_output(&mut self, id: u32, output: Main<wl_output::WlOutput>) {
|
||||||
|
self.outputs.push((id, output));
|
||||||
|
self.outputs_changed();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove_output(&mut self, id: u32) {
|
||||||
|
let old_output = self.outputs.iter().find(|(output_id, _)| *output_id == id);
|
||||||
|
if let Some(output) = old_output {
|
||||||
|
let new_outputs = self
|
||||||
|
.outputs
|
||||||
|
.iter()
|
||||||
|
.filter(|(output_id, _)| *output_id != id)
|
||||||
|
.map(|(x, y)| (*x, y.clone()))
|
||||||
|
.collect();
|
||||||
|
if output.1.as_ref().version() >= 3 {
|
||||||
|
output.1.release()
|
||||||
|
}
|
||||||
|
self.outputs = new_outputs;
|
||||||
|
self.outputs_changed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_compositor(&mut self, compositor: Option<Main<wl_compositor::WlCompositor>>) {
|
||||||
|
self.compositor = compositor
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_shell(&mut self, shell: Option<Main<zwlr_layer_shell_v1::ZwlrLayerShellV1>>) {
|
||||||
|
self.shell = shell
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct AppKeyboard {
|
||||||
|
current: Option<Cmd>,
|
||||||
|
delay: i32,
|
||||||
|
rate: i32,
|
||||||
|
next: Option<NaiveDateTime>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct App<'a> {
|
||||||
|
pools: DoubleMemPool,
|
||||||
|
display: Display,
|
||||||
|
event_queue: EventQueue,
|
||||||
|
cmd_queue: Arc<Mutex<VecDeque<Cmd>>>,
|
||||||
|
widget: Option<Box<dyn Widget + Send + 'a>>,
|
||||||
|
bg: Color,
|
||||||
|
inner: Arc<Mutex<AppInner>>,
|
||||||
|
last_damage: Option<Vec<(i32, i32, i32, i32)>>,
|
||||||
|
last_dim: (u32, u32),
|
||||||
|
keyboard: Arc<Mutex<AppKeyboard>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> App<'a> {
|
||||||
|
pub fn redraw(&mut self, force: bool) -> Result<(), ::std::io::Error> {
|
||||||
|
let widget = match self.widget {
|
||||||
|
Some(ref mut widget) => widget,
|
||||||
|
None => return Ok(()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let inner = self.inner.lock().unwrap();
|
||||||
|
let time = Local::now().naive_local();
|
||||||
|
|
||||||
|
if !inner.visible
|
||||||
|
|| inner.shell_surfaces.len() != *inner.configured_surfaces.lock().unwrap()
|
||||||
|
|| inner.surfaces.is_empty()
|
||||||
|
{
|
||||||
|
// Not ready yet
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let (last, pool) = match self.pools.pool() {
|
||||||
|
Some((last, pool)) => (last, pool),
|
||||||
|
None => {
|
||||||
|
self.pools.never_mind();
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let size = widget.size();
|
||||||
|
let size_changed = self.last_dim != size;
|
||||||
|
let force = force | size_changed;
|
||||||
|
|
||||||
|
// resize the pool if relevant
|
||||||
|
pool.resize((4 * size.0 * size.1) as usize)
|
||||||
|
.expect("Failed to resize the memory pool.");
|
||||||
|
let mmap = pool.mmap();
|
||||||
|
let mut buf = Buffer::new(mmap, size);
|
||||||
|
|
||||||
|
// Copy old damage
|
||||||
|
let force = match (force, &self.last_damage) {
|
||||||
|
(false, Some(d)) => {
|
||||||
|
let lastmmap = last.mmap();
|
||||||
|
let last = Buffer::new(lastmmap, size);
|
||||||
|
|
||||||
|
if cfg!(feature = "damage_debug") {
|
||||||
|
buf.memset(&Color::new(0.5, 0.75, 0.75, 1.0));
|
||||||
|
}
|
||||||
|
for d in d {
|
||||||
|
last.copy_to(&mut buf, d.clone());
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
_ => true,
|
||||||
|
};
|
||||||
|
|
||||||
|
if force {
|
||||||
|
buf.memset(&self.bg);
|
||||||
|
}
|
||||||
|
let report = widget.draw(
|
||||||
|
&mut DrawContext {
|
||||||
|
buf: &mut buf,
|
||||||
|
bg: &self.bg,
|
||||||
|
time,
|
||||||
|
force,
|
||||||
|
},
|
||||||
|
(0, 0),
|
||||||
|
size,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
mmap.flush().unwrap();
|
||||||
|
|
||||||
|
if !force && !report.full_damage && report.damage.is_empty() {
|
||||||
|
// Nothing to do
|
||||||
|
self.pools.never_mind();
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// get a buffer and attach it
|
||||||
|
let new_buffer = pool.buffer(
|
||||||
|
0,
|
||||||
|
report.width as i32,
|
||||||
|
report.height as i32,
|
||||||
|
4 * size.0 as i32,
|
||||||
|
wl_shm::Format::Argb8888,
|
||||||
|
);
|
||||||
|
if size_changed {
|
||||||
|
for shell_surface in inner.shell_surfaces.iter() {
|
||||||
|
shell_surface.set_size(size.0 / inner.scale, size.1 / inner.scale);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for surface in inner.surfaces.iter() {
|
||||||
|
surface.attach(Some(&new_buffer), 0, 0);
|
||||||
|
if cfg!(feature = "damage_debug") || force || report.full_damage {
|
||||||
|
surface.damage_buffer(0, 0, size.0 as i32, size.1 as i32);
|
||||||
|
} else {
|
||||||
|
for d in report.damage.iter() {
|
||||||
|
surface.damage_buffer(d.0, d.1, d.2, d.3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
surface.commit();
|
||||||
|
}
|
||||||
|
self.last_damage = if force || report.full_damage {
|
||||||
|
Some(vec![(0, 0, size.0 as i32, size.1 as i32)])
|
||||||
|
} else {
|
||||||
|
Some(report.damage)
|
||||||
|
};
|
||||||
|
self.last_dim = size;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn hide(&mut self) {
|
||||||
|
let mut inner = self.inner.lock().unwrap();
|
||||||
|
inner.visible = false;
|
||||||
|
self.last_dim = (0, 0);
|
||||||
|
inner.outputs_changed();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn show(&mut self) {
|
||||||
|
let mut inner = self.inner.lock().unwrap();
|
||||||
|
inner.visible = true;
|
||||||
|
self.last_dim = (0, 0);
|
||||||
|
inner.outputs_changed();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cmd_queue(&self) -> Arc<Mutex<VecDeque<Cmd>>> {
|
||||||
|
self.cmd_queue.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn flush_display(&mut self) {
|
||||||
|
self.display.flush().expect("unable to flush display");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn event_queue(&mut self) -> &mut EventQueue {
|
||||||
|
&mut self.event_queue
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_widget(&mut self) -> &mut Box<dyn Widget + Send + 'a> {
|
||||||
|
self.widget.as_mut().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_widget(&mut self, w: Box<dyn Widget + Send + 'a>) -> Result<(), ::std::io::Error> {
|
||||||
|
self.widget = Some(w);
|
||||||
|
self.redraw(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_keyboard_repeat(&mut self, ctx: &mut WaitContext) {
|
||||||
|
let kbd = self.keyboard.lock().unwrap();
|
||||||
|
if let Some(t) = kbd.next {
|
||||||
|
ctx.set_time(t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn key_repeat(&mut self) -> Option<Cmd> {
|
||||||
|
let time = Local::now().naive_local();
|
||||||
|
let mut kbd = self.keyboard.lock().unwrap();
|
||||||
|
if let Some(target) = kbd.next {
|
||||||
|
if time >= target {
|
||||||
|
let cmd = kbd.current.as_ref().unwrap().clone();
|
||||||
|
kbd.next = Some(time + Duration::milliseconds(kbd.rate.into()));
|
||||||
|
return Some(cmd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new(tx: Sender<Cmd>, output_mode: OutputMode, bg: Color, scale: u32) -> App<'a> {
|
||||||
|
let inner = Arc::new(Mutex::new(AppInner::new(tx, output_mode, scale)));
|
||||||
|
|
||||||
|
//
|
||||||
|
// Set up modules
|
||||||
|
//
|
||||||
|
|
||||||
|
let cmd_queue = Arc::new(Mutex::new(VecDeque::new()));
|
||||||
|
|
||||||
|
let display = Display::connect_to_env().unwrap();
|
||||||
|
let mut event_queue = display.create_event_queue();
|
||||||
|
let display_wrapper = (*display).clone().attach(event_queue.token());
|
||||||
|
|
||||||
|
//
|
||||||
|
// Set up global manager
|
||||||
|
//
|
||||||
|
let inner_global = inner.clone();
|
||||||
|
let manager =
|
||||||
|
GlobalManager::new_with_cb(&display_wrapper, move |event, registry, _| match event {
|
||||||
|
GlobalEvent::New {
|
||||||
|
id,
|
||||||
|
ref interface,
|
||||||
|
version,
|
||||||
|
} => {
|
||||||
|
if let "wl_output" = &interface[..] {
|
||||||
|
let output = registry.bind(std::cmp::min(version, 3), id);
|
||||||
|
inner_global.lock().unwrap().add_output(id, output);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
GlobalEvent::Removed { id, ref interface } => {
|
||||||
|
if let "wl_output" = &interface[..] {
|
||||||
|
inner_global.lock().unwrap().remove_output(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// double sync to retrieve the global list
|
||||||
|
// and the globals metadata
|
||||||
|
event_queue.sync_roundtrip(&mut (), |_, _, _| {}).unwrap();
|
||||||
|
event_queue.sync_roundtrip(&mut (), |_, _, _| {}).unwrap();
|
||||||
|
|
||||||
|
// wl_compositor
|
||||||
|
let compositor = manager
|
||||||
|
.instantiate_range(1, 4)
|
||||||
|
.expect("server didn't advertise `wl_compositor`");
|
||||||
|
|
||||||
|
inner.lock().unwrap().set_compositor(Some(compositor));
|
||||||
|
|
||||||
|
// wl_shm
|
||||||
|
let shm: Main<wl_shm::WlShm> = manager
|
||||||
|
.instantiate_range(1, 1)
|
||||||
|
.expect("server didn't advertise `wl_shm`");
|
||||||
|
|
||||||
|
let pools = DoubleMemPool::new(shm).expect("Failed to create a memory pool !");
|
||||||
|
|
||||||
|
//
|
||||||
|
// Get our seat
|
||||||
|
//
|
||||||
|
let seat: Main<wl_seat::WlSeat> = manager.instantiate_range(1, 6).unwrap();
|
||||||
|
event_queue.sync_roundtrip(&mut (), |_, _, _| {}).unwrap();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Keyboard processing
|
||||||
|
//
|
||||||
|
let kbd_clone = cmd_queue.clone();
|
||||||
|
let modifiers_state = Arc::new(Mutex::new(ModifiersState {
|
||||||
|
ctrl: false,
|
||||||
|
alt: false,
|
||||||
|
shift: false,
|
||||||
|
caps_lock: false,
|
||||||
|
logo: false,
|
||||||
|
num_lock: false,
|
||||||
|
}));
|
||||||
|
|
||||||
|
let keyboard = Arc::new(Mutex::new(AppKeyboard {
|
||||||
|
current: None,
|
||||||
|
delay: 0,
|
||||||
|
rate: 0,
|
||||||
|
next: None,
|
||||||
|
}));
|
||||||
|
|
||||||
|
let kb2 = keyboard.clone();
|
||||||
|
|
||||||
|
map_keyboard(&seat, None, move |event: KbEvent, _, _| match event {
|
||||||
|
KbEvent::Key {
|
||||||
|
keysym,
|
||||||
|
utf8,
|
||||||
|
state,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
if let KeyState::Pressed = state {
|
||||||
|
match keysym {
|
||||||
|
keysyms::XKB_KEY_Escape => kbd_clone.lock().unwrap().push_back(Cmd::Exit),
|
||||||
|
keysyms::XKB_KEY_c if modifiers_state.lock().unwrap().ctrl => {
|
||||||
|
kbd_clone.lock().unwrap().push_back(Cmd::Exit)
|
||||||
|
}
|
||||||
|
v => {
|
||||||
|
let ev = Cmd::Keyboard {
|
||||||
|
key: v,
|
||||||
|
key_state: state,
|
||||||
|
modifiers_state: *modifiers_state.lock().unwrap(),
|
||||||
|
interpreted: utf8,
|
||||||
|
};
|
||||||
|
let mut kbd = kb2.lock().unwrap();
|
||||||
|
kbd.current = Some(ev.clone());
|
||||||
|
kbd.next = if kbd.delay > 0 {
|
||||||
|
Some(
|
||||||
|
Local::now().naive_local()
|
||||||
|
+ Duration::milliseconds(kbd.delay.into()),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
drop(kbd);
|
||||||
|
kbd_clone.lock().unwrap().push_back(ev);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
kb2.lock().unwrap().next = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
KbEvent::Leave { .. } => {
|
||||||
|
kb2.lock().unwrap().next = None;
|
||||||
|
}
|
||||||
|
KbEvent::RepeatInfo { delay, rate } => {
|
||||||
|
let mut kbd = kb2.lock().unwrap();
|
||||||
|
kbd.delay = delay;
|
||||||
|
kbd.rate = rate;
|
||||||
|
}
|
||||||
|
KbEvent::Modifiers { modifiers } => *modifiers_state.lock().unwrap() = modifiers,
|
||||||
|
_ => (),
|
||||||
|
})
|
||||||
|
.expect("could not map keyboard");
|
||||||
|
|
||||||
|
//
|
||||||
|
// Prepare shell so that we can create our shell surface
|
||||||
|
//
|
||||||
|
inner
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.set_shell(Some(if let Ok(layer) = manager.instantiate_exact(1) {
|
||||||
|
layer
|
||||||
|
} else {
|
||||||
|
panic!("server didn't advertise `zwlr_layer_shell_v1`");
|
||||||
|
}));
|
||||||
|
|
||||||
|
event_queue.sync_roundtrip(&mut (), |_, _, _| {}).unwrap();
|
||||||
|
|
||||||
|
//
|
||||||
|
// Cursor processing
|
||||||
|
//
|
||||||
|
let pointer_clone = cmd_queue.clone();
|
||||||
|
let pointer = seat.get_pointer();
|
||||||
|
let mut pos: (u32, u32) = (0, 0);
|
||||||
|
let mut vert_scroll: f64 = 0.0;
|
||||||
|
let mut horiz_scroll: f64 = 0.0;
|
||||||
|
let mut btn: u32 = 0;
|
||||||
|
let mut btn_clicked = false;
|
||||||
|
pointer.quick_assign(move |_, event, _| match event {
|
||||||
|
wl_pointer::Event::Enter {
|
||||||
|
surface_x,
|
||||||
|
surface_y,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
pos = (surface_x as u32, surface_y as u32);
|
||||||
|
}
|
||||||
|
wl_pointer::Event::Leave { .. } => {
|
||||||
|
pos = (0, 0);
|
||||||
|
}
|
||||||
|
wl_pointer::Event::Motion {
|
||||||
|
surface_x,
|
||||||
|
surface_y,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
pos = (surface_x as u32 * scale, surface_y as u32 * scale);
|
||||||
|
}
|
||||||
|
wl_pointer::Event::Axis { axis, value, .. } => {
|
||||||
|
if axis == wl_pointer::Axis::VerticalScroll {
|
||||||
|
vert_scroll += value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wl_pointer::Event::Button { button, state, .. } => {
|
||||||
|
if let wl_pointer::ButtonState::Released = state {
|
||||||
|
btn = button;
|
||||||
|
btn_clicked = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wl_pointer::Event::Frame => {
|
||||||
|
if vert_scroll != 0.0 || horiz_scroll != 0.0 {
|
||||||
|
pointer_clone.lock().unwrap().push_back(Cmd::MouseScroll {
|
||||||
|
scroll: (horiz_scroll, vert_scroll),
|
||||||
|
pos,
|
||||||
|
});
|
||||||
|
vert_scroll = 0.0;
|
||||||
|
horiz_scroll = 0.0;
|
||||||
|
}
|
||||||
|
if btn_clicked {
|
||||||
|
pointer_clone
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.push_back(Cmd::MouseClick { btn, pos });
|
||||||
|
btn_clicked = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
});
|
||||||
|
|
||||||
|
display.flush().unwrap();
|
||||||
|
|
||||||
|
App {
|
||||||
|
display,
|
||||||
|
event_queue,
|
||||||
|
cmd_queue,
|
||||||
|
pools,
|
||||||
|
widget: None,
|
||||||
|
bg,
|
||||||
|
inner,
|
||||||
|
last_damage: None,
|
||||||
|
last_dim: (0, 0),
|
||||||
|
keyboard,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+180
@@ -0,0 +1,180 @@
|
|||||||
|
use memmap::MmapMut;
|
||||||
|
|
||||||
|
use crate::color::Color;
|
||||||
|
|
||||||
|
pub struct Buffer<'a> {
|
||||||
|
buf: &'a mut MmapMut,
|
||||||
|
dimensions: (u32, u32),
|
||||||
|
subdimensions: Option<(u32, u32, u32, u32)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Buffer<'a> {
|
||||||
|
pub fn new(buf: &'a mut MmapMut, dimensions: (u32, u32)) -> Buffer {
|
||||||
|
Buffer {
|
||||||
|
buf,
|
||||||
|
dimensions,
|
||||||
|
subdimensions: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_bounds(&self) -> (u32, u32, u32, u32) {
|
||||||
|
if let Some(subdim) = self.subdimensions {
|
||||||
|
subdim
|
||||||
|
} else {
|
||||||
|
(0, 0, self.dimensions.0, self.dimensions.1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_signed_bounds(&self) -> (i32, i32, i32, i32) {
|
||||||
|
if let Some(subdim) = self.subdimensions {
|
||||||
|
(
|
||||||
|
subdim.0 as i32,
|
||||||
|
subdim.1 as i32,
|
||||||
|
subdim.2 as i32,
|
||||||
|
subdim.3 as i32,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(0, 0, self.dimensions.0 as i32, self.dimensions.1 as i32)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn copy_to(&self, other: &mut Buffer, (x, y, width, height): (i32, i32, i32, i32)) {
|
||||||
|
debug_assert!(self.dimensions == other.dimensions);
|
||||||
|
debug_assert!(self.subdimensions.is_none() && other.subdimensions.is_none());
|
||||||
|
|
||||||
|
if x == 0 && width as u32 == self.dimensions.0 {
|
||||||
|
// Full-width copy
|
||||||
|
let offset = y as isize * self.dimensions.0 as isize;
|
||||||
|
let n = height as usize * self.dimensions.0 as usize;
|
||||||
|
unsafe {
|
||||||
|
std::ptr::copy(
|
||||||
|
(self.buf.as_ptr() as *const u32).offset(offset),
|
||||||
|
(other.buf.as_mut_ptr() as *mut u32).offset(offset),
|
||||||
|
n,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Row-by-row copy
|
||||||
|
for cur_y in y as isize..(y + height) as isize {
|
||||||
|
let offset = x as isize + cur_y as isize * self.dimensions.0 as isize;
|
||||||
|
unsafe {
|
||||||
|
std::ptr::copy(
|
||||||
|
(self.buf.as_ptr() as *const u32).offset(offset),
|
||||||
|
(other.buf.as_mut_ptr() as *mut u32).offset(offset),
|
||||||
|
width as usize,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn subdimensions(
|
||||||
|
&mut self,
|
||||||
|
subdimensions: (u32, u32, u32, u32),
|
||||||
|
) -> Result<Buffer, ::std::io::Error> {
|
||||||
|
let bounds = self.get_bounds();
|
||||||
|
if subdimensions.0 + subdimensions.2 >= bounds.2
|
||||||
|
|| subdimensions.1 + subdimensions.3 >= bounds.3
|
||||||
|
{
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
format!(
|
||||||
|
"cannot create subdimensions larger than buffer: {:?} > {:?}",
|
||||||
|
subdimensions, bounds
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Buffer {
|
||||||
|
buf: self.buf,
|
||||||
|
dimensions: self.dimensions,
|
||||||
|
subdimensions: Some((
|
||||||
|
subdimensions.0 + bounds.0,
|
||||||
|
subdimensions.1 + bounds.1,
|
||||||
|
subdimensions.2,
|
||||||
|
subdimensions.3,
|
||||||
|
)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn offset(&mut self, offset: (u32, u32)) -> Result<Buffer, ::std::io::Error> {
|
||||||
|
let bounds = self.get_bounds();
|
||||||
|
if offset.0 > bounds.2 || offset.1 > bounds.3 {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
format!(
|
||||||
|
"cannot create offset outside buffer: {:?} > {:?}",
|
||||||
|
offset, bounds
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Buffer {
|
||||||
|
buf: self.buf,
|
||||||
|
dimensions: self.dimensions,
|
||||||
|
subdimensions: Some((
|
||||||
|
offset.0 + bounds.0,
|
||||||
|
offset.1 + bounds.1,
|
||||||
|
bounds.2 - offset.0,
|
||||||
|
bounds.3 - offset.1,
|
||||||
|
)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn memset(&mut self, c: &Color) {
|
||||||
|
if let Some(subdim) = self.subdimensions {
|
||||||
|
unsafe {
|
||||||
|
let ptr = self.buf.as_mut_ptr();
|
||||||
|
for y in subdim.1..(subdim.1 + subdim.3) {
|
||||||
|
for x in subdim.0..(subdim.0 + subdim.2) {
|
||||||
|
*((ptr as *mut u32).offset((x + y * self.dimensions.0) as isize)) =
|
||||||
|
c.as_argb8888();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
unsafe {
|
||||||
|
let ptr = self.buf.as_mut_ptr();
|
||||||
|
for p in 0..(self.dimensions.0 * self.dimensions.1) {
|
||||||
|
*((ptr as *mut u32).offset(p as isize)) = c.as_argb8888();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn put(&mut self, pos: (u32, u32), c: &Color) -> Result<(), ::std::io::Error> {
|
||||||
|
let true_pos = if let Some(subdim) = self.subdimensions {
|
||||||
|
if pos.0 >= subdim.2 || pos.1 >= subdim.3 {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
format!(
|
||||||
|
"put({:?}) is not within subdimensions of buffer ({:?})",
|
||||||
|
pos, subdim
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
(pos.0 + subdim.0, pos.1 + subdim.1)
|
||||||
|
} else {
|
||||||
|
if pos.0 >= self.dimensions.0 || pos.1 >= self.dimensions.1 {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
format!(
|
||||||
|
"put({:?}) is not within dimensions of buffer ({:?})",
|
||||||
|
pos, self.dimensions
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
pos
|
||||||
|
};
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
let ptr = self
|
||||||
|
.buf
|
||||||
|
.as_mut_ptr()
|
||||||
|
.offset(4 * (true_pos.0 + (true_pos.1 * self.dimensions.0)) as isize);
|
||||||
|
*(ptr as *mut u32) = c.as_argb8888();
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
use crate::keyboard::{KeyState, ModifiersState};
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub enum Cmd {
|
||||||
|
Exit,
|
||||||
|
Draw,
|
||||||
|
ForceDraw,
|
||||||
|
ToggleVisible,
|
||||||
|
MouseClick {
|
||||||
|
btn: u32,
|
||||||
|
pos: (u32, u32),
|
||||||
|
},
|
||||||
|
MouseScroll {
|
||||||
|
scroll: (f64, f64),
|
||||||
|
pos: (u32, u32),
|
||||||
|
},
|
||||||
|
KeyboardTest,
|
||||||
|
Keyboard {
|
||||||
|
key: u32,
|
||||||
|
key_state: KeyState,
|
||||||
|
modifiers_state: ModifiersState,
|
||||||
|
interpreted: Option<String>,
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default)]
|
||||||
|
pub struct Color {
|
||||||
|
red: f32,
|
||||||
|
green: f32,
|
||||||
|
blue: f32,
|
||||||
|
opacity: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Color {
|
||||||
|
pub fn new(red: f32, green: f32, blue: f32, opacity: f32) -> Color {
|
||||||
|
let (red, green, blue, opacity) = clamp(red, green, blue, opacity);
|
||||||
|
Color {
|
||||||
|
red,
|
||||||
|
green,
|
||||||
|
blue,
|
||||||
|
opacity,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn blend(&self, other: &Color, ratio: f32) -> Color {
|
||||||
|
let ratio = clamp_f32(ratio, 0.0, 1.0);
|
||||||
|
|
||||||
|
Color {
|
||||||
|
red: blend_f32(self.red, other.red, ratio),
|
||||||
|
green: blend_f32(self.green, other.green, ratio),
|
||||||
|
blue: blend_f32(self.blue, other.blue, ratio),
|
||||||
|
opacity: blend_f32(self.opacity, other.opacity, ratio),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn as_argb8888(&self) -> u32 {
|
||||||
|
((255.0 * self.opacity) as u32 & 0xFF) << 24
|
||||||
|
| ((255.0 * self.red) as u32 & 0xFF) << 16
|
||||||
|
| ((255.0 * self.green) as u32 & 0xFF) << 8
|
||||||
|
| ((255.0 * self.blue) as u32 & 0xFF)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn clamp(r: f32, g: f32, b: f32, o: f32) -> (f32, f32, f32, f32) {
|
||||||
|
clamp_naive(r, g, b, o)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn clamp_naive(r: f32, g: f32, b: f32, o: f32) -> (f32, f32, f32, f32) {
|
||||||
|
(
|
||||||
|
clamp_f32(r, 0.0, 1.0),
|
||||||
|
clamp_f32(g, 0.0, 1.0),
|
||||||
|
clamp_f32(b, 0.0, 1.0),
|
||||||
|
clamp_f32(o, 0.0, 1.0),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn clamp_f32(v: f32, a: f32, b: f32) -> f32 {
|
||||||
|
if v > b {
|
||||||
|
b
|
||||||
|
} else if v < a {
|
||||||
|
a
|
||||||
|
} else {
|
||||||
|
v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn blend_f32(a: f32, b: f32, r: f32) -> f32 {
|
||||||
|
a + ((b - a) * r)
|
||||||
|
}
|
||||||
+350
@@ -0,0 +1,350 @@
|
|||||||
|
use crate::cmd::Cmd;
|
||||||
|
use crate::color::Color;
|
||||||
|
use crate::widget;
|
||||||
|
use crate::{
|
||||||
|
fonts::{FontMap, FontRef},
|
||||||
|
widgets,
|
||||||
|
};
|
||||||
|
use chrono::NaiveDateTime;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::default::Default;
|
||||||
|
use std::{collections::HashMap, sync::mpsc::Sender};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub enum Widget {
|
||||||
|
Margin {
|
||||||
|
margins: (u32, u32, u32, u32),
|
||||||
|
widget: Box<Widget>,
|
||||||
|
},
|
||||||
|
Fixed {
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
widget: Box<Widget>,
|
||||||
|
},
|
||||||
|
HorizontalLayout(Vec<Widget>),
|
||||||
|
VerticalLayout(Vec<Widget>),
|
||||||
|
Clock {
|
||||||
|
font: Option<String>,
|
||||||
|
font_size: f32,
|
||||||
|
},
|
||||||
|
Date {
|
||||||
|
font: Option<String>,
|
||||||
|
font_size: f32,
|
||||||
|
},
|
||||||
|
Calendar {
|
||||||
|
font_primary: Option<String>,
|
||||||
|
font_secondary: Option<String>,
|
||||||
|
font_size: f32,
|
||||||
|
sections: u32,
|
||||||
|
},
|
||||||
|
Launcher {
|
||||||
|
font: Option<String>,
|
||||||
|
font_size: f32,
|
||||||
|
length: u32,
|
||||||
|
#[serde(default)]
|
||||||
|
app_opener: String,
|
||||||
|
#[serde(default)]
|
||||||
|
term_opener: String,
|
||||||
|
#[serde(default)]
|
||||||
|
url_opener: String,
|
||||||
|
},
|
||||||
|
Battery {
|
||||||
|
font: Option<String>,
|
||||||
|
font_size: f32,
|
||||||
|
length: u32,
|
||||||
|
},
|
||||||
|
Backlight {
|
||||||
|
#[serde(default)]
|
||||||
|
device: String,
|
||||||
|
font: Option<String>,
|
||||||
|
font_size: f32,
|
||||||
|
length: u32,
|
||||||
|
},
|
||||||
|
#[cfg(feature = "pulseaudio-widget")]
|
||||||
|
PulseAudio {
|
||||||
|
font: Option<String>,
|
||||||
|
font_size: f32,
|
||||||
|
length: u32,
|
||||||
|
},
|
||||||
|
#[cfg(feature = "alsa-widget")]
|
||||||
|
AlsaSound {
|
||||||
|
font: Option<String>,
|
||||||
|
font_size: f32,
|
||||||
|
length: u32,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Widget {
|
||||||
|
pub fn construct<'a>(
|
||||||
|
self,
|
||||||
|
time: NaiveDateTime,
|
||||||
|
tx: Sender<Cmd>,
|
||||||
|
fonts: &'a FontMap,
|
||||||
|
) -> Option<Box<dyn widget::Widget + Send + 'a>> {
|
||||||
|
match self {
|
||||||
|
Widget::Margin { margins, widget } => match widget.construct(time, tx, fonts) {
|
||||||
|
Some(w) => Some(widget::Margin::new(margins, w)),
|
||||||
|
None => None,
|
||||||
|
},
|
||||||
|
Widget::Fixed {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
widget,
|
||||||
|
} => match widget.construct(time, tx, fonts) {
|
||||||
|
Some(w) => Some(widget::Fixed::new((width, height), w)),
|
||||||
|
None => None,
|
||||||
|
},
|
||||||
|
Widget::HorizontalLayout(widgets) => Some(widget::HorizontalLayout::new(
|
||||||
|
widgets
|
||||||
|
.into_iter()
|
||||||
|
.map(|x| x.construct(time, tx.clone(), fonts))
|
||||||
|
.filter(|x| x.is_some())
|
||||||
|
.map(|x| x.unwrap())
|
||||||
|
.collect(),
|
||||||
|
)),
|
||||||
|
Widget::VerticalLayout(widgets) => Some(widget::VerticalLayout::new(
|
||||||
|
widgets
|
||||||
|
.into_iter()
|
||||||
|
.map(|x| x.construct(time, tx.clone(), fonts))
|
||||||
|
.filter(|x| x.is_some())
|
||||||
|
.map(|x| x.unwrap())
|
||||||
|
.collect(),
|
||||||
|
)),
|
||||||
|
Widget::Clock { font, font_size } => match widgets::clock::Clock::new(
|
||||||
|
time,
|
||||||
|
get_font(&font.or_else(|| Some("sans".to_string())).unwrap(), &fonts),
|
||||||
|
font_size,
|
||||||
|
) {
|
||||||
|
Ok(w) => Some(w),
|
||||||
|
Err(_) => None,
|
||||||
|
},
|
||||||
|
Widget::Date { font, font_size } => match widgets::date::Date::new(
|
||||||
|
time,
|
||||||
|
get_font(&font.or_else(|| Some("sans".to_string())).unwrap(), &fonts),
|
||||||
|
font_size,
|
||||||
|
) {
|
||||||
|
Ok(w) => Some(w),
|
||||||
|
Err(_) => None,
|
||||||
|
},
|
||||||
|
Widget::Calendar {
|
||||||
|
font_primary,
|
||||||
|
font_secondary,
|
||||||
|
font_size,
|
||||||
|
sections,
|
||||||
|
} => Some(widgets::calendar::Calendar::new(
|
||||||
|
time,
|
||||||
|
get_font(
|
||||||
|
&font_primary.or_else(|| Some("sans".to_string())).unwrap(),
|
||||||
|
&fonts,
|
||||||
|
),
|
||||||
|
get_font(
|
||||||
|
&font_secondary.or_else(|| Some("mono".to_string())).unwrap(),
|
||||||
|
&fonts,
|
||||||
|
),
|
||||||
|
font_size,
|
||||||
|
sections,
|
||||||
|
)),
|
||||||
|
Widget::Launcher {
|
||||||
|
font,
|
||||||
|
font_size,
|
||||||
|
length,
|
||||||
|
app_opener,
|
||||||
|
term_opener,
|
||||||
|
url_opener,
|
||||||
|
} => Some(widgets::launcher::Launcher::new(
|
||||||
|
get_font(&font.or_else(|| Some("sans".to_string())).unwrap(), &fonts),
|
||||||
|
font_size,
|
||||||
|
length,
|
||||||
|
tx,
|
||||||
|
app_opener,
|
||||||
|
term_opener,
|
||||||
|
if url_opener.is_empty() {
|
||||||
|
"xdg_open ".to_string()
|
||||||
|
} else {
|
||||||
|
url_opener
|
||||||
|
},
|
||||||
|
)),
|
||||||
|
Widget::Battery {
|
||||||
|
font,
|
||||||
|
font_size,
|
||||||
|
length,
|
||||||
|
} => {
|
||||||
|
match widgets::battery::UpowerBattery::new(
|
||||||
|
get_font(&font.or_else(|| Some("sans".to_string())).unwrap(), &fonts),
|
||||||
|
font_size,
|
||||||
|
length,
|
||||||
|
tx,
|
||||||
|
) {
|
||||||
|
Ok(w) => Some(w),
|
||||||
|
Err(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Widget::Backlight {
|
||||||
|
device,
|
||||||
|
font,
|
||||||
|
font_size,
|
||||||
|
length,
|
||||||
|
} => {
|
||||||
|
let d = if device == "" {
|
||||||
|
"intel_backlight"
|
||||||
|
} else {
|
||||||
|
&device
|
||||||
|
};
|
||||||
|
match widgets::backlight::Backlight::new(
|
||||||
|
d,
|
||||||
|
get_font(&font.or_else(|| Some("sans".to_string())).unwrap(), &fonts),
|
||||||
|
font_size,
|
||||||
|
length,
|
||||||
|
) {
|
||||||
|
Ok(w) => Some(w),
|
||||||
|
Err(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(feature = "pulseaudio-widget")]
|
||||||
|
Widget::PulseAudio {
|
||||||
|
font,
|
||||||
|
font_size,
|
||||||
|
length,
|
||||||
|
} => {
|
||||||
|
match widgets::audio::PulseAudio::new(
|
||||||
|
get_font(&font.or_else(|| Some("sans".to_string())).unwrap(), &fonts),
|
||||||
|
font_size,
|
||||||
|
length,
|
||||||
|
tx,
|
||||||
|
) {
|
||||||
|
Ok(w) => Some(w),
|
||||||
|
Err(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[cfg(feature = "alsa-widget")]
|
||||||
|
Widget::AlsaSound {
|
||||||
|
font,
|
||||||
|
font_size,
|
||||||
|
length,
|
||||||
|
} => {
|
||||||
|
match widgets::audio::Alsa::new(
|
||||||
|
get_font(&font.or_else(|| Some("sans".to_string())).unwrap(), &fonts),
|
||||||
|
font_size,
|
||||||
|
length,
|
||||||
|
) {
|
||||||
|
Ok(w) => Some(w),
|
||||||
|
Err(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub enum OutputMode {
|
||||||
|
All,
|
||||||
|
Active,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for OutputMode {
|
||||||
|
fn default() -> Self {
|
||||||
|
OutputMode::Active
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_fonts() -> HashMap<String, String> {
|
||||||
|
let mut map = HashMap::with_capacity(2);
|
||||||
|
map.insert("mono".to_string(), "mono".to_string());
|
||||||
|
map.insert("sans".to_string(), "sans".to_string());
|
||||||
|
map
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Debug)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Config {
|
||||||
|
pub output_mode: OutputMode,
|
||||||
|
pub scale: u32,
|
||||||
|
pub background: Color,
|
||||||
|
pub widget: Widget,
|
||||||
|
|
||||||
|
#[serde(default = "default_fonts")]
|
||||||
|
pub fonts: HashMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Config {
|
||||||
|
fn default() -> Self {
|
||||||
|
Config {
|
||||||
|
widget: Widget::Margin {
|
||||||
|
margins: (20, 20, 20, 20),
|
||||||
|
widget: Box::new(Widget::VerticalLayout(vec![
|
||||||
|
Widget::HorizontalLayout(vec![
|
||||||
|
Widget::Margin {
|
||||||
|
margins: (0, 88, 0, 32),
|
||||||
|
widget: Box::new(Widget::VerticalLayout(vec![
|
||||||
|
Widget::Date {
|
||||||
|
font: None,
|
||||||
|
font_size: 64.0,
|
||||||
|
},
|
||||||
|
Widget::Clock {
|
||||||
|
font: None,
|
||||||
|
font_size: 256.0,
|
||||||
|
},
|
||||||
|
])),
|
||||||
|
},
|
||||||
|
Widget::VerticalLayout(vec![
|
||||||
|
Widget::Margin {
|
||||||
|
margins: (0, 0, 0, 8),
|
||||||
|
widget: Box::new(Widget::Battery {
|
||||||
|
font: None,
|
||||||
|
font_size: 24.0,
|
||||||
|
length: 0,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
Widget::Margin {
|
||||||
|
margins: (0, 0, 0, 8),
|
||||||
|
widget: Box::new(Widget::Backlight {
|
||||||
|
device: "intel_backlight".to_string(),
|
||||||
|
font: None,
|
||||||
|
font_size: 24.0,
|
||||||
|
length: 0,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
#[cfg(feature = "pulseaudio-widget")]
|
||||||
|
Widget::Margin {
|
||||||
|
margins: (0, 0, 0, 8),
|
||||||
|
widget: Box::new(Widget::PulseAudio {
|
||||||
|
font: None,
|
||||||
|
font_size: 24.0,
|
||||||
|
length: 0,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
]),
|
||||||
|
Widget::Calendar {
|
||||||
|
font_primary: None,
|
||||||
|
font_secondary: None,
|
||||||
|
font_size: 16.0,
|
||||||
|
sections: 3,
|
||||||
|
},
|
||||||
|
Widget::Launcher {
|
||||||
|
font: None,
|
||||||
|
font_size: 32.0,
|
||||||
|
length: 0,
|
||||||
|
app_opener: "".to_string(),
|
||||||
|
term_opener: "".to_string(),
|
||||||
|
url_opener: "".to_string(),
|
||||||
|
},
|
||||||
|
])),
|
||||||
|
},
|
||||||
|
output_mode: Default::default(),
|
||||||
|
scale: 1,
|
||||||
|
background: Color::new(0.0, 0.0, 0.0, 0.9),
|
||||||
|
fonts: default_fonts(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn get_font<'a>(name: &str, map: &'a FontMap) -> FontRef<'a> {
|
||||||
|
match map.get(name) {
|
||||||
|
Some(f) => f,
|
||||||
|
None => panic!("Font {} is missing from the config", name),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
use serde::{de::DeserializeOwned, Serialize};
|
||||||
|
use std::io::BufRead;
|
||||||
|
|
||||||
|
pub enum ConfigFmt {
|
||||||
|
#[cfg(feature = "yaml-cfg")]
|
||||||
|
Yaml,
|
||||||
|
#[cfg(feature = "json-cfg")]
|
||||||
|
Json,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const CONFIG_NAMES: &[&str] = &[
|
||||||
|
#[cfg(feature = "yaml-cfg")]
|
||||||
|
"config.yaml",
|
||||||
|
#[cfg(feature = "json-cfg")]
|
||||||
|
"config.json",
|
||||||
|
];
|
||||||
|
|
||||||
|
impl ConfigFmt {
|
||||||
|
#[inline]
|
||||||
|
pub fn new(ext: &str) -> Option<Self> {
|
||||||
|
match ext {
|
||||||
|
#[cfg(feature = "yaml-cfg")]
|
||||||
|
"yaml" => Some(ConfigFmt::Yaml),
|
||||||
|
#[cfg(feature = "json-cfg")]
|
||||||
|
"json" => Some(ConfigFmt::Json),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[inline]
|
||||||
|
pub fn from_reader<B: BufRead, T: DeserializeOwned>(&self, r: B) -> T {
|
||||||
|
match self {
|
||||||
|
#[cfg(feature = "yaml-cfg")]
|
||||||
|
ConfigFmt::Yaml => serde_yaml::from_reader(r).unwrap(),
|
||||||
|
#[cfg(feature = "json-cfg")]
|
||||||
|
ConfigFmt::Json => serde_json::from_reader(r).unwrap(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[inline]
|
||||||
|
pub fn to_string<T: Serialize + ?Sized>(&self, src: &T) -> String {
|
||||||
|
match self {
|
||||||
|
#[cfg(feature = "yaml-cfg")]
|
||||||
|
ConfigFmt::Yaml => serde_yaml::to_string(&src).unwrap(),
|
||||||
|
#[cfg(feature = "json-cfg")]
|
||||||
|
ConfigFmt::Json => serde_json::to_string_pretty(&src).unwrap(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ConfigFmt {
|
||||||
|
fn default() -> Self {
|
||||||
|
// attributes require curly braces to work
|
||||||
|
#[cfg(feature = "yaml-cfg")]
|
||||||
|
{
|
||||||
|
ConfigFmt::Yaml
|
||||||
|
}
|
||||||
|
#[cfg(all(feature = "json-cfg", not(feature = "yaml-cfg")))]
|
||||||
|
{
|
||||||
|
ConfigFmt::Json
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+57
@@ -0,0 +1,57 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::env;
|
||||||
|
use std::error::Error;
|
||||||
|
use std::fs::{create_dir_all, File, OpenOptions};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone, Default)]
|
||||||
|
pub struct Data {
|
||||||
|
pub entries: HashMap<String, i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Data {
|
||||||
|
pub fn load() -> Result<Data, Box<dyn Error>> {
|
||||||
|
Ok(serde_yaml::from_reader(Self::read_file()?)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save(&self) -> Result<(), Box<dyn Error>> {
|
||||||
|
Ok(serde_yaml::to_writer(Self::write_file()?, self)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_file() -> Result<File, Box<dyn Error>> {
|
||||||
|
Ok(OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.write(true)
|
||||||
|
.read(true)
|
||||||
|
.open(Self::path()?)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_file() -> Result<File, Box<dyn Error>> {
|
||||||
|
Ok(OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.write(true)
|
||||||
|
.truncate(true)
|
||||||
|
.open(Self::path()?)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn path() -> Result<PathBuf, Box<dyn Error>> {
|
||||||
|
let xdg_cache = match env::var_os("XDG_CACHE_HOME") {
|
||||||
|
Some(s) => s
|
||||||
|
.into_string()
|
||||||
|
.map_err(|_| "Unable to resolve $XDG_CACHE_HOME")?,
|
||||||
|
None => format!(
|
||||||
|
"{}/.cache",
|
||||||
|
env::var_os("HOME")
|
||||||
|
.ok_or("Unable to resolve $HOME")?
|
||||||
|
.into_string()
|
||||||
|
.map_err(|_| "Unable to resolve $HOME")?
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
let cache_dir = PathBuf::from(xdg_cache).join("wldash");
|
||||||
|
create_dir_all(&cache_dir)?;
|
||||||
|
|
||||||
|
Ok(cache_dir.join("data.yaml"))
|
||||||
|
}
|
||||||
|
}
|
||||||
+113
@@ -0,0 +1,113 @@
|
|||||||
|
extern crate ini;
|
||||||
|
use ini::{Ini, ParseOption};
|
||||||
|
use itertools::Itertools;
|
||||||
|
use std::cmp::Ordering;
|
||||||
|
use std::env;
|
||||||
|
use std::error::Error;
|
||||||
|
use std::io::Error as io_error;
|
||||||
|
use std::io::ErrorKind;
|
||||||
|
use walkdir::WalkDir;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Eq, Hash)]
|
||||||
|
pub struct Desktop {
|
||||||
|
pub entry_type: String,
|
||||||
|
pub name: String,
|
||||||
|
pub no_display: bool,
|
||||||
|
pub hidden: bool,
|
||||||
|
pub exec: Option<String>,
|
||||||
|
pub url: Option<String>,
|
||||||
|
pub term: bool,
|
||||||
|
pub keywords: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Desktop {
|
||||||
|
fn parse(f: &str) -> Result<Desktop, Box<dyn Error>> {
|
||||||
|
let file = Ini::load_from_file_opt(
|
||||||
|
f,
|
||||||
|
ParseOption {
|
||||||
|
enabled_quote: false,
|
||||||
|
enabled_escape: false,
|
||||||
|
},
|
||||||
|
)?;
|
||||||
|
match file.section(Some("Desktop Entry")) {
|
||||||
|
Some(desktop) => Ok(Desktop {
|
||||||
|
entry_type: desktop.get("Type").unwrap_or(&"".to_string()).to_string(),
|
||||||
|
name: desktop.get("Name").unwrap_or(&"".to_string()).to_string(),
|
||||||
|
term: desktop.get("Terminal").unwrap_or(&"".to_string()) == "true",
|
||||||
|
no_display: desktop.get("NoDisplay").unwrap_or(&"".to_string()) == "true",
|
||||||
|
hidden: desktop.get("Hidden").unwrap_or(&"".to_string()) == "true",
|
||||||
|
exec: desktop.get("Exec").map(|x| x.to_string()),
|
||||||
|
url: desktop.get("URL").map(|x| x.to_string()),
|
||||||
|
keywords: desktop
|
||||||
|
.get("Keywords")
|
||||||
|
.map(|x| {
|
||||||
|
x.split(';')
|
||||||
|
.map(|y| y.trim().to_string())
|
||||||
|
.filter(|z| z != "")
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| vec![]),
|
||||||
|
}),
|
||||||
|
None => Err(Box::new(io_error::new(
|
||||||
|
ErrorKind::NotFound,
|
||||||
|
"no desktop entry in file",
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_dir(d: &str) -> Result<Vec<Desktop>, Box<dyn Error>> {
|
||||||
|
let mut files: Vec<Desktop> = Vec::with_capacity(16);
|
||||||
|
for entry in WalkDir::new(d) {
|
||||||
|
let entry = entry?;
|
||||||
|
let path = entry.path();
|
||||||
|
|
||||||
|
if let Ok(d) = Desktop::parse(path.to_str().unwrap()) {
|
||||||
|
files.push(d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(files)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ord for Desktop {
|
||||||
|
fn cmp(&self, other: &Self) -> Ordering {
|
||||||
|
self.name.cmp(&other.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialOrd for Desktop {
|
||||||
|
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||||
|
Some(self.cmp(other))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for Desktop {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.name == other.name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_desktop_files() -> Vec<Desktop> {
|
||||||
|
let home = env::var_os("HOME").unwrap().into_string().unwrap();
|
||||||
|
|
||||||
|
let xdg_data_home = match env::var_os("XDG_DATA_HOME") {
|
||||||
|
Some(s) => s.into_string().unwrap(),
|
||||||
|
None => format!("{}/.local/share", home),
|
||||||
|
};
|
||||||
|
let xdg_data_dirs = match env::var_os("XDG_DATA_DIRS") {
|
||||||
|
Some(s) => s.into_string().unwrap(),
|
||||||
|
None => "/usr/local/share:/usr/share".to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
std::iter::once(xdg_data_home.as_str())
|
||||||
|
.chain(xdg_data_dirs.split(':'))
|
||||||
|
.map(|p| Desktop::parse_dir(&format!("{}/applications", p)))
|
||||||
|
.filter_map(Result::ok)
|
||||||
|
.flatten()
|
||||||
|
.filter(|d| {
|
||||||
|
!d.hidden && !d.no_display && (d.entry_type == "Application" || d.entry_type == "Link")
|
||||||
|
})
|
||||||
|
.unique_by(|x| x.name.clone())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
use std::{
|
||||||
|
cell::RefCell,
|
||||||
|
ffi::CStr,
|
||||||
|
fs::File,
|
||||||
|
io,
|
||||||
|
os::unix::io::{FromRawFd, RawFd},
|
||||||
|
rc::Rc,
|
||||||
|
time::SystemTime,
|
||||||
|
time::UNIX_EPOCH,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
use nix::sys::memfd;
|
||||||
|
use nix::{
|
||||||
|
errno::Errno,
|
||||||
|
fcntl,
|
||||||
|
sys::{mman, stat},
|
||||||
|
unistd,
|
||||||
|
};
|
||||||
|
|
||||||
|
use memmap::MmapMut;
|
||||||
|
|
||||||
|
use wayland_client::{
|
||||||
|
protocol::{wl_buffer, wl_shm, wl_shm_pool},
|
||||||
|
Main,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A wrapper handling an SHM memory pool backed by a shared memory file
|
||||||
|
///
|
||||||
|
/// This wrapper handles for you the creation of the shared memory file and its synchronization
|
||||||
|
/// with the protocol.
|
||||||
|
///
|
||||||
|
/// Mempool internally tracks the release of the buffers by the compositor. As such, creating a buffer
|
||||||
|
/// that is not commited to a surface (and then never released by the server) would cause the Mempool
|
||||||
|
/// to be stuck believing it is still in use.
|
||||||
|
///
|
||||||
|
/// Mempool will also handle the destruction of buffers and as such the `destroy()` method should not
|
||||||
|
/// be used on buffers created from Mempool.
|
||||||
|
///
|
||||||
|
/// Overwriting the contents of the memory pool before it is completely freed may cause graphical
|
||||||
|
/// glitches due to the possible corruption of data while the compositor is reading it.
|
||||||
|
///
|
||||||
|
/// Mempool requires a callback that will be called when the pool becomes free, this
|
||||||
|
/// happens when all the pools buffers are released by the server.
|
||||||
|
pub struct MemPool {
|
||||||
|
file: File,
|
||||||
|
len: usize,
|
||||||
|
pool: Main<wl_shm_pool::WlShmPool>,
|
||||||
|
buffer_count: Rc<RefCell<u32>>,
|
||||||
|
mmap: MmapMut,
|
||||||
|
callback: Rc<RefCell<dyn FnMut(wayland_client::DispatchData)>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MemPool {
|
||||||
|
/// Create a new memory pool associated with given shm
|
||||||
|
pub fn new<F>(shm: Main<wl_shm::WlShm>, callback: F) -> io::Result<MemPool>
|
||||||
|
where
|
||||||
|
F: FnMut(wayland_client::DispatchData) + 'static,
|
||||||
|
{
|
||||||
|
let mem_fd = create_shm_fd()?;
|
||||||
|
let mem_file = unsafe { File::from_raw_fd(mem_fd) };
|
||||||
|
mem_file.set_len(128)?;
|
||||||
|
|
||||||
|
let pool = shm.create_pool(mem_fd, 128);
|
||||||
|
|
||||||
|
let mmap = unsafe { MmapMut::map_mut(&mem_file).unwrap() };
|
||||||
|
|
||||||
|
Ok(MemPool {
|
||||||
|
file: mem_file,
|
||||||
|
len: 128,
|
||||||
|
pool,
|
||||||
|
buffer_count: Rc::new(RefCell::new(0)),
|
||||||
|
mmap,
|
||||||
|
callback: Rc::new(RefCell::new(callback)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resize the memory pool
|
||||||
|
///
|
||||||
|
/// This affect the size as it is seen by the wayland server. Even
|
||||||
|
/// if you extend the temporary file size by writing to it, you need to
|
||||||
|
/// call this method otherwise the server won't see the new size.
|
||||||
|
///
|
||||||
|
/// Memory pools can only be extented, as such this method will do nothing
|
||||||
|
/// if the requested new size is smaller than the current size.
|
||||||
|
///
|
||||||
|
/// This method allows you to ensure the underlying pool is large enough to
|
||||||
|
/// hold what you want to write to it.
|
||||||
|
pub fn resize(&mut self, newsize: usize) -> io::Result<()> {
|
||||||
|
if newsize > self.len {
|
||||||
|
self.file.set_len(newsize as u64)?;
|
||||||
|
self.pool.resize(newsize as i32);
|
||||||
|
self.len = newsize;
|
||||||
|
self.mmap = unsafe { MmapMut::map_mut(&self.file).unwrap() };
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a new buffer to this pool
|
||||||
|
///
|
||||||
|
/// The parameters are:
|
||||||
|
///
|
||||||
|
/// - `offset`: the offset (in bytes) from the beginning of the pool at which this
|
||||||
|
/// buffer starts
|
||||||
|
/// - `width`: the width of this buffer (in pixels)
|
||||||
|
/// - `height`: the height of this buffer (in pixels)
|
||||||
|
/// - `stride`: distance (in bytes) between the beginning of a row and the next one
|
||||||
|
/// - `format`: the encoding format of the pixels. Using a format that was not
|
||||||
|
/// advertised to the `wl_shm` global by the server is a protocol error and will
|
||||||
|
/// terminate your connection
|
||||||
|
pub fn buffer(
|
||||||
|
&self,
|
||||||
|
offset: i32,
|
||||||
|
width: i32,
|
||||||
|
height: i32,
|
||||||
|
stride: i32,
|
||||||
|
format: wl_shm::Format,
|
||||||
|
) -> wl_buffer::WlBuffer {
|
||||||
|
*self.buffer_count.borrow_mut() += 1;
|
||||||
|
let my_buffer_count = self.buffer_count.clone();
|
||||||
|
let my_callback = self.callback.clone();
|
||||||
|
let buffer = self
|
||||||
|
.pool
|
||||||
|
.create_buffer(offset, width, height, stride, format);
|
||||||
|
buffer.quick_assign(move |buffer, event, dispatch_data| match event {
|
||||||
|
wl_buffer::Event::Release => {
|
||||||
|
buffer.destroy();
|
||||||
|
let new_count = {
|
||||||
|
// borrow the buffer_count for as short as possible, in case
|
||||||
|
// the user wants to create a new buffer from the callback
|
||||||
|
let mut my_buffer_count = my_buffer_count.borrow_mut();
|
||||||
|
*my_buffer_count -= 1;
|
||||||
|
*my_buffer_count
|
||||||
|
};
|
||||||
|
if new_count == 0 {
|
||||||
|
(&mut *my_callback.borrow_mut())(dispatch_data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => unreachable!(),
|
||||||
|
});
|
||||||
|
(*buffer).clone().detach()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Uses the memmap crate to map the underlying shared memory file
|
||||||
|
pub fn mmap(&mut self) -> &mut MmapMut {
|
||||||
|
&mut self.mmap
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns true if the pool contains buffers that are currently in use by the server
|
||||||
|
pub fn is_used(&self) -> bool {
|
||||||
|
*self.buffer_count.borrow() != 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for MemPool {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.pool.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl io::Write for MemPool {
|
||||||
|
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
||||||
|
io::Write::write(&mut self.file, buf)
|
||||||
|
}
|
||||||
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
|
io::Write::flush(&mut self.file)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl io::Seek for MemPool {
|
||||||
|
fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
|
||||||
|
io::Seek::seek(&mut self.file, pos)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_shm_fd() -> io::Result<RawFd> {
|
||||||
|
// Only try memfd on linux
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
loop {
|
||||||
|
match memfd::memfd_create(
|
||||||
|
CStr::from_bytes_with_nul(b"smithay-client-toolkit\0").unwrap(),
|
||||||
|
memfd::MemFdCreateFlag::MFD_CLOEXEC,
|
||||||
|
) {
|
||||||
|
Ok(fd) => return Ok(fd),
|
||||||
|
Err(Errno::EINTR) => continue,
|
||||||
|
Err(Errno::ENOSYS) => break,
|
||||||
|
Err(errno) => return Err(io::Error::from(errno)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback to using shm_open
|
||||||
|
let sys_time = SystemTime::now();
|
||||||
|
let mut mem_file_handle = format!(
|
||||||
|
"/smithay-client-toolkit-{}",
|
||||||
|
sys_time.duration_since(UNIX_EPOCH).unwrap().subsec_nanos()
|
||||||
|
);
|
||||||
|
loop {
|
||||||
|
match mman::shm_open(
|
||||||
|
mem_file_handle.as_str(),
|
||||||
|
fcntl::OFlag::O_CREAT
|
||||||
|
| fcntl::OFlag::O_EXCL
|
||||||
|
| fcntl::OFlag::O_RDWR
|
||||||
|
| fcntl::OFlag::O_CLOEXEC,
|
||||||
|
stat::Mode::S_IRUSR | stat::Mode::S_IWUSR,
|
||||||
|
) {
|
||||||
|
Ok(fd) => match mman::shm_unlink(mem_file_handle.as_str()) {
|
||||||
|
Ok(_) => return Ok(fd),
|
||||||
|
Err(errno) => match unistd::close(fd) {
|
||||||
|
Ok(_) => return Err(io::Error::from(errno)),
|
||||||
|
Err(errno) => return Err(io::Error::from(errno)),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Err(Errno::EEXIST) => {
|
||||||
|
// If a file with that handle exists then change the handle
|
||||||
|
mem_file_handle = format!(
|
||||||
|
"/smithay-client-toolkit-{}",
|
||||||
|
sys_time.duration_since(UNIX_EPOCH).unwrap().subsec_nanos()
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Err(Errno::EINTR) => continue,
|
||||||
|
Err(errno) => return Err(io::Error::from(errno)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct DoubleMemPool {
|
||||||
|
pool1: MemPool,
|
||||||
|
pool2: MemPool,
|
||||||
|
switch: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DoubleMemPool {
|
||||||
|
pub fn new(shm: Main<wl_shm::WlShm>) -> ::std::io::Result<DoubleMemPool> {
|
||||||
|
Ok(DoubleMemPool {
|
||||||
|
pool1: MemPool::new(shm.clone(), move |_| {})?,
|
||||||
|
pool2: MemPool::new(shm.clone(), move |_| {})?,
|
||||||
|
switch: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pool(&mut self) -> Option<(&mut MemPool, &mut MemPool)> {
|
||||||
|
let switch = self.switch;
|
||||||
|
self.switch = !self.switch;
|
||||||
|
let (last, cur) = if !switch {
|
||||||
|
(&mut self.pool2, &mut self.pool1)
|
||||||
|
} else {
|
||||||
|
(&mut self.pool1, &mut self.pool2)
|
||||||
|
};
|
||||||
|
|
||||||
|
if cur.is_used() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some((last, cur))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn never_mind(&mut self) {
|
||||||
|
self.switch = !self.switch;
|
||||||
|
}
|
||||||
|
}
|
||||||
+339
@@ -0,0 +1,339 @@
|
|||||||
|
use crate::buffer::Buffer;
|
||||||
|
use crate::{color::Color, fonts::FontRef};
|
||||||
|
|
||||||
|
use rusttype::{point, Scale};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
struct CachedGlyph {
|
||||||
|
dimensions: (u32, u32),
|
||||||
|
origin: (i32, i32),
|
||||||
|
render: Vec<f32>,
|
||||||
|
advance: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CachedGlyph {
|
||||||
|
fn new(font: FontRef, size: f32, ch: char) -> CachedGlyph {
|
||||||
|
let scale = Scale::uniform(size);
|
||||||
|
let v_metrics = font.v_metrics(scale);
|
||||||
|
let glyph = font.glyph(ch).scaled(scale);
|
||||||
|
let advance = glyph.h_metrics().advance_width as i32;
|
||||||
|
let glyph = glyph.positioned(point(0.0, v_metrics.ascent));
|
||||||
|
|
||||||
|
if let Some(bounding_box) = glyph.pixel_bounding_box() {
|
||||||
|
let origin = (bounding_box.min.x, bounding_box.min.y);
|
||||||
|
|
||||||
|
let dimensions = (
|
||||||
|
(bounding_box.max.x - bounding_box.min.x) as u32,
|
||||||
|
(bounding_box.max.y - bounding_box.min.y) as u32,
|
||||||
|
);
|
||||||
|
let mut render = vec![0.0; (dimensions.0 * dimensions.1) as usize];
|
||||||
|
glyph.draw(|x, y, o| {
|
||||||
|
let pos = x + (y * dimensions.0);
|
||||||
|
render[pos as usize] = o;
|
||||||
|
});
|
||||||
|
CachedGlyph {
|
||||||
|
origin,
|
||||||
|
dimensions,
|
||||||
|
render,
|
||||||
|
advance,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
CachedGlyph {
|
||||||
|
origin: (0, 0),
|
||||||
|
dimensions: (0, 0),
|
||||||
|
render: Vec::new(),
|
||||||
|
advance: (size / 4.0) as i32,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw(&self, buf: &mut Buffer, pos: (i32, i32), bg: &Color, c: &Color) {
|
||||||
|
let mut x = 0;
|
||||||
|
let mut y = 0;
|
||||||
|
for v in &self.render {
|
||||||
|
let _ = buf.put(
|
||||||
|
(
|
||||||
|
(x + pos.0 + self.origin.0) as u32,
|
||||||
|
(y + pos.1 + self.origin.1) as u32,
|
||||||
|
),
|
||||||
|
&bg.blend(&c, *v),
|
||||||
|
);
|
||||||
|
|
||||||
|
if x == self.dimensions.0 as i32 - 1 {
|
||||||
|
y += 1;
|
||||||
|
x = 0;
|
||||||
|
} else {
|
||||||
|
x += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Font<'a> {
|
||||||
|
glyphs: HashMap<char, CachedGlyph>,
|
||||||
|
font: FontRef<'a>,
|
||||||
|
size: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Font<'a> {
|
||||||
|
pub fn new(font: FontRef<'a>, size: f32) -> Font {
|
||||||
|
Font {
|
||||||
|
glyphs: HashMap::new(),
|
||||||
|
font,
|
||||||
|
size,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_str_to_cache(&mut self, s: &str) {
|
||||||
|
for ch in s.chars() {
|
||||||
|
if self.glyphs.get(&ch).is_none() {
|
||||||
|
let glyph = CachedGlyph::new(self.font, self.size, ch);
|
||||||
|
self.glyphs.insert(ch, glyph);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw_text(
|
||||||
|
&self,
|
||||||
|
buf: &mut Buffer,
|
||||||
|
bg: &Color,
|
||||||
|
c: &Color,
|
||||||
|
s: &str,
|
||||||
|
) -> Result<(u32, u32), ::std::io::Error> {
|
||||||
|
let mut x_off = 0;
|
||||||
|
let mut off = 0;
|
||||||
|
let mut glyphs = Vec::with_capacity(s.len());
|
||||||
|
for ch in s.chars() {
|
||||||
|
let glyph = match self.glyphs.get(&ch) {
|
||||||
|
Some(glyph) => glyph,
|
||||||
|
None => {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
format!("glyph for {:} not in cache", ch),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
glyphs.push(glyph);
|
||||||
|
if glyph.origin.1 < off {
|
||||||
|
off = glyph.origin.1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for glyph in glyphs {
|
||||||
|
glyph.draw(buf, (x_off, -off), bg, c);
|
||||||
|
x_off += glyph.advance;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((x_off as u32, self.size as u32))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw_text_with_cursor(
|
||||||
|
&self,
|
||||||
|
buf: &mut Buffer,
|
||||||
|
bg: &Color,
|
||||||
|
c: &Color,
|
||||||
|
s: &str,
|
||||||
|
cursor: usize,
|
||||||
|
) -> Result<(u32, u32), ::std::io::Error> {
|
||||||
|
let mut x_off: i32 = 0;
|
||||||
|
let mut off: i32 = 0;
|
||||||
|
let mut glyphs = Vec::with_capacity(s.len());
|
||||||
|
for ch in s.chars() {
|
||||||
|
let glyph = match self.glyphs.get(&ch) {
|
||||||
|
Some(glyph) => glyph,
|
||||||
|
None => {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
format!("glyph for {:} not in cache", ch),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
glyphs.push(glyph);
|
||||||
|
if glyph.origin.1 < off {
|
||||||
|
off = glyph.origin.1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let height = buf.get_bounds().3;
|
||||||
|
for (i, glyph) in glyphs.iter().enumerate() {
|
||||||
|
if i == cursor {
|
||||||
|
self.draw_cursor(buf, c, x_off as u32, height)?;
|
||||||
|
}
|
||||||
|
glyph.draw(buf, (x_off, -off), bg, c);
|
||||||
|
x_off += glyph.advance;
|
||||||
|
}
|
||||||
|
if cursor == glyphs.len() {
|
||||||
|
self.draw_cursor(buf, c, x_off as u32, height)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((x_off as u32, self.size as u32))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw_cursor(
|
||||||
|
&self,
|
||||||
|
buf: &mut Buffer,
|
||||||
|
c: &Color,
|
||||||
|
offset: u32,
|
||||||
|
height: u32,
|
||||||
|
) -> Result<(), ::std::io::Error> {
|
||||||
|
// draw cursor
|
||||||
|
for i in 1..height {
|
||||||
|
buf.put((offset, i), c)?
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn auto_widest(&mut self, s: &str) -> Result<u32, ::std::io::Error> {
|
||||||
|
self.add_str_to_cache(s);
|
||||||
|
let mut max = 0;
|
||||||
|
for ch in s.chars() {
|
||||||
|
let glyph = match self.glyphs.get(&ch) {
|
||||||
|
Some(glyph) => glyph,
|
||||||
|
None => {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
format!("glyph for {:} not in cache", ch),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let width = glyph.advance;
|
||||||
|
if width > max {
|
||||||
|
max = width
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(max as u32)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn auto_draw_text(
|
||||||
|
&mut self,
|
||||||
|
buf: &mut Buffer,
|
||||||
|
bg: &Color,
|
||||||
|
c: &Color,
|
||||||
|
s: &str,
|
||||||
|
) -> Result<(u32, u32), ::std::io::Error> {
|
||||||
|
self.add_str_to_cache(s);
|
||||||
|
self.draw_text(buf, bg, c, s)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn auto_draw_text_with_cursor(
|
||||||
|
&mut self,
|
||||||
|
buf: &mut Buffer,
|
||||||
|
bg: &Color,
|
||||||
|
c: &Color,
|
||||||
|
s: &str,
|
||||||
|
cursor: usize,
|
||||||
|
) -> Result<(u32, u32), ::std::io::Error> {
|
||||||
|
self.add_str_to_cache(s);
|
||||||
|
self.draw_text_with_cursor(buf, bg, c, s, cursor)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw_text_fixed_width(
|
||||||
|
&self,
|
||||||
|
buf: &mut Buffer,
|
||||||
|
bg: &Color,
|
||||||
|
c: &Color,
|
||||||
|
distances: &[u32],
|
||||||
|
s: &str,
|
||||||
|
) -> Result<(u32, u32), ::std::io::Error> {
|
||||||
|
let mut x_off = 0;
|
||||||
|
let mut off = 0;
|
||||||
|
let mut glyphs = Vec::with_capacity(s.len());
|
||||||
|
for ch in s.chars() {
|
||||||
|
let glyph = match self.glyphs.get(&ch) {
|
||||||
|
Some(glyph) => glyph,
|
||||||
|
None => {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
format!("glyph for {:} not in cache", ch),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
glyphs.push(glyph);
|
||||||
|
if glyph.origin.1 < off {
|
||||||
|
off = glyph.origin.1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (idx, glyph) in glyphs.into_iter().enumerate() {
|
||||||
|
glyph.draw(buf, (x_off, -off), bg, c);
|
||||||
|
x_off += distances[idx] as i32;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((x_off as u32, self.size as u32))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw_text_individual_colors(
|
||||||
|
&self,
|
||||||
|
buf: &mut Buffer,
|
||||||
|
bg: &Color,
|
||||||
|
color: &[Color],
|
||||||
|
s: &str,
|
||||||
|
) -> Result<(u32, u32), ::std::io::Error> {
|
||||||
|
let mut x_off = 0;
|
||||||
|
let mut off = 0;
|
||||||
|
let mut glyphs = Vec::with_capacity(s.len());
|
||||||
|
for ch in s.chars() {
|
||||||
|
let glyph = match self.glyphs.get(&ch) {
|
||||||
|
Some(glyph) => glyph,
|
||||||
|
None => {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
format!("glyph for {:} not in cache", ch),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
glyphs.push(glyph);
|
||||||
|
if glyph.origin.1 < off {
|
||||||
|
off = glyph.origin.1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (idx, glyph) in glyphs.into_iter().enumerate() {
|
||||||
|
glyph.draw(buf, (x_off, -off), bg, &color[idx]);
|
||||||
|
x_off += glyph.advance;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok((x_off as u32, self.size as u32))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn auto_draw_text_individual_colors(
|
||||||
|
&mut self,
|
||||||
|
buf: &mut Buffer,
|
||||||
|
bg: &Color,
|
||||||
|
color: &[Color],
|
||||||
|
s: &str,
|
||||||
|
) -> Result<(u32, u32), ::std::io::Error> {
|
||||||
|
self.add_str_to_cache(s);
|
||||||
|
self.draw_text_individual_colors(buf, bg, color, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw_box(buf: &mut Buffer, c: &Color, dim: (u32, u32)) -> Result<(), ::std::io::Error> {
|
||||||
|
for x in 0..dim.0 {
|
||||||
|
let _ = buf.put((x, 0), c);
|
||||||
|
let _ = buf.put((x, dim.1 - 1), c);
|
||||||
|
}
|
||||||
|
for y in 0..dim.1 {
|
||||||
|
buf.put((0, y), c)?;
|
||||||
|
buf.put((dim.0 - 1, y), c)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw_bar(
|
||||||
|
buf: &mut Buffer,
|
||||||
|
color: &Color,
|
||||||
|
length: u32,
|
||||||
|
height: u32,
|
||||||
|
fill: f32,
|
||||||
|
) -> Result<(), ::std::io::Error> {
|
||||||
|
let mut fill_pos = ((length as f32) * fill) as u32;
|
||||||
|
if fill_pos > length {
|
||||||
|
fill_pos = length;
|
||||||
|
}
|
||||||
|
for y in 0..height {
|
||||||
|
for x in 0..fill_pos {
|
||||||
|
let _ = buf.put((x, y), color);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
//! Utility module for fonts
|
||||||
|
|
||||||
|
use fontconfig::Fontconfig as FontConfig;
|
||||||
|
use rusttype::Font;
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
fs::File,
|
||||||
|
io::Read,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// FontMap is used to store different font configurations
|
||||||
|
pub type FontMap<'a> = HashMap<String, rusttype::Font<'a>>;
|
||||||
|
|
||||||
|
/// FontRef is used to store Fonts on widgets.
|
||||||
|
pub type FontRef<'a> = &'a rusttype::Font<'a>;
|
||||||
|
|
||||||
|
/// FontSeeker is a marker struct that is used to look up fonts
|
||||||
|
pub(crate) struct FontSeeker;
|
||||||
|
|
||||||
|
impl FontSeeker {
|
||||||
|
/// Acts like fc-match.
|
||||||
|
/// Given a string, it matches it to a font file and returns its path.
|
||||||
|
pub(crate) fn from_string(name: &str) -> PathBuf {
|
||||||
|
let fc = FontConfig::new().unwrap();
|
||||||
|
fc.find(name, None).unwrap().path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// FontLoader is a marker struct that is used to load files
|
||||||
|
pub(crate) struct FontLoader;
|
||||||
|
|
||||||
|
impl FontLoader {
|
||||||
|
/// Given a path, loads it as a Font, which can be rendered to the screen.
|
||||||
|
pub(crate) fn from_path<'a, P>(path: P) -> Option<Font<'a>>
|
||||||
|
where
|
||||||
|
P: AsRef<Path>,
|
||||||
|
{
|
||||||
|
let mut file = File::open(path).expect("Font file not found");
|
||||||
|
let mut data = match file.metadata() {
|
||||||
|
Ok(metadata) => Vec::with_capacity(metadata.len() as usize),
|
||||||
|
Err(_) => vec![],
|
||||||
|
};
|
||||||
|
file.read_to_end(&mut data).unwrap();
|
||||||
|
Font::try_from_vec(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,269 @@
|
|||||||
|
#![allow(dead_code, non_camel_case_types, clippy::identity_op)]
|
||||||
|
#![cfg_attr(rustfmt, rustfmt_skip)]
|
||||||
|
|
||||||
|
use std::os::raw::{c_char, c_int, c_void, c_uint};
|
||||||
|
|
||||||
|
pub const XKB_MOD_NAME_SHIFT : &[u8] = b"Shift\0";
|
||||||
|
pub const XKB_MOD_NAME_CAPS : &[u8] = b"Lock\0";
|
||||||
|
pub const XKB_MOD_NAME_CTRL : &[u8] = b"Control\0";
|
||||||
|
pub const XKB_MOD_NAME_ALT : &[u8] = b"Mod1\0";
|
||||||
|
pub const XKB_MOD_NAME_NUM : &[u8] = b"Mod2\0";
|
||||||
|
pub const XKB_MOD_NAME_LOGO : &[u8] = b"Mod4\0";
|
||||||
|
|
||||||
|
pub const XKB_LED_NAME_CAPS : &[u8] = b"Caps Lock\0";
|
||||||
|
pub const XKB_LED_NAME_NUM : &[u8] = b"Num Lock\0";
|
||||||
|
pub const XKB_LED_NAME_SCROLL : &[u8] = b"Scroll Lock\0";
|
||||||
|
|
||||||
|
pub struct xkb_context;
|
||||||
|
pub struct xkb_keymap;
|
||||||
|
pub struct xkb_state;
|
||||||
|
pub struct xkb_compose_table;
|
||||||
|
pub struct xkb_compose_state;
|
||||||
|
|
||||||
|
pub type xkb_keycode_t = u32;
|
||||||
|
pub type xkb_keysym_t = u32;
|
||||||
|
pub type xkb_layout_index_t = u32;
|
||||||
|
pub type xkb_layout_mask_t = u32;
|
||||||
|
pub type xkb_level_index_t = u32;
|
||||||
|
pub type xkb_mod_index_t = u32;
|
||||||
|
pub type xkb_mod_mask_t = u32;
|
||||||
|
pub type xkb_led_index_t = u32;
|
||||||
|
pub type xkb_led_mask_t = u32;
|
||||||
|
|
||||||
|
pub const XKB_KEYCODE_INVALID :u32 = 0xffff_ffff;
|
||||||
|
pub const XKB_LAYOUT_INVALID :u32 = 0xffff_ffff;
|
||||||
|
pub const XKB_LEVEL_INVALID :u32 = 0xffff_ffff;
|
||||||
|
pub const XKB_MOD_INVALID :u32 = 0xffff_ffff;
|
||||||
|
pub const XKB_LED_INVALID :u32 = 0xffff_ffff;
|
||||||
|
pub const XKB_KEYCODE_MAX :u32 = 0xffff_fffe;
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Copy, Clone)]
|
||||||
|
pub struct xkb_rule_names {
|
||||||
|
pub rules: *const c_char,
|
||||||
|
pub model: *const c_char ,
|
||||||
|
pub layout: *const c_char,
|
||||||
|
pub variant: *const c_char,
|
||||||
|
pub options: *const c_char,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||||
|
pub enum xkb_keysym_flags {
|
||||||
|
/** Do not apply any flags. */
|
||||||
|
XKB_KEYSYM_NO_FLAGS = 0,
|
||||||
|
/** Find keysym by case-insensitive search. */
|
||||||
|
XKB_KEYSYM_CASE_INSENSITIVE = (1 << 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||||
|
pub enum xkb_context_flags {
|
||||||
|
/** Do not apply any context flags. */
|
||||||
|
XKB_CONTEXT_NO_FLAGS = 0,
|
||||||
|
/** Create this context with an empty include path. */
|
||||||
|
XKB_CONTEXT_NO_DEFAULT_INCLUDES = (1 << 0),
|
||||||
|
/**
|
||||||
|
* Don't take RMLVO names from the environment.
|
||||||
|
* @since 0.3.0
|
||||||
|
*/
|
||||||
|
XKB_CONTEXT_NO_ENVIRONMENT_NAMES = (1 << 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||||
|
pub enum xkb_log_level {
|
||||||
|
/** Log critical internal errors only. */
|
||||||
|
XKB_LOG_LEVEL_CRITICAL = 10,
|
||||||
|
/** Log all errors. */
|
||||||
|
XKB_LOG_LEVEL_ERROR = 20,
|
||||||
|
/** Log warnings and errors. */
|
||||||
|
XKB_LOG_LEVEL_WARNING = 30,
|
||||||
|
/** Log information, warnings, and errors. */
|
||||||
|
XKB_LOG_LEVEL_INFO = 40,
|
||||||
|
/** Log everything. */
|
||||||
|
XKB_LOG_LEVEL_DEBUG = 50
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||||
|
pub enum xkb_keymap_compile_flags {
|
||||||
|
/** Do not apply any flags. */
|
||||||
|
XKB_KEYMAP_COMPILE_NO_FLAGS = 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||||
|
pub enum xkb_keymap_format {
|
||||||
|
/** Cannot be used for creation */
|
||||||
|
XKB_KEYMAP_USE_ORIGINAL_FORMAT = 0,
|
||||||
|
/** The current/classic XKB text format, as generated by xkbcomp -xkb. */
|
||||||
|
XKB_KEYMAP_FORMAT_TEXT_V1 = 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||||
|
pub enum xkb_key_direction {
|
||||||
|
/** The key was released. */
|
||||||
|
XKB_KEY_UP,
|
||||||
|
/** The key was pressed. */
|
||||||
|
XKB_KEY_DOWN
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||||
|
pub enum xkb_compose_compile_flags {
|
||||||
|
XKB_COMPOSE_COMPILE_NO_FLAGS = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||||
|
pub enum xkb_compose_format {
|
||||||
|
XKB_COMPOSE_FORMAT_TEXT_V1 = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||||
|
pub enum xkb_compose_state_flags {
|
||||||
|
XKB_COMPOSE_STATE_NO_FLAGS = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||||
|
pub enum xkb_compose_status {
|
||||||
|
XKB_COMPOSE_NOTHING,
|
||||||
|
XKB_COMPOSE_COMPOSING,
|
||||||
|
XKB_COMPOSE_COMPOSED,
|
||||||
|
XKB_COMPOSE_CANCELLED
|
||||||
|
}
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||||
|
pub enum xkb_compose_feed_result {
|
||||||
|
XKB_COMPOSE_FEED_IGNORED,
|
||||||
|
XKB_COMPOSE_FEED_ACCEPTED
|
||||||
|
}
|
||||||
|
|
||||||
|
bitflags::bitflags!(
|
||||||
|
pub struct xkb_state_component: u32 {
|
||||||
|
/** Depressed modifiers, i.e. a key is physically holding them. */
|
||||||
|
const XKB_STATE_MODS_DEPRESSED = (1 << 0);
|
||||||
|
/** Latched modifiers, i.e. will be unset after the next non-modifier
|
||||||
|
* key press. */
|
||||||
|
const XKB_STATE_MODS_LATCHED = (1 << 1);
|
||||||
|
/** Locked modifiers, i.e. will be unset after the key provoking the
|
||||||
|
* lock has been pressed again. */
|
||||||
|
const XKB_STATE_MODS_LOCKED = (1 << 2);
|
||||||
|
/** Effective modifiers, i.e. currently active and affect key
|
||||||
|
* processing (derived from the other state components).
|
||||||
|
* Use this unless you explictly care how the state came about. */
|
||||||
|
const XKB_STATE_MODS_EFFECTIVE = (1 << 3);
|
||||||
|
/** Depressed layout, i.e. a key is physically holding it. */
|
||||||
|
const XKB_STATE_LAYOUT_DEPRESSED = (1 << 4);
|
||||||
|
/** Latched layout, i.e. will be unset after the next non-modifier
|
||||||
|
* key press. */
|
||||||
|
const XKB_STATE_LAYOUT_LATCHED = (1 << 5);
|
||||||
|
/** Locked layout, i.e. will be unset after the key provoking the lock
|
||||||
|
* has been pressed again. */
|
||||||
|
const XKB_STATE_LAYOUT_LOCKED = (1 << 6);
|
||||||
|
/** Effective layout, i.e. currently active and affects key processing
|
||||||
|
* (derived from the other state components).
|
||||||
|
* Use this unless you explictly care how the state came about. */
|
||||||
|
const XKB_STATE_LAYOUT_EFFECTIVE = (1 << 7);
|
||||||
|
/** LEDs (derived from the other state components). */
|
||||||
|
const XKB_STATE_LEDS = (1 << 8);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
dlopen_external_library!(XkbCommon,
|
||||||
|
functions:
|
||||||
|
fn xkb_keysym_get_name(xkb_keysym_t, *mut c_char, usize) -> c_int,
|
||||||
|
fn xkb_keysym_from_name(*const c_char, xkb_keysym_flags) -> xkb_keysym_t,
|
||||||
|
fn xkb_keysym_to_utf8(xkb_keysym_t, *mut c_char, usize) -> c_int,
|
||||||
|
fn xkb_keysym_to_utf32(xkb_keysym_t) -> u32,
|
||||||
|
fn xkb_context_new(xkb_context_flags) -> *mut xkb_context,
|
||||||
|
fn xkb_context_ref(*mut xkb_context) -> *mut xkb_context,
|
||||||
|
fn xkb_context_unref(*mut xkb_context) -> (),
|
||||||
|
fn xkb_context_set_user_data(*mut xkb_context, *mut c_void) -> (),
|
||||||
|
fn xkb_context_get_user_data(*mut xkb_context) -> *mut c_void,
|
||||||
|
fn xkb_context_include_path_append(*mut xkb_context, *const c_char) -> c_int,
|
||||||
|
fn xkb_context_include_path_append_default(*mut xkb_context) -> c_int,
|
||||||
|
fn xkb_context_include_path_reset_defaults(*mut xkb_context) -> c_int,
|
||||||
|
fn xkb_context_include_path_clear(*mut xkb_context) -> (),
|
||||||
|
fn xkb_context_num_include_paths(*mut xkb_context) -> c_uint,
|
||||||
|
fn xkb_context_include_path_get(*mut xkb_context, c_uint) -> *const c_char,
|
||||||
|
fn xkb_context_set_log_level(*mut xkb_context, xkb_log_level) -> (),
|
||||||
|
fn xkb_context_get_log_level(*mut xkb_context) -> xkb_log_level,
|
||||||
|
fn xkb_context_set_log_verbosity(*mut xkb_context, c_int) -> (),
|
||||||
|
fn xkb_context_get_log_verbosity(*mut xkb_context) -> c_int,
|
||||||
|
fn xkb_keymap_new_from_names(*mut xkb_context,
|
||||||
|
*const xkb_rule_names,
|
||||||
|
xkb_keymap_compile_flags
|
||||||
|
) -> *mut xkb_keymap,
|
||||||
|
fn xkb_keymap_new_from_string(*mut xkb_context,
|
||||||
|
*const c_char,
|
||||||
|
xkb_keymap_format,
|
||||||
|
xkb_keymap_compile_flags
|
||||||
|
) -> *mut xkb_keymap,
|
||||||
|
fn xkb_keymap_new_from_buffer(*mut xkb_context,
|
||||||
|
*const c_char,
|
||||||
|
usize,
|
||||||
|
xkb_keymap_format,
|
||||||
|
xkb_keymap_compile_flags
|
||||||
|
) -> *mut xkb_keymap,
|
||||||
|
fn xkb_keymap_ref(*mut xkb_keymap) -> *mut xkb_keymap,
|
||||||
|
fn xkb_keymap_unref(*mut xkb_keymap) -> (),
|
||||||
|
fn xkb_keymap_get_as_string(*mut xkb_keymap, xkb_keymap_format) -> *const c_char,
|
||||||
|
fn xkb_keymap_key_repeats(*mut xkb_keymap, xkb_keycode_t) -> c_int,
|
||||||
|
|
||||||
|
fn xkb_state_new(*mut xkb_keymap) -> *mut xkb_state,
|
||||||
|
fn xkb_state_ref(*mut xkb_state) -> *mut xkb_state,
|
||||||
|
fn xkb_state_unref(*mut xkb_state) -> (),
|
||||||
|
fn xkb_state_update_mask(*mut xkb_state,
|
||||||
|
xkb_mod_mask_t,
|
||||||
|
xkb_mod_mask_t,
|
||||||
|
xkb_mod_mask_t,
|
||||||
|
xkb_layout_index_t,
|
||||||
|
xkb_layout_index_t,
|
||||||
|
xkb_layout_index_t
|
||||||
|
) -> xkb_state_component,
|
||||||
|
fn xkb_state_update_key(*mut xkb_state,
|
||||||
|
xkb_keycode_t,
|
||||||
|
xkb_key_direction
|
||||||
|
) -> xkb_state_component,
|
||||||
|
fn xkb_state_key_get_syms(*mut xkb_state,
|
||||||
|
xkb_keycode_t,
|
||||||
|
*const *mut xkb_keysym_t
|
||||||
|
) -> c_int,
|
||||||
|
fn xkb_state_key_get_utf8(*mut xkb_state,
|
||||||
|
xkb_keycode_t,
|
||||||
|
*mut c_char,
|
||||||
|
usize
|
||||||
|
) -> c_int,
|
||||||
|
fn xkb_state_key_get_utf32(*mut xkb_state, xkb_keycode_t) -> u32,
|
||||||
|
fn xkb_state_key_get_one_sym(*mut xkb_state, xkb_keycode_t) -> xkb_keysym_t,
|
||||||
|
fn xkb_state_mod_name_is_active(*mut xkb_state, *const c_char, xkb_state_component) -> c_int,
|
||||||
|
fn xkb_compose_table_new_from_locale(*mut xkb_context, *const c_char, xkb_compose_compile_flags) -> *mut xkb_compose_table,
|
||||||
|
fn xkb_compose_table_unref(*mut xkb_compose_table) -> (),
|
||||||
|
fn xkb_compose_state_new(*mut xkb_compose_table, xkb_compose_state_flags) -> *mut xkb_compose_state,
|
||||||
|
fn xkb_compose_state_unref(*mut xkb_compose_state) -> (),
|
||||||
|
fn xkb_compose_state_feed(*mut xkb_compose_state, xkb_keysym_t) -> xkb_compose_feed_result,
|
||||||
|
fn xkb_compose_state_reset(*mut xkb_compose_state) -> (),
|
||||||
|
fn xkb_compose_state_get_status(*mut xkb_compose_state) -> xkb_compose_status,
|
||||||
|
fn xkb_compose_state_get_utf8(*mut xkb_compose_state, *mut c_char, usize) -> c_int,
|
||||||
|
fn xkb_compose_state_get_one_sym(*mut xkb_compose_state) -> xkb_keysym_t,
|
||||||
|
);
|
||||||
|
|
||||||
|
lazy_static::lazy_static!(
|
||||||
|
pub static ref XKBCOMMON_OPTION: Option<XkbCommon> = {
|
||||||
|
unsafe {
|
||||||
|
XkbCommon::open("libxkbcommon.so.0")
|
||||||
|
.or_else(|_| XkbCommon::open("libxkbcommon.so"))
|
||||||
|
.ok()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
pub static ref XKBCOMMON_HANDLE: &'static XkbCommon = {
|
||||||
|
XKBCOMMON_OPTION.as_ref().expect("Library libxkbcommon.so could not be loaded.")
|
||||||
|
};
|
||||||
|
);
|
||||||
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
#![allow(missing_docs, non_upper_case_globals, unused_parens, clippy::all)]
|
||||||
|
|
||||||
|
pub const XKB_KEY_BackSpace: u32 = 0xff08; /* Back space, back char */
|
||||||
|
pub const XKB_KEY_Tab: u32 = 0xff09;
|
||||||
|
pub const XKB_KEY_Return: u32 = 0xff0d; /* Return, enter */
|
||||||
|
pub const XKB_KEY_Escape: u32 = 0xff1b;
|
||||||
|
pub const XKB_KEY_Delete: u32 = 0xffff; /* Delete, rubout */
|
||||||
|
pub const XKB_KEY_Home: u32 = 0xff50;
|
||||||
|
pub const XKB_KEY_Left: u32 = 0xff51; /* Move left, left arrow */
|
||||||
|
pub const XKB_KEY_Right: u32 = 0xff53; /* Move right, right arrow */
|
||||||
|
pub const XKB_KEY_End: u32 = 0xff57; /* EOL */
|
||||||
|
|
||||||
|
pub const XKB_KEY_ISO_Left_Tab: u32 = 0xfe20;
|
||||||
|
pub const XKB_KEY_e: u32 = 0x0065; /* U+0065 LATIN SMALL LETTER E */
|
||||||
|
pub const XKB_KEY_a: u32 = 0x0061; /* U+0061 LATIN SMALL LETTER A */
|
||||||
|
pub const XKB_KEY_c: u32 = 0x0063; /* U+0063 LATIN SMALL LETTER C */
|
||||||
|
pub const XKB_KEY_u: u32 = 0x0075; /* U+0075 LATIN SMALL LETTER U */
|
||||||
@@ -0,0 +1,344 @@
|
|||||||
|
//! Utilities for keymap interpretation of keyboard input
|
||||||
|
//!
|
||||||
|
//! This module provides an implementation for `wl_keyboard`
|
||||||
|
//! objects using `libxkbcommon` to interpret the keyboard input
|
||||||
|
//! given the user keymap.
|
||||||
|
//!
|
||||||
|
//! The entry point of this module is the [`map_keyboard`](fn.map_keyboard.html)
|
||||||
|
//! function which, given a `wl_seat` and a callback, setup keymap interpretation
|
||||||
|
//! and key repetition for the `wl_keyboard` of this seat.
|
||||||
|
//!
|
||||||
|
//! Key repetition relies on an event source, that needs to be inserted in your
|
||||||
|
//! calloop event loop. Not doing so will prevent key repetition to work
|
||||||
|
//! (but the rest of the functionnality will not be affected).
|
||||||
|
|
||||||
|
use std::{cell::RefCell, os::unix::io::RawFd, rc::Rc};
|
||||||
|
|
||||||
|
use byteorder::{ByteOrder, NativeEndian};
|
||||||
|
|
||||||
|
pub use wayland_client::protocol::wl_keyboard::KeyState;
|
||||||
|
use wayland_client::{
|
||||||
|
protocol::{wl_keyboard, wl_seat, wl_surface},
|
||||||
|
Attached,
|
||||||
|
};
|
||||||
|
|
||||||
|
mod ffi;
|
||||||
|
pub mod keysyms;
|
||||||
|
mod state;
|
||||||
|
|
||||||
|
use self::state::KbState;
|
||||||
|
pub use self::state::{ModifiersState, RMLVO};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
/// An error that occurred while trying to initialize a mapped keyboard
|
||||||
|
pub enum Error {
|
||||||
|
/// libxkbcommon is not available
|
||||||
|
XKBNotFound,
|
||||||
|
/// Provided RMLVO specified a keymap that would not be loaded
|
||||||
|
BadNames,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Events received from a mapped keyboard
|
||||||
|
pub enum Event<'a> {
|
||||||
|
/// The keyboard focus has entered a surface
|
||||||
|
Enter {
|
||||||
|
/// serial number of the event
|
||||||
|
serial: u32,
|
||||||
|
/// surface that was entered
|
||||||
|
surface: wl_surface::WlSurface,
|
||||||
|
/// raw values of the currently pressed keys
|
||||||
|
rawkeys: &'a [u32],
|
||||||
|
/// interpreted symbols of the currently pressed keys
|
||||||
|
keysyms: &'a [u32],
|
||||||
|
},
|
||||||
|
/// The keyboard focus has left a surface
|
||||||
|
Leave {
|
||||||
|
/// serial number of the event
|
||||||
|
serial: u32,
|
||||||
|
/// surface that was left
|
||||||
|
surface: wl_surface::WlSurface,
|
||||||
|
},
|
||||||
|
/// The key modifiers have changed state
|
||||||
|
Modifiers {
|
||||||
|
/// current state of the modifiers
|
||||||
|
modifiers: ModifiersState,
|
||||||
|
},
|
||||||
|
/// A key event occurred
|
||||||
|
Key {
|
||||||
|
/// serial number of the event
|
||||||
|
serial: u32,
|
||||||
|
/// time at which the keypress occurred
|
||||||
|
time: u32,
|
||||||
|
/// raw value of the key
|
||||||
|
rawkey: u32,
|
||||||
|
/// interpreted symbol of the key
|
||||||
|
keysym: u32,
|
||||||
|
/// new state of the key
|
||||||
|
state: KeyState,
|
||||||
|
/// utf8 interpretation of the entered text
|
||||||
|
///
|
||||||
|
/// will always be `None` on key release events
|
||||||
|
utf8: Option<String>,
|
||||||
|
repeats: bool,
|
||||||
|
},
|
||||||
|
RepeatInfo {
|
||||||
|
rate: i32,
|
||||||
|
delay: i32,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Implement a keyboard for keymap translation with key repetition
|
||||||
|
///
|
||||||
|
/// This requires you to provide a callback to receive the events after they
|
||||||
|
/// have been interpreted with the keymap.
|
||||||
|
///
|
||||||
|
/// The keymap will be loaded from the provided RMLVO rules, or from the compositor
|
||||||
|
/// provided keymap if `None`.
|
||||||
|
///
|
||||||
|
/// Returns an error if xkbcommon could not be initialized, the RMLVO specification
|
||||||
|
/// contained invalid values, or if the provided seat does not have keyboard capability.
|
||||||
|
///
|
||||||
|
/// **Note:** This adapter does not handle key repetition. See `map_keyboard_repeat` for that.
|
||||||
|
pub fn map_keyboard<F>(
|
||||||
|
seat: &Attached<wl_seat::WlSeat>,
|
||||||
|
rmlvo: Option<RMLVO>,
|
||||||
|
callback: F,
|
||||||
|
) -> Result<wl_keyboard::WlKeyboard, Error>
|
||||||
|
where
|
||||||
|
F: FnMut(Event<'_>, wl_keyboard::WlKeyboard, wayland_client::DispatchData<'_>) + 'static,
|
||||||
|
{
|
||||||
|
let keyboard = seat.get_keyboard();
|
||||||
|
|
||||||
|
let state = Rc::new(RefCell::new(
|
||||||
|
rmlvo
|
||||||
|
.map(KbState::from_rmlvo)
|
||||||
|
.unwrap_or_else(KbState::new)?,
|
||||||
|
));
|
||||||
|
|
||||||
|
let callback = Rc::new(RefCell::new(callback));
|
||||||
|
|
||||||
|
// prepare the handler
|
||||||
|
let mut kbd_handler = KbdHandler { callback, state };
|
||||||
|
|
||||||
|
keyboard.quick_assign(move |keyboard, event, data| {
|
||||||
|
kbd_handler.event(keyboard.detach(), event, data)
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(keyboard.detach())
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Classic handling
|
||||||
|
*/
|
||||||
|
|
||||||
|
type KbdCallback = dyn FnMut(Event<'_>, wl_keyboard::WlKeyboard, wayland_client::DispatchData<'_>);
|
||||||
|
|
||||||
|
struct KbdHandler {
|
||||||
|
state: Rc<RefCell<KbState>>,
|
||||||
|
callback: Rc<RefCell<KbdCallback>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KbdHandler {
|
||||||
|
fn event(
|
||||||
|
&mut self,
|
||||||
|
kbd: wl_keyboard::WlKeyboard,
|
||||||
|
event: wl_keyboard::Event,
|
||||||
|
dispatch_data: wayland_client::DispatchData,
|
||||||
|
) {
|
||||||
|
use wl_keyboard::Event;
|
||||||
|
|
||||||
|
match event {
|
||||||
|
Event::Keymap { format, fd, size } => self.keymap(kbd, format, fd, size),
|
||||||
|
Event::Enter {
|
||||||
|
serial,
|
||||||
|
surface,
|
||||||
|
keys,
|
||||||
|
} => self.enter(kbd, serial, surface, keys, dispatch_data),
|
||||||
|
Event::Leave { serial, surface } => self.leave(kbd, serial, surface, dispatch_data),
|
||||||
|
Event::Key {
|
||||||
|
serial,
|
||||||
|
time,
|
||||||
|
key,
|
||||||
|
state,
|
||||||
|
} => self.key(kbd, serial, time, key, state, dispatch_data),
|
||||||
|
Event::Modifiers {
|
||||||
|
mods_depressed,
|
||||||
|
mods_latched,
|
||||||
|
mods_locked,
|
||||||
|
group,
|
||||||
|
..
|
||||||
|
} => self.modifiers(
|
||||||
|
kbd,
|
||||||
|
mods_depressed,
|
||||||
|
mods_latched,
|
||||||
|
mods_locked,
|
||||||
|
group,
|
||||||
|
dispatch_data,
|
||||||
|
),
|
||||||
|
Event::RepeatInfo { rate, delay } => self.repeat_info(kbd, rate, delay, dispatch_data),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keymap(
|
||||||
|
&mut self,
|
||||||
|
_: wl_keyboard::WlKeyboard,
|
||||||
|
format: wl_keyboard::KeymapFormat,
|
||||||
|
fd: RawFd,
|
||||||
|
size: u32,
|
||||||
|
) {
|
||||||
|
let mut state = self.state.borrow_mut();
|
||||||
|
if state.locked() {
|
||||||
|
// state is locked, ignore keymap updates
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if state.ready() {
|
||||||
|
// new keymap, we first deinit to free resources
|
||||||
|
unsafe {
|
||||||
|
state.de_init();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match format {
|
||||||
|
wl_keyboard::KeymapFormat::XkbV1 => unsafe {
|
||||||
|
state.init_with_fd(fd, size as usize);
|
||||||
|
},
|
||||||
|
wl_keyboard::KeymapFormat::NoKeymap => {
|
||||||
|
// TODO: how to handle this (hopefully never occuring) case?
|
||||||
|
}
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn enter(
|
||||||
|
&mut self,
|
||||||
|
object: wl_keyboard::WlKeyboard,
|
||||||
|
serial: u32,
|
||||||
|
surface: wl_surface::WlSurface,
|
||||||
|
keys: Vec<u8>,
|
||||||
|
dispatch_data: wayland_client::DispatchData,
|
||||||
|
) {
|
||||||
|
let mut state = self.state.borrow_mut();
|
||||||
|
let rawkeys = keys
|
||||||
|
.chunks_exact(4)
|
||||||
|
.map(NativeEndian::read_u32)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let keys: Vec<u32> = rawkeys.iter().map(|k| state.get_one_sym_raw(*k)).collect();
|
||||||
|
(&mut *self.callback.borrow_mut())(
|
||||||
|
Event::Enter {
|
||||||
|
serial,
|
||||||
|
surface,
|
||||||
|
rawkeys: &rawkeys,
|
||||||
|
keysyms: &keys,
|
||||||
|
},
|
||||||
|
object,
|
||||||
|
dispatch_data,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn leave(
|
||||||
|
&mut self,
|
||||||
|
object: wl_keyboard::WlKeyboard,
|
||||||
|
serial: u32,
|
||||||
|
surface: wl_surface::WlSurface,
|
||||||
|
dispatch_data: wayland_client::DispatchData,
|
||||||
|
) {
|
||||||
|
(&mut *self.callback.borrow_mut())(Event::Leave { serial, surface }, object, dispatch_data);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key(
|
||||||
|
&mut self,
|
||||||
|
object: wl_keyboard::WlKeyboard,
|
||||||
|
serial: u32,
|
||||||
|
time: u32,
|
||||||
|
key: u32,
|
||||||
|
key_state: wl_keyboard::KeyState,
|
||||||
|
dispatch_data: wayland_client::DispatchData,
|
||||||
|
) {
|
||||||
|
let (sym, utf8, repeats) = {
|
||||||
|
let mut state = self.state.borrow_mut();
|
||||||
|
// Get the values to generate a key event
|
||||||
|
let sym = state.get_one_sym_raw(key);
|
||||||
|
let utf8 = if key_state == wl_keyboard::KeyState::Pressed {
|
||||||
|
match state.compose_feed(sym) {
|
||||||
|
Some(ffi::xkb_compose_feed_result::XKB_COMPOSE_FEED_ACCEPTED) => {
|
||||||
|
if let Some(status) = state.compose_status() {
|
||||||
|
match status {
|
||||||
|
ffi::xkb_compose_status::XKB_COMPOSE_COMPOSED => {
|
||||||
|
state.compose_get_utf8()
|
||||||
|
}
|
||||||
|
ffi::xkb_compose_status::XKB_COMPOSE_NOTHING => {
|
||||||
|
state.get_utf8_raw(key)
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
state.get_utf8_raw(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(_) => {
|
||||||
|
// XKB_COMPOSE_FEED_IGNORED
|
||||||
|
None
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
// XKB COMPOSE is not initialized
|
||||||
|
state.get_utf8_raw(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let repeats = unsafe { state.key_repeats(key + 8) };
|
||||||
|
(sym, utf8, repeats)
|
||||||
|
};
|
||||||
|
|
||||||
|
(&mut *self.callback.borrow_mut())(
|
||||||
|
Event::Key {
|
||||||
|
serial,
|
||||||
|
time,
|
||||||
|
rawkey: key,
|
||||||
|
keysym: sym,
|
||||||
|
state: key_state,
|
||||||
|
utf8,
|
||||||
|
repeats,
|
||||||
|
},
|
||||||
|
object,
|
||||||
|
dispatch_data,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn modifiers(
|
||||||
|
&mut self,
|
||||||
|
object: wl_keyboard::WlKeyboard,
|
||||||
|
mods_depressed: u32,
|
||||||
|
mods_latched: u32,
|
||||||
|
mods_locked: u32,
|
||||||
|
group: u32,
|
||||||
|
dispatch_data: wayland_client::DispatchData,
|
||||||
|
) {
|
||||||
|
{
|
||||||
|
let mut state = self.state.borrow_mut();
|
||||||
|
state.update_modifiers(mods_depressed, mods_latched, mods_locked, group);
|
||||||
|
(&mut *self.callback.borrow_mut())(
|
||||||
|
Event::Modifiers {
|
||||||
|
modifiers: state.mods_state(),
|
||||||
|
},
|
||||||
|
object,
|
||||||
|
dispatch_data,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn repeat_info(
|
||||||
|
&mut self,
|
||||||
|
object: wl_keyboard::WlKeyboard,
|
||||||
|
rate: i32,
|
||||||
|
delay: i32,
|
||||||
|
dispatch_data: wayland_client::DispatchData,
|
||||||
|
) {
|
||||||
|
(&mut *self.callback.borrow_mut())(
|
||||||
|
Event::RepeatInfo { rate, delay },
|
||||||
|
object,
|
||||||
|
dispatch_data,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,400 @@
|
|||||||
|
use std::{
|
||||||
|
env,
|
||||||
|
ffi::CString,
|
||||||
|
fs::File,
|
||||||
|
os::raw::c_char,
|
||||||
|
os::unix::{
|
||||||
|
ffi::OsStringExt,
|
||||||
|
io::{FromRawFd, RawFd},
|
||||||
|
},
|
||||||
|
ptr,
|
||||||
|
};
|
||||||
|
|
||||||
|
use memmap::MmapOptions;
|
||||||
|
|
||||||
|
use super::ffi::{self, xkb_state_component, XKBCOMMON_HANDLE as XKBH};
|
||||||
|
use super::Error;
|
||||||
|
|
||||||
|
pub struct KbState {
|
||||||
|
xkb_context: *mut ffi::xkb_context,
|
||||||
|
xkb_keymap: *mut ffi::xkb_keymap,
|
||||||
|
xkb_state: *mut ffi::xkb_state,
|
||||||
|
xkb_compose_table: *mut ffi::xkb_compose_table,
|
||||||
|
xkb_compose_state: *mut ffi::xkb_compose_state,
|
||||||
|
mods_state: ModifiersState,
|
||||||
|
locked: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The RMLVO description of a keymap
|
||||||
|
///
|
||||||
|
/// All fields are optional, and the system default
|
||||||
|
/// will be used if set to `None`.
|
||||||
|
pub struct RMLVO {
|
||||||
|
/// The rules file to use
|
||||||
|
pub rules: Option<String>,
|
||||||
|
/// The keyboard model by which to interpret keycodes and LEDs
|
||||||
|
pub model: Option<String>,
|
||||||
|
/// A comma separated list of layouts (languages) to include in the keymap
|
||||||
|
pub layout: Option<String>,
|
||||||
|
/// A comma separated list of variants, one per layout, which may modify or
|
||||||
|
/// augment the respective layout in various ways
|
||||||
|
pub variant: Option<String>,
|
||||||
|
/// A comma separated list of options, through which the user specifies
|
||||||
|
/// non-layout related preferences, like which key combinations are
|
||||||
|
/// used for switching layouts, or which key is the Compose key.
|
||||||
|
pub options: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Represents the current state of the keyboard modifiers
|
||||||
|
///
|
||||||
|
/// Each field of this struct represents a modifier and is `true` if this modifier is active.
|
||||||
|
///
|
||||||
|
/// For some modifiers, this means that the key is currently pressed, others are toggled
|
||||||
|
/// (like caps lock).
|
||||||
|
#[derive(Copy, Clone, Debug, Default)]
|
||||||
|
pub struct ModifiersState {
|
||||||
|
/// The "control" key
|
||||||
|
pub ctrl: bool,
|
||||||
|
/// The "alt" key
|
||||||
|
pub alt: bool,
|
||||||
|
/// The "shift" key
|
||||||
|
pub shift: bool,
|
||||||
|
/// The "Caps lock" key
|
||||||
|
pub caps_lock: bool,
|
||||||
|
/// The "logo" key
|
||||||
|
///
|
||||||
|
/// Also known as the "windows" key on most keyboards
|
||||||
|
pub logo: bool,
|
||||||
|
/// The "Num lock" key
|
||||||
|
pub num_lock: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ModifiersState {
|
||||||
|
fn new() -> ModifiersState {
|
||||||
|
ModifiersState::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_with(&mut self, state: *mut ffi::xkb_state) {
|
||||||
|
self.ctrl = unsafe {
|
||||||
|
(XKBH.xkb_state_mod_name_is_active)(
|
||||||
|
state,
|
||||||
|
ffi::XKB_MOD_NAME_CTRL.as_ptr() as *const c_char,
|
||||||
|
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
|
||||||
|
) > 0
|
||||||
|
};
|
||||||
|
self.alt = unsafe {
|
||||||
|
(XKBH.xkb_state_mod_name_is_active)(
|
||||||
|
state,
|
||||||
|
ffi::XKB_MOD_NAME_ALT.as_ptr() as *const c_char,
|
||||||
|
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
|
||||||
|
) > 0
|
||||||
|
};
|
||||||
|
self.shift = unsafe {
|
||||||
|
(XKBH.xkb_state_mod_name_is_active)(
|
||||||
|
state,
|
||||||
|
ffi::XKB_MOD_NAME_SHIFT.as_ptr() as *const c_char,
|
||||||
|
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
|
||||||
|
) > 0
|
||||||
|
};
|
||||||
|
self.caps_lock = unsafe {
|
||||||
|
(XKBH.xkb_state_mod_name_is_active)(
|
||||||
|
state,
|
||||||
|
ffi::XKB_MOD_NAME_CAPS.as_ptr() as *const c_char,
|
||||||
|
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
|
||||||
|
) > 0
|
||||||
|
};
|
||||||
|
self.logo = unsafe {
|
||||||
|
(XKBH.xkb_state_mod_name_is_active)(
|
||||||
|
state,
|
||||||
|
ffi::XKB_MOD_NAME_LOGO.as_ptr() as *const c_char,
|
||||||
|
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
|
||||||
|
) > 0
|
||||||
|
};
|
||||||
|
self.num_lock = unsafe {
|
||||||
|
(XKBH.xkb_state_mod_name_is_active)(
|
||||||
|
state,
|
||||||
|
ffi::XKB_MOD_NAME_NUM.as_ptr() as *const c_char,
|
||||||
|
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
|
||||||
|
) > 0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl KbState {
|
||||||
|
pub(crate) fn update_modifiers(
|
||||||
|
&mut self,
|
||||||
|
mods_depressed: u32,
|
||||||
|
mods_latched: u32,
|
||||||
|
mods_locked: u32,
|
||||||
|
group: u32,
|
||||||
|
) {
|
||||||
|
if !self.ready() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let mask = unsafe {
|
||||||
|
(XKBH.xkb_state_update_mask)(
|
||||||
|
self.xkb_state,
|
||||||
|
mods_depressed,
|
||||||
|
mods_latched,
|
||||||
|
mods_locked,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
group,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
if mask.contains(xkb_state_component::XKB_STATE_MODS_EFFECTIVE) {
|
||||||
|
// effective value of mods have changed, we need to update our state
|
||||||
|
self.mods_state.update_with(self.xkb_state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn get_one_sym_raw(&mut self, keycode: u32) -> u32 {
|
||||||
|
if !self.ready() {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
unsafe { (XKBH.xkb_state_key_get_one_sym)(self.xkb_state, keycode + 8) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn get_utf8_raw(&mut self, keycode: u32) -> Option<String> {
|
||||||
|
if !self.ready() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let size = unsafe {
|
||||||
|
(XKBH.xkb_state_key_get_utf8)(self.xkb_state, keycode + 8, ptr::null_mut(), 0)
|
||||||
|
} + 1;
|
||||||
|
if size <= 1 {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let mut buffer = Vec::with_capacity(size as usize);
|
||||||
|
unsafe {
|
||||||
|
buffer.set_len(size as usize);
|
||||||
|
(XKBH.xkb_state_key_get_utf8)(
|
||||||
|
self.xkb_state,
|
||||||
|
keycode + 8,
|
||||||
|
buffer.as_mut_ptr() as *mut _,
|
||||||
|
size as usize,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
// remove the final `\0`
|
||||||
|
buffer.pop();
|
||||||
|
// libxkbcommon will always provide valid UTF8
|
||||||
|
Some(unsafe { String::from_utf8_unchecked(buffer) })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn compose_feed(&mut self, keysym: u32) -> Option<ffi::xkb_compose_feed_result> {
|
||||||
|
if !self.ready() || self.xkb_compose_state.is_null() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(unsafe { (XKBH.xkb_compose_state_feed)(self.xkb_compose_state, keysym) })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn compose_status(&mut self) -> Option<ffi::xkb_compose_status> {
|
||||||
|
if !self.ready() || self.xkb_compose_state.is_null() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(unsafe { (XKBH.xkb_compose_state_get_status)(self.xkb_compose_state) })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn compose_get_utf8(&mut self) -> Option<String> {
|
||||||
|
if !self.ready() || self.xkb_compose_state.is_null() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let size = unsafe {
|
||||||
|
(XKBH.xkb_compose_state_get_utf8)(self.xkb_compose_state, ptr::null_mut(), 0)
|
||||||
|
} + 1;
|
||||||
|
if size <= 1 {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let mut buffer = Vec::with_capacity(size as usize);
|
||||||
|
unsafe {
|
||||||
|
buffer.set_len(size as usize);
|
||||||
|
(XKBH.xkb_compose_state_get_utf8)(
|
||||||
|
self.xkb_compose_state,
|
||||||
|
buffer.as_mut_ptr() as *mut _,
|
||||||
|
size as usize,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
// remove the final `\0`
|
||||||
|
buffer.pop();
|
||||||
|
// libxkbcommon will always provide valid UTF8
|
||||||
|
Some(unsafe { String::from_utf8_unchecked(buffer) })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn new() -> Result<KbState, Error> {
|
||||||
|
let xkbh = match ffi::XKBCOMMON_OPTION.as_ref() {
|
||||||
|
Some(h) => h,
|
||||||
|
None => return Err(Error::XKBNotFound),
|
||||||
|
};
|
||||||
|
let xkb_context =
|
||||||
|
unsafe { (xkbh.xkb_context_new)(ffi::xkb_context_flags::XKB_CONTEXT_NO_FLAGS) };
|
||||||
|
if xkb_context.is_null() {
|
||||||
|
return Err(Error::XKBNotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut me = KbState {
|
||||||
|
xkb_context,
|
||||||
|
xkb_keymap: ptr::null_mut(),
|
||||||
|
xkb_state: ptr::null_mut(),
|
||||||
|
xkb_compose_table: ptr::null_mut(),
|
||||||
|
xkb_compose_state: ptr::null_mut(),
|
||||||
|
mods_state: ModifiersState::new(),
|
||||||
|
locked: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
me.init_compose();
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(me)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn from_rmlvo(rmlvo: RMLVO) -> Result<KbState, Error> {
|
||||||
|
fn to_cstring(s: Option<String>) -> Result<Option<CString>, Error> {
|
||||||
|
s.map_or(Ok(None), |s| CString::new(s).map(Option::Some))
|
||||||
|
.map_err(|_| Error::BadNames)
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut state = KbState::new()?;
|
||||||
|
|
||||||
|
let rules = to_cstring(rmlvo.rules)?;
|
||||||
|
let model = to_cstring(rmlvo.model)?;
|
||||||
|
let layout = to_cstring(rmlvo.layout)?;
|
||||||
|
let variant = to_cstring(rmlvo.variant)?;
|
||||||
|
let options = to_cstring(rmlvo.options)?;
|
||||||
|
|
||||||
|
let xkb_names = ffi::xkb_rule_names {
|
||||||
|
rules: rules.map_or(ptr::null(), |s| s.as_ptr()),
|
||||||
|
model: model.map_or(ptr::null(), |s| s.as_ptr()),
|
||||||
|
layout: layout.map_or(ptr::null(), |s| s.as_ptr()),
|
||||||
|
variant: variant.map_or(ptr::null(), |s| s.as_ptr()),
|
||||||
|
options: options.map_or(ptr::null(), |s| s.as_ptr()),
|
||||||
|
};
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
state.init_with_rmlvo(xkb_names)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
state.locked = true;
|
||||||
|
Ok(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) unsafe fn init_compose(&mut self) {
|
||||||
|
let locale = env::var_os("LC_ALL")
|
||||||
|
.and_then(|v| if v.is_empty() { None } else { Some(v) })
|
||||||
|
.or_else(|| env::var_os("LC_CTYPE"))
|
||||||
|
.and_then(|v| if v.is_empty() { None } else { Some(v) })
|
||||||
|
.or_else(|| env::var_os("LANG"))
|
||||||
|
.and_then(|v| if v.is_empty() { None } else { Some(v) })
|
||||||
|
.unwrap_or_else(|| "C".into());
|
||||||
|
let locale = CString::new(locale.into_vec()).unwrap();
|
||||||
|
|
||||||
|
let compose_table = (XKBH.xkb_compose_table_new_from_locale)(
|
||||||
|
self.xkb_context,
|
||||||
|
locale.as_ptr(),
|
||||||
|
ffi::xkb_compose_compile_flags::XKB_COMPOSE_COMPILE_NO_FLAGS,
|
||||||
|
);
|
||||||
|
|
||||||
|
if compose_table.is_null() {
|
||||||
|
// init of compose table failed, continue without compose
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let compose_state = (XKBH.xkb_compose_state_new)(
|
||||||
|
compose_table,
|
||||||
|
ffi::xkb_compose_state_flags::XKB_COMPOSE_STATE_NO_FLAGS,
|
||||||
|
);
|
||||||
|
|
||||||
|
if compose_state.is_null() {
|
||||||
|
// init of compose state failed, continue without compose
|
||||||
|
(XKBH.xkb_compose_table_unref)(compose_table);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.xkb_compose_table = compose_table;
|
||||||
|
self.xkb_compose_state = compose_state;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) unsafe fn post_init(&mut self, xkb_keymap: *mut ffi::xkb_keymap) {
|
||||||
|
let xkb_state = (XKBH.xkb_state_new)(xkb_keymap);
|
||||||
|
self.xkb_keymap = xkb_keymap;
|
||||||
|
self.xkb_state = xkb_state;
|
||||||
|
self.mods_state.update_with(xkb_state);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) unsafe fn de_init(&mut self) {
|
||||||
|
(XKBH.xkb_state_unref)(self.xkb_state);
|
||||||
|
self.xkb_state = ptr::null_mut();
|
||||||
|
(XKBH.xkb_keymap_unref)(self.xkb_keymap);
|
||||||
|
self.xkb_keymap = ptr::null_mut();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) unsafe fn init_with_fd(&mut self, fd: RawFd, size: usize) {
|
||||||
|
let map = MmapOptions::new()
|
||||||
|
.len(size)
|
||||||
|
.map(&File::from_raw_fd(fd))
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let xkb_keymap = (XKBH.xkb_keymap_new_from_string)(
|
||||||
|
self.xkb_context,
|
||||||
|
map.as_ptr() as *const _,
|
||||||
|
ffi::xkb_keymap_format::XKB_KEYMAP_FORMAT_TEXT_V1,
|
||||||
|
ffi::xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS,
|
||||||
|
);
|
||||||
|
|
||||||
|
if xkb_keymap.is_null() {
|
||||||
|
panic!("Received invalid keymap from compositor.");
|
||||||
|
}
|
||||||
|
|
||||||
|
self.post_init(xkb_keymap);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) unsafe fn init_with_rmlvo(
|
||||||
|
&mut self,
|
||||||
|
names: ffi::xkb_rule_names,
|
||||||
|
) -> Result<(), Error> {
|
||||||
|
let xkb_keymap = (XKBH.xkb_keymap_new_from_names)(
|
||||||
|
self.xkb_context,
|
||||||
|
&names,
|
||||||
|
ffi::xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS,
|
||||||
|
);
|
||||||
|
|
||||||
|
if xkb_keymap.is_null() {
|
||||||
|
return Err(Error::BadNames);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.post_init(xkb_keymap);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) unsafe fn key_repeats(&mut self, xkb_keycode_t: ffi::xkb_keycode_t) -> bool {
|
||||||
|
(XKBH.xkb_keymap_key_repeats)(self.xkb_keymap, xkb_keycode_t) == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub(crate) fn ready(&self) -> bool {
|
||||||
|
!self.xkb_state.is_null()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub(crate) fn locked(&self) -> bool {
|
||||||
|
self.locked
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub(crate) fn mods_state(&self) -> ModifiersState {
|
||||||
|
self.mods_state
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for KbState {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
(XKBH.xkb_compose_state_unref)(self.xkb_compose_state);
|
||||||
|
(XKBH.xkb_compose_table_unref)(self.xkb_compose_table);
|
||||||
|
(XKBH.xkb_state_unref)(self.xkb_state);
|
||||||
|
(XKBH.xkb_keymap_unref)(self.xkb_keymap);
|
||||||
|
(XKBH.xkb_context_unref)(self.xkb_context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+389
@@ -0,0 +1,389 @@
|
|||||||
|
use std::env;
|
||||||
|
use std::fs::File;
|
||||||
|
use std::io::{BufRead, BufReader, Read, Write};
|
||||||
|
use std::os::unix::io::AsRawFd;
|
||||||
|
use std::os::unix::net::{UnixListener, UnixStream};
|
||||||
|
use std::{collections::HashMap, sync::mpsc::channel};
|
||||||
|
|
||||||
|
use chrono::{Duration, Local};
|
||||||
|
use nix::poll::{poll, PollFd, PollFlags};
|
||||||
|
use os_pipe::pipe;
|
||||||
|
use timerfd::{SetTimeFlags, TimerFd, TimerState};
|
||||||
|
|
||||||
|
mod app;
|
||||||
|
mod buffer;
|
||||||
|
mod cmd;
|
||||||
|
mod color;
|
||||||
|
mod config;
|
||||||
|
mod configfmt;
|
||||||
|
mod data;
|
||||||
|
mod desktop;
|
||||||
|
mod doublemempool;
|
||||||
|
mod draw;
|
||||||
|
mod fonts;
|
||||||
|
mod keyboard;
|
||||||
|
mod widget;
|
||||||
|
mod widgets;
|
||||||
|
|
||||||
|
#[macro_use]
|
||||||
|
extern crate dlib;
|
||||||
|
|
||||||
|
use app::{App, OutputMode};
|
||||||
|
use cmd::Cmd;
|
||||||
|
use config::Config;
|
||||||
|
use configfmt::ConfigFmt;
|
||||||
|
use fonts::{FontLoader, FontMap, FontSeeker};
|
||||||
|
use widget::WaitContext;
|
||||||
|
|
||||||
|
enum Mode {
|
||||||
|
Start,
|
||||||
|
Daemonize,
|
||||||
|
StartOrKill,
|
||||||
|
ToggleVisible,
|
||||||
|
PrintConfig(ConfigFmt),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let socket_path = match env::var("XDG_RUNTIME_DIR") {
|
||||||
|
Ok(dir) => dir + "/wldash",
|
||||||
|
Err(_) => "/tmp/wldash".to_string(),
|
||||||
|
};
|
||||||
|
let config_home = match env::var("XDG_CONFIG_HOME") {
|
||||||
|
Ok(dir) => dir + "/wldash",
|
||||||
|
Err(_) => match env::var("HOME") {
|
||||||
|
Ok(home) => home + "/.config/wldash",
|
||||||
|
_ => panic!("unable to find user folder"),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// From all existing files take the first readable one and write it's extension to `ext`
|
||||||
|
let mut ext = [0x0; 8];
|
||||||
|
let file = configfmt::CONFIG_NAMES
|
||||||
|
.iter()
|
||||||
|
.map(|name| std::path::Path::new(&config_home).join(name))
|
||||||
|
.filter_map(|path| {
|
||||||
|
match File::open(&path) {
|
||||||
|
Ok(file) => {
|
||||||
|
let e = path.extension().and_then(|e| e.to_str())?;
|
||||||
|
let len = e.len();
|
||||||
|
let from = len.saturating_sub(8); // the longest possible extension
|
||||||
|
ext[0..len - from].copy_from_slice(&e.as_bytes()[from..]);
|
||||||
|
Some(file)
|
||||||
|
}
|
||||||
|
Err(_) => None,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.next();
|
||||||
|
|
||||||
|
let fmt = std::str::from_utf8(&ext)
|
||||||
|
.ok()
|
||||||
|
.and_then(ConfigFmt::new)
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let config: Config = file
|
||||||
|
.map(|f| fmt.from_reader(BufReader::new(f)))
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let scale = config.scale;
|
||||||
|
|
||||||
|
let fonts: FontMap = {
|
||||||
|
let load_font = |font_name| {
|
||||||
|
let path = FontSeeker::from_string(font_name);
|
||||||
|
FontLoader::from_path(&path).expect(&format!("Loading {} failed", path.display()))
|
||||||
|
};
|
||||||
|
|
||||||
|
config
|
||||||
|
.fonts
|
||||||
|
.iter()
|
||||||
|
.map(|(key, val)| (key.clone(), load_font(val)))
|
||||||
|
.collect::<HashMap<_, _>>()
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut args = env::args();
|
||||||
|
let _ = args.next();
|
||||||
|
let mode = match args.next() {
|
||||||
|
Some(arg) => match arg.as_str() {
|
||||||
|
"start" => Mode::Daemonize,
|
||||||
|
"start-or-kill" => Mode::StartOrKill,
|
||||||
|
"toggle-visible" => Mode::ToggleVisible,
|
||||||
|
"print-config" => Mode::PrintConfig(fmt),
|
||||||
|
s => {
|
||||||
|
let p = "print-config-";
|
||||||
|
let l = p.len();
|
||||||
|
let fmt = if s.starts_with(p) {
|
||||||
|
ConfigFmt::new(&s[l..])
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
if let Some(fmt) = fmt {
|
||||||
|
Mode::PrintConfig(fmt)
|
||||||
|
} else {
|
||||||
|
eprintln!("unsupported sub-command {}", s);
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None => Mode::Start,
|
||||||
|
};
|
||||||
|
if args.next().is_some() {
|
||||||
|
// total = args.count + 2 (the two we skipped + the rest)
|
||||||
|
eprintln!("expected 0 or 1 arguments, got {}", args.count() + 2);
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut daemon = false;
|
||||||
|
|
||||||
|
match mode {
|
||||||
|
Mode::ToggleVisible => {
|
||||||
|
if let Ok(mut socket) = UnixStream::connect(socket_path) {
|
||||||
|
socket.write_all(b"toggle_visible\n").unwrap();
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
eprintln!("wldash is not running");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
Mode::StartOrKill => {
|
||||||
|
if let Ok(mut socket) = UnixStream::connect(socket_path.clone()) {
|
||||||
|
socket.write_all(b"kill\n").unwrap();
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
Mode::Start => {
|
||||||
|
if UnixStream::connect(socket_path.clone()).is_ok() {
|
||||||
|
eprintln!("wldash is already running");
|
||||||
|
std::process::exit(1);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
Mode::Daemonize => {
|
||||||
|
if UnixStream::connect(socket_path.clone()).is_ok() {
|
||||||
|
eprintln!("wldash is already running");
|
||||||
|
std::process::exit(1);
|
||||||
|
};
|
||||||
|
daemon = true;
|
||||||
|
}
|
||||||
|
Mode::PrintConfig(fmt) => {
|
||||||
|
println!("{}", fmt.to_string(&config));
|
||||||
|
std::process::exit(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let _ = std::fs::remove_file(socket_path.clone());
|
||||||
|
let listener = UnixListener::bind(socket_path.clone()).unwrap();
|
||||||
|
|
||||||
|
let output_mode = match config.output_mode {
|
||||||
|
config::OutputMode::All => OutputMode::All,
|
||||||
|
config::OutputMode::Active => OutputMode::Active,
|
||||||
|
};
|
||||||
|
|
||||||
|
let background = config.background;
|
||||||
|
|
||||||
|
let (tx_draw, rx_draw) = channel();
|
||||||
|
let tx_draw_mod = tx_draw.clone();
|
||||||
|
|
||||||
|
// Print, write to a file, or send to an HTTP server.
|
||||||
|
let widget = config
|
||||||
|
.widget
|
||||||
|
.construct(Local::now().naive_local(), tx_draw_mod, &fonts)
|
||||||
|
.expect("no widget configured");
|
||||||
|
|
||||||
|
let mut app = App::new(tx_draw, output_mode, background, scale);
|
||||||
|
if daemon {
|
||||||
|
app.hide();
|
||||||
|
} else {
|
||||||
|
app.show();
|
||||||
|
}
|
||||||
|
app.set_widget(widget).unwrap();
|
||||||
|
|
||||||
|
let (mut rx_pipe, mut tx_pipe) = pipe().unwrap();
|
||||||
|
let ipc_pipe = tx_pipe.try_clone().unwrap();
|
||||||
|
|
||||||
|
let worker_queue = app.cmd_queue();
|
||||||
|
let _ = std::thread::Builder::new()
|
||||||
|
.name("cmd_proxy".to_string())
|
||||||
|
.spawn(move || loop {
|
||||||
|
let cmd = rx_draw.recv().unwrap();
|
||||||
|
worker_queue.lock().unwrap().push_back(cmd);
|
||||||
|
tx_pipe.write_all(&[0x1]).unwrap();
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut timer = TimerFd::new().unwrap();
|
||||||
|
let ev_fd = PollFd::new(
|
||||||
|
app.event_queue().display().get_connection_fd(),
|
||||||
|
PollFlags::POLLIN,
|
||||||
|
);
|
||||||
|
let rx_fd = PollFd::new(rx_pipe.as_raw_fd(), PollFlags::POLLIN);
|
||||||
|
let tm_fd = PollFd::new(timer.as_raw_fd(), PollFlags::POLLIN);
|
||||||
|
let ipc_fd = PollFd::new(listener.as_raw_fd(), PollFlags::POLLIN);
|
||||||
|
|
||||||
|
app.cmd_queue().lock().unwrap().push_back(Cmd::Draw);
|
||||||
|
|
||||||
|
let mut visible = !daemon;
|
||||||
|
let mut wait_ctx = WaitContext {
|
||||||
|
fds: Vec::new(),
|
||||||
|
target_time: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let q = app.cmd_queue();
|
||||||
|
loop {
|
||||||
|
let cmd = q.lock().unwrap().pop_front();
|
||||||
|
match cmd {
|
||||||
|
Some(cmd) => match cmd {
|
||||||
|
Cmd::Draw => {
|
||||||
|
app.redraw(false).expect("Failed to draw");
|
||||||
|
app.flush_display();
|
||||||
|
}
|
||||||
|
Cmd::KeyboardTest => {
|
||||||
|
if let Some(cmd) = app.key_repeat() {
|
||||||
|
q.lock().unwrap().push_back(cmd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Cmd::ForceDraw => {
|
||||||
|
app.redraw(true).expect("Failed to draw");
|
||||||
|
app.flush_display();
|
||||||
|
}
|
||||||
|
Cmd::MouseClick { btn, pos } => {
|
||||||
|
app.get_widget().mouse_click(btn, pos);
|
||||||
|
q.lock().unwrap().push_back(Cmd::Draw);
|
||||||
|
}
|
||||||
|
Cmd::MouseScroll { scroll, pos } => {
|
||||||
|
app.get_widget().mouse_scroll(scroll, pos);
|
||||||
|
q.lock().unwrap().push_back(Cmd::Draw);
|
||||||
|
}
|
||||||
|
Cmd::Keyboard {
|
||||||
|
key,
|
||||||
|
key_state,
|
||||||
|
modifiers_state,
|
||||||
|
interpreted,
|
||||||
|
} => {
|
||||||
|
app.get_widget()
|
||||||
|
.keyboard_input(key, modifiers_state, key_state, interpreted);
|
||||||
|
q.lock().unwrap().push_back(Cmd::Draw);
|
||||||
|
}
|
||||||
|
Cmd::ToggleVisible => {
|
||||||
|
visible = !visible;
|
||||||
|
if visible {
|
||||||
|
app.get_widget().enter();
|
||||||
|
app.show();
|
||||||
|
} else {
|
||||||
|
app.hide();
|
||||||
|
app.get_widget().leave();
|
||||||
|
}
|
||||||
|
app.flush_display();
|
||||||
|
}
|
||||||
|
Cmd::Exit => {
|
||||||
|
if daemon {
|
||||||
|
visible = false;
|
||||||
|
app.hide();
|
||||||
|
app.get_widget().leave();
|
||||||
|
app.flush_display();
|
||||||
|
} else {
|
||||||
|
let _ = std::fs::remove_file(socket_path);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None => {
|
||||||
|
app.flush_display();
|
||||||
|
|
||||||
|
wait_ctx.fds.clear();
|
||||||
|
wait_ctx.fds.push(ev_fd);
|
||||||
|
wait_ctx.fds.push(rx_fd);
|
||||||
|
wait_ctx.fds.push(ipc_fd);
|
||||||
|
wait_ctx.target_time = None;
|
||||||
|
|
||||||
|
app.get_widget().wait(&mut wait_ctx);
|
||||||
|
app.set_keyboard_repeat(&mut wait_ctx);
|
||||||
|
|
||||||
|
if let Some(target_time) = wait_ctx.target_time {
|
||||||
|
let n = Local::now().naive_local();
|
||||||
|
let sleep = if target_time > n {
|
||||||
|
target_time - n
|
||||||
|
} else {
|
||||||
|
Duration::seconds(0)
|
||||||
|
};
|
||||||
|
timer.set_state(
|
||||||
|
TimerState::Oneshot(sleep.to_std().unwrap()),
|
||||||
|
SetTimeFlags::Default,
|
||||||
|
);
|
||||||
|
wait_ctx.fds.push(tm_fd);
|
||||||
|
}
|
||||||
|
|
||||||
|
poll(&mut wait_ctx.fds, -1).unwrap();
|
||||||
|
|
||||||
|
if wait_ctx.fds[0]
|
||||||
|
.revents()
|
||||||
|
.unwrap()
|
||||||
|
.contains(PollFlags::POLLIN)
|
||||||
|
{
|
||||||
|
if let Some(guard) = app.event_queue().prepare_read() {
|
||||||
|
if let Err(e) = guard.read_events() {
|
||||||
|
if e.kind() != ::std::io::ErrorKind::WouldBlock {
|
||||||
|
eprintln!(
|
||||||
|
"Error while trying to read from the wayland socket: {:?}",
|
||||||
|
e
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
app.event_queue()
|
||||||
|
.dispatch_pending(&mut (), |_, _, _| {})
|
||||||
|
.expect("Failed to dispatch all messages.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if wait_ctx.fds[1]
|
||||||
|
.revents()
|
||||||
|
.unwrap()
|
||||||
|
.contains(PollFlags::POLLIN)
|
||||||
|
{
|
||||||
|
let mut v = [0x00];
|
||||||
|
rx_pipe.read_exact(&mut v).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
if wait_ctx.fds[2]
|
||||||
|
.revents()
|
||||||
|
.unwrap()
|
||||||
|
.contains(PollFlags::POLLIN)
|
||||||
|
{
|
||||||
|
if let Ok((stream, _)) = listener.accept() {
|
||||||
|
let client_queue = q.clone();
|
||||||
|
let mut client_pipe = ipc_pipe.try_clone().unwrap();
|
||||||
|
let _ = std::thread::Builder::new()
|
||||||
|
.name("ipc_client".to_string())
|
||||||
|
.spawn(move || {
|
||||||
|
let r = BufReader::new(stream);
|
||||||
|
for line in r.lines() {
|
||||||
|
match line {
|
||||||
|
Ok(v) => match v.as_str() {
|
||||||
|
"kill" => {
|
||||||
|
client_queue.lock().unwrap().push_back(Cmd::Exit)
|
||||||
|
}
|
||||||
|
"toggle_visible" => client_queue
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.push_back(Cmd::ToggleVisible),
|
||||||
|
v => eprintln!("unknown command: {}", v),
|
||||||
|
},
|
||||||
|
Err(_) => return,
|
||||||
|
}
|
||||||
|
client_pipe.write_all(&[0x1]).unwrap();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if wait_ctx.target_time.is_some()
|
||||||
|
&& wait_ctx.fds[wait_ctx.fds.len() - 1]
|
||||||
|
.revents()
|
||||||
|
.unwrap()
|
||||||
|
.contains(PollFlags::POLLIN)
|
||||||
|
{
|
||||||
|
timer.read();
|
||||||
|
let mut qq = q.lock().unwrap();
|
||||||
|
qq.push_back(Cmd::KeyboardTest);
|
||||||
|
qq.push_back(Cmd::Draw);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+458
@@ -0,0 +1,458 @@
|
|||||||
|
use crate::buffer::Buffer;
|
||||||
|
use crate::color::Color;
|
||||||
|
pub use crate::keyboard::{KeyState, ModifiersState};
|
||||||
|
use chrono::NaiveDateTime;
|
||||||
|
use nix::poll::PollFd;
|
||||||
|
|
||||||
|
pub struct DrawContext<'a> {
|
||||||
|
pub buf: &'a mut Buffer<'a>,
|
||||||
|
pub bg: &'a Color,
|
||||||
|
pub time: NaiveDateTime,
|
||||||
|
pub force: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct DrawReport {
|
||||||
|
pub width: u32,
|
||||||
|
pub height: u32,
|
||||||
|
pub damage: Vec<(i32, i32, i32, i32)>,
|
||||||
|
pub full_damage: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DrawReport {
|
||||||
|
pub fn empty(width: u32, height: u32) -> DrawReport {
|
||||||
|
DrawReport {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
damage: Vec::new(),
|
||||||
|
full_damage: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct WaitContext {
|
||||||
|
pub fds: Vec<PollFd>,
|
||||||
|
pub target_time: Option<NaiveDateTime>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WaitContext {
|
||||||
|
pub fn set_time(&mut self, new_time: NaiveDateTime) {
|
||||||
|
if let Some(ot) = self.target_time {
|
||||||
|
if new_time < ot {
|
||||||
|
self.target_time = Some(new_time);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.target_time = Some(new_time);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait Widget {
|
||||||
|
fn wait(&mut self, ctx: &mut WaitContext);
|
||||||
|
fn enter(&mut self);
|
||||||
|
fn leave(&mut self);
|
||||||
|
fn size(&self) -> (u32, u32);
|
||||||
|
fn draw(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut DrawContext,
|
||||||
|
pos: (u32, u32),
|
||||||
|
expansion: (u32, u32),
|
||||||
|
) -> Result<DrawReport, ::std::io::Error>;
|
||||||
|
|
||||||
|
fn keyboard_input(
|
||||||
|
&mut self,
|
||||||
|
keysym: u32,
|
||||||
|
modifier_state: ModifiersState,
|
||||||
|
key_state: KeyState,
|
||||||
|
interpreted: Option<String>,
|
||||||
|
);
|
||||||
|
fn mouse_click(&mut self, button: u32, pos: (u32, u32));
|
||||||
|
fn mouse_scroll(&mut self, scroll: (f64, f64), pos: (u32, u32));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct VerticalLayout<'a> {
|
||||||
|
pub children: Vec<Box<dyn Widget + Send + 'a>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl<'a> VerticalLayout<'a> {
|
||||||
|
pub fn new(children: Vec<Box<dyn Widget + Send + 'a>>) -> Box<VerticalLayout> {
|
||||||
|
Box::new(VerticalLayout { children })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Widget for VerticalLayout<'a> {
|
||||||
|
fn wait(&mut self, ctx: &mut WaitContext) {
|
||||||
|
for child in &mut self.children {
|
||||||
|
child.wait(ctx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn enter(&mut self) {
|
||||||
|
for child in &mut self.children {
|
||||||
|
child.enter();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn leave(&mut self) {
|
||||||
|
for child in &mut self.children {
|
||||||
|
child.leave();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn size(&self) -> (u32, u32) {
|
||||||
|
let mut width = 0;
|
||||||
|
let mut height = 0;
|
||||||
|
|
||||||
|
for child in &self.children {
|
||||||
|
let size = child.size();
|
||||||
|
if size.0 > width {
|
||||||
|
width = size.0;
|
||||||
|
}
|
||||||
|
height += size.1;
|
||||||
|
}
|
||||||
|
|
||||||
|
(width, height)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut DrawContext,
|
||||||
|
pos: (u32, u32),
|
||||||
|
expansion: (u32, u32),
|
||||||
|
) -> Result<DrawReport, ::std::io::Error> {
|
||||||
|
let mut offset = 0;
|
||||||
|
let mut width = 0;
|
||||||
|
let mut damage = Vec::new();
|
||||||
|
let mut full_damage = false;
|
||||||
|
for child in &mut self.children {
|
||||||
|
let mut report = child.draw(
|
||||||
|
ctx,
|
||||||
|
(pos.0, offset + pos.1),
|
||||||
|
(expansion.0, expansion.1 - offset),
|
||||||
|
)?;
|
||||||
|
if report.width > width {
|
||||||
|
width = report.width
|
||||||
|
}
|
||||||
|
offset += report.height;
|
||||||
|
full_damage |= report.full_damage;
|
||||||
|
damage.append(&mut report.damage);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(DrawReport {
|
||||||
|
width,
|
||||||
|
height: offset,
|
||||||
|
damage,
|
||||||
|
full_damage,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyboard_input(
|
||||||
|
&mut self,
|
||||||
|
keysym: u32,
|
||||||
|
modifier_state: ModifiersState,
|
||||||
|
key_state: KeyState,
|
||||||
|
interpreted: Option<String>,
|
||||||
|
) {
|
||||||
|
for child in &mut self.children {
|
||||||
|
child.keyboard_input(keysym, modifier_state, key_state, interpreted.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mouse_click(&mut self, button: u32, pos: (u32, u32)) {
|
||||||
|
let mut height = 0;
|
||||||
|
|
||||||
|
for child in &mut self.children {
|
||||||
|
let size = child.size();
|
||||||
|
if pos.1 >= height && pos.1 < height + size.1 {
|
||||||
|
let pos = (pos.0, pos.1 - height);
|
||||||
|
child.mouse_click(button, pos);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
height += size.1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mouse_scroll(&mut self, scroll: (f64, f64), pos: (u32, u32)) {
|
||||||
|
let mut height = 0;
|
||||||
|
|
||||||
|
for child in &mut self.children {
|
||||||
|
let size = child.size();
|
||||||
|
if pos.1 >= height && pos.1 < height + size.1 {
|
||||||
|
let pos = (pos.0, pos.1 - height);
|
||||||
|
child.mouse_scroll(scroll, pos);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
height += size.1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct HorizontalLayout<'a> {
|
||||||
|
pub children: Vec<Box<dyn Widget + Send + 'a>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl<'a> HorizontalLayout<'a> {
|
||||||
|
pub fn new(children: Vec<Box<dyn Widget + Send + 'a>>) -> Box<HorizontalLayout> {
|
||||||
|
Box::new(HorizontalLayout { children })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn height(&self) -> u32 {
|
||||||
|
let mut height = 0;
|
||||||
|
|
||||||
|
for child in &self.children {
|
||||||
|
let size = child.size();
|
||||||
|
if size.1 > height {
|
||||||
|
height = size.1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
height
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Widget for HorizontalLayout<'a> {
|
||||||
|
fn wait(&mut self, ctx: &mut WaitContext) {
|
||||||
|
for child in &mut self.children {
|
||||||
|
child.wait(ctx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn enter(&mut self) {
|
||||||
|
for child in &mut self.children {
|
||||||
|
child.enter();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn leave(&mut self) {
|
||||||
|
for child in &mut self.children {
|
||||||
|
child.leave();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn size(&self) -> (u32, u32) {
|
||||||
|
let mut width = 0;
|
||||||
|
let mut height = 0;
|
||||||
|
|
||||||
|
for child in &self.children {
|
||||||
|
let size = child.size();
|
||||||
|
if size.1 > height {
|
||||||
|
height = size.1;
|
||||||
|
}
|
||||||
|
width += size.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
(width, height)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut DrawContext,
|
||||||
|
pos: (u32, u32),
|
||||||
|
expansion: (u32, u32),
|
||||||
|
) -> Result<DrawReport, ::std::io::Error> {
|
||||||
|
let mut offset = 0;
|
||||||
|
let mut height = 0;
|
||||||
|
let mut damage = Vec::new();
|
||||||
|
let mut full_damage = false;
|
||||||
|
for child in &mut self.children {
|
||||||
|
let mut report = child.draw(
|
||||||
|
ctx,
|
||||||
|
(offset + pos.0, pos.1),
|
||||||
|
(expansion.0 - offset, expansion.1),
|
||||||
|
)?;
|
||||||
|
if report.height > height {
|
||||||
|
height = report.height
|
||||||
|
}
|
||||||
|
offset += report.width;
|
||||||
|
full_damage |= report.full_damage;
|
||||||
|
damage.append(&mut report.damage);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(DrawReport {
|
||||||
|
width: offset,
|
||||||
|
height,
|
||||||
|
damage,
|
||||||
|
full_damage,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyboard_input(
|
||||||
|
&mut self,
|
||||||
|
keysym: u32,
|
||||||
|
modifier_state: ModifiersState,
|
||||||
|
key_state: KeyState,
|
||||||
|
interpreted: Option<String>,
|
||||||
|
) {
|
||||||
|
for child in &mut self.children {
|
||||||
|
child.keyboard_input(keysym, modifier_state, key_state, interpreted.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mouse_click(&mut self, button: u32, pos: (u32, u32)) {
|
||||||
|
let mut width = 0;
|
||||||
|
|
||||||
|
for child in &mut self.children {
|
||||||
|
let size = child.size();
|
||||||
|
if pos.0 >= width && pos.0 < width + size.0 {
|
||||||
|
let pos = (pos.0 - width, pos.1);
|
||||||
|
child.mouse_click(button, pos);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
width += size.0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mouse_scroll(&mut self, scroll: (f64, f64), pos: (u32, u32)) {
|
||||||
|
let mut width = 0;
|
||||||
|
|
||||||
|
for child in &mut self.children {
|
||||||
|
let size = child.size();
|
||||||
|
if pos.0 >= width && pos.0 < width + size.0 {
|
||||||
|
let pos = (pos.0 - width, pos.1);
|
||||||
|
child.mouse_scroll(scroll, pos);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
width += size.0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Margin<'a> {
|
||||||
|
pub child: Box<dyn Widget + Send + 'a>,
|
||||||
|
pub margins: (u32, u32, u32, u32), // left, right, top, bottom
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl<'a> Margin<'a> {
|
||||||
|
pub fn new(margins: (u32, u32, u32, u32), child: Box<dyn Widget + Send + 'a>) -> Box<Margin> {
|
||||||
|
Box::new(Margin { child, margins })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Widget for Margin<'a> {
|
||||||
|
fn wait(&mut self, ctx: &mut WaitContext) {
|
||||||
|
self.child.wait(ctx)
|
||||||
|
}
|
||||||
|
fn enter(&mut self) {
|
||||||
|
self.child.enter()
|
||||||
|
}
|
||||||
|
fn leave(&mut self) {
|
||||||
|
self.child.leave()
|
||||||
|
}
|
||||||
|
fn size(&self) -> (u32, u32) {
|
||||||
|
let size = self.child.size();
|
||||||
|
(
|
||||||
|
size.0 + self.margins.0 + self.margins.1,
|
||||||
|
size.1 + self.margins.2 + self.margins.3,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut DrawContext,
|
||||||
|
pos: (u32, u32),
|
||||||
|
expansion: (u32, u32),
|
||||||
|
) -> Result<DrawReport, ::std::io::Error> {
|
||||||
|
let expansion = (
|
||||||
|
expansion.0 - self.margins.0 - self.margins.1,
|
||||||
|
expansion.1 - self.margins.2 - self.margins.3,
|
||||||
|
);
|
||||||
|
let report = self.child.draw(
|
||||||
|
ctx,
|
||||||
|
(pos.0 + self.margins.0, pos.1 + self.margins.2),
|
||||||
|
expansion,
|
||||||
|
)?;
|
||||||
|
Ok(DrawReport {
|
||||||
|
width: report.width + self.margins.0 + self.margins.1,
|
||||||
|
height: report.height + self.margins.2 + self.margins.3,
|
||||||
|
damage: report.damage,
|
||||||
|
full_damage: report.full_damage,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyboard_input(
|
||||||
|
&mut self,
|
||||||
|
keysym: u32,
|
||||||
|
modifier_state: ModifiersState,
|
||||||
|
key_state: KeyState,
|
||||||
|
interpreted: Option<String>,
|
||||||
|
) {
|
||||||
|
self.child
|
||||||
|
.keyboard_input(keysym, modifier_state, key_state, interpreted);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mouse_click(&mut self, button: u32, pos: (u32, u32)) {
|
||||||
|
let pos = (
|
||||||
|
pos.0.saturating_sub(self.margins.0),
|
||||||
|
pos.1.saturating_sub(self.margins.2),
|
||||||
|
);
|
||||||
|
self.child.mouse_click(button, pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mouse_scroll(&mut self, scroll: (f64, f64), pos: (u32, u32)) {
|
||||||
|
let pos = (
|
||||||
|
pos.0.saturating_sub(self.margins.0),
|
||||||
|
pos.1.saturating_sub(self.margins.2),
|
||||||
|
);
|
||||||
|
self.child.mouse_scroll(scroll, pos);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Fixed<'a> {
|
||||||
|
pub child: Box<dyn Widget + Send + 'a>,
|
||||||
|
pub size: (u32, u32),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl<'a> Fixed<'a> {
|
||||||
|
pub fn new(size: (u32, u32), child: Box<dyn Widget + Send + 'a>) -> Box<Fixed> {
|
||||||
|
Box::new(Fixed { child, size })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Widget for Fixed<'a> {
|
||||||
|
fn wait(&mut self, ctx: &mut WaitContext) {
|
||||||
|
self.child.wait(ctx)
|
||||||
|
}
|
||||||
|
fn enter(&mut self) {
|
||||||
|
self.child.enter()
|
||||||
|
}
|
||||||
|
fn leave(&mut self) {
|
||||||
|
self.child.leave()
|
||||||
|
}
|
||||||
|
fn size(&self) -> (u32, u32) {
|
||||||
|
self.size
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut DrawContext,
|
||||||
|
pos: (u32, u32),
|
||||||
|
expansion: (u32, u32),
|
||||||
|
) -> Result<DrawReport, ::std::io::Error> {
|
||||||
|
let report = self.child.draw(ctx, pos, expansion)?;
|
||||||
|
Ok(DrawReport {
|
||||||
|
width: self.size.0,
|
||||||
|
height: self.size.1,
|
||||||
|
damage: report.damage,
|
||||||
|
full_damage: report.full_damage,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyboard_input(
|
||||||
|
&mut self,
|
||||||
|
keysym: u32,
|
||||||
|
modifier_state: ModifiersState,
|
||||||
|
key_state: KeyState,
|
||||||
|
interpreted: Option<String>,
|
||||||
|
) {
|
||||||
|
self.child
|
||||||
|
.keyboard_input(keysym, modifier_state, key_state, interpreted);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mouse_click(&mut self, button: u32, pos: (u32, u32)) {
|
||||||
|
self.child.mouse_click(button, pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mouse_scroll(&mut self, scroll: (f64, f64), pos: (u32, u32)) {
|
||||||
|
self.child.mouse_scroll(scroll, pos);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
use crate::color::Color;
|
||||||
|
use crate::widget::WaitContext;
|
||||||
|
use crate::{
|
||||||
|
fonts::FontRef,
|
||||||
|
widgets::bar_widget::{BarWidget, BarWidgetImpl},
|
||||||
|
};
|
||||||
|
|
||||||
|
use alsa::mixer::{Mixer, Selem, SelemChannelId, SelemId};
|
||||||
|
|
||||||
|
const CARD_NAME: &str = "default";
|
||||||
|
const SELEM_NAME: &str = "Master";
|
||||||
|
const SELEM_ID: u32 = 0u32;
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn alsa_error_to_io_error(fail: &'static str, err: &alsa::Error) -> ::std::io::Error {
|
||||||
|
let kind = ::std::io::ErrorKind::Other;
|
||||||
|
let func = err.func();
|
||||||
|
::std::io::Error::new(kind, format!("{}: {}{}", fail, func, err.errno()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn alsa_volume_to_f32(volume: i64, min: i64, max: i64) -> f32 {
|
||||||
|
(volume - min) as f32 / (max - min) as f32
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn f32_to_alsa_volume(volume: f32, min: i64, max: i64) -> i64 {
|
||||||
|
min + ((max - min) as f32 * volume) as i64
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Alsa {
|
||||||
|
pub mixer: Mixer,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Alsa {
|
||||||
|
pub fn new(font: FontRef, font_size: f32, length: u32) -> ::std::io::Result<Box<BarWidget>> {
|
||||||
|
let mixer = Mixer::new(CARD_NAME, true)
|
||||||
|
.map_err(|err| alsa_error_to_io_error("Failed to create ALSA mixer", &err))?;
|
||||||
|
let mixer = Self { mixer };
|
||||||
|
mixer.get_master_volume()?; // probing
|
||||||
|
Ok(BarWidget::new_simple(
|
||||||
|
font,
|
||||||
|
font_size,
|
||||||
|
length,
|
||||||
|
Box::new(mixer),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
#[inline]
|
||||||
|
pub fn get_master(&self) -> ::std::io::Result<Selem> {
|
||||||
|
let master_id = SelemId::new(SELEM_NAME, SELEM_ID);
|
||||||
|
match self.mixer.find_selem(&master_id) {
|
||||||
|
Some(master) => Ok(master),
|
||||||
|
None => {
|
||||||
|
let kind = ::std::io::ErrorKind::NotFound;
|
||||||
|
let desc = "`Master` not found";
|
||||||
|
Err(::std::io::Error::new(kind, desc))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn get_master_volume(&self) -> ::std::io::Result<f32> {
|
||||||
|
let master = self.get_master()?;
|
||||||
|
let (min, max) = master.get_playback_volume_range();
|
||||||
|
master
|
||||||
|
.get_playback_volume(SelemChannelId::mono())
|
||||||
|
.map(|volume| alsa_volume_to_f32(volume, min, max))
|
||||||
|
.map_err(|e| alsa_error_to_io_error("Failed to get `Master` volume", &e))
|
||||||
|
}
|
||||||
|
pub fn set_master_volume(&self, volume: f32) -> ::std::io::Result<()> {
|
||||||
|
let master = self.get_master()?;
|
||||||
|
let (min, max) = master.get_playback_volume_range();
|
||||||
|
let volume = f32_to_alsa_volume(volume, min, max);
|
||||||
|
master
|
||||||
|
.set_playback_volume_all(volume)
|
||||||
|
.map_err(|e| alsa_error_to_io_error("Failed to set `Master` volume", &e))
|
||||||
|
}
|
||||||
|
pub fn inc_master_volume(&self, diff: f32) -> ::std::io::Result<()> {
|
||||||
|
let master = self.get_master()?;
|
||||||
|
let (min, max) = master.get_playback_volume_range();
|
||||||
|
master
|
||||||
|
.get_playback_volume(SelemChannelId::mono())
|
||||||
|
.and_then(|volume| {
|
||||||
|
let volume = alsa_volume_to_f32(volume, min, max);
|
||||||
|
let volume = f32_to_alsa_volume(volume + diff, min, max);
|
||||||
|
master.set_playback_volume_all(volume)
|
||||||
|
})
|
||||||
|
.map_err(|e| alsa_error_to_io_error("Failed to inc/dec `Master` volume", &e))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BarWidgetImpl for Alsa {
|
||||||
|
fn wait(&mut self, _: &mut WaitContext) {}
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"volume"
|
||||||
|
}
|
||||||
|
fn value(&self) -> f32 {
|
||||||
|
match self.get_master_volume() {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => panic!("{}", e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn color(&self) -> Color {
|
||||||
|
Color::new(1.0, 1.0, 1.0, 1.0)
|
||||||
|
}
|
||||||
|
fn inc(&mut self, diff: f32) {
|
||||||
|
if let Err(e) = self.inc_master_volume(diff) {
|
||||||
|
panic!("{}", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn set(&mut self, abs: f32) {
|
||||||
|
if let Err(e) = self.set_master_volume(abs) {
|
||||||
|
panic!("{}", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn toggle(&mut self) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
#[cfg(feature = "alsa-widget")]
|
||||||
|
mod alsa_sound;
|
||||||
|
#[cfg(feature = "alsa-widget")]
|
||||||
|
pub use alsa_sound::Alsa;
|
||||||
|
|
||||||
|
#[cfg(feature = "pulseaudio-widget")]
|
||||||
|
mod pulse_sound;
|
||||||
|
#[cfg(feature = "pulseaudio-widget")]
|
||||||
|
pub use pulse_sound::PulseAudio;
|
||||||
@@ -0,0 +1,544 @@
|
|||||||
|
use crate::cmd::Cmd;
|
||||||
|
use crate::color::Color;
|
||||||
|
use crate::widget::WaitContext;
|
||||||
|
use crate::{
|
||||||
|
fonts::FontRef,
|
||||||
|
widgets::bar_widget::{BarWidget, BarWidgetImpl},
|
||||||
|
};
|
||||||
|
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::ops::Deref;
|
||||||
|
use std::rc::Rc;
|
||||||
|
use std::sync::mpsc::{channel, Sender};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::thread;
|
||||||
|
|
||||||
|
use libpulse_binding::callbacks::ListResult;
|
||||||
|
use libpulse_binding::context::{
|
||||||
|
introspect::ServerInfo, introspect::SinkInfo, subscribe::Facility, subscribe::InterestMaskSet,
|
||||||
|
subscribe::Operation as SubscribeOperation, Context, FlagSet, State as PulseState,
|
||||||
|
};
|
||||||
|
use libpulse_binding::mainloop::standard::IterateResult;
|
||||||
|
use libpulse_binding::mainloop::standard::Mainloop;
|
||||||
|
use libpulse_binding::proplist::{properties, Proplist};
|
||||||
|
use libpulse_binding::volume::{ChannelVolumes, Volume};
|
||||||
|
|
||||||
|
struct PulseAudioConnection {
|
||||||
|
mainloop: Rc<RefCell<Mainloop>>,
|
||||||
|
context: Rc<RefCell<Context>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct PulseAudioSinkInfo {
|
||||||
|
volume: ChannelVolumes,
|
||||||
|
mute: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct PulseAudioClient {
|
||||||
|
sender: Sender<PulseAudioClientRequest>,
|
||||||
|
default_sink: String,
|
||||||
|
sinks: HashMap<String, PulseAudioSinkInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum PulseAudioClientRequest {
|
||||||
|
GetDefaultDevice(Option<Sender<bool>>),
|
||||||
|
GetSinkInfoByIndex(Option<Sender<bool>>, u32),
|
||||||
|
GetSinkInfoByName(Option<Sender<bool>>, String),
|
||||||
|
SetSinkVolumeByName(Option<Sender<bool>>, String, ChannelVolumes),
|
||||||
|
SetSinkMuteByName(Option<Sender<bool>>, String, bool),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct PulseAudioSoundDeviceInner {
|
||||||
|
name: Option<String>,
|
||||||
|
volume: Option<ChannelVolumes>,
|
||||||
|
volume_avg: f32,
|
||||||
|
muted: bool,
|
||||||
|
default_sink: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct PulseAudioSoundDevice {
|
||||||
|
client: Arc<Mutex<PulseAudioClient>>,
|
||||||
|
inner: Arc<Mutex<PulseAudioSoundDeviceInner>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PulseAudioConnection {
|
||||||
|
fn new() -> Result<Self, ::std::io::Error> {
|
||||||
|
let mut proplist = Proplist::new().unwrap();
|
||||||
|
proplist
|
||||||
|
.set_str(properties::APPLICATION_NAME, "wldash")
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let mainloop = Rc::new(RefCell::new(Mainloop::new().unwrap()));
|
||||||
|
|
||||||
|
let context = Rc::new(RefCell::new(
|
||||||
|
Context::new_with_proplist(mainloop.borrow().deref(), "wldash_context", &proplist)
|
||||||
|
.unwrap(),
|
||||||
|
));
|
||||||
|
|
||||||
|
context
|
||||||
|
.borrow_mut()
|
||||||
|
.connect(None, FlagSet::NOFLAGS, None)
|
||||||
|
.map_err(|_e| {
|
||||||
|
::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
"unable to connect to pulseaudio context",
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let mut connection = PulseAudioConnection { mainloop, context };
|
||||||
|
|
||||||
|
// Wait for context to be ready
|
||||||
|
loop {
|
||||||
|
connection.iterate(false)?;
|
||||||
|
match connection.context.borrow().get_state() {
|
||||||
|
PulseState::Ready => {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
PulseState::Failed | PulseState::Terminated => {}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(connection)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn iterate(&mut self, blocking: bool) -> Result<(), ::std::io::Error> {
|
||||||
|
match self.mainloop.borrow_mut().iterate(blocking) {
|
||||||
|
IterateResult::Quit(_) | IterateResult::Err(_) => Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
"unable to iterate pulseaudio state",
|
||||||
|
)),
|
||||||
|
IterateResult::Success(_) => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PulseAudioClient {
|
||||||
|
fn new<F>(listener: F) -> Result<Arc<Mutex<Self>>, ::std::io::Error>
|
||||||
|
where
|
||||||
|
F: Fn(Arc<Mutex<Self>>) -> (),
|
||||||
|
F: Send + 'static + Clone,
|
||||||
|
{
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
|
||||||
|
let client = Arc::new(Mutex::new(PulseAudioClient {
|
||||||
|
sender: tx,
|
||||||
|
default_sink: "@DEFAULT_SINK@".to_string(),
|
||||||
|
sinks: HashMap::new(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
let loop_client = client.clone();
|
||||||
|
let (tx1, rx1) = channel();
|
||||||
|
let _ = thread::Builder::new()
|
||||||
|
.name("pa_writer".to_string())
|
||||||
|
.spawn(move || {
|
||||||
|
let mut conn = match PulseAudioConnection::new() {
|
||||||
|
Ok(v) => {
|
||||||
|
tx1.send(true).unwrap();
|
||||||
|
v
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
tx1.send(false).unwrap();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// make sure mainloop dispatched everything
|
||||||
|
for _ in 0..10 {
|
||||||
|
conn.iterate(false).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let cl = loop_client.clone();
|
||||||
|
let l = listener.clone();
|
||||||
|
match rx.recv() {
|
||||||
|
Err(_) => return,
|
||||||
|
Ok(req) => {
|
||||||
|
let mut introspector = conn.context.borrow_mut().introspect();
|
||||||
|
|
||||||
|
let done = Arc::new(Mutex::new(false));
|
||||||
|
let done_reader = done.clone();
|
||||||
|
let s = match req {
|
||||||
|
PulseAudioClientRequest::GetDefaultDevice(s) => {
|
||||||
|
introspector.get_server_info(move |info| {
|
||||||
|
*done.lock().unwrap() = true;
|
||||||
|
PulseAudioClient::server_info_callback(
|
||||||
|
cl.clone(),
|
||||||
|
l.clone(),
|
||||||
|
info,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
s
|
||||||
|
}
|
||||||
|
PulseAudioClientRequest::GetSinkInfoByIndex(s, index) => {
|
||||||
|
introspector.get_sink_info_by_index(index, move |res| {
|
||||||
|
*done.lock().unwrap() = true;
|
||||||
|
PulseAudioClient::sink_info_callback(
|
||||||
|
cl.clone(),
|
||||||
|
l.clone(),
|
||||||
|
res,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
s
|
||||||
|
}
|
||||||
|
PulseAudioClientRequest::GetSinkInfoByName(s, name) => {
|
||||||
|
introspector.get_sink_info_by_name(&name, move |res| {
|
||||||
|
*done.lock().unwrap() = true;
|
||||||
|
PulseAudioClient::sink_info_callback(
|
||||||
|
cl.clone(),
|
||||||
|
l.clone(),
|
||||||
|
res,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
s
|
||||||
|
}
|
||||||
|
PulseAudioClientRequest::SetSinkVolumeByName(s, name, volumes) => {
|
||||||
|
introspector.set_sink_volume_by_name(
|
||||||
|
&name,
|
||||||
|
&volumes,
|
||||||
|
Some(Box::new(move |_| {
|
||||||
|
*done.lock().unwrap() = true;
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
s
|
||||||
|
}
|
||||||
|
PulseAudioClientRequest::SetSinkMuteByName(s, name, mute) => {
|
||||||
|
introspector.set_sink_mute_by_name(
|
||||||
|
&name,
|
||||||
|
mute,
|
||||||
|
Some(Box::new(move |_| {
|
||||||
|
*done.lock().unwrap() = true;
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
s
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// send request and receive response
|
||||||
|
loop {
|
||||||
|
if *done_reader.lock().unwrap() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
conn.iterate(true).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(s) = s {
|
||||||
|
let _ = s.send(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// subscribe
|
||||||
|
let cl2 = client.clone();
|
||||||
|
let (tx2, rx2) = channel();
|
||||||
|
let _ = thread::Builder::new()
|
||||||
|
.name("pa_reader".to_string())
|
||||||
|
.spawn(move || {
|
||||||
|
let conn = match PulseAudioConnection::new() {
|
||||||
|
Ok(v) => {
|
||||||
|
tx2.send(true).unwrap();
|
||||||
|
v
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
tx2.send(false).unwrap();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// subcribe for events
|
||||||
|
conn.context
|
||||||
|
.borrow_mut()
|
||||||
|
.set_subscribe_callback(Some(Box::new(move |facility, operation, index| {
|
||||||
|
cl2.lock()
|
||||||
|
.unwrap()
|
||||||
|
.subscribe_callback(facility, operation, index)
|
||||||
|
})));
|
||||||
|
conn.context
|
||||||
|
.borrow_mut()
|
||||||
|
.subscribe(InterestMaskSet::SERVER | InterestMaskSet::SINK, |_| {});
|
||||||
|
|
||||||
|
conn.mainloop.borrow_mut().run().unwrap();
|
||||||
|
});
|
||||||
|
|
||||||
|
let pa_writer_res = rx1.recv().unwrap();
|
||||||
|
let pa_reader_res = rx2.recv().unwrap();
|
||||||
|
|
||||||
|
if !pa_writer_res || !pa_reader_res {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
"unable to start pulseaudio thread",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(client)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send(&self, request: PulseAudioClientRequest) -> Result<(), ::std::io::Error> {
|
||||||
|
self.sender.send(request).map_err(|_e| {
|
||||||
|
::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
"unable to send pulseaudio request",
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn server_info_callback<F>(s: Arc<Mutex<Self>>, listener: F, server_info: &ServerInfo)
|
||||||
|
where
|
||||||
|
F: Fn(Arc<Mutex<Self>>) -> (),
|
||||||
|
F: Send + 'static,
|
||||||
|
{
|
||||||
|
match server_info.default_sink_name.clone() {
|
||||||
|
None => {}
|
||||||
|
Some(default_sink) => {
|
||||||
|
(*s.lock().unwrap()).default_sink = default_sink.into();
|
||||||
|
listener(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sink_info_callback<F>(s: Arc<Mutex<Self>>, listener: F, result: ListResult<&SinkInfo>)
|
||||||
|
where
|
||||||
|
F: Fn(Arc<Mutex<Self>>) -> (),
|
||||||
|
F: Send + 'static,
|
||||||
|
{
|
||||||
|
match result {
|
||||||
|
ListResult::End | ListResult::Error => {}
|
||||||
|
ListResult::Item(sink_info) => match sink_info.name.clone() {
|
||||||
|
None => {}
|
||||||
|
Some(name) => {
|
||||||
|
let info = PulseAudioSinkInfo {
|
||||||
|
volume: sink_info.volume,
|
||||||
|
mute: sink_info.mute,
|
||||||
|
};
|
||||||
|
s.lock().unwrap().sinks.insert(name.into(), info);
|
||||||
|
listener(s);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn subscribe_callback(
|
||||||
|
&self,
|
||||||
|
facility: Option<Facility>,
|
||||||
|
_operation: Option<SubscribeOperation>,
|
||||||
|
index: u32,
|
||||||
|
) {
|
||||||
|
match facility {
|
||||||
|
None => {}
|
||||||
|
Some(facility) => match facility {
|
||||||
|
Facility::Server => {
|
||||||
|
let _ = self.send(PulseAudioClientRequest::GetDefaultDevice(None));
|
||||||
|
}
|
||||||
|
Facility::Sink => {
|
||||||
|
let _ = self.send(PulseAudioClientRequest::GetSinkInfoByIndex(None, index));
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PulseAudioSoundDevice {
|
||||||
|
fn new<F>(listener: F) -> Result<Self, ::std::io::Error>
|
||||||
|
where
|
||||||
|
F: Fn() -> (),
|
||||||
|
F: Send + 'static + Clone,
|
||||||
|
{
|
||||||
|
let inner = Arc::new(Mutex::new(PulseAudioSoundDeviceInner {
|
||||||
|
name: None,
|
||||||
|
volume: None,
|
||||||
|
volume_avg: 0.0,
|
||||||
|
muted: false,
|
||||||
|
default_sink: "@DEFAULT_SINK@".to_string(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
let cb_inner = inner.clone();
|
||||||
|
let client = PulseAudioClient::new(move |client| {
|
||||||
|
let mut inner = cb_inner.lock().unwrap();
|
||||||
|
inner.default_sink = client.lock().unwrap().default_sink.clone();
|
||||||
|
let name = inner
|
||||||
|
.name
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| inner.default_sink.clone());
|
||||||
|
let sink_info = match client.lock().unwrap().sinks.get(&name) {
|
||||||
|
None => return,
|
||||||
|
Some(sink_info) => (*sink_info).clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
inner.volume = Some(sink_info.volume);
|
||||||
|
inner.volume_avg = sink_info.volume.avg().0 as f32 / Volume::NORMAL.0 as f32;
|
||||||
|
inner.muted = sink_info.mute;
|
||||||
|
|
||||||
|
listener();
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let cl = client.clone();
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
{
|
||||||
|
let cl = client.lock().unwrap();
|
||||||
|
cl.send(PulseAudioClientRequest::GetDefaultDevice(Some(tx)))?;
|
||||||
|
}
|
||||||
|
rx.recv().unwrap();
|
||||||
|
let name = {
|
||||||
|
let cl = client.lock().unwrap();
|
||||||
|
cl.default_sink.to_string()
|
||||||
|
};
|
||||||
|
(*inner.lock().unwrap()).name = Some(name.clone());
|
||||||
|
let device = PulseAudioSoundDevice { client: cl, inner };
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
{
|
||||||
|
let cl = client.lock().unwrap();
|
||||||
|
cl.send(PulseAudioClientRequest::GetSinkInfoByName(Some(tx), name))?;
|
||||||
|
}
|
||||||
|
rx.recv().unwrap();
|
||||||
|
|
||||||
|
Ok(device)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn muted(&self) -> bool {
|
||||||
|
let inner = self.inner.lock().unwrap();
|
||||||
|
inner.muted
|
||||||
|
}
|
||||||
|
|
||||||
|
fn volume(&self) -> f32 {
|
||||||
|
let inner = self.inner.lock().unwrap();
|
||||||
|
inner.volume_avg
|
||||||
|
}
|
||||||
|
|
||||||
|
fn inc_volume(&mut self, step: f32) -> Result<(), ::std::io::Error> {
|
||||||
|
let mut inner = self.inner.lock().unwrap();
|
||||||
|
let mut volume = match inner.volume {
|
||||||
|
Some(volume) => volume,
|
||||||
|
None => {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
"unable to set volume",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// apply step to volumes
|
||||||
|
let step = (step * Volume::NORMAL.0 as f32).round() as i32;
|
||||||
|
if step > 0 {
|
||||||
|
volume.inc_clamp(Volume(step as u32), Volume::MAX);
|
||||||
|
} else {
|
||||||
|
volume.decrease(Volume(-step as u32));
|
||||||
|
}
|
||||||
|
|
||||||
|
let name = inner
|
||||||
|
.name
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| inner.default_sink.clone());
|
||||||
|
|
||||||
|
// update volumes
|
||||||
|
inner.volume = Some(volume);
|
||||||
|
inner.volume_avg = volume.avg().0 as f32 / Volume::NORMAL.0 as f32;
|
||||||
|
self.client
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.send(PulseAudioClientRequest::SetSinkVolumeByName(
|
||||||
|
None, name, volume,
|
||||||
|
))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_volume(&mut self, val: f32) -> Result<(), ::std::io::Error> {
|
||||||
|
let mut inner = self.inner.lock().unwrap();
|
||||||
|
let mut volume = match inner.volume {
|
||||||
|
Some(volume) => volume,
|
||||||
|
None => {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
"unable to set volume",
|
||||||
|
))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// apply step to volumes
|
||||||
|
volume.scale(Volume((val * Volume::NORMAL.0 as f32).round() as u32));
|
||||||
|
|
||||||
|
let name = inner
|
||||||
|
.name
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| inner.default_sink.clone());
|
||||||
|
|
||||||
|
// update volumes
|
||||||
|
inner.volume = Some(volume);
|
||||||
|
inner.volume_avg = volume.avg().0 as f32 / Volume::NORMAL.0 as f32;
|
||||||
|
self.client
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.send(PulseAudioClientRequest::SetSinkVolumeByName(
|
||||||
|
None, name, volume,
|
||||||
|
))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn toggle(&mut self) -> Result<(), ::std::io::Error> {
|
||||||
|
let mut inner = self.inner.lock().unwrap();
|
||||||
|
inner.muted = !inner.muted;
|
||||||
|
self.client
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.send(PulseAudioClientRequest::SetSinkMuteByName(
|
||||||
|
None,
|
||||||
|
inner
|
||||||
|
.name
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| inner.default_sink.clone()),
|
||||||
|
inner.muted,
|
||||||
|
))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct PulseAudio {
|
||||||
|
device: PulseAudioSoundDevice,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PulseAudio {
|
||||||
|
pub fn new(
|
||||||
|
font: FontRef,
|
||||||
|
font_size: f32,
|
||||||
|
length: u32,
|
||||||
|
sender: Sender<Cmd>,
|
||||||
|
) -> Result<Box<BarWidget>, ::std::io::Error> {
|
||||||
|
BarWidget::new(font, font_size, length, move |dirty| {
|
||||||
|
let device = PulseAudioSoundDevice::new(move || {
|
||||||
|
*dirty.lock().unwrap() = true;
|
||||||
|
sender.send(Cmd::Draw).unwrap();
|
||||||
|
})?;
|
||||||
|
Ok(Box::new(PulseAudio { device }))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BarWidgetImpl for PulseAudio {
|
||||||
|
fn wait(&mut self, _: &mut WaitContext) {}
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"volume"
|
||||||
|
}
|
||||||
|
fn value(&self) -> f32 {
|
||||||
|
self.device.volume()
|
||||||
|
}
|
||||||
|
fn color(&self) -> Color {
|
||||||
|
let muted = self.device.muted();
|
||||||
|
if muted {
|
||||||
|
Color::new(1.0, 1.0, 0.0, 1.0)
|
||||||
|
} else {
|
||||||
|
Color::new(1.0, 1.0, 1.0, 1.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn inc(&mut self, inc: f32) {
|
||||||
|
self.device.inc_volume(inc).unwrap();
|
||||||
|
}
|
||||||
|
fn set(&mut self, val: f32) {
|
||||||
|
self.device.set_volume(val).unwrap();
|
||||||
|
}
|
||||||
|
fn toggle(&mut self) {
|
||||||
|
self.device.toggle().unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
use crate::color::Color;
|
||||||
|
use crate::widget::WaitContext;
|
||||||
|
use crate::{
|
||||||
|
fonts::FontRef,
|
||||||
|
widgets::bar_widget::{BarWidget, BarWidgetImpl},
|
||||||
|
};
|
||||||
|
|
||||||
|
use std::fs;
|
||||||
|
use std::fs::OpenOptions;
|
||||||
|
use std::io::Write;
|
||||||
|
use std::io::{Error, ErrorKind};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
pub struct Backlight {
|
||||||
|
device_path: PathBuf,
|
||||||
|
cur_brightness: u64,
|
||||||
|
max_brightness: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_file_as_u64(path: &Path) -> Result<u64, Error> {
|
||||||
|
let mut s = fs::read_to_string(path)?;
|
||||||
|
s.pop();
|
||||||
|
s.parse::<u64>()
|
||||||
|
.map_err(|_e| Error::new(ErrorKind::Other, "unable to parse value"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn write_file_as_u64(path: &Path, value: u64) -> Result<(), Error> {
|
||||||
|
let mut file = OpenOptions::new().write(true).open(path)?;
|
||||||
|
file.write_fmt(format_args!("{}", value))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Backlight {
|
||||||
|
pub fn update(&mut self) -> Result<(), Error> {
|
||||||
|
self.cur_brightness = read_file_as_u64(self.device_path.join("brightness").as_path())?;
|
||||||
|
self.max_brightness = read_file_as_u64(self.device_path.join("max_brightness").as_path())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sync(&mut self) -> Result<(), Error> {
|
||||||
|
write_file_as_u64(
|
||||||
|
self.device_path.join("brightness").as_path(),
|
||||||
|
self.cur_brightness,
|
||||||
|
)?;
|
||||||
|
self.update()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn brightness(&self) -> f32 {
|
||||||
|
if self.cur_brightness > self.max_brightness {
|
||||||
|
// what.
|
||||||
|
return 1.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.cur_brightness as f32 / self.max_brightness as f32
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set(&mut self, val: f32) -> Result<(), Error> {
|
||||||
|
self.cur_brightness = (self.max_brightness as f32 * val) as u64;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add(&mut self, diff: f32) -> Result<(), Error> {
|
||||||
|
let inc = (self.max_brightness as f32 * diff) as i64;
|
||||||
|
|
||||||
|
self.cur_brightness = if self.cur_brightness as i64 + inc < 1 {
|
||||||
|
1
|
||||||
|
} else if self.cur_brightness as i64 + inc > self.max_brightness as i64 {
|
||||||
|
self.max_brightness
|
||||||
|
} else {
|
||||||
|
(self.cur_brightness as i64 + inc) as u64
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new<'a>(
|
||||||
|
path: &str,
|
||||||
|
font: FontRef<'a>,
|
||||||
|
font_size: f32,
|
||||||
|
length: u32,
|
||||||
|
) -> Result<Box<BarWidget<'a>>, Error> {
|
||||||
|
let mut dev = Backlight {
|
||||||
|
device_path: Path::new("/sys/class/backlight").to_path_buf().join(path),
|
||||||
|
cur_brightness: 0,
|
||||||
|
max_brightness: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
dev.update()?;
|
||||||
|
|
||||||
|
Ok(BarWidget::new_simple(
|
||||||
|
font,
|
||||||
|
font_size,
|
||||||
|
length,
|
||||||
|
Box::new(dev),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BarWidgetImpl for Backlight {
|
||||||
|
fn wait(&mut self, _: &mut WaitContext) {}
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"backlight"
|
||||||
|
}
|
||||||
|
fn value(&self) -> f32 {
|
||||||
|
self.brightness()
|
||||||
|
}
|
||||||
|
fn color(&self) -> Color {
|
||||||
|
Color::new(1.0, 1.0, 1.0, 1.0)
|
||||||
|
}
|
||||||
|
fn inc(&mut self, inc: f32) {
|
||||||
|
self.add(inc).unwrap();
|
||||||
|
match self.sync() {
|
||||||
|
Ok(val) => val,
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Error while trying to change brightness: {}", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn set(&mut self, val: f32) {
|
||||||
|
self.set(val).unwrap();
|
||||||
|
match self.sync() {
|
||||||
|
Ok(val) => val,
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Error while trying to change brightness: {}", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn toggle(&mut self) {
|
||||||
|
self.cur_brightness = if self.cur_brightness == 1 {
|
||||||
|
self.max_brightness
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
};
|
||||||
|
match self.sync() {
|
||||||
|
Ok(val) => val,
|
||||||
|
Err(err) => {
|
||||||
|
eprintln!("Error while trying to change brightness: {}", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
use crate::color::Color;
|
||||||
|
use crate::draw::{draw_bar, draw_box, Font};
|
||||||
|
use crate::{
|
||||||
|
fonts::FontRef,
|
||||||
|
widget::{DrawContext, DrawReport, KeyState, ModifiersState, WaitContext, Widget},
|
||||||
|
};
|
||||||
|
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
pub trait BarWidgetImpl {
|
||||||
|
fn wait(&mut self, ctx: &mut WaitContext);
|
||||||
|
fn name(&self) -> &str;
|
||||||
|
fn value(&self) -> f32;
|
||||||
|
fn color(&self) -> Color;
|
||||||
|
fn inc(&mut self, inc: f32);
|
||||||
|
fn set(&mut self, val: f32);
|
||||||
|
fn toggle(&mut self);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct BarWidget<'a> {
|
||||||
|
bar_impl: Box<dyn BarWidgetImpl + Send>,
|
||||||
|
font: Font<'a>,
|
||||||
|
font_size: u32,
|
||||||
|
length: u32,
|
||||||
|
dirty: Arc<Mutex<bool>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> BarWidget<'a> {
|
||||||
|
pub fn new_simple(
|
||||||
|
font: FontRef,
|
||||||
|
font_size: f32,
|
||||||
|
length: u32,
|
||||||
|
w: Box<dyn BarWidgetImpl + Send>,
|
||||||
|
) -> Box<BarWidget> {
|
||||||
|
let mut font = Font::new(font, font_size);
|
||||||
|
font.add_str_to_cache(w.name());
|
||||||
|
|
||||||
|
Box::new(BarWidget {
|
||||||
|
bar_impl: w,
|
||||||
|
dirty: Arc::new(Mutex::new(true)),
|
||||||
|
font,
|
||||||
|
font_size: font_size as u32,
|
||||||
|
length,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new<F>(
|
||||||
|
font: FontRef<'a>,
|
||||||
|
font_size: f32,
|
||||||
|
length: u32,
|
||||||
|
f: F,
|
||||||
|
) -> Result<Box<BarWidget>, ::std::io::Error>
|
||||||
|
where
|
||||||
|
F: FnOnce(Arc<Mutex<bool>>) -> Result<Box<dyn BarWidgetImpl + Send>, ::std::io::Error>,
|
||||||
|
F: Send + 'a + Clone,
|
||||||
|
{
|
||||||
|
let dirty = Arc::new(Mutex::new(true));
|
||||||
|
let im = f(dirty.clone())?;
|
||||||
|
|
||||||
|
let mut font = Font::new(font, font_size);
|
||||||
|
font.add_str_to_cache(im.name());
|
||||||
|
|
||||||
|
Ok(Box::new(BarWidget {
|
||||||
|
bar_impl: im,
|
||||||
|
dirty,
|
||||||
|
font,
|
||||||
|
font_size: font_size as u32,
|
||||||
|
length,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Widget for BarWidget<'a> {
|
||||||
|
fn wait(&mut self, ctx: &mut WaitContext) {
|
||||||
|
self.bar_impl.wait(ctx);
|
||||||
|
}
|
||||||
|
fn enter(&mut self) {}
|
||||||
|
fn leave(&mut self) {}
|
||||||
|
fn size(&self) -> (u32, u32) {
|
||||||
|
(self.length, self.font_size)
|
||||||
|
}
|
||||||
|
fn draw(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut DrawContext,
|
||||||
|
pos: (u32, u32),
|
||||||
|
expansion: (u32, u32),
|
||||||
|
) -> Result<DrawReport, ::std::io::Error> {
|
||||||
|
if self.length == 0 {
|
||||||
|
self.length = expansion.0;
|
||||||
|
}
|
||||||
|
let (width, height) = (self.length, self.font_size);
|
||||||
|
{
|
||||||
|
let mut d = self.dirty.lock().unwrap();
|
||||||
|
if !*d && !ctx.force {
|
||||||
|
return Ok(DrawReport::empty(width, height));
|
||||||
|
}
|
||||||
|
*d = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let buf = &mut ctx.buf.subdimensions((pos.0, pos.1, width, height))?;
|
||||||
|
buf.memset(ctx.bg);
|
||||||
|
|
||||||
|
let c = Color::new(1.0, 1.0, 1.0, 1.0);
|
||||||
|
self.font.draw_text(buf, ctx.bg, &c, self.bar_impl.name())?;
|
||||||
|
|
||||||
|
let c = self.bar_impl.color();
|
||||||
|
let bar_off = 5 * self.font_size;
|
||||||
|
let mut val = self.bar_impl.value();
|
||||||
|
draw_bar(
|
||||||
|
&mut buf.offset((bar_off, 0))?,
|
||||||
|
&c,
|
||||||
|
width - bar_off,
|
||||||
|
self.font_size,
|
||||||
|
val,
|
||||||
|
)?;
|
||||||
|
let mut iter = 1.0;
|
||||||
|
while val > 1.0 {
|
||||||
|
let c = &Color::new(0.75 / iter, 0.25 / iter, 0.25 / iter, 1.0);
|
||||||
|
val -= 1.0;
|
||||||
|
iter += 1.0;
|
||||||
|
draw_bar(
|
||||||
|
&mut buf.offset((bar_off, 0))?,
|
||||||
|
&c,
|
||||||
|
width - bar_off,
|
||||||
|
self.font_size,
|
||||||
|
val,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
draw_box(
|
||||||
|
&mut buf.offset((bar_off, 0))?,
|
||||||
|
&c,
|
||||||
|
(width - bar_off, self.font_size),
|
||||||
|
)?;
|
||||||
|
Ok(DrawReport {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
damage: vec![buf.get_signed_bounds()],
|
||||||
|
full_damage: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyboard_input(&mut self, _: u32, _: ModifiersState, _: KeyState, _: Option<String>) {}
|
||||||
|
fn mouse_click(&mut self, button: u32, (x, _): (u32, u32)) {
|
||||||
|
*self.dirty.lock().unwrap() = true;
|
||||||
|
match button {
|
||||||
|
272 => {
|
||||||
|
let offset = 5 * self.font_size;
|
||||||
|
if x > offset {
|
||||||
|
self.bar_impl
|
||||||
|
.set(((x - offset) + 1) as f32 / (self.length - offset) as f32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
273 => self.bar_impl.toggle(),
|
||||||
|
x => {
|
||||||
|
dbg!(x);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn mouse_scroll(&mut self, (_, y): (f64, f64), _: (u32, u32)) {
|
||||||
|
*self.dirty.lock().unwrap() = true;
|
||||||
|
self.bar_impl.inc(y as f32 / -800.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
use crate::cmd::Cmd;
|
||||||
|
use crate::color::Color;
|
||||||
|
use crate::widget::WaitContext;
|
||||||
|
use crate::{
|
||||||
|
fonts::FontRef,
|
||||||
|
widgets::bar_widget::{BarWidget, BarWidgetImpl},
|
||||||
|
};
|
||||||
|
|
||||||
|
use std::sync::mpsc::Sender;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use nix::poll::{PollFd, PollFlags};
|
||||||
|
|
||||||
|
fn get_upower_property(
|
||||||
|
con: &dbus::Connection,
|
||||||
|
device_path: &str,
|
||||||
|
property: &str,
|
||||||
|
) -> Result<dbus::Message, ::std::io::Error> {
|
||||||
|
let msg = dbus::Message::new_method_call(
|
||||||
|
"org.freedesktop.UPower",
|
||||||
|
device_path,
|
||||||
|
"org.freedesktop.DBus.Properties",
|
||||||
|
"Get",
|
||||||
|
)
|
||||||
|
.map_err(|_| {
|
||||||
|
::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
"could not send make dbus method call",
|
||||||
|
)
|
||||||
|
})?
|
||||||
|
.append2(
|
||||||
|
dbus::MessageItem::Str("org.freedesktop.UPower.Device".to_string()),
|
||||||
|
dbus::MessageItem::Str(property.to_string()),
|
||||||
|
);
|
||||||
|
|
||||||
|
con.send_with_reply_and_block(msg, 1000).map_err(|_| {
|
||||||
|
::std::io::Error::new(::std::io::ErrorKind::Other, "could not send dbus message")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// The widget is created on a different thread than where it will be used, so
|
||||||
|
// we need it to be Send. However, dbus::Connection has a void*, so it's not
|
||||||
|
// auto-derived. So, we make a small wrapper where we make it Send.
|
||||||
|
struct DbusConnection(dbus::Connection);
|
||||||
|
|
||||||
|
impl std::convert::AsRef<dbus::Connection> for DbusConnection {
|
||||||
|
fn as_ref(&self) -> &dbus::Connection {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl Send for DbusConnection {}
|
||||||
|
|
||||||
|
pub struct UpowerBattery {
|
||||||
|
device_path: String,
|
||||||
|
sender: Sender<Cmd>,
|
||||||
|
dirty: Arc<Mutex<bool>>,
|
||||||
|
state: UpowerBatteryState,
|
||||||
|
capacity: f64,
|
||||||
|
con: DbusConnection,
|
||||||
|
watch: dbus::Watch,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum UpowerBatteryState {
|
||||||
|
Charging,
|
||||||
|
Discharging,
|
||||||
|
Empty,
|
||||||
|
Full,
|
||||||
|
NotCharging,
|
||||||
|
Unknown,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UpowerBattery {
|
||||||
|
pub fn from_device(
|
||||||
|
dirty: Arc<Mutex<bool>>,
|
||||||
|
sender: Sender<Cmd>,
|
||||||
|
device: &str,
|
||||||
|
) -> Result<Self, ::std::io::Error> {
|
||||||
|
let con = dbus::Connection::get_private(dbus::BusType::System).map_err(|_| {
|
||||||
|
::std::io::Error::new(::std::io::ErrorKind::Other, "unable to open dbus")
|
||||||
|
})?;
|
||||||
|
let device_path = format!("/org/freedesktop/UPower/devices/{}", device);
|
||||||
|
|
||||||
|
let rule = format!(
|
||||||
|
"type='signal',\
|
||||||
|
path='{}',\
|
||||||
|
interface='org.freedesktop.DBus.Properties',\
|
||||||
|
member='PropertiesChanged'",
|
||||||
|
&device_path
|
||||||
|
);
|
||||||
|
con.add_match(&rule).map_err(|_| {
|
||||||
|
::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
"unable to add match rule to dbus connection",
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let upower_type: dbus::arg::Variant<u32> =
|
||||||
|
match get_upower_property(&con, &device_path, "Type")?.get1() {
|
||||||
|
Some(v) => v,
|
||||||
|
None => {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
"no such upower device",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// https://upower.freedesktop.org/docs/Device.html#Device:Type
|
||||||
|
if upower_type.0 != 2 {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
"UPower device is not a battery.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let capacity: f64 = match get_upower_property(&con, &device_path, "Percentage")?
|
||||||
|
.get1::<dbus::arg::Variant<f64>>()
|
||||||
|
{
|
||||||
|
Some(v) => v.0,
|
||||||
|
None => {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
"no such upower device",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let state: UpowerBatteryState = match get_upower_property(&con, &device_path, "State")?
|
||||||
|
.get1::<dbus::arg::Variant<u32>>()
|
||||||
|
{
|
||||||
|
Some(v) => match v.0 {
|
||||||
|
1 => UpowerBatteryState::Charging,
|
||||||
|
2 => UpowerBatteryState::Discharging,
|
||||||
|
3 => UpowerBatteryState::Empty,
|
||||||
|
4 => UpowerBatteryState::Full,
|
||||||
|
5 => UpowerBatteryState::NotCharging,
|
||||||
|
6 => UpowerBatteryState::Discharging,
|
||||||
|
_ => UpowerBatteryState::Unknown,
|
||||||
|
},
|
||||||
|
None => {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
"no such upower device",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let fds = con.watch_fds();
|
||||||
|
if fds.len() != 1 {
|
||||||
|
return Err(::std::io::Error::new(
|
||||||
|
::std::io::ErrorKind::Other,
|
||||||
|
"expected 1 watch fd from dbus",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(UpowerBattery {
|
||||||
|
device_path,
|
||||||
|
con: DbusConnection(con),
|
||||||
|
dirty,
|
||||||
|
sender,
|
||||||
|
capacity,
|
||||||
|
state,
|
||||||
|
watch: fds[0],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new(
|
||||||
|
font: FontRef,
|
||||||
|
font_size: f32,
|
||||||
|
length: u32,
|
||||||
|
sender: Sender<Cmd>,
|
||||||
|
) -> Result<Box<BarWidget>, ::std::io::Error> {
|
||||||
|
BarWidget::new(font, font_size, length, move |dirty| {
|
||||||
|
let d = UpowerBattery::from_device(dirty, sender, "DisplayDevice")?;
|
||||||
|
Ok(Box::new(d))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BarWidgetImpl for UpowerBattery {
|
||||||
|
fn wait(&mut self, ctx: &mut WaitContext) {
|
||||||
|
for _ in self
|
||||||
|
.con
|
||||||
|
.as_ref()
|
||||||
|
.watch_handle(self.watch.fd(), dbus::WatchEvent::Readable as u32)
|
||||||
|
{
|
||||||
|
let capacity = get_upower_property(self.con.as_ref(), &self.device_path, "Percentage")
|
||||||
|
.unwrap()
|
||||||
|
.get1::<dbus::arg::Variant<f64>>()
|
||||||
|
.unwrap()
|
||||||
|
.0;
|
||||||
|
let state = match get_upower_property(self.con.as_ref(), &self.device_path, "State")
|
||||||
|
.unwrap()
|
||||||
|
.get1::<dbus::arg::Variant<u32>>()
|
||||||
|
.unwrap()
|
||||||
|
.0
|
||||||
|
{
|
||||||
|
1 => UpowerBatteryState::Charging,
|
||||||
|
2 => UpowerBatteryState::Discharging,
|
||||||
|
3 => UpowerBatteryState::Empty,
|
||||||
|
4 => UpowerBatteryState::Full,
|
||||||
|
5 => UpowerBatteryState::NotCharging,
|
||||||
|
6 => UpowerBatteryState::Discharging,
|
||||||
|
_ => UpowerBatteryState::Unknown,
|
||||||
|
};
|
||||||
|
self.state = state;
|
||||||
|
self.capacity = capacity;
|
||||||
|
*self.dirty.lock().unwrap() = true;
|
||||||
|
self.sender.send(Cmd::Draw).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.fds
|
||||||
|
.push(PollFd::new(self.watch.fd(), PollFlags::POLLIN));
|
||||||
|
}
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"battery"
|
||||||
|
}
|
||||||
|
fn value(&self) -> f32 {
|
||||||
|
(self.capacity as f32) / 100.0
|
||||||
|
}
|
||||||
|
fn color(&self) -> Color {
|
||||||
|
match self.state {
|
||||||
|
UpowerBatteryState::Discharging | UpowerBatteryState::Unknown => {
|
||||||
|
if self.capacity > 10.0 {
|
||||||
|
Color::new(1.0, 1.0, 1.0, 1.0)
|
||||||
|
} else {
|
||||||
|
Color::new(1.0, 0.5, 0.0, 1.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
UpowerBatteryState::Charging | UpowerBatteryState::Full => {
|
||||||
|
Color::new(0.5, 1.0, 0.5, 1.0)
|
||||||
|
}
|
||||||
|
UpowerBatteryState::NotCharging | UpowerBatteryState::Empty => {
|
||||||
|
Color::new(1.0, 0.5, 0.5, 1.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn inc(&mut self, _: f32) {}
|
||||||
|
fn set(&mut self, _: f32) {}
|
||||||
|
fn toggle(&mut self) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
use crate::buffer::Buffer;
|
||||||
|
use crate::color::Color;
|
||||||
|
use crate::draw::Font;
|
||||||
|
use crate::{
|
||||||
|
fonts::FontRef,
|
||||||
|
widget::{DrawContext, DrawReport, KeyState, ModifiersState, WaitContext, Widget},
|
||||||
|
};
|
||||||
|
|
||||||
|
use chrono::{Datelike, NaiveDate, NaiveDateTime};
|
||||||
|
|
||||||
|
pub struct Calendar<'a> {
|
||||||
|
cur_date: NaiveDate,
|
||||||
|
dirty: bool,
|
||||||
|
offset: f64,
|
||||||
|
sections: u32,
|
||||||
|
font_size: u32,
|
||||||
|
calendar_cache: Font<'a>,
|
||||||
|
month_cache: Font<'a>,
|
||||||
|
year_cache: Font<'a>,
|
||||||
|
day_cache: Font<'a>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Calendar<'a> {
|
||||||
|
fn draw_month(
|
||||||
|
&self,
|
||||||
|
buf: &mut Buffer,
|
||||||
|
background_color: &Color,
|
||||||
|
orig: NaiveDate,
|
||||||
|
time: NaiveDate,
|
||||||
|
) -> Result<(i32, i32, i32, i32), ::std::io::Error> {
|
||||||
|
let mut time = time;
|
||||||
|
let mut y_off = 1;
|
||||||
|
let mut done = false;
|
||||||
|
|
||||||
|
let month_str = match time.month() {
|
||||||
|
1 => "January",
|
||||||
|
2 => "February",
|
||||||
|
3 => "March",
|
||||||
|
4 => "April",
|
||||||
|
5 => "May",
|
||||||
|
6 => "June",
|
||||||
|
7 => "July",
|
||||||
|
8 => "August",
|
||||||
|
9 => "September",
|
||||||
|
10 => "October",
|
||||||
|
11 => "November",
|
||||||
|
12 => "December",
|
||||||
|
_ => panic!("impossible value"),
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
// Draw the of the month
|
||||||
|
//
|
||||||
|
|
||||||
|
self.month_cache.draw_text(
|
||||||
|
buf,
|
||||||
|
background_color,
|
||||||
|
&Color::new(1.0, 1.0, 1.0, 1.0),
|
||||||
|
month_str,
|
||||||
|
)?;
|
||||||
|
if time.year() != orig.year() {
|
||||||
|
self.year_cache.draw_text(
|
||||||
|
&mut buf.offset((self.font_size * 20, 0))?,
|
||||||
|
background_color,
|
||||||
|
&Color::new(0.8, 0.8, 0.8, 1.0),
|
||||||
|
&format!("{:}", time.year()),
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Draw the week day
|
||||||
|
//
|
||||||
|
|
||||||
|
for idx in 1..8 {
|
||||||
|
let wk_chr = match idx {
|
||||||
|
1 => "MON",
|
||||||
|
2 => "TUE",
|
||||||
|
3 => "WED",
|
||||||
|
4 => "THU",
|
||||||
|
5 => "FRI",
|
||||||
|
6 => "SAT",
|
||||||
|
7 => "SUN",
|
||||||
|
_ => panic!("impossible value"),
|
||||||
|
};
|
||||||
|
|
||||||
|
self.day_cache.draw_text(
|
||||||
|
&mut buf.offset((
|
||||||
|
idx * self.font_size * 3 + self.font_size / 5,
|
||||||
|
y_off * self.font_size * 2 + self.font_size * 4,
|
||||||
|
))?,
|
||||||
|
background_color,
|
||||||
|
&Color::new(1.0, 1.0, 1.0, 1.0),
|
||||||
|
&wk_chr,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
y_off += 1;
|
||||||
|
|
||||||
|
while !done {
|
||||||
|
let mut x_pos = 0;
|
||||||
|
|
||||||
|
//
|
||||||
|
// Find the start of this week
|
||||||
|
//
|
||||||
|
let mut wkday = time.weekday();
|
||||||
|
while wkday != chrono::Weekday::Mon {
|
||||||
|
x_pos += 1;
|
||||||
|
wkday = wkday.pred();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// Draw the week number
|
||||||
|
//
|
||||||
|
let wk = time.iso_week();
|
||||||
|
self.calendar_cache.draw_text(
|
||||||
|
&mut buf.offset((0, y_off * self.font_size * 2 + self.font_size * 4))?,
|
||||||
|
background_color,
|
||||||
|
&Color::new(0.75, 0.75, 0.75, 1.0),
|
||||||
|
&format!("{:02}", wk.week()),
|
||||||
|
)?;
|
||||||
|
x_pos += 1;
|
||||||
|
|
||||||
|
//
|
||||||
|
// Draw the dates
|
||||||
|
//
|
||||||
|
while x_pos < 8 {
|
||||||
|
let c = if time.day() == orig.day() && time.month() == orig.month() {
|
||||||
|
Color::new(1.0, 1.0, 1.0, 1.0)
|
||||||
|
} else {
|
||||||
|
Color::new(0.5, 0.5, 0.5, 1.0)
|
||||||
|
};
|
||||||
|
|
||||||
|
self.calendar_cache.draw_text(
|
||||||
|
&mut buf.offset((
|
||||||
|
x_pos * self.font_size * 3,
|
||||||
|
y_off * self.font_size * 2 + self.font_size * 4,
|
||||||
|
))?,
|
||||||
|
background_color,
|
||||||
|
&c,
|
||||||
|
&format!("{:02}", time.day()),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
let t = time.with_day(time.day() + 1);
|
||||||
|
if t.is_none() {
|
||||||
|
done = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
time = t.unwrap();
|
||||||
|
x_pos += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
y_off += 1;
|
||||||
|
}
|
||||||
|
Ok(buf.get_signed_bounds())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Calendar<'a> {
|
||||||
|
pub fn new(
|
||||||
|
time: NaiveDateTime,
|
||||||
|
font_primary: FontRef<'a>,
|
||||||
|
font_secondary: FontRef<'a>,
|
||||||
|
font_size: f32,
|
||||||
|
sections: u32,
|
||||||
|
) -> Box<Calendar<'a>> {
|
||||||
|
let mut calendar_cache = Font::new(font_secondary, font_size * 2.0);
|
||||||
|
calendar_cache.add_str_to_cache("0123456789");
|
||||||
|
let mut month_cache = Font::new(font_primary, font_size * 4.0);
|
||||||
|
month_cache.add_str_to_cache("JanuryFebMchApilJgstSmOoNvD");
|
||||||
|
let mut year_cache = Font::new(font_primary, font_size * 1.5);
|
||||||
|
year_cache.add_str_to_cache("-0123456789");
|
||||||
|
let mut day_cache = Font::new(font_primary, font_size);
|
||||||
|
day_cache.add_str_to_cache("MONTUEWDHFRISA");
|
||||||
|
Box::new(Calendar {
|
||||||
|
cur_date: time.date(),
|
||||||
|
dirty: true,
|
||||||
|
offset: 0.0,
|
||||||
|
sections,
|
||||||
|
font_size: font_size as u32,
|
||||||
|
calendar_cache,
|
||||||
|
month_cache,
|
||||||
|
year_cache,
|
||||||
|
day_cache,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Widget for Calendar<'a> {
|
||||||
|
fn wait(&mut self, _: &mut WaitContext) {}
|
||||||
|
fn enter(&mut self) {}
|
||||||
|
fn leave(&mut self) {}
|
||||||
|
|
||||||
|
fn size(&self) -> (u32, u32) {
|
||||||
|
let cal_width = 7 * self.font_size * 3 + self.font_size * 2;
|
||||||
|
let cal_pad = self.font_size * 3;
|
||||||
|
(
|
||||||
|
cal_width * self.sections + cal_pad * (self.sections - 1),
|
||||||
|
(self.font_size as f32 * 21.5) as u32,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut DrawContext,
|
||||||
|
pos: (u32, u32),
|
||||||
|
_expansion: (u32, u32),
|
||||||
|
) -> Result<DrawReport, ::std::io::Error> {
|
||||||
|
let (width, height) = self.size();
|
||||||
|
if ctx.time.date() == self.cur_date && !ctx.force && !self.dirty {
|
||||||
|
return Ok(DrawReport::empty(width, height));
|
||||||
|
}
|
||||||
|
self.dirty = false;
|
||||||
|
self.cur_date = ctx.time.date();
|
||||||
|
|
||||||
|
let buf = &mut ctx.buf.subdimensions((pos.0, pos.1, width, height))?;
|
||||||
|
buf.memset(ctx.bg);
|
||||||
|
let time = ctx.time.date();
|
||||||
|
let mut t = time.with_day(1).unwrap();
|
||||||
|
let o = (self.offset / 100.0) as i32;
|
||||||
|
|
||||||
|
let cals = self.sections - 1;
|
||||||
|
let pre_cals = cals / 2;
|
||||||
|
for _ in 0..pre_cals {
|
||||||
|
t = t.pred_opt().unwrap().with_day(1).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
if o != 0 {
|
||||||
|
let mut month = (t.month() - 1) as i32 + o;
|
||||||
|
let mut year = t.year();
|
||||||
|
while month > 11 {
|
||||||
|
year += 1;
|
||||||
|
month -= 12;
|
||||||
|
}
|
||||||
|
while month < 0 {
|
||||||
|
year -= 1;
|
||||||
|
month += 12;
|
||||||
|
}
|
||||||
|
t = t
|
||||||
|
.with_year(year)
|
||||||
|
.unwrap()
|
||||||
|
.with_month((month + 1) as u32)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let cal_pad = 7 * self.font_size * 3 + self.font_size * 5;
|
||||||
|
for idx in 0..self.sections {
|
||||||
|
self.draw_month(&mut buf.offset((cal_pad * idx, 0))?, ctx.bg, time, t)?;
|
||||||
|
|
||||||
|
t = if t.month() == 12 {
|
||||||
|
t.with_year(t.year() + 1).unwrap().with_month(1).unwrap()
|
||||||
|
} else {
|
||||||
|
t.with_month(t.month() + 1).unwrap()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
Ok(DrawReport {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
damage: vec![buf.get_signed_bounds()],
|
||||||
|
full_damage: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyboard_input(&mut self, _: u32, _: ModifiersState, _: KeyState, _: Option<String>) {}
|
||||||
|
fn mouse_click(&mut self, _: u32, (x, _): (u32, u32)) {
|
||||||
|
let cal_pad = 7 * self.font_size * 3 + self.font_size * 5;
|
||||||
|
let cals = self.sections - 1;
|
||||||
|
let pre_cals = cals / 2;
|
||||||
|
if x < pre_cals * cal_pad {
|
||||||
|
self.offset -= 100.0;
|
||||||
|
} else if x >= (pre_cals + 1) * cal_pad {
|
||||||
|
self.offset += 100.0;
|
||||||
|
} else {
|
||||||
|
self.offset = 0.0;
|
||||||
|
}
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
fn mouse_scroll(&mut self, (_, y): (f64, f64), _: (u32, u32)) {
|
||||||
|
self.offset += y;
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
use crate::color::Color;
|
||||||
|
use crate::draw::Font;
|
||||||
|
use crate::{
|
||||||
|
fonts::FontRef,
|
||||||
|
widget::{DrawContext, DrawReport, KeyState, ModifiersState, WaitContext, Widget},
|
||||||
|
};
|
||||||
|
|
||||||
|
use chrono::{Duration, NaiveDateTime, Timelike};
|
||||||
|
|
||||||
|
pub struct Clock<'a> {
|
||||||
|
cur_time: NaiveDateTime,
|
||||||
|
clock_cache: Font<'a>,
|
||||||
|
size: f32,
|
||||||
|
digit: u32,
|
||||||
|
colon: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Clock<'a> {
|
||||||
|
pub fn new(time: NaiveDateTime, font: FontRef, size: f32) -> ::std::io::Result<Box<Clock>> {
|
||||||
|
let mut clock_cache = Font::new(font, size);
|
||||||
|
clock_cache.add_str_to_cache("0123456789:");
|
||||||
|
|
||||||
|
let digit = clock_cache.auto_widest("123456789")?;
|
||||||
|
let colon = clock_cache.auto_widest(":")?;
|
||||||
|
|
||||||
|
Ok(Box::new(Clock {
|
||||||
|
cur_time: time,
|
||||||
|
clock_cache,
|
||||||
|
size,
|
||||||
|
digit,
|
||||||
|
colon,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Widget for Clock<'a> {
|
||||||
|
fn wait(&mut self, ctx: &mut WaitContext) {
|
||||||
|
let target = (self.cur_time + Duration::seconds(60))
|
||||||
|
.with_second(0)
|
||||||
|
.unwrap()
|
||||||
|
.with_nanosecond(0)
|
||||||
|
.unwrap();
|
||||||
|
ctx.set_time(target);
|
||||||
|
}
|
||||||
|
fn enter(&mut self) {}
|
||||||
|
fn leave(&mut self) {}
|
||||||
|
fn size(&self) -> (u32, u32) {
|
||||||
|
(self.digit * 4 + self.colon, self.size.ceil() as u32)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut DrawContext,
|
||||||
|
pos: (u32, u32),
|
||||||
|
_expansion: (u32, u32),
|
||||||
|
) -> Result<DrawReport, ::std::io::Error> {
|
||||||
|
let (width, height) = self.size();
|
||||||
|
if !(ctx.time.date() != self.cur_time.date()
|
||||||
|
|| ctx.time.hour() != self.cur_time.hour()
|
||||||
|
|| ctx.time.minute() != self.cur_time.minute()
|
||||||
|
|| ctx.force)
|
||||||
|
{
|
||||||
|
return Ok(DrawReport::empty(width, height));
|
||||||
|
}
|
||||||
|
|
||||||
|
self.cur_time = ctx.time;
|
||||||
|
|
||||||
|
let buf = &mut ctx.buf.subdimensions((pos.0, pos.1, width, height))?;
|
||||||
|
buf.memset(ctx.bg);
|
||||||
|
|
||||||
|
let digit = self.digit;
|
||||||
|
let colon = self.colon;
|
||||||
|
self.clock_cache.draw_text_fixed_width(
|
||||||
|
buf,
|
||||||
|
ctx.bg,
|
||||||
|
&Color::new(1.0, 1.0, 1.0, 1.0),
|
||||||
|
&[digit, digit, colon, digit, digit],
|
||||||
|
&format!("{:02}:{:02}", ctx.time.hour(), ctx.time.minute()),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
Ok(DrawReport {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
damage: vec![(pos.0 as i32, pos.1 as i32, width as i32, height as i32)],
|
||||||
|
full_damage: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyboard_input(&mut self, _: u32, _: ModifiersState, _: KeyState, _: Option<String>) {}
|
||||||
|
fn mouse_click(&mut self, _: u32, _: (u32, u32)) {}
|
||||||
|
fn mouse_scroll(&mut self, _: (f64, f64), _: (u32, u32)) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
use crate::color::Color;
|
||||||
|
use crate::draw::Font;
|
||||||
|
use crate::{
|
||||||
|
fonts::FontRef,
|
||||||
|
widget::{DrawContext, DrawReport, KeyState, ModifiersState, WaitContext, Widget},
|
||||||
|
};
|
||||||
|
|
||||||
|
use chrono::{Datelike, NaiveDateTime};
|
||||||
|
|
||||||
|
pub struct Date<'a> {
|
||||||
|
cur_time: NaiveDateTime,
|
||||||
|
date_cache: Font<'a>,
|
||||||
|
size: f32,
|
||||||
|
ch_width: u32,
|
||||||
|
digit_width: u32,
|
||||||
|
spacing_width: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Date<'a> {
|
||||||
|
pub fn new(time: NaiveDateTime, font: FontRef, size: f32) -> ::std::io::Result<Box<Date>> {
|
||||||
|
let mut date_cache = Font::new(font, size);
|
||||||
|
let chs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||||
|
let digits = "0123456789,/ ";
|
||||||
|
let spacings = ",/ ";
|
||||||
|
|
||||||
|
date_cache.add_str_to_cache(chs);
|
||||||
|
date_cache.add_str_to_cache(digits);
|
||||||
|
date_cache.add_str_to_cache(spacings);
|
||||||
|
let ch_width = date_cache.auto_widest(chs)?;
|
||||||
|
let digit_width = date_cache.auto_widest(digits)?;
|
||||||
|
let spacing_width = date_cache.auto_widest(spacings)?;
|
||||||
|
|
||||||
|
Ok(Box::new(Date {
|
||||||
|
cur_time: time,
|
||||||
|
date_cache,
|
||||||
|
size,
|
||||||
|
ch_width,
|
||||||
|
digit_width,
|
||||||
|
spacing_width,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Widget for Date<'a> {
|
||||||
|
fn wait(&mut self, _: &mut WaitContext) {}
|
||||||
|
fn enter(&mut self) {}
|
||||||
|
fn leave(&mut self) {}
|
||||||
|
fn size(&self) -> (u32, u32) {
|
||||||
|
(
|
||||||
|
(3 * self.ch_width + 8 * self.digit_width + 4 * self.spacing_width) as u32,
|
||||||
|
self.size.ceil() as u32,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut DrawContext,
|
||||||
|
pos: (u32, u32),
|
||||||
|
_expansion: (u32, u32),
|
||||||
|
) -> Result<DrawReport, ::std::io::Error> {
|
||||||
|
let (width, height) = self.size();
|
||||||
|
|
||||||
|
if !(ctx.time.date() != self.cur_time.date() || ctx.force) {
|
||||||
|
return Ok(DrawReport::empty(width, height));
|
||||||
|
}
|
||||||
|
|
||||||
|
self.cur_time = ctx.time;
|
||||||
|
|
||||||
|
let buf = &mut ctx.buf.subdimensions((pos.0, pos.1, width, height))?;
|
||||||
|
buf.memset(ctx.bg);
|
||||||
|
self.date_cache.draw_text(
|
||||||
|
buf,
|
||||||
|
ctx.bg,
|
||||||
|
&Color::new(1.0, 1.0, 1.0, 1.0),
|
||||||
|
&format!(
|
||||||
|
"{:?}, {:02}/{:02}/{:4}",
|
||||||
|
ctx.time.weekday(),
|
||||||
|
ctx.time.day(),
|
||||||
|
ctx.time.month(),
|
||||||
|
ctx.time.year()
|
||||||
|
),
|
||||||
|
)?;
|
||||||
|
|
||||||
|
Ok(DrawReport {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
damage: vec![(pos.0 as i32, pos.1 as i32, width as i32, height as i32)],
|
||||||
|
full_damage: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyboard_input(&mut self, _: u32, _: ModifiersState, _: KeyState, _: Option<String>) {}
|
||||||
|
fn mouse_click(&mut self, _: u32, _: (u32, u32)) {}
|
||||||
|
fn mouse_scroll(&mut self, _: (f64, f64), _: (u32, u32)) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,509 @@
|
|||||||
|
use crate::buffer::Buffer;
|
||||||
|
use crate::cmd::Cmd;
|
||||||
|
use crate::color::Color;
|
||||||
|
use crate::desktop::{load_desktop_files, Desktop};
|
||||||
|
use crate::draw::Font;
|
||||||
|
use crate::{
|
||||||
|
fonts::FontRef,
|
||||||
|
widget::{DrawContext, DrawReport, KeyState, ModifiersState, WaitContext, Widget},
|
||||||
|
};
|
||||||
|
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::cmp::Ordering;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::process::Command;
|
||||||
|
use std::sync::mpsc::Sender;
|
||||||
|
|
||||||
|
use crate::data::Data;
|
||||||
|
use crate::keyboard::keysyms;
|
||||||
|
use fuzzy_matcher::skim::SkimMatcherV2;
|
||||||
|
use fuzzy_matcher::FuzzyMatcher;
|
||||||
|
use unicode_segmentation::UnicodeSegmentation;
|
||||||
|
|
||||||
|
pub struct Launcher<'a> {
|
||||||
|
cursor: usize,
|
||||||
|
options: Vec<Desktop>,
|
||||||
|
term_opener: String,
|
||||||
|
app_opener: String,
|
||||||
|
url_opener: String,
|
||||||
|
matches: Vec<Desktop>,
|
||||||
|
input: String,
|
||||||
|
result: Option<String>,
|
||||||
|
offset: usize,
|
||||||
|
font: RefCell<Font<'a>>,
|
||||||
|
font_size: u32,
|
||||||
|
length: u32,
|
||||||
|
dirty: bool,
|
||||||
|
tx: Sender<Cmd>,
|
||||||
|
counter: Data,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Launcher<'a> {
|
||||||
|
pub fn new(
|
||||||
|
font: FontRef,
|
||||||
|
font_size: f32,
|
||||||
|
length: u32,
|
||||||
|
listener: Sender<Cmd>,
|
||||||
|
app: String,
|
||||||
|
term: String,
|
||||||
|
url: String,
|
||||||
|
) -> Box<Launcher> {
|
||||||
|
Box::new(Launcher {
|
||||||
|
cursor: 0,
|
||||||
|
options: load_desktop_files(),
|
||||||
|
term_opener: term,
|
||||||
|
app_opener: app,
|
||||||
|
url_opener: url,
|
||||||
|
matches: vec![],
|
||||||
|
input: "".to_string(),
|
||||||
|
result: None,
|
||||||
|
offset: 0,
|
||||||
|
font: RefCell::new(Font::new(font, font_size)),
|
||||||
|
font_size: font_size as u32,
|
||||||
|
length,
|
||||||
|
dirty: true,
|
||||||
|
tx: listener,
|
||||||
|
counter: Data::load().unwrap_or_default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_launcher(
|
||||||
|
&self,
|
||||||
|
buf: &mut Buffer,
|
||||||
|
bg: &Color,
|
||||||
|
width: u32,
|
||||||
|
) -> Result<(), ::std::io::Error> {
|
||||||
|
let mut x_off = if !self.input.is_empty() {
|
||||||
|
let c = if self.matches.is_empty() {
|
||||||
|
Color::new(1.0, 0.5, 0.5, 1.0)
|
||||||
|
} else {
|
||||||
|
Color::new(1.0, 1.0, 1.0, 1.0)
|
||||||
|
};
|
||||||
|
|
||||||
|
let dim = self.font.borrow_mut().auto_draw_text_with_cursor(
|
||||||
|
buf,
|
||||||
|
bg,
|
||||||
|
&c,
|
||||||
|
&self.input,
|
||||||
|
self.cursor,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
dim.0 + self.font_size / 4
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut width_remaining: i32 = (width - x_off) as i32;
|
||||||
|
let fuzzy_matcher = SkimMatcherV2::default();
|
||||||
|
for (idx, m) in self.matches.iter().enumerate() {
|
||||||
|
let mut b = match buf.offset((x_off, 0)) {
|
||||||
|
Ok(b) => b,
|
||||||
|
Err(_) => break,
|
||||||
|
};
|
||||||
|
let size = if idx == self.offset {
|
||||||
|
let (_, indices) = fuzzy_matcher
|
||||||
|
.fuzzy_indices(&m.name.to_lowercase(), &self.input.to_lowercase())
|
||||||
|
.unwrap_or((0, vec![]));
|
||||||
|
|
||||||
|
let mut colors = Vec::with_capacity(m.name.len());
|
||||||
|
for pos in 0..m.name.len() {
|
||||||
|
if indices.contains(&pos) {
|
||||||
|
colors.push(Color::new(1.0, 1.0, 1.0, 1.0));
|
||||||
|
} else {
|
||||||
|
colors.push(Color::new(0.75, 0.75, 0.75, 1.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.font
|
||||||
|
.borrow_mut()
|
||||||
|
.auto_draw_text_individual_colors(&mut b, bg, &colors, &m.name)?
|
||||||
|
} else {
|
||||||
|
self.font.borrow_mut().auto_draw_text(
|
||||||
|
&mut b,
|
||||||
|
bg,
|
||||||
|
&Color::new(0.5, 0.5, 0.5, 1.0),
|
||||||
|
&m.name,
|
||||||
|
)?
|
||||||
|
};
|
||||||
|
|
||||||
|
x_off += size.0 + self.font_size / 2;
|
||||||
|
width_remaining -= (size.0 + self.font_size / 2) as i32;
|
||||||
|
|
||||||
|
if width_remaining < 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_calc(&self, buf: &mut Buffer, bg: &Color) -> Result<(), ::std::io::Error> {
|
||||||
|
let x_off = self
|
||||||
|
.font
|
||||||
|
.borrow_mut()
|
||||||
|
.auto_draw_text(buf, bg, &Color::new(1.0, 1.0, 0.0, 1.0), "=")?
|
||||||
|
.0
|
||||||
|
+ self.font_size / 4;
|
||||||
|
|
||||||
|
let x_off = if !self.input.is_empty() {
|
||||||
|
let dim = self.font.borrow_mut().auto_draw_text_with_cursor(
|
||||||
|
&mut buf.offset((x_off, 0))?,
|
||||||
|
bg,
|
||||||
|
&Color::new(1.0, 1.0, 1.0, 1.0),
|
||||||
|
&self.input[1..],
|
||||||
|
self.cursor - 1,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
x_off + dim.0 + self.font_size / 4
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Some(result) = &self.result {
|
||||||
|
self.font.borrow_mut().auto_draw_text(
|
||||||
|
&mut buf.offset((x_off, 0))?,
|
||||||
|
bg,
|
||||||
|
&Color::new(0.75, 0.75, 0.75, 1.0),
|
||||||
|
&format!(" = {:}", result),
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_shell(&self, buf: &mut Buffer, bg: &Color) -> Result<(), ::std::io::Error> {
|
||||||
|
let x_off = self
|
||||||
|
.font
|
||||||
|
.borrow_mut()
|
||||||
|
.auto_draw_text(
|
||||||
|
&mut buf.offset((0, 0))?,
|
||||||
|
bg,
|
||||||
|
&Color::new(1.0, 1.0, 0.0, 1.0),
|
||||||
|
"!",
|
||||||
|
)?
|
||||||
|
.0
|
||||||
|
+ self.font_size / 4;
|
||||||
|
|
||||||
|
if !self.input.is_empty() {
|
||||||
|
self.font.borrow_mut().auto_draw_text_with_cursor(
|
||||||
|
&mut buf.offset((x_off, 0))?,
|
||||||
|
bg,
|
||||||
|
&Color::new(1.0, 1.0, 1.0, 1.0),
|
||||||
|
&self.input[1..],
|
||||||
|
self.cursor - 1,
|
||||||
|
)?;
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn calc(s: &str) -> Result<String, String> {
|
||||||
|
rcalc_lib::parse::eval(s, &mut rcalc_lib::parse::CalcState::new())
|
||||||
|
.map(|x| format!("{}", x))
|
||||||
|
.map_err(|x| format!("{}", x))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wlcopy(s: &str) -> Result<(), String> {
|
||||||
|
let mut child = std::process::Command::new("wl-copy")
|
||||||
|
.stdin(std::process::Stdio::null())
|
||||||
|
.stdout(std::process::Stdio::null())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.arg(s)
|
||||||
|
.spawn()
|
||||||
|
.map_err(|_| "wl-copy not available".to_string())?;
|
||||||
|
child
|
||||||
|
.wait()
|
||||||
|
.map_err(|_| "unable to run wl-copy".to_string())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Matcher {
|
||||||
|
matches: HashMap<Desktop, i64>,
|
||||||
|
counter: Data,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Matcher {
|
||||||
|
fn new(counter: Data) -> Self {
|
||||||
|
Self {
|
||||||
|
matches: HashMap::new(),
|
||||||
|
counter,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_match(&mut self, dtop: Desktop, val: &str, input: &str, prio: f32) {
|
||||||
|
let fuzzy_matcher = SkimMatcherV2::default();
|
||||||
|
if let Some(ma) = fuzzy_matcher.fuzzy_match(val, input) {
|
||||||
|
let ma = ((ma as f32) * prio) as i64;
|
||||||
|
if let Some(ma_old) = self.matches.get(&dtop) {
|
||||||
|
// Skip over new matches for the same program that are worse
|
||||||
|
// than the one we already have.
|
||||||
|
if ma_old > &ma {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.matches.insert(dtop, ma);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn matches(&self) -> Vec<Desktop> {
|
||||||
|
let mut m = self
|
||||||
|
.matches
|
||||||
|
.iter()
|
||||||
|
.map(|(key, ma)| (*ma, key.clone()))
|
||||||
|
.collect::<Vec<(i64, Desktop)>>();
|
||||||
|
|
||||||
|
m.sort_by(|(ma1, d1), (ma2, d2)| {
|
||||||
|
let count1 = self.counter.entries.get(&d1.name).unwrap_or(&0);
|
||||||
|
let count2 = self.counter.entries.get(&d2.name).unwrap_or(&0);
|
||||||
|
|
||||||
|
if ma1 + count1 > ma2 + count2 {
|
||||||
|
Ordering::Less
|
||||||
|
} else if ma1 + count1 < ma2 + count2 {
|
||||||
|
Ordering::Greater
|
||||||
|
} else if d1.name.len() < d2.name.len() {
|
||||||
|
Ordering::Less
|
||||||
|
} else if d1.name.len() > d2.name.len() {
|
||||||
|
Ordering::Greater
|
||||||
|
} else {
|
||||||
|
d1.cmp(d2)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
m.into_iter().map(|(_, x)| x).collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Widget for Launcher<'a> {
|
||||||
|
fn wait(&mut self, _: &mut WaitContext) {}
|
||||||
|
fn enter(&mut self) {}
|
||||||
|
fn leave(&mut self) {
|
||||||
|
self.input = "".to_string();
|
||||||
|
self.cursor = 0;
|
||||||
|
self.offset = 0;
|
||||||
|
self.result = None;
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn size(&self) -> (u32, u32) {
|
||||||
|
(self.length, self.font_size)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw(
|
||||||
|
&mut self,
|
||||||
|
ctx: &mut DrawContext,
|
||||||
|
pos: (u32, u32),
|
||||||
|
expansion: (u32, u32),
|
||||||
|
) -> Result<DrawReport, ::std::io::Error> {
|
||||||
|
if self.length == 0 {
|
||||||
|
self.length = expansion.0;
|
||||||
|
}
|
||||||
|
let (width, height) = (self.length, self.font_size);
|
||||||
|
if !self.dirty && !ctx.force {
|
||||||
|
return Ok(DrawReport::empty(width, height));
|
||||||
|
}
|
||||||
|
self.dirty = false;
|
||||||
|
|
||||||
|
match self.input.chars().next() {
|
||||||
|
Some('=') => {
|
||||||
|
if self.input.len() > 1 {
|
||||||
|
match calc(&self.input.chars().skip(1).collect::<String>()) {
|
||||||
|
Ok(v) => self.result = Some(v),
|
||||||
|
Err(_) => self.result = None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some('!') => (),
|
||||||
|
_ => {
|
||||||
|
let mut matcher = Matcher::new(self.counter.clone());
|
||||||
|
|
||||||
|
for desktop in self.options.iter() {
|
||||||
|
matcher.try_match(
|
||||||
|
desktop.clone(),
|
||||||
|
&desktop.name.to_lowercase(),
|
||||||
|
&self.input.to_lowercase(),
|
||||||
|
1.0,
|
||||||
|
);
|
||||||
|
for keyword in desktop.keywords.iter() {
|
||||||
|
matcher.try_match(
|
||||||
|
desktop.clone(),
|
||||||
|
&keyword.to_lowercase(),
|
||||||
|
&self.input.to_lowercase(),
|
||||||
|
0.5,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.matches = matcher.matches();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let buf = &mut ctx.buf.subdimensions((pos.0, pos.1, width, height))?;
|
||||||
|
buf.memset(ctx.bg);
|
||||||
|
|
||||||
|
match self.input.chars().next() {
|
||||||
|
Some('=') => self.draw_calc(buf, ctx.bg),
|
||||||
|
Some('!') => self.draw_shell(buf, ctx.bg),
|
||||||
|
_ => self.draw_launcher(buf, ctx.bg, width),
|
||||||
|
}?;
|
||||||
|
|
||||||
|
Ok(DrawReport {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
damage: vec![buf.get_signed_bounds()],
|
||||||
|
full_damage: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyboard_input(
|
||||||
|
&mut self,
|
||||||
|
key: u32,
|
||||||
|
modifiers: ModifiersState,
|
||||||
|
_: KeyState,
|
||||||
|
interpreted: Option<String>,
|
||||||
|
) {
|
||||||
|
match key {
|
||||||
|
keysyms::XKB_KEY_u if modifiers.ctrl => self.leave(),
|
||||||
|
keysyms::XKB_KEY_a if modifiers.ctrl => {
|
||||||
|
self.cursor = 0;
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
keysyms::XKB_KEY_e if modifiers.ctrl => {
|
||||||
|
self.cursor = self.input.len();
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
keysyms::XKB_KEY_Home => {
|
||||||
|
self.cursor = 0;
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
keysyms::XKB_KEY_End => {
|
||||||
|
self.cursor = self.input.len();
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
keysyms::XKB_KEY_BackSpace => {
|
||||||
|
let mut indices: Vec<(usize, &str)> = self.input.grapheme_indices(true).collect();
|
||||||
|
if !indices.is_empty() && self.cursor > 0 {
|
||||||
|
self.cursor -= 1;
|
||||||
|
indices.remove(self.cursor);
|
||||||
|
self.input = indices.iter().fold("".into(), |acc, el| acc + el.1);
|
||||||
|
self.offset = 0;
|
||||||
|
self.result = None;
|
||||||
|
self.dirty = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
keysyms::XKB_KEY_Delete => {
|
||||||
|
let mut indices: Vec<(usize, &str)> = self.input.grapheme_indices(true).collect();
|
||||||
|
if !indices.is_empty() && self.cursor < indices.len() {
|
||||||
|
indices.remove(self.cursor);
|
||||||
|
self.input = indices.iter().fold("".into(), |acc, el| acc + el.1);
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
keysyms::XKB_KEY_Return => {
|
||||||
|
match self.input.chars().next() {
|
||||||
|
Some('=') => {
|
||||||
|
if let Some(ref v) = self.result {
|
||||||
|
let _ = wlcopy(&v);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some('!') => {
|
||||||
|
self.cursor = 0;
|
||||||
|
let _ = Command::new("sh")
|
||||||
|
.arg("-c")
|
||||||
|
.arg(self.input.chars().skip(1).collect::<String>())
|
||||||
|
.spawn();
|
||||||
|
self.tx.send(Cmd::Exit).unwrap();
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
if self.matches.len() > self.offset {
|
||||||
|
let d = &self.matches[self.offset];
|
||||||
|
if let Some(exec) = &d.exec {
|
||||||
|
let exec = exec
|
||||||
|
.replace("%f", "")
|
||||||
|
.replace("%F", "")
|
||||||
|
.replace("%u", "")
|
||||||
|
.replace("%U", "");
|
||||||
|
let prefix = if d.term {
|
||||||
|
&self.term_opener
|
||||||
|
} else {
|
||||||
|
&self.app_opener
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut lexed = shlex::split(&exec).unwrap();
|
||||||
|
let lexed = if !prefix.is_empty() {
|
||||||
|
let mut prefix = shlex::split(prefix).unwrap();
|
||||||
|
prefix.append(&mut lexed);
|
||||||
|
prefix
|
||||||
|
} else {
|
||||||
|
lexed
|
||||||
|
};
|
||||||
|
|
||||||
|
*self.counter.entries.entry(d.name.clone()).or_insert(0) += 1;
|
||||||
|
self.counter.save().expect("Unable to save data");
|
||||||
|
|
||||||
|
if !lexed.is_empty() {
|
||||||
|
let _ =
|
||||||
|
Command::new(lexed[0].clone()).args(&lexed[1..]).spawn();
|
||||||
|
self.tx.send(Cmd::Exit).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(url) = &d.url {
|
||||||
|
if !self.url_opener.is_empty() {
|
||||||
|
let mut lexed = shlex::split(&self.url_opener).unwrap();
|
||||||
|
lexed.push(url.to_string());
|
||||||
|
if !lexed.is_empty() {
|
||||||
|
let _ = Command::new(lexed[0].clone())
|
||||||
|
.args(&lexed[1..])
|
||||||
|
.spawn();
|
||||||
|
self.tx.send(Cmd::Exit).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
keysyms::XKB_KEY_Tab => {
|
||||||
|
if !self.matches.is_empty() && self.offset < self.matches.len() - 1 {
|
||||||
|
self.offset += 1;
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
keysyms::XKB_KEY_ISO_Left_Tab => {
|
||||||
|
if !self.matches.is_empty() && self.offset > 0 {
|
||||||
|
self.offset -= 1;
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
keysyms::XKB_KEY_Left => {
|
||||||
|
if self.cursor > 0 {
|
||||||
|
self.cursor -= 1;
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
keysyms::XKB_KEY_Right => {
|
||||||
|
if self.cursor < self.input.len() {
|
||||||
|
self.cursor += 1;
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
if let Some(v) = interpreted {
|
||||||
|
let indices: Vec<(usize, &str)> = self.input.grapheme_indices(true).collect();
|
||||||
|
if self.cursor == indices.len() {
|
||||||
|
self.input += &v;
|
||||||
|
} else {
|
||||||
|
let index_at = indices[self.cursor].0;
|
||||||
|
self.input.insert_str(index_at, &v);
|
||||||
|
}
|
||||||
|
self.cursor += 1;
|
||||||
|
self.offset = 0;
|
||||||
|
self.result = None;
|
||||||
|
self.dirty = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn mouse_click(&mut self, _: u32, _: (u32, u32)) {}
|
||||||
|
fn mouse_scroll(&mut self, _: (f64, f64), _: (u32, u32)) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
pub mod backlight;
|
||||||
|
pub mod bar_widget;
|
||||||
|
pub mod battery;
|
||||||
|
pub mod calendar;
|
||||||
|
pub mod clock;
|
||||||
|
pub mod date;
|
||||||
|
pub mod launcher;
|
||||||
|
|
||||||
|
#[cfg(any(feature = "alsa-widget", feature = "pulseaudio-widget"))]
|
||||||
|
pub mod audio;
|
||||||
Reference in New Issue
Block a user