Initial Release
This commit is contained in:
commit
8b3b95aae8
54 changed files with 5601 additions and 0 deletions
13
.gitignore
vendored
Normal file
13
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
.cargo
|
||||
target/
|
||||
vendor/
|
||||
vendor.tar
|
||||
debian/*
|
||||
!debian/source
|
||||
!debian/changelog
|
||||
!debian/control
|
||||
!debian/copyright
|
||||
!debian/pop-launcher.links
|
||||
!debian/pop-launcher.install
|
||||
!debian/pop-launcher-system76-power.install
|
||||
!debian/rules
|
||||
1396
Cargo.lock
generated
Normal file
1396
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
30
Cargo.toml
Normal file
30
Cargo.toml
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
[package]
|
||||
name = "pop-launcher"
|
||||
version = "1.0.0"
|
||||
authors = ["Michael Aaron Murphy <mmstick@pm.me>"]
|
||||
edition = "2018"
|
||||
|
||||
[workspace]
|
||||
members = ["plugins"]
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
async-io = "1"
|
||||
async-oneshot = "0.5"
|
||||
async-trait = "0.1"
|
||||
flume = "=0.10.7" # Restrict version to build with 1.47.0
|
||||
futures_codec = "0.4"
|
||||
futures-lite = "1"
|
||||
regex = "1.5"
|
||||
ron = "0.6"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
serde_with = "1"
|
||||
slab = "0.4"
|
||||
smol = "1.2.5"
|
||||
strsim = "0.10"
|
||||
toml = "0.5"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.2", features = ["fmt"] }
|
||||
gen-z = "0.1.0"
|
||||
async-executor = "1.4.1"
|
||||
674
LICENSE
Normal file
674
LICENSE
Normal file
|
|
@ -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>.
|
||||
100
Makefile
Normal file
100
Makefile
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
TARGET = debug
|
||||
DEBUG ?= 0
|
||||
|
||||
ifeq ($(DESTDIR),)
|
||||
BASE_PATH = $(HOME)/.local/
|
||||
LIB_PATH = $(BASE_PATH)/share
|
||||
else
|
||||
BASE_PATH = $(DESTDIR)/usr/
|
||||
LIB_PATH = $(BASE_PATH)/lib
|
||||
endif
|
||||
|
||||
LAUNCHER_DIR = $(LIB_PATH)/pop-launcher
|
||||
SCRIPTS_DIR = $(LAUNCHER_DIR)/scripts
|
||||
PLUGIN_DIR = $(LAUNCHER_DIR)/plugins
|
||||
DEFAULT_PLUGINS_BIN = $(PLUGIN_DIR)/pop-launcher-plugins
|
||||
BIN_DIR = $(BASE_PATH)/bin
|
||||
|
||||
PLUGINS=calc desktop_entries files find pop_shell pulse recent scripts terminal web
|
||||
|
||||
.PHONY = all clean install uninstall vendor
|
||||
|
||||
ifeq ($(DEBUG),0)
|
||||
TARGET = release
|
||||
ARGS += --release
|
||||
endif
|
||||
|
||||
VENDOR ?= 0
|
||||
ifneq ($(VENDOR),0)
|
||||
ARGS += --frozen --offline
|
||||
DESKTOP_ARGS += --frozen --offline
|
||||
endif
|
||||
|
||||
all: extract-vendor
|
||||
cargo build -p pop-launcher-plugins $(ARGS)
|
||||
cargo build $(ARGS)
|
||||
|
||||
clean:
|
||||
cargo clean
|
||||
|
||||
distclean:
|
||||
rm -rf .cargo vendor vendor.tar target
|
||||
|
||||
vendor:
|
||||
mkdir -p .cargo
|
||||
cargo vendor --sync plugins/Cargo.toml | head -n -1 > .cargo/config
|
||||
echo 'directory = "vendor"' >> .cargo/config
|
||||
tar pcf vendor.tar vendor
|
||||
rm -rf vendor
|
||||
|
||||
extract-vendor:
|
||||
ifeq ($(VENDOR),1)
|
||||
rm -rf vendor; tar pxf vendor.tar
|
||||
endif
|
||||
|
||||
install:
|
||||
for plugin in $(PLUGINS); do \
|
||||
dest=$(PLUGIN_DIR)/$${plugin}; \
|
||||
mkdir -p $${dest}; \
|
||||
install -Dm0644 plugins/src/plugins/$${plugin}/plugin.ron $${dest}/plugin.ron; \
|
||||
done
|
||||
|
||||
install -Dm0755 target/$(TARGET)/pop-launcher $(BIN_DIR)/pop-launcher
|
||||
install -Dm0755 target/$(TARGET)/pop-launcher-plugins $(DEFAULT_PLUGINS_BIN)
|
||||
|
||||
# Pop Shell Windows plugin
|
||||
ln -sf $(DEFAULT_PLUGINS_BIN) $(PLUGIN_DIR)/pop_shell/pop-shell
|
||||
|
||||
# Desktop Entries plugin
|
||||
ln -sf $(DEFAULT_PLUGINS_BIN) $(PLUGIN_DIR)/desktop_entries/desktop-entries
|
||||
|
||||
# Find plugin
|
||||
ln -sf $(DEFAULT_PLUGINS_BIN) $(PLUGIN_DIR)/find/find
|
||||
|
||||
# Scripts plugin
|
||||
ln -sf $(DEFAULT_PLUGINS_BIN) $(PLUGIN_DIR)/scripts/scripts
|
||||
|
||||
# Calculator plugin
|
||||
install -Dm0755 plugins/src/plugins/calc/calc.js $(PLUGIN_DIR)/calc
|
||||
install -Dm0644 plugins/src/plugins/calc/math.js $(PLUGIN_DIR)/calc
|
||||
|
||||
# Files plugin
|
||||
install -Dm0755 plugins/src/plugins/files/files.js $(PLUGIN_DIR)/files
|
||||
|
||||
# Recent plugin
|
||||
install -Dm0755 plugins/src/plugins/recent/recent.js $(PLUGIN_DIR)/recent
|
||||
|
||||
# Pulse plugin
|
||||
install -Dm0755 plugins/src/plugins/pulse/pulse.js $(PLUGIN_DIR)/pulse
|
||||
|
||||
# Terminal plugin
|
||||
install -Dm0755 plugins/src/plugins/terminal/terminal.js $(PLUGIN_DIR)/terminal
|
||||
|
||||
# Web plugin
|
||||
install -Dm0755 plugins/src/plugins/web/web.js $(PLUGIN_DIR)/web
|
||||
|
||||
# Scripts
|
||||
mkdir -p $(SCRIPTS_DIR)
|
||||
for script in $(PWD)/scripts/session/*.sh scripts/system76-power/*.sh; do \
|
||||
install -Dm0644 $${script} $(SCRIPTS_DIR); \
|
||||
done
|
||||
145
README.md
Normal file
145
README.md
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
# Pop Launcher
|
||||
|
||||
Modular IPC-based desktop launcher service, written in Rust. Desktop launchers may interface with this service via spawning the pop-launcher process and communicating to it via JSON IPC over the stdin and stdout pipes. The launcher service will also spawn plugins found in plugin directories on demand, based on the queries sent to the service.
|
||||
|
||||
Using IPC enables each plugin to isolate their data from other plugin processes and frontends that are interacting with them. If a plugin crashes, the launcher will continue functioning normally, gracefully cleaning up after the crashed process. Frontends and plugins may also be written in any language. The pop-launcher will do its part to schedule the execution of these plugins in parallel, on demand.
|
||||
|
||||
## Plugin Directories
|
||||
|
||||
- User-local plugins: `~/.local/share/pop-shell/plugins`
|
||||
- System-wide install for system administrators: `/etc/pop-shell/plugins`
|
||||
- Distribution packaging: `/usr/lib/pop-shell/plugins`
|
||||
|
||||
## Script Directories
|
||||
|
||||
- User-local plugins: `~/.local/share/pop-shell/scripts`
|
||||
- System-wide install for system administrators: `/etc/pop-shell/scripts`
|
||||
- Distribution packaging: `/usr/lib/pop-shell/scripts`
|
||||
|
||||
## JSON IPC
|
||||
|
||||
Whether implementing a frontend or a plugin, the JSON codec used by pop-launcher is line-based. Every line will contain a single JSON message That will be serialized or decoded as a `Request`, `PluginResponse`, or `Response`. These types can be referenced in [docs.rs](https://docs.rs/pop-launcher). IPC is based on standard input/output streams, so you should take care not to write logs to stdout.
|
||||
|
||||
### Frontend JSON IPC
|
||||
|
||||
The frontend will send `Request`s to the pop-launcher service through the stdin pipe. The stdout pipe will respond with `Response`s. It is ideal to design your frontend to accept responses asynchronously. Sending `Interrupt` or `Search` will cancel any active searches being performed, if the plugins that are still actively searching support cancellation.
|
||||
|
||||
### Plugin JSON IPC
|
||||
|
||||
Plugins will receive `Request`s from pop-launcher through their stdin pipe. They should respond with `PluginResponse` messages.
|
||||
|
||||
### Request
|
||||
|
||||
If you are writing a frontend, you are sending these events to the pop-launcher stdin pipe. If you are writing a plugin, the plugin will be receiving these events from its stdin.
|
||||
|
||||
```rust
|
||||
pub enum Request {
|
||||
/// Activate on the selected item
|
||||
Activate(Indice),
|
||||
/// Perform a tab completion from the selected item
|
||||
Complete(Indice),
|
||||
/// Request to end the service
|
||||
Exit,
|
||||
/// Requests to cancel any active searches
|
||||
Interrupt,
|
||||
/// Request to close the selected item
|
||||
Quit(Indice),
|
||||
/// Perform a search in our database
|
||||
Search(String),
|
||||
}
|
||||
```
|
||||
|
||||
#### JSON Equivalent
|
||||
|
||||
- `{ "Activate": number }`
|
||||
- `{ "Complete": number }`
|
||||
- `"Exit"`
|
||||
- `"Interrupt"`
|
||||
- `{ "Quit": number }`
|
||||
- `{ "Search": string }`
|
||||
|
||||
### PluginResponse
|
||||
|
||||
If you are writing a plugin, you should send these events to your stdout.
|
||||
|
||||
```rust
|
||||
pub enum PluginResponse {
|
||||
/// Append a new search item to the launcher
|
||||
Append(SearchMeta),
|
||||
/// Clear all results in the launcher list
|
||||
Clear,
|
||||
/// Close the launcher
|
||||
Close,
|
||||
// Notifies that a .desktop entry should be launched by the frontend
|
||||
DesktopEntry(PathBuf),
|
||||
/// Update the text in the launcher
|
||||
Fill(String),
|
||||
/// Indicoates that a plugin is finished with its queries
|
||||
Finished,
|
||||
}
|
||||
```
|
||||
|
||||
#### JSON Equivalent
|
||||
|
||||
- `{ "Append": SearchMeta }`,
|
||||
- `"Clear"`,
|
||||
- `"Close"`,
|
||||
- `{ "DesktopEntry": string }`
|
||||
- `{ "Fill": string }`
|
||||
- `"Finished"`
|
||||
|
||||
Where `SearchMeta` is:
|
||||
|
||||
```ts
|
||||
{
|
||||
id: number,
|
||||
name: string,
|
||||
description: string,
|
||||
keywords?: Array<string>,
|
||||
icon?: IconSource,
|
||||
exec?: string,
|
||||
window?: [number, number],
|
||||
}
|
||||
```
|
||||
|
||||
And `IconSource` is either:
|
||||
|
||||
- `{ "Name": string }`, where the name is a system icon, or an icon referred to by path
|
||||
- `{ "Mime": string }`, where the mime is a mime essence string, to display file-based icons
|
||||
|
||||
### Response
|
||||
|
||||
Those implementing frontends should listen for these events:
|
||||
|
||||
```rust
|
||||
pub enum Response {
|
||||
// An operation was performed and the frontend may choose to exit its process.
|
||||
Close,
|
||||
// Notifies that a .desktop entry should be launched by the frontend
|
||||
DesktopEntry(PathBuf),
|
||||
// The frontend should clear its search results and display a new list
|
||||
Update(Vec<SearchResult>),
|
||||
// An item was selected that resulted in a need to autofill the launcher
|
||||
Fill(String),
|
||||
}
|
||||
```
|
||||
|
||||
#### JSON Equivalent
|
||||
|
||||
- `"Close"`
|
||||
- `{ "DesktopEntry": string }`
|
||||
- `{ "Update": Array<SearchResult>}`
|
||||
- `{ "Fill": string }`
|
||||
|
||||
Where `SearchResult` is:
|
||||
|
||||
```ts
|
||||
{
|
||||
id: number,
|
||||
name: string,
|
||||
description: string,
|
||||
icon?: IconSource,
|
||||
category_icon?: IconSource,
|
||||
window?: [number, number]
|
||||
}
|
||||
```
|
||||
5
debian/changelog
vendored
Normal file
5
debian/changelog
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
pop-launcher (1.0.0) hirsute; urgency=medium
|
||||
|
||||
* Initial release.
|
||||
|
||||
-- Michael Aaron Murphy <mmstick@pm.me> Thu, 12 Aug 2021 22:01:44 +0200
|
||||
20
debian/control
vendored
Normal file
20
debian/control
vendored
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
Source: pop-launcher
|
||||
Section: utils
|
||||
Priority: optional
|
||||
Maintainer: Michael Aaron Murphy <mmstick@pm.me>
|
||||
Build-Depends:
|
||||
cargo,
|
||||
debhelper-compat (=10),
|
||||
rustc (>=1.47),
|
||||
Standards-Version: 4.1.1
|
||||
Homepage: https://github.com/pop-os/launcher
|
||||
|
||||
Package: pop-launcher
|
||||
Architecture: amd64
|
||||
Depends: ${misc:Depends}, ${shlibs:Depends}
|
||||
Description: Modular IPC-based desktop launcher service
|
||||
|
||||
Package: pop-launcher-system76-power
|
||||
Architecture: all
|
||||
Depends: ${misc:Depends}, ${shlibs:Depends}
|
||||
Description: System76 Power scripts for the launcher
|
||||
1
debian/pop-launcher-system76-power.install
vendored
Normal file
1
debian/pop-launcher-system76-power.install
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
/usr/lib/pop-launcher/scripts/graphics-*
|
||||
6
debian/pop-launcher.install
vendored
Normal file
6
debian/pop-launcher.install
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
/usr/bin/
|
||||
/usr/lib/pop-launcher/plugins/
|
||||
/usr/lib/pop-launcher/scripts/session-logout.sh
|
||||
/usr/lib/pop-launcher/scripts/session-reboot.sh
|
||||
/usr/lib/pop-launcher/scripts/session-shutdown.sh
|
||||
/usr/lib/pop-launcher/scripts/session-suspend.sh
|
||||
4
debian/pop-launcher.links
vendored
Normal file
4
debian/pop-launcher.links
vendored
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
/usr/lib/pop-launcher/plugins/pop-launcher-plugins /usr/lib/pop-launcher/plugins/desktop_entries/desktop-entries
|
||||
/usr/lib/pop-launcher/plugins/pop-launcher-plugins /usr/lib/pop-launcher/plugins/find/find
|
||||
/usr/lib/pop-launcher/plugins/pop-launcher-plugins /usr/lib/pop-launcher/plugins/pop_shell/pop-shell
|
||||
/usr/lib/pop-launcher/plugins/pop-launcher-plugins /usr/lib/pop-launcher/plugins/scripts/scripts
|
||||
24
debian/rules
vendored
Executable file
24
debian/rules
vendored
Executable file
|
|
@ -0,0 +1,24 @@
|
|||
#!/usr/bin/make -f
|
||||
|
||||
export VENDOR ?= 1
|
||||
CLEAN ?= 1
|
||||
DESTDIR=debian/tmp
|
||||
|
||||
%:
|
||||
dh $@ --with=systemd
|
||||
|
||||
override_dh_auto_clean:
|
||||
ifeq ($(CLEAN),1)
|
||||
make clean
|
||||
endif
|
||||
ifeq ($(VENDOR),1)
|
||||
if ! ischroot; then make vendor; fi
|
||||
endif
|
||||
|
||||
override_dh_auto_build:
|
||||
CARGO_HOME="$$(pwd)/target/cargo" make DESTDIR=$(DESTDIR)
|
||||
|
||||
override_dh_fixperms:
|
||||
dh_fixperms
|
||||
chmod +x debian/pop-launcher/usr/lib/pop-launcher/plugins/**/*.js
|
||||
chmod +x debian/pop-launcher/usr/lib/pop-launcher/scripts/*.sh
|
||||
22
plugins/Cargo.toml
Normal file
22
plugins/Cargo.toml
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
[package]
|
||||
name = "pop-launcher-plugins"
|
||||
version = "1.0.0"
|
||||
authors = ["Michael Aaron Murphy <mmstick@pm.me>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
flume = "=0.10.7"
|
||||
freedesktop-desktop-entry = "0.3"
|
||||
futures_codec = "0.4"
|
||||
futures-lite = "1.12"
|
||||
fork = "0.1"
|
||||
new_mime_guess = "3.0.0"
|
||||
pop-launcher = { path = "../" }
|
||||
serde = "1.0"
|
||||
serde_json = "1.0"
|
||||
smol = "1.2"
|
||||
strsim = "0.10"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = "0.2"
|
||||
zbus = "1.9"
|
||||
zvariant = "2.8"
|
||||
11
plugins/src/lib.rs
Normal file
11
plugins/src/lib.rs
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
use futures_lite::{AsyncWrite, AsyncWriteExt};
|
||||
|
||||
use pop_launcher::PluginResponse;
|
||||
|
||||
pub async fn send<W: AsyncWrite + Unpin>(tx: &mut W, response: PluginResponse) {
|
||||
if let Ok(mut bytes) = serde_json::to_string(&response) {
|
||||
bytes.push('\n');
|
||||
let _ = tx.write(bytes.as_bytes()).await;
|
||||
let _ = tx.flush().await;
|
||||
}
|
||||
}
|
||||
26
plugins/src/main.rs
Normal file
26
plugins/src/main.rs
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
mod plugins;
|
||||
|
||||
use smol::block_on;
|
||||
use std::io;
|
||||
|
||||
fn main() {
|
||||
tracing_subscriber::fmt()
|
||||
.with_writer(io::stderr)
|
||||
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
|
||||
.init();
|
||||
|
||||
std::env::args();
|
||||
|
||||
if let Some(plugin) = std::env::args().next() {
|
||||
let start = plugin.rfind('/').map(|v| v + 1).unwrap_or(0);
|
||||
match &plugin.as_str()[start..] {
|
||||
"desktop-entries" => block_on(plugins::desktop_entries::main()),
|
||||
"pop-shell" => block_on(plugins::pop_shell::main()),
|
||||
"find" => block_on(plugins::find::main()),
|
||||
"scripts" => block_on(plugins::scripts::main()),
|
||||
unknown => {
|
||||
eprintln!("unknown cmd: {}", unknown);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
99
plugins/src/plugins/calc/calc.js
Executable file
99
plugins/src/plugins/calc/calc.js
Executable file
|
|
@ -0,0 +1,99 @@
|
|||
#!/usr/bin/gjs
|
||||
|
||||
const { GLib, Gio } = imports.gi;
|
||||
|
||||
/** The directory that this script is executed from. */
|
||||
const SCRIPT_DIR = GLib.path_get_dirname(new Error().stack.split(':')[0].slice(1));
|
||||
|
||||
/** Add our directory so we can import modules from it. */
|
||||
imports.searchPath.push(SCRIPT_DIR)
|
||||
|
||||
const math = imports.math.math;
|
||||
math.config({number: 'BigNumber' });
|
||||
|
||||
const STDIN = new Gio.DataInputStream({ base_stream: new Gio.UnixInputStream({ fd: 0 }) })
|
||||
const STDOUT = new Gio.DataOutputStream({ base_stream: new Gio.UnixOutputStream({ fd: 1 }) })
|
||||
|
||||
class App {
|
||||
constructor() {
|
||||
this.last_query = ""
|
||||
this.last_value = ""
|
||||
}
|
||||
|
||||
search(input) {
|
||||
this.last_query = input.substr(1)
|
||||
|
||||
try {
|
||||
this.last_value = math.evaluate(this.last_query).toString()
|
||||
} catch (e) {
|
||||
this.last_value = this.last_query + ` x = ?`
|
||||
}
|
||||
|
||||
this.send({ "Append": {
|
||||
id: 0,
|
||||
name: this.last_value,
|
||||
description: '',
|
||||
icon: { Name: 'accessories-calculator' },
|
||||
}})
|
||||
|
||||
this.send("Finished")
|
||||
}
|
||||
|
||||
activate(_id) {
|
||||
this.send({ "Fill": '= ' + this.last_value })
|
||||
}
|
||||
|
||||
send(object) {
|
||||
STDOUT.write_bytes(new GLib.Bytes(JSON.stringify(object) + "\n"), null)
|
||||
STDOUT.flush(null)
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
/** @type {null | ByteArray} */
|
||||
let input_array
|
||||
|
||||
/** @type {string} */
|
||||
let input_str
|
||||
|
||||
/** @type {null | LauncherRequest} */
|
||||
let event
|
||||
|
||||
let app = new App()
|
||||
|
||||
mainloop:
|
||||
while (true) {
|
||||
try {
|
||||
[input_array,] = STDIN.read_line(null)
|
||||
} catch (e) {
|
||||
break
|
||||
}
|
||||
|
||||
input_str = imports.byteArray.toString(input_array)
|
||||
if ((event = parse_event(input_str)) !== null) {
|
||||
if ("Search" in event) {
|
||||
app.search(event.Search);
|
||||
} else if ("Activate" in event) {
|
||||
app.activate(event.Activate);
|
||||
} else if ("Exit" === event) {
|
||||
break mainloop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an IPC event received from STDIN
|
||||
* @param {string} input
|
||||
* @returns {null | LauncherRequest}
|
||||
*/
|
||||
function parse_event(input) {
|
||||
try {
|
||||
return JSON.parse(input)
|
||||
} catch (e) {
|
||||
log(`Input not valid JSON`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
47
plugins/src/plugins/calc/math.js
Normal file
47
plugins/src/plugins/calc/math.js
Normal file
File diff suppressed because one or more lines are too long
11
plugins/src/plugins/calc/plugin.ron
Normal file
11
plugins/src/plugins/calc/plugin.ron
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
(
|
||||
name: "Calculator",
|
||||
description: "Math.JS calculations",
|
||||
query: (
|
||||
regex: "^(=)+",
|
||||
help: "= ",
|
||||
isolate: true,
|
||||
),
|
||||
bin: (path: "calc.js"),
|
||||
icon: Name("x-office-spreadsheet")
|
||||
)
|
||||
216
plugins/src/plugins/desktop_entries/mod.rs
Normal file
216
plugins/src/plugins/desktop_entries/mod.rs
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
use freedesktop_desktop_entry::{default_paths, DesktopEntry, Iter as DesktopIter, PathSource};
|
||||
use futures_lite::{AsyncWrite, StreamExt};
|
||||
use pop_launcher::*;
|
||||
use pop_launcher_plugins::*;
|
||||
use std::borrow::Cow;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, Eq)]
|
||||
struct Item {
|
||||
appid: String,
|
||||
description: String,
|
||||
exec: String,
|
||||
icon: Option<String>,
|
||||
keywords: Option<Vec<String>>,
|
||||
name: String,
|
||||
path: PathBuf,
|
||||
prefers_non_default_gpu: bool,
|
||||
src: PathSource,
|
||||
terminal_command: bool,
|
||||
}
|
||||
|
||||
impl Hash for Item {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.name.hash(state);
|
||||
self.src.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Item {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.name == other.name && self.src == other.src
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn main() {
|
||||
let mut app = DesktopEntryPlugin::new(async_stdout());
|
||||
app.reload().await;
|
||||
|
||||
let mut requests = json_input_stream(async_stdin());
|
||||
|
||||
while let Some(result) = requests.next().await {
|
||||
match result {
|
||||
Ok(request) => {
|
||||
tracing::debug!("received request: {:?}", request);
|
||||
match request {
|
||||
Request::Activate(id) => app.activate(id).await,
|
||||
Request::Search(query) => app.search(&query).await,
|
||||
Request::Exit => break,
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
Err(why) => {
|
||||
tracing::error!("malformed JSON request: {}", why);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct DesktopEntryPlugin<W> {
|
||||
entries: Vec<Item>,
|
||||
locale: Option<String>,
|
||||
tx: W,
|
||||
}
|
||||
|
||||
impl<W: AsyncWrite + Unpin> DesktopEntryPlugin<W> {
|
||||
fn new(tx: W) -> Self {
|
||||
let lang = std::env::var("LANG").ok();
|
||||
|
||||
Self {
|
||||
entries: Vec::new(),
|
||||
locale: lang
|
||||
.as_ref()
|
||||
.and_then(|l| l.split('.').next())
|
||||
.map(String::from),
|
||||
tx,
|
||||
}
|
||||
}
|
||||
|
||||
async fn reload(&mut self) {
|
||||
self.entries.clear();
|
||||
|
||||
let locale = self.locale.as_ref().map(String::as_ref);
|
||||
|
||||
let mut deduplicator = std::collections::HashSet::new();
|
||||
|
||||
let current = current_desktop();
|
||||
let current = current
|
||||
.as_ref()
|
||||
.map(|x| x.split(':').collect::<Vec<&str>>());
|
||||
|
||||
for (src, path) in DesktopIter::new(default_paths()) {
|
||||
if let Ok(bytes) = std::fs::read_to_string(&path) {
|
||||
if let Ok(entry) = DesktopEntry::decode(&path, &bytes) {
|
||||
if entry.no_display() {
|
||||
let matched = current
|
||||
.as_ref()
|
||||
.zip(entry.only_show_in())
|
||||
.map(|(current, desktops)| {
|
||||
!desktops
|
||||
.to_ascii_lowercase()
|
||||
.split(';')
|
||||
.any(|desktop| current.iter().any(|c| *c == desktop))
|
||||
})
|
||||
.unwrap_or(false);
|
||||
|
||||
if matched {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((name, exec)) = entry.name(locale).zip(entry.exec()) {
|
||||
if let Some(exec) = exec.split_ascii_whitespace().next() {
|
||||
let item = Item {
|
||||
appid: entry.appid.to_owned(),
|
||||
name: name.to_owned(),
|
||||
description: entry.comment(locale).unwrap_or("").to_owned(),
|
||||
keywords: entry.keywords().map(|keywords| {
|
||||
keywords.split(';').map(String::from).collect()
|
||||
}),
|
||||
icon: entry.icon().map(|x| x.to_owned()),
|
||||
exec: exec.to_owned(),
|
||||
path: path.clone(),
|
||||
terminal_command: entry.terminal(),
|
||||
prefers_non_default_gpu: entry.prefers_non_default_gpu(),
|
||||
src,
|
||||
};
|
||||
|
||||
deduplicator.insert(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.entries.extend(deduplicator)
|
||||
}
|
||||
|
||||
async fn activate(&mut self, id: u32) {
|
||||
tracing::debug!("activate {} from {:?}", id, self.entries);
|
||||
if let Some(entry) = self.entries.get(id as usize) {
|
||||
let response = PluginResponse::DesktopEntry(entry.path.clone());
|
||||
send(&mut self.tx, response).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn search(&mut self, query: &str) {
|
||||
let query = query.to_ascii_lowercase();
|
||||
|
||||
let &mut Self {
|
||||
ref entries,
|
||||
ref mut tx,
|
||||
..
|
||||
} = self;
|
||||
|
||||
let mut items = Vec::with_capacity(16);
|
||||
|
||||
for (id, entry) in entries.iter().enumerate() {
|
||||
items.extend(entry.name.split_ascii_whitespace());
|
||||
|
||||
if let Some(keywords) = entry.keywords.as_ref() {
|
||||
items.extend(keywords.iter().map(String::as_str));
|
||||
}
|
||||
|
||||
items.push(entry.exec.as_str());
|
||||
|
||||
for search_interest in items.drain(..) {
|
||||
let search_interest = search_interest.to_ascii_lowercase();
|
||||
let append = search_interest.starts_with(&*query)
|
||||
|| search_interest.contains(&*query)
|
||||
|| strsim::damerau_levenshtein(&*query, &*search_interest) < 3;
|
||||
|
||||
if append {
|
||||
let response = PluginResponse::Append(SearchMeta {
|
||||
id: id as u32,
|
||||
name: entry.name.clone(),
|
||||
description: format!("{} - {}", path_string(&entry.src), entry.description),
|
||||
keywords: entry.keywords.clone(),
|
||||
icon: entry.icon.clone().map(Cow::Owned).map(IconSource::Name),
|
||||
exec: Some(entry.exec.clone()),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
send(tx, response).await;
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
send(tx, PluginResponse::Finished).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn current_desktop() -> Option<String> {
|
||||
std::env::var("XDG_CURRENT_DESKTOP").ok().map(|x| {
|
||||
let x = x.to_ascii_lowercase();
|
||||
if x == "unity" {
|
||||
"gnome".to_owned()
|
||||
} else {
|
||||
x
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn path_string(source: &PathSource) -> Cow<'static, str> {
|
||||
match source {
|
||||
PathSource::Local | PathSource::LocalDesktop => "Local".into(),
|
||||
PathSource::LocalFlatpak => "Flatpak".into(),
|
||||
PathSource::System => "System".into(),
|
||||
PathSource::SystemFlatpak => "Flatpak (System)".into(),
|
||||
PathSource::SystemSnap => "Snap (System)".into(),
|
||||
PathSource::Other(other) => Cow::Owned(other.clone()),
|
||||
}
|
||||
}
|
||||
6
plugins/src/plugins/desktop_entries/plugin.ron
Normal file
6
plugins/src/plugins/desktop_entries/plugin.ron
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
(
|
||||
name: "Desktop Entries",
|
||||
description: "Query applications by their .desktop entries",
|
||||
bin: (path: "desktop-entries"),
|
||||
icon: Name("new-window-symbolic"),
|
||||
)
|
||||
225
plugins/src/plugins/files/files.js
Executable file
225
plugins/src/plugins/files/files.js
Executable file
|
|
@ -0,0 +1,225 @@
|
|||
#!/usr/bin/gjs
|
||||
|
||||
const { GLib, Gio } = imports.gi;
|
||||
|
||||
const STDIN = new Gio.DataInputStream({ base_stream: new Gio.UnixInputStream({ fd: 0 }) })
|
||||
const STDOUT = new Gio.DataOutputStream({ base_stream: new Gio.UnixOutputStream({ fd: 1 }) })
|
||||
|
||||
class App {
|
||||
constructor() {
|
||||
/** @type Array<Selection> */
|
||||
this.selections = new Array()
|
||||
|
||||
/** @type string */
|
||||
this.parent = ""
|
||||
|
||||
/** @type string */
|
||||
this.last_query = ""
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs tab completion based on the last-given search query.
|
||||
*
|
||||
* @param {number} id
|
||||
*/
|
||||
complete(id) {
|
||||
let text
|
||||
|
||||
const selected = this.selections[id]
|
||||
if (selected) {
|
||||
text = selection_path(this.parent, selected)
|
||||
} else {
|
||||
text = this.last_query
|
||||
}
|
||||
|
||||
this.send({ "Fill": text })
|
||||
}
|
||||
|
||||
/**
|
||||
* Queries the plugin for results from this input
|
||||
*
|
||||
* @param {string} input
|
||||
*/
|
||||
search(input) {
|
||||
if (input.startsWith('~')) {
|
||||
input = GLib.get_home_dir() + input.substr(1)
|
||||
}
|
||||
|
||||
this.last_query = input
|
||||
|
||||
// Add `/` to query if the input is a directory
|
||||
this.last_query = (!input.endsWith('/') && Gio.file_new_for_path(input).query_file_type(0, null) === 2)
|
||||
? input + '/'
|
||||
: input
|
||||
|
||||
this.selections.splice(0)
|
||||
this.parent = GLib.path_get_dirname(this.last_query)
|
||||
|
||||
/** @type string */
|
||||
let base = GLib.path_get_basename(this.last_query)
|
||||
|
||||
const show_hidden = base.startsWith('.')
|
||||
|
||||
if (this.parent.endsWith(base)) base = ""
|
||||
|
||||
try {
|
||||
const dir = Gio.file_new_for_path(this.parent)
|
||||
if (dir.query_exists(null)) {
|
||||
const entries = dir.enumerate_children('standard::*', Gio.FileQueryInfoFlags.NONE, null);
|
||||
let entry;
|
||||
|
||||
while ((entry = entries.next_file(null)) !== null) {
|
||||
/** @type {string} */
|
||||
const name = entry.get_name()
|
||||
|
||||
if (base.length !== 0 && name.toLowerCase().indexOf(base.toLowerCase()) === -1) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (!show_hidden && name.startsWith('.')) continue
|
||||
|
||||
const content_type = entry.get_content_type()
|
||||
const directory = entry.get_file_type() === 2
|
||||
|
||||
this.selections.push({
|
||||
id: 0,
|
||||
name,
|
||||
description: GLib.format_size_for_display(entry.get_size()),
|
||||
content_type,
|
||||
directory
|
||||
})
|
||||
|
||||
if (this.selections.length === 20) break
|
||||
}
|
||||
}
|
||||
|
||||
const pattern_lower = this.last_query.toLowerCase()
|
||||
|
||||
this.selections
|
||||
.sort((a, b) => {
|
||||
const a_name = a.name.toLowerCase()
|
||||
const b_name = b.name.toLowerCase()
|
||||
|
||||
const a_includes = a_name.includes(pattern_lower)
|
||||
const b_includes = b_name.includes(pattern_lower)
|
||||
|
||||
return ((a_includes && b_includes) || (!a_includes && !b_includes)) ? (a_name > b_name ? 1 : 0) : a_includes ? -1 : b_includes ? 1 : 0;
|
||||
})
|
||||
|
||||
let id = 0
|
||||
for (const v of this.selections) {
|
||||
v.id = id
|
||||
id += 1
|
||||
}
|
||||
} catch (e) {
|
||||
log(`QUERY ERROR: ${e} `)
|
||||
}
|
||||
|
||||
for (const selection of this.selections) {
|
||||
this.send({ "Append": {
|
||||
id: selection.id,
|
||||
name: selection.name,
|
||||
description: selection.description,
|
||||
icon: { "Mime": selection.content_type }
|
||||
}})
|
||||
}
|
||||
|
||||
this.send("Finished")
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies an option that the user selected
|
||||
*
|
||||
* @param {number} id
|
||||
*/
|
||||
activate(id) {
|
||||
const selected = this.selections[id]
|
||||
|
||||
if (selected) {
|
||||
const path = selection_path(this.parent, selected)
|
||||
try {
|
||||
GLib.spawn_command_line_async(`xdg-open '${path}'`)
|
||||
} catch (e) {
|
||||
log(`xdg-open failed: ${e} `)
|
||||
}
|
||||
}
|
||||
|
||||
this.send("Close")
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends message back to Pop Shell
|
||||
*
|
||||
* @param {Object} object
|
||||
*/
|
||||
send(object) {
|
||||
STDOUT.write_bytes(new GLib.Bytes(JSON.stringify(object) + "\n"), null)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} parent
|
||||
* @param {Selection} selection
|
||||
* @returns {string}
|
||||
*/
|
||||
function selection_path(parent, selection) {
|
||||
let text = parent
|
||||
+ (parent.endsWith("/") ? "" : "/")
|
||||
+ selection.name
|
||||
|
||||
if (selection.directory) text += "/"
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
function main() {
|
||||
/** @type {null | ByteArray} */
|
||||
let input_array
|
||||
|
||||
/** @type {string} */
|
||||
let input_str
|
||||
|
||||
/** @type {null | LauncherRequest} */
|
||||
let event
|
||||
|
||||
let app = new App()
|
||||
|
||||
mainloop:
|
||||
while (true) {
|
||||
try {
|
||||
[input_array,] = STDIN.read_line(null)
|
||||
} catch (e) {
|
||||
break
|
||||
}
|
||||
|
||||
input_str = imports.byteArray.toString(input_array)
|
||||
if ((event = parse_event(input_str)) !== null) {
|
||||
if ("Search" in event) {
|
||||
app.search(event.Search)
|
||||
} else if ("Activate" in event) {
|
||||
app.activate(event.Activate)
|
||||
} else if ("Complete" in event) {
|
||||
app.complete(event.Complete)
|
||||
} else if ("Exit" === event) {
|
||||
break mainloop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an IPC event received from STDIN
|
||||
* @param {string} input
|
||||
* @returns {null | LauncherRequest}
|
||||
*/
|
||||
function parse_event(input) {
|
||||
try {
|
||||
return JSON.parse(input)
|
||||
} catch (e) {
|
||||
log(`Input not valid JSON`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
12
plugins/src/plugins/files/plugin.ron
Normal file
12
plugins/src/plugins/files/plugin.ron
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
(
|
||||
name: "File Navigation",
|
||||
description: "Navigate with tab autocomplete",
|
||||
query: (
|
||||
regex: "^(/|~).*",
|
||||
help: "~/",
|
||||
isolate: true,
|
||||
no_sort: true,
|
||||
),
|
||||
bin: (path: "files.js"),
|
||||
icon: Name("system-file-manager")
|
||||
)
|
||||
211
plugins/src/plugins/find/mod.rs
Normal file
211
plugins/src/plugins/find/mod.rs
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
use futures_lite::*;
|
||||
use pop_launcher::*;
|
||||
use pop_launcher_plugins::send;
|
||||
use smol::process::{ChildStdout, Command, Stdio};
|
||||
use std::borrow::Cow;
|
||||
use std::cell::Cell;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
|
||||
enum Event {
|
||||
Activate(u32),
|
||||
Search(String),
|
||||
}
|
||||
|
||||
pub async fn main() {
|
||||
let (event_tx, event_rx) = flume::unbounded::<Event>();
|
||||
|
||||
// Channel for cancelling searches that are in progress.
|
||||
let (interrupt_tx, interrupt_rx) = flume::bounded::<()>(0);
|
||||
|
||||
// Indicates if a search is being performed in the background.
|
||||
let active = Rc::new(Cell::new(false));
|
||||
|
||||
let mut app = SearchContext {
|
||||
search_results: Vec::with_capacity(128),
|
||||
active: active.clone(),
|
||||
interrupt_rx,
|
||||
out: async_stdout(),
|
||||
};
|
||||
|
||||
// Manages the external process, tracks search results, and executes activate requests
|
||||
let search_handler = async move {
|
||||
while let Ok(search) = event_rx.recv_async().await {
|
||||
match search {
|
||||
Event::Activate(id) => {
|
||||
if let Some(selection) = app.search_results.get(id as usize) {
|
||||
let path = selection.clone();
|
||||
let handle = smol::spawn(async move {
|
||||
xdg_open(&path).await;
|
||||
});
|
||||
|
||||
handle.detach();
|
||||
|
||||
send(&mut app.out, PluginResponse::Close).await;
|
||||
}
|
||||
}
|
||||
|
||||
Event::Search(search) => app.search(search).await,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Forwards requests to the search handler, and performs an interrupt as necessary.
|
||||
let request_handler = async move {
|
||||
let interrupt = || async {
|
||||
if active.get() && !interrupt_tx.is_full() {
|
||||
tracing::debug!("sending interrupt");
|
||||
let _ = interrupt_tx.send_async(()).await;
|
||||
}
|
||||
};
|
||||
|
||||
let mut requests = json_input_stream(async_stdin());
|
||||
|
||||
while let Some(result) = requests.next().await {
|
||||
match result {
|
||||
Ok(request) => match request {
|
||||
// Launch the default application with the selected file
|
||||
Request::Activate(id) => {
|
||||
event_tx.send_async(Event::Activate(id)).await?;
|
||||
}
|
||||
|
||||
// Interrupt any active searches being performed
|
||||
Request::Interrupt => interrupt().await,
|
||||
|
||||
// Schedule a new search process to be launched
|
||||
Request::Search(query) => {
|
||||
interrupt().await;
|
||||
|
||||
let query = match query.find(' ') {
|
||||
Some(pos) => query[pos..].trim_start(),
|
||||
None => &query,
|
||||
};
|
||||
|
||||
event_tx.send_async(Event::Search(query.to_owned())).await?;
|
||||
active.set(true);
|
||||
}
|
||||
|
||||
_ => (),
|
||||
},
|
||||
|
||||
Err(why) => {
|
||||
tracing::error!("malformed JSON input: {}", why);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok::<(), flume::SendError<Event>>(())
|
||||
};
|
||||
|
||||
let _ = future::zip(request_handler, search_handler).await;
|
||||
}
|
||||
|
||||
/// Maintains state for search requests
|
||||
struct SearchContext {
|
||||
pub active: Rc<Cell<bool>>,
|
||||
pub interrupt_rx: flume::Receiver<()>,
|
||||
pub out: smol::Unblock<io::Stdout>,
|
||||
pub search_results: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl SearchContext {
|
||||
/// Appends a new search result to the context.
|
||||
async fn append(&mut self, id: u32, line: String) {
|
||||
let name = line
|
||||
.rfind('/')
|
||||
.map(|pos| line[pos + 1..].to_owned())
|
||||
.unwrap_or_else(|| line.clone());
|
||||
|
||||
let description = ["~/", line.as_str()].concat();
|
||||
|
||||
let path = PathBuf::from(line);
|
||||
|
||||
let response = PluginResponse::Append(SearchMeta {
|
||||
id,
|
||||
description,
|
||||
name,
|
||||
icon: Some(IconSource::Mime(if path.is_dir() {
|
||||
Cow::Borrowed("inode/directory")
|
||||
} else if let Some(guess) = new_mime_guess::from_path(&path).first() {
|
||||
Cow::Owned(guess.essence_str().to_owned())
|
||||
} else {
|
||||
Cow::Borrowed("text/plain")
|
||||
})),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
send(&mut self.out, response).await;
|
||||
self.search_results.push(path);
|
||||
}
|
||||
|
||||
/// Submits the query to `fdfind` and actively monitors the search results while handling interrupts.
|
||||
async fn search(&mut self, search: String) {
|
||||
tracing::debug!("searching for {}", search);
|
||||
|
||||
let mut stdout = match query(&search).await {
|
||||
Ok(stdout) => futures_lite::io::BufReader::new(stdout).lines(),
|
||||
Err(why) => {
|
||||
tracing::error!("failed to spawn fdfind process: {}", why);
|
||||
self.active.set(false);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
self.search_results.clear();
|
||||
let mut id = 0;
|
||||
let mut append;
|
||||
|
||||
'stream: loop {
|
||||
let interrupt = async {
|
||||
let _ = self.interrupt_rx.recv_async().await;
|
||||
None
|
||||
};
|
||||
|
||||
match interrupt.or(stdout.next()).await {
|
||||
Some(result) => match result {
|
||||
Ok(line) => append = line,
|
||||
Err(why) => {
|
||||
tracing::error!("error on stdout line read: {}", why);
|
||||
break 'stream;
|
||||
}
|
||||
},
|
||||
|
||||
None => break 'stream,
|
||||
}
|
||||
|
||||
self.append(id, append).await;
|
||||
|
||||
id += 1;
|
||||
|
||||
if id == 10 {
|
||||
break 'stream;
|
||||
}
|
||||
}
|
||||
|
||||
send(&mut self.out, PluginResponse::Finished).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Submits the search query to `fdfind`, and returns its stdout pipe.
|
||||
async fn query(arg: &str) -> io::Result<ChildStdout> {
|
||||
let mut child = Command::new("fdfind")
|
||||
.arg(arg)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()?;
|
||||
|
||||
match child.stdout.take() {
|
||||
Some(stdout) => Ok(stdout),
|
||||
None => Err(io::Error::new(
|
||||
io::ErrorKind::BrokenPipe,
|
||||
"stdout pipe is missing",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Launches a file with its default appplication via `xdg-open`.
|
||||
async fn xdg_open(file: &Path) {
|
||||
let _ = Command::new("xdg-open").arg(file).spawn();
|
||||
}
|
||||
11
plugins/src/plugins/find/plugin.ron
Normal file
11
plugins/src/plugins/find/plugin.ron
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
(
|
||||
name: "Find",
|
||||
description: "Find files in the home folder",
|
||||
query: (
|
||||
regex: "^(find )+",
|
||||
help: "find ",
|
||||
isolate: true,
|
||||
),
|
||||
bin: (path: "find"),
|
||||
icon: Name("system-file-manager")
|
||||
)
|
||||
4
plugins/src/plugins/mod.rs
Normal file
4
plugins/src/plugins/mod.rs
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
pub mod desktop_entries;
|
||||
pub mod find;
|
||||
pub mod pop_shell;
|
||||
pub mod scripts;
|
||||
124
plugins/src/plugins/pop_shell/mod.rs
Normal file
124
plugins/src/plugins/pop_shell/mod.rs
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
use futures_lite::{AsyncWrite, AsyncWriteExt, StreamExt};
|
||||
use pop_launcher::*;
|
||||
use pop_launcher_plugins::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::convert::TryFrom;
|
||||
use zbus::Connection;
|
||||
use zvariant::{Signature, Type};
|
||||
|
||||
const DEST: &str = "com.System76.PopShell";
|
||||
const PATH: &str = "/com/System76/PopShell";
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct Item {
|
||||
entity: (u32, u32),
|
||||
name: String,
|
||||
description: String,
|
||||
}
|
||||
|
||||
impl Type for Item {
|
||||
fn signature() -> Signature<'static> {
|
||||
Signature::try_from("((uu)ss)").expect("bad dbus signature")
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn main() {
|
||||
let connection = match Connection::new_session() {
|
||||
Ok(conn) => conn,
|
||||
Err(_) => return,
|
||||
};
|
||||
|
||||
let mut app = App::new(connection, async_stdout());
|
||||
app.reload().await;
|
||||
|
||||
let mut requests = json_input_stream(async_stdin());
|
||||
while let Some(request) = requests.next().await {
|
||||
match request {
|
||||
Ok(request) => match request {
|
||||
Request::Activate(id) => app.activate(id).await,
|
||||
Request::Complete(_) | Request::Interrupt => (),
|
||||
Request::Quit(_id) => (),
|
||||
Request::Search(query) => app.search(&query).await,
|
||||
Request::Exit => break,
|
||||
},
|
||||
Err(why) => {
|
||||
tracing::error!("malformed JSON request: {}", why);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct App<W> {
|
||||
entries: Vec<Item>,
|
||||
connection: Connection,
|
||||
tx: W,
|
||||
}
|
||||
|
||||
impl<W: AsyncWrite + Unpin> App<W> {
|
||||
fn new(connection: Connection, tx: W) -> Self {
|
||||
Self {
|
||||
entries: Vec::new(),
|
||||
connection,
|
||||
tx,
|
||||
}
|
||||
}
|
||||
|
||||
fn call_method<A: Serialize + Type>(
|
||||
&mut self,
|
||||
method: &str,
|
||||
args: &A,
|
||||
) -> zbus::Result<zbus::Message> {
|
||||
self.connection
|
||||
.call_method(Some(DEST), PATH, Some(DEST), method, args)
|
||||
}
|
||||
|
||||
async fn reload(&mut self) {
|
||||
if let Ok(message) = self.call_method("WindowList", &()) {
|
||||
self.entries = message
|
||||
.body::<Vec<Item>>()
|
||||
.expect("pop-shell returned invalid WindowList response");
|
||||
}
|
||||
}
|
||||
|
||||
async fn activate(&mut self, id: u32) {
|
||||
if let Some(id) = self.entries.get(id as usize) {
|
||||
let entity = id.entity;
|
||||
let _ = self.call_method("WindowFocus", &(entity,));
|
||||
}
|
||||
}
|
||||
|
||||
async fn search(&mut self, query: &str) {
|
||||
let query = query.to_ascii_lowercase();
|
||||
let haystack = query.split_ascii_whitespace().collect::<Vec<&str>>();
|
||||
|
||||
fn contains_pattern(needle: &str, haystack: &[&str]) -> bool {
|
||||
let needle = needle.to_ascii_lowercase();
|
||||
haystack.iter().all(|h| needle.contains(h))
|
||||
}
|
||||
|
||||
for (id, item) in self.entries.iter().enumerate() {
|
||||
let retain = contains_pattern(&item.name, &haystack)
|
||||
|| contains_pattern(&item.description, &haystack);
|
||||
|
||||
if !retain {
|
||||
continue;
|
||||
}
|
||||
|
||||
send(
|
||||
&mut self.tx,
|
||||
PluginResponse::Append(SearchMeta {
|
||||
id: id as u32,
|
||||
name: item.name.clone(),
|
||||
description: item.description.clone(),
|
||||
icon: Some(IconSource::Window(item.entity)),
|
||||
window: Some(item.entity),
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
send(&mut self.tx, PluginResponse::Finished).await;
|
||||
let _ = self.tx.flush();
|
||||
}
|
||||
}
|
||||
7
plugins/src/plugins/pop_shell/plugin.ron
Normal file
7
plugins/src/plugins/pop_shell/plugin.ron
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
(
|
||||
name: "Pop Shell Windows",
|
||||
description: "Active windows controllable via Pop Shell",
|
||||
query: (persistent: true),
|
||||
bin: (path: "pop-shell"),
|
||||
icon: Name("focus-windows-symbolic"),
|
||||
)
|
||||
6
plugins/src/plugins/pulse/plugin.ron
Normal file
6
plugins/src/plugins/pulse/plugin.ron
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
(
|
||||
name: "PulseAudio Volume Control",
|
||||
description: "Control PulseAudio devices and volume",
|
||||
bin: (path: "pulse.js"),
|
||||
icon: Name("multimedia-volume-control")
|
||||
)
|
||||
216
plugins/src/plugins/pulse/pulse.js
Executable file
216
plugins/src/plugins/pulse/pulse.js
Executable file
|
|
@ -0,0 +1,216 @@
|
|||
#!/usr/bin/gjs
|
||||
|
||||
const { GLib, Gio } = imports.gi;
|
||||
|
||||
const STDIN = new Gio.DataInputStream({ base_stream: new Gio.UnixInputStream({ fd: 0 }) })
|
||||
const STDOUT = new Gio.DataOutputStream({ base_stream: new Gio.UnixOutputStream({ fd: 1 }) })
|
||||
|
||||
/**
|
||||
* @typedef {Object} Sink
|
||||
* @property {number} id
|
||||
* @property {string} description
|
||||
*/
|
||||
|
||||
/**
|
||||
* @returns {null | Array<Sink>}
|
||||
*/
|
||||
function pactl_sinks() {
|
||||
try {
|
||||
const resp = async_process(["pactl", "list", "sinks"])
|
||||
if (!resp) return null
|
||||
|
||||
const { proc, stdout } = resp
|
||||
|
||||
let sinks = new Array()
|
||||
let sink = {}
|
||||
|
||||
while (true) {
|
||||
const [bytes] = stdout.read_line(null)
|
||||
if (bytes === null) break
|
||||
|
||||
const line = imports.byteArray.toString(bytes)
|
||||
if (line.startsWith("Sink")) {
|
||||
sink.id = line.substr(6)
|
||||
} else if (line.includes("Description:")) {
|
||||
sink.description = line.split(' ').slice(1).join(' ')
|
||||
sinks.push({ ...sink })
|
||||
}
|
||||
}
|
||||
|
||||
return sinks
|
||||
} catch (e) {
|
||||
log(`error: ${e}`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
class App {
|
||||
constructor() {
|
||||
this.last_query = ""
|
||||
this.shell_only = false
|
||||
|
||||
this.default_selections = [
|
||||
{
|
||||
id: 0,
|
||||
name: "Toggle Mute",
|
||||
description: "Silence and unsilence the default audio sink",
|
||||
},
|
||||
|
||||
{
|
||||
id: 1,
|
||||
name: "Volume Up",
|
||||
description: "Raise volume 5%"
|
||||
},
|
||||
|
||||
{
|
||||
id: 2,
|
||||
name: "Volume Down",
|
||||
description: "Lower volume 5%"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
query(input) {
|
||||
const selections = filter_selections(this.default_selections, input.toLowerCase());
|
||||
for (const selection of selections) {
|
||||
this.send({ "Append": selection})
|
||||
}
|
||||
|
||||
this.send("Finished")
|
||||
}
|
||||
|
||||
submit(id) {
|
||||
let cmd = null
|
||||
|
||||
let sinks = pactl_sinks()
|
||||
|
||||
switch (id) {
|
||||
case 0:
|
||||
cmd = ["pactl set-sink-mute", "toggle"]
|
||||
break
|
||||
case 1:
|
||||
cmd = ["pactl set-sink-volume", "+5%"]
|
||||
break
|
||||
case 2:
|
||||
cmd = ["pactl set-sink-volume", "-5%"]
|
||||
}
|
||||
|
||||
if (cmd) {
|
||||
try {
|
||||
for (const { id } of sinks) {
|
||||
GLib.spawn_command_line_async(`${cmd[0]} ${id} ${cmd[1]}`)
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
log(`session command '${cmd}' failed: ${e}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
send(object) {
|
||||
STDOUT.write_bytes(new GLib.Bytes(JSON.stringify(object) + "\n"), null)
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
/** @type {null | ByteArray} */
|
||||
let input_array
|
||||
|
||||
/** @type {string} */
|
||||
let input_str
|
||||
|
||||
/** @type {null | LauncherRequest} */
|
||||
let event
|
||||
|
||||
let app = new App()
|
||||
|
||||
mainloop:
|
||||
while (true) {
|
||||
try {
|
||||
[input_array,] = STDIN.read_line(null)
|
||||
} catch (e) {
|
||||
break
|
||||
}
|
||||
|
||||
input_str = imports.byteArray.toString(input_array)
|
||||
if ((event = parse_event(input_str)) !== null) {
|
||||
if ("Exit" === event) {
|
||||
break mainloop
|
||||
} else if ("Search" in event) {
|
||||
app.query(event.Search)
|
||||
} else if ("Activate" in event) {
|
||||
app.submit(event.Activate)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an IPC event received from STDIN
|
||||
* @param {string} input
|
||||
* @returns {null | LauncherRequest}
|
||||
*/
|
||||
function parse_event(input) {
|
||||
try {
|
||||
return JSON.parse(input)
|
||||
} catch (e) {
|
||||
log(`Input not valid JSON`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Array<string>} argv
|
||||
* @returns {null | Process}
|
||||
*/
|
||||
function async_process(argv) {
|
||||
const { DataInputStream, SubprocessFlags, SubprocessLauncher } = Gio
|
||||
|
||||
try {
|
||||
const launcher = new SubprocessLauncher({
|
||||
flags: SubprocessFlags.STDIN_PIPE
|
||||
| SubprocessFlags.STDOUT_PIPE
|
||||
})
|
||||
|
||||
const proc = launcher.spawnv(argv)
|
||||
let stdout = new DataInputStream({
|
||||
base_stream: proc.get_stdout_pipe(),
|
||||
close_base_stream: true
|
||||
})
|
||||
|
||||
return { proc, stdout }
|
||||
} catch (e) {
|
||||
log(`failed to spawn process: ${argv}\n\tCaused by: ${e}`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function filter_selections(initial, input) {
|
||||
if (input.length === 0) return []
|
||||
let selections = initial.map(v => ({ ...v }))
|
||||
|
||||
let remove = new Array()
|
||||
for (let id = 0; id < selections.length; id += 1) {
|
||||
const { name, description } = selections[id]
|
||||
if (name.toLowerCase().includes(input) || description.toLowerCase().includes(input)) continue
|
||||
remove.push(id)
|
||||
}
|
||||
|
||||
for (const id of remove.reverse()) swap_remove(selections, id)
|
||||
|
||||
return selections
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Array<T>} array
|
||||
* @param {number} index
|
||||
* @returns {T | undefined}
|
||||
*/
|
||||
function swap_remove(array, index) {
|
||||
array[index] = array[array.length - 1];
|
||||
return array.pop();
|
||||
}
|
||||
|
||||
main()
|
||||
11
plugins/src/plugins/recent/plugin.ron
Normal file
11
plugins/src/plugins/recent/plugin.ron
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
(
|
||||
name: "Recent Documents",
|
||||
description: "Show recently-opened files",
|
||||
query: (
|
||||
regex: "^(recent)\\s.*",
|
||||
help: "recent ",
|
||||
isolate: true
|
||||
),
|
||||
bin: (path: "recent.js"),
|
||||
icon: Name("system-file-manager")
|
||||
)
|
||||
142
plugins/src/plugins/recent/recent.js
Executable file
142
plugins/src/plugins/recent/recent.js
Executable file
|
|
@ -0,0 +1,142 @@
|
|||
#!/usr/bin/gjs
|
||||
|
||||
const { GLib, Gio, Gtk } = imports.gi
|
||||
|
||||
const STDIN = new Gio.DataInputStream({ base_stream: new Gio.UnixInputStream({ fd: 0 }) })
|
||||
const STDOUT = new Gio.DataOutputStream({ base_stream: new Gio.UnixOutputStream({ fd: 1 }) })
|
||||
|
||||
class App {
|
||||
constructor() {
|
||||
this.last_query = ""
|
||||
this.manager = Gtk.RecentManager.get_default()
|
||||
this.results = new Array()
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {null | Array<RecentItem>}
|
||||
*/
|
||||
items() {
|
||||
const recent_items = this.manager.get_items()
|
||||
log(`got items`)
|
||||
|
||||
if (!recent_items) { return null }
|
||||
|
||||
const items = new Array()
|
||||
|
||||
for (const item of recent_items) {
|
||||
if (item.exists()) {
|
||||
items.push({
|
||||
display_name: item.get_display_name(),
|
||||
mime: item.get_mime_type(),
|
||||
uri: item.get_uri()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
query(input) {
|
||||
input = input.substr(input.indexOf(" ") + 1).trim()
|
||||
|
||||
try {
|
||||
const items = this.items()
|
||||
|
||||
if (items) {
|
||||
const normalized = input.toLowerCase()
|
||||
|
||||
this.results = items
|
||||
.filter(item => item.display_name.toLowerCase().includes(normalized))
|
||||
.sort((a, b) => a.display_name.localeCompare(b.display_name))
|
||||
.slice(0, 7)
|
||||
|
||||
log(`sorted`)
|
||||
|
||||
let id = 0
|
||||
|
||||
for (const item of this.results) {
|
||||
this.send({ "Append": {
|
||||
id,
|
||||
name: item.display_name,
|
||||
description: decodeURI(item.uri),
|
||||
icon: { Mime: item.mime }
|
||||
}})
|
||||
|
||||
id += 1
|
||||
}
|
||||
}
|
||||
} catch (why) {
|
||||
log(`query exception: ${why}`)
|
||||
}
|
||||
|
||||
this.send("Finished")
|
||||
}
|
||||
|
||||
submit(id) {
|
||||
const result = this.results[id]
|
||||
|
||||
if (result) {
|
||||
try {
|
||||
GLib.spawn_command_line_async(`xdg-open '${result.uri}'`)
|
||||
} catch (e) {
|
||||
log(`xdg-open failed: ${e}`)
|
||||
}
|
||||
}
|
||||
|
||||
this.send("Close")
|
||||
}
|
||||
|
||||
send(object) {
|
||||
STDOUT.write_bytes(new GLib.Bytes(JSON.stringify(object) + "\n"), null)
|
||||
STDOUT.flush(null)
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
/** @type {null | ByteArray} */
|
||||
let input_array
|
||||
|
||||
/** @type {string} */
|
||||
let input_str
|
||||
|
||||
/** @type {null | LauncherRequest} */
|
||||
let event
|
||||
|
||||
let app = new App()
|
||||
|
||||
mainloop:
|
||||
while (true) {
|
||||
try {
|
||||
[input_array,] = STDIN.read_line(null)
|
||||
} catch (e) {
|
||||
break
|
||||
}
|
||||
|
||||
input_str = imports.byteArray.toString(input_array)
|
||||
if ((event = parse_event(input_str)) !== null) {
|
||||
if ("Search" in event) {
|
||||
app.query(event.Search)
|
||||
} else if ("Activate" in event) {
|
||||
app.submit(event.Activate);
|
||||
} else if (event === "Exit") {
|
||||
break mainloop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an IPC event received from STDIN
|
||||
* @param {string} input
|
||||
* @returns {null | LauncherRequest}
|
||||
*/
|
||||
function parse_event(input) {
|
||||
try {
|
||||
return JSON.parse(input)
|
||||
} catch (e) {
|
||||
log(`Input not valid JSON`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
201
plugins/src/plugins/scripts/mod.rs
Normal file
201
plugins/src/plugins/scripts/mod.rs
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
use pop_launcher::*;
|
||||
use pop_launcher_plugins::*;
|
||||
|
||||
use flume::Sender;
|
||||
use futures_lite::{AsyncBufReadExt, StreamExt};
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::{
|
||||
io,
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, Stdio},
|
||||
};
|
||||
|
||||
const LOCAL_PATH: &str = ".local/share/pop-launcher/scripts";
|
||||
const SYSTEM_ADMIN_PATH: &str = "/etc/pop-launcher/scripts";
|
||||
const DISTRIBUTION_PATH: &str = "/usr/lib/pop-launcher/scripts";
|
||||
|
||||
pub async fn main() {
|
||||
let mut requests = json_input_stream(async_stdin());
|
||||
|
||||
let mut app = App::new();
|
||||
|
||||
app.reload().await;
|
||||
|
||||
while let Some(result) = requests.next().await {
|
||||
match result {
|
||||
Ok(response) => match response {
|
||||
Request::Activate(id) => app.activate(id).await,
|
||||
Request::Search(query) => app.search(&query).await,
|
||||
Request::Exit => break,
|
||||
_ => (),
|
||||
},
|
||||
|
||||
Err(why) => {
|
||||
tracing::error!("malformed JSON input: {}", why);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct App {
|
||||
scripts: Vec<ScriptInfo>,
|
||||
out: smol::Unblock<io::Stdout>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn new() -> Self {
|
||||
App {
|
||||
scripts: Vec::with_capacity(16),
|
||||
out: async_stdout(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn activate(&mut self, id: u32) {
|
||||
use fork::{daemon, Fork};
|
||||
|
||||
if let Ok(Fork::Child) = daemon(true, true) {
|
||||
if let Some(script) = self.scripts.get(id as usize) {
|
||||
let interpreter = script.interpreter.as_deref().unwrap_or("sh");
|
||||
|
||||
let why = dbg!(Command::new(interpreter).arg(script.path.as_os_str()))
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.exec();
|
||||
|
||||
tracing::error!("failed to exec: {}", why);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
send(&mut self.out, PluginResponse::Close).await;
|
||||
}
|
||||
|
||||
async fn reload(&mut self) {
|
||||
#[allow(deprecated)]
|
||||
let home = std::env::home_dir()
|
||||
.expect("user does not have home dir")
|
||||
.join(LOCAL_PATH);
|
||||
|
||||
let paths = &[
|
||||
&home,
|
||||
Path::new(SYSTEM_ADMIN_PATH),
|
||||
Path::new(DISTRIBUTION_PATH),
|
||||
];
|
||||
let (tx, rx) = flume::unbounded();
|
||||
|
||||
let script_sender = async move {
|
||||
for path in paths {
|
||||
load_from(path, tx.clone()).await;
|
||||
}
|
||||
};
|
||||
|
||||
let script_receiver = async {
|
||||
while let Ok(script) = rx.recv_async().await {
|
||||
tracing::debug!("appending script: {:?}", script);
|
||||
self.scripts.push(script);
|
||||
}
|
||||
};
|
||||
|
||||
futures_lite::future::zip(script_sender, script_receiver).await;
|
||||
}
|
||||
|
||||
async fn search(&mut self, query: &str) {
|
||||
let &mut Self {
|
||||
ref scripts,
|
||||
ref mut out,
|
||||
..
|
||||
} = self;
|
||||
for (id, script) in scripts.iter().enumerate() {
|
||||
let should_include = script.name.to_ascii_lowercase().contains(query)
|
||||
|| script.description.to_ascii_lowercase().contains(query)
|
||||
|| script.keywords.iter().any(|k| k.contains(query));
|
||||
|
||||
if should_include {
|
||||
send(
|
||||
out,
|
||||
PluginResponse::Append(SearchMeta {
|
||||
id: id as u32,
|
||||
name: script.name.clone(),
|
||||
description: script.description.clone(),
|
||||
icon: script
|
||||
.icon
|
||||
.as_ref()
|
||||
.map(|icon| IconSource::Name(icon.clone().into())),
|
||||
keywords: Some(script.keywords.clone()),
|
||||
..Default::default()
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
send(out, PluginResponse::Finished).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct ScriptInfo {
|
||||
interpreter: Option<String>,
|
||||
name: String,
|
||||
icon: Option<String>,
|
||||
path: PathBuf,
|
||||
keywords: Vec<String>,
|
||||
description: String,
|
||||
}
|
||||
|
||||
async fn load_from(path: &Path, tx: Sender<ScriptInfo>) {
|
||||
if let Ok(directory) = path.read_dir() {
|
||||
for entry in directory.filter_map(Result::ok) {
|
||||
let tx = tx.clone();
|
||||
let path = entry.path();
|
||||
|
||||
smol::spawn(async move {
|
||||
let mut file = match smol::fs::File::open(&path).await {
|
||||
Ok(file) => smol::io::BufReader::new(file).lines(),
|
||||
Err(why) => {
|
||||
tracing::error!("cannot open script at {}: {}", path.display(), why);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let mut info = ScriptInfo {
|
||||
path,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut first = true;
|
||||
|
||||
while let Some(Ok(line)) = file.next().await {
|
||||
if !line.starts_with('#') {
|
||||
break;
|
||||
}
|
||||
|
||||
let line = line[1..].trim();
|
||||
|
||||
if first {
|
||||
first = false;
|
||||
if let Some(interpreter) = line.strip_prefix('!') {
|
||||
info.interpreter = Some(interpreter.to_owned());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(stripped) = line.strip_prefix("name:") {
|
||||
info.name = stripped.trim_start().to_owned();
|
||||
} else if let Some(stripped) = line.strip_prefix("description:") {
|
||||
info.description = stripped.trim_start().to_owned();
|
||||
} else if let Some(stripped) = line.strip_prefix("icon:") {
|
||||
info.icon = Some(stripped.trim_start().to_owned());
|
||||
} else if let Some(stripped) = line.strip_prefix("keywords:") {
|
||||
info.keywords =
|
||||
stripped.trim_start().split(' ').map(String::from).collect();
|
||||
}
|
||||
}
|
||||
|
||||
let _ = tx.send_async(info).await;
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
}
|
||||
}
|
||||
6
plugins/src/plugins/scripts/plugin.ron
Normal file
6
plugins/src/plugins/scripts/plugin.ron
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
(
|
||||
name: "Scripts",
|
||||
description: "Shell scripts as launcher options",
|
||||
bin: (path: "scripts"),
|
||||
icon: Name("utilities-terminal"),
|
||||
)
|
||||
11
plugins/src/plugins/terminal/plugin.ron
Normal file
11
plugins/src/plugins/terminal/plugin.ron
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
(
|
||||
name: "Terminal Commands",
|
||||
description: "Run commands in a terminal",
|
||||
query: (
|
||||
regex: "^(:|t:|run ).*",
|
||||
help: "run ",
|
||||
isolate: true,
|
||||
),
|
||||
bin: (path: "terminal.js"),
|
||||
icon: Name("utilities-terminal"),
|
||||
)
|
||||
112
plugins/src/plugins/terminal/terminal.js
Executable file
112
plugins/src/plugins/terminal/terminal.js
Executable file
|
|
@ -0,0 +1,112 @@
|
|||
#!/usr/bin/gjs
|
||||
|
||||
const { GLib, Gio } = imports.gi;
|
||||
|
||||
const STDIN = new Gio.DataInputStream({ base_stream: new Gio.UnixInputStream({ fd: 0 }) })
|
||||
const STDOUT = new Gio.DataOutputStream({ base_stream: new Gio.UnixOutputStream({ fd: 1 }) })
|
||||
|
||||
class App {
|
||||
constructor() {
|
||||
this.last_query = ""
|
||||
this.shell_only = false
|
||||
}
|
||||
|
||||
/** @param {string} input */
|
||||
query(input) {
|
||||
if (input.startsWith(':')) {
|
||||
this.shell_only = true
|
||||
this.last_query = input.substr(1).trim()
|
||||
} else {
|
||||
this.shell_only = false
|
||||
this.last_query = input.startsWith('t:')
|
||||
? input.substr(2).trim()
|
||||
: input.substr(input.indexOf(" ") + 1).trim()
|
||||
}
|
||||
|
||||
this.send({ "Append": {
|
||||
id: 0,
|
||||
name: this.last_query,
|
||||
description: "run command in terminal"
|
||||
}})
|
||||
|
||||
this.send("Finished")
|
||||
}
|
||||
|
||||
/** @param {number} _id */
|
||||
submit(_id) {
|
||||
try {
|
||||
let runner
|
||||
if (this.shell_only) {
|
||||
runner = ""
|
||||
} else {
|
||||
let path = GLib.find_program_in_path('x-terminal-emulator');
|
||||
let [terminal, splitter] = path ? [path, "-e"] : ["gnome-terminal", "--"];
|
||||
runner = `${terminal} ${splitter} `
|
||||
}
|
||||
|
||||
GLib.spawn_command_line_async(`${runner}sh -c '${this.last_query}; echo "Press to exit"; read t'`);
|
||||
} catch (e) {
|
||||
log(`command launch error: ${e}`)
|
||||
}
|
||||
|
||||
this.send("Close")
|
||||
}
|
||||
|
||||
/** @param {Object} object */
|
||||
send(object) {
|
||||
try {
|
||||
STDOUT.write_bytes(new GLib.Bytes(JSON.stringify(object) + "\n"), null)
|
||||
} catch (e) {
|
||||
log(`failed to send response to Pop Shell: ${e}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
/** @type {null | ByteArray} */
|
||||
let input_array
|
||||
|
||||
/** @type {string} */
|
||||
let input_str
|
||||
|
||||
/** @type {null | LauncherRequest} */
|
||||
let event
|
||||
|
||||
let app = new App()
|
||||
|
||||
mainloop:
|
||||
while (true) {
|
||||
try {
|
||||
[input_array,] = STDIN.read_line(null)
|
||||
} catch (e) {
|
||||
break
|
||||
}
|
||||
|
||||
input_str = imports.byteArray.toString(input_array)
|
||||
if ((event = parse_event(input_str)) !== null) {
|
||||
if ("Search" in event) {
|
||||
app.query(event.Search)
|
||||
} else if ("Activate" in event) {
|
||||
app.submit(event.Activate)
|
||||
} else if ("Exit" === event) {
|
||||
break mainloop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an IPC event received from STDIN
|
||||
* @param {string} input
|
||||
* @returns {null | LauncherRequest}
|
||||
*/
|
||||
function parse_event(input) {
|
||||
try {
|
||||
return JSON.parse(input)
|
||||
} catch (e) {
|
||||
log(`Input not valid JSON`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
10
plugins/src/plugins/web/plugin.ron
Normal file
10
plugins/src/plugins/web/plugin.ron
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
(
|
||||
name: "Web Search",
|
||||
description: "Site-specific web search",
|
||||
query: (
|
||||
regex: "^(amazon|wiki|bing|ddg|google|yt|stack|crates|arch|pp|ppw|rdt|bc|lib|npm|gist|fh|gh|dev|sdcl|twitch|yh|alie)\\s.*",
|
||||
help: "ddg ",
|
||||
),
|
||||
bin: (path: "web.js"),
|
||||
icon: Name("system-search"),
|
||||
)
|
||||
128
plugins/src/plugins/web/web.js
Normal file
128
plugins/src/plugins/web/web.js
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
#!/usr/bin/env gjs
|
||||
|
||||
const { GLib, Gio } = imports.gi
|
||||
|
||||
const STDIN = new Gio.DataInputStream({ base_stream: new Gio.UnixInputStream({ fd: 0 }) })
|
||||
const STDOUT = new Gio.DataOutputStream({ base_stream: new Gio.UnixOutputStream({ fd: 1 }) })
|
||||
|
||||
const ENTRIES = new Map([
|
||||
['wiki', { query: 'https://wikipedia.org/w/index.php?search=', name: 'Wikipedia' }],
|
||||
['bing', { query: 'https://www.bing.com/search?q=', name: 'Bing' }],
|
||||
['ddg', { query: 'https://www.duckduckgo.com/?q=', name: 'DuckDuckGo' }],
|
||||
['google', { query: 'https://www.google.com/search?q=', name: 'Google' }],
|
||||
['yt', { query: 'https://www.youtube.com/results?search_query=', name: 'YouTube' }],
|
||||
['amazon', { query: 'https://smile.amazon.com/s?k=', name: 'Amazon' }],
|
||||
['stack', { query: 'https://stackoverflow.com/search?q=', name: 'Stack Overflow' }],
|
||||
['crates', { query: 'https://crates.io/search?q=', name: 'Crates.io' }],
|
||||
['rdt', { query: 'https://www.reddit.com/search/?q=', name: 'reddit' }],
|
||||
['arch', { query: 'https://wiki.archlinux.org/index.php/', name: 'Arch Wiki' }],
|
||||
['pp', { query: 'https://pop-planet.info/forums/search/1/?q=', name: 'Pop!_Planet' }],
|
||||
['ppw', { query: 'https://pop-planet.info/wiki/?search=', name: 'Pop!_Planet Wiki' }],
|
||||
['bc', { query: 'https://bandcamp.com/search?q=', name: 'Bandcamp' }],
|
||||
['npm', { query: 'https://www.npmjs.com/search?q=', name: 'npm' }],
|
||||
['lib', { query: 'https://libraries.io/search?q=', name: 'Libraries.io' }],
|
||||
['gist', { query: 'https://gist.github.com/search?q=', name: 'GitHub Gist' }],
|
||||
['fh', { query: 'https://flathub.org/apps/search/', name: 'Flathub' }],
|
||||
['gh', { query: 'https://github.com/search?q=', name: 'GitHub' }],
|
||||
['sdcl', { query: 'https://soundcloud.com/search?q=', name: 'SoundCloud' }],
|
||||
['twitch', { query: 'https://www.twitch.tv/search?term=', name: 'Twitch' }],
|
||||
['yh', { query: 'https://search.yahoo.com/search?p=', name: 'Yahoo!' }],
|
||||
['alie', { query: 'https://www.aliexpress.com/wholesale?SearchText=', name: 'AliExpress' }],
|
||||
['dev', { query: 'https://dev.to/search?q=', name: 'DEV Community' }]
|
||||
])
|
||||
|
||||
class App {
|
||||
constructor() {
|
||||
this.last_query = ''
|
||||
this.last_value = ''
|
||||
this.query_base = ''
|
||||
this.name_base = ''
|
||||
this.app_info = Gio.AppInfo.get_default_for_uri_scheme('https')
|
||||
}
|
||||
|
||||
build_query() {
|
||||
return `${this.query_base}${encodeURIComponent(this.last_query)}`
|
||||
}
|
||||
|
||||
search(input) {
|
||||
const delim_position = input.indexOf(' ')
|
||||
const key = input.substring(0, delim_position)
|
||||
this.last_query = input.substr(delim_position + 1).trim()
|
||||
|
||||
const entry = ENTRIES.get(key) || { query: 'https://www.duckduckgo.com/?q=', name: 'DuckDuckGo' }
|
||||
this.query_base = entry.query;
|
||||
this.name_base = entry.name;
|
||||
|
||||
this.send({ "Append": {
|
||||
id: 0,
|
||||
description: this.build_query(),
|
||||
name: `${this.name_base}: ${this.last_query}`,
|
||||
icon: { Name: this.app_info.get_icon().to_string() },
|
||||
}})
|
||||
|
||||
this.send("Finished")
|
||||
}
|
||||
|
||||
submit(_id) {
|
||||
try {
|
||||
GLib.spawn_command_line_async(`xdg-open ${this.build_query()}`)
|
||||
} catch (e) {
|
||||
log(`xdg-open failed: ${e} `)
|
||||
}
|
||||
|
||||
this.send("Close")
|
||||
}
|
||||
|
||||
send(object) {
|
||||
STDOUT.write_bytes(new GLib.Bytes(JSON.stringify(object) + "\n"), null)
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
/** @type {null | ByteArray} */
|
||||
let input_array
|
||||
|
||||
/** @type {string} */
|
||||
let input_str
|
||||
|
||||
/** @type {null | LauncherRequest} */
|
||||
let event
|
||||
|
||||
let app = new App()
|
||||
|
||||
mainloop:
|
||||
while (true) {
|
||||
try {
|
||||
[input_array,] = STDIN.read_line(null)
|
||||
} catch (e) {
|
||||
break
|
||||
}
|
||||
|
||||
input_str = imports.byteArray.toString(input_array)
|
||||
if ((event = parse_event(input_str)) !== null) {
|
||||
if ("Search" in event) {
|
||||
app.search(event.Search)
|
||||
} else if ("Activate" in event) {
|
||||
app.submit(event.Activate)
|
||||
} else if ("Exit" === event) {
|
||||
break mainloop
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an IPC event received from STDIN
|
||||
* @param {string} input
|
||||
* @returns {null | LauncherRequest}
|
||||
*/
|
||||
function parse_event(input) {
|
||||
try {
|
||||
return JSON.parse(input)
|
||||
} catch (e) {
|
||||
log(`Input not valid JSON`)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
8
scripts/session/session-logout.sh
Normal file
8
scripts/session/session-logout.sh
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
#!/bin/sh
|
||||
#
|
||||
# name: Log Out
|
||||
# icon: system-log-out
|
||||
# description: Log out to the login screen
|
||||
# keywords: log out logout
|
||||
|
||||
gnome-session-quit --logout
|
||||
8
scripts/session/session-reboot.sh
Normal file
8
scripts/session/session-reboot.sh
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
#!/bin/sh
|
||||
#
|
||||
# name: Restart
|
||||
# icon: system-restart
|
||||
# description: Reboot the system
|
||||
# keywords: power reboot restart
|
||||
|
||||
gnome-session-quit --reboot
|
||||
8
scripts/session/session-shutdown.sh
Normal file
8
scripts/session/session-shutdown.sh
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
#!/bin/sh
|
||||
#
|
||||
# name: Power off
|
||||
# icon: system-shutdown
|
||||
# description: Shut down the system
|
||||
# keywords: power off shutdown
|
||||
|
||||
gnome-session-quit --power-off
|
||||
8
scripts/session/session-suspend.sh
Normal file
8
scripts/session/session-suspend.sh
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
#!/bin/sh
|
||||
#
|
||||
# name: Suspend
|
||||
# icon: system-suspend
|
||||
# description: Suspend the system
|
||||
# keywords: suspend
|
||||
|
||||
systemctl suspend
|
||||
16
scripts/system76-power/graphics-compute.sh
Normal file
16
scripts/system76-power/graphics-compute.sh
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
#!/bin/sh
|
||||
#
|
||||
# name: Switch to Compute Graphics
|
||||
# icon: preferences-system-symbolic
|
||||
# description: Use integrated GPU for display; discrete for CUDA / OpenCL
|
||||
# keywords: compute graphics switch nvidia
|
||||
|
||||
gnome-terminal -- sh -c '
|
||||
if system76-power graphics compute; then
|
||||
echo "Succesfully switched. You may now reboot"
|
||||
else
|
||||
echo "Failed to switch\nPress key to exit"
|
||||
fi
|
||||
|
||||
read x
|
||||
'
|
||||
16
scripts/system76-power/graphics-discrete.sh
Normal file
16
scripts/system76-power/graphics-discrete.sh
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
#!/bin/sh
|
||||
#
|
||||
# name: Switch to NVIDIA Graphics
|
||||
# icon: preferences-system-symbolic
|
||||
# description: Use NVIDIA GPU for display and applications
|
||||
# keywords: nvidia graphics switch
|
||||
|
||||
gnome-terminal -- sh -c '
|
||||
if system76-power graphics nvidia; then
|
||||
echo "Succesfully switched. You may now reboot"
|
||||
else
|
||||
echo "Failed to switch\nPress key to exit"
|
||||
fi
|
||||
|
||||
read x
|
||||
'
|
||||
16
scripts/system76-power/graphics-hybrid.sh
Normal file
16
scripts/system76-power/graphics-hybrid.sh
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
#!/bin/sh
|
||||
#
|
||||
# name: Switch to Hybrid Graphics
|
||||
# icon: preferences-system-symbolic
|
||||
# description: Use integrated GPU for display; applications may request discrete
|
||||
# keywords: integrated graphics switch intel nvidia hybrid
|
||||
|
||||
gnome-terminal -- sh -c '
|
||||
if system76-power graphics hybrid; then
|
||||
echo "Succesfully switched. You may now reboot"
|
||||
else
|
||||
echo "Failed to switch\nPress key to exit"
|
||||
fi
|
||||
|
||||
read x
|
||||
'
|
||||
16
scripts/system76-power/graphics-integrated.sh
Normal file
16
scripts/system76-power/graphics-integrated.sh
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
#!/bin/sh
|
||||
#
|
||||
# name: Switch to Integrated Graphics
|
||||
# icon: preferences-system-symbolic
|
||||
# description: Use integrated GPU for display and applications
|
||||
# keywords: integrated graphics switch intel
|
||||
|
||||
gnome-terminal -- sh -c '
|
||||
if system76-power graphics integrated; then
|
||||
echo "Succesfully switched. You may now reboot"
|
||||
else
|
||||
echo "Failed to switch\nPress key to exit"
|
||||
fi
|
||||
|
||||
read x
|
||||
'
|
||||
27
src/codec.rs
Normal file
27
src/codec.rs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
use futures_codec::{FramedRead, LinesCodec};
|
||||
use futures_lite::{AsyncRead, Stream, StreamExt};
|
||||
use serde::Deserialize;
|
||||
use smol::Unblock;
|
||||
use std::io;
|
||||
|
||||
/// stdin with AsyncRead support
|
||||
pub fn async_stdin() -> Unblock<io::Stdin> {
|
||||
Unblock::new(io::stdin())
|
||||
}
|
||||
|
||||
/// stdout with AsyncWrite support
|
||||
pub fn async_stdout() -> Unblock<io::Stdout> {
|
||||
Unblock::new(io::stdout())
|
||||
}
|
||||
|
||||
/// Creates a stream that parses JSON input line-by-line
|
||||
pub fn json_input_stream<I, S>(input: I) -> impl Stream<Item = serde_json::Result<S>> + Unpin + Send
|
||||
where
|
||||
I: AsyncRead + Unpin + Send,
|
||||
S: for<'a> Deserialize<'a>,
|
||||
{
|
||||
FramedRead::new(input, LinesCodec)
|
||||
.take_while(Result::is_ok)
|
||||
.map(Result::unwrap)
|
||||
.map(|line| serde_json::from_str::<S>(&line))
|
||||
}
|
||||
115
src/lib.rs
Normal file
115
src/lib.rs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
mod codec;
|
||||
mod plugins;
|
||||
mod service;
|
||||
|
||||
pub use self::codec::*;
|
||||
pub use self::plugins::*;
|
||||
pub use self::service::Service;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use slab::Slab;
|
||||
use std::{borrow::Cow, path::PathBuf};
|
||||
|
||||
pub type PluginKey = usize;
|
||||
pub type Generation = u32;
|
||||
pub type Indice = u32;
|
||||
|
||||
pub enum Event {
|
||||
Request(Request),
|
||||
Response((PluginKey, PluginResponse)),
|
||||
PluginExit(PluginKey),
|
||||
Help(async_oneshot::Sender<Slab<PluginHelp>>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub enum IconSource {
|
||||
// Locate by name or path
|
||||
Name(Cow<'static, str>),
|
||||
// Icon is a mime type
|
||||
Mime(Cow<'static, str>),
|
||||
// Window Entity ID
|
||||
Window((Generation, Indice)),
|
||||
}
|
||||
|
||||
// Launcher frontends shall send these requests to the launcher service.
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub enum Request {
|
||||
/// Activate on the selected item
|
||||
Activate(Indice),
|
||||
/// Perform a tab completion from the selected item
|
||||
Complete(Indice),
|
||||
/// Request to end the service
|
||||
Exit,
|
||||
/// Requests to cancel any active searches
|
||||
Interrupt,
|
||||
/// Request to close the selected item
|
||||
Quit(Indice),
|
||||
/// Perform a search in our database
|
||||
Search(String),
|
||||
}
|
||||
|
||||
/// Launcher frontends shall react to these responses from the launcher service.
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub enum Response {
|
||||
// An operation was performed and the frontend may choose to exit its process.
|
||||
Close,
|
||||
// Notifies that a .desktop entry should be launched by the frontend
|
||||
DesktopEntry(PathBuf),
|
||||
// The frontend should clear its search results and display a new list
|
||||
Update(Vec<SearchResult>),
|
||||
// An item was selected that resulted in a need to autofill the launcher
|
||||
Fill(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub enum PluginResponse {
|
||||
/// Append a new search item to the launcher
|
||||
Append(SearchMeta),
|
||||
/// Clear all results in the launcher list
|
||||
Clear,
|
||||
/// Close the launcher
|
||||
Close,
|
||||
// Notifies that a .desktop entry should be launched by the frontend
|
||||
DesktopEntry(PathBuf),
|
||||
/// Update the text in the launcher
|
||||
Fill(String),
|
||||
/// Indicoates that a plugin is finished with its queries
|
||||
Finished,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize)]
|
||||
pub struct SearchMeta {
|
||||
pub id: Indice,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub keywords: Option<Vec<String>>,
|
||||
pub icon: Option<IconSource>,
|
||||
pub exec: Option<String>,
|
||||
pub window: Option<(Generation, Indice)>,
|
||||
}
|
||||
|
||||
/// Serialized response to launcher frontend about a search result.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct SearchResult {
|
||||
pub id: Indice,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "::serde_with::rust::unwrap_or_skip"
|
||||
)]
|
||||
pub icon: Option<IconSource>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "::serde_with::rust::unwrap_or_skip"
|
||||
)]
|
||||
pub category_icon: Option<IconSource>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "::serde_with::rust::unwrap_or_skip"
|
||||
)]
|
||||
pub window: Option<(Generation, Indice)>,
|
||||
}
|
||||
12
src/main.rs
Normal file
12
src/main.rs
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
use pop_launcher::Service;
|
||||
use std::io;
|
||||
|
||||
fn main() {
|
||||
tracing_subscriber::fmt()
|
||||
.with_writer(io::stderr)
|
||||
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
|
||||
.init();
|
||||
|
||||
let stdout = io::stdout();
|
||||
smol::block_on(Service::new(stdout.lock()).exec());
|
||||
}
|
||||
99
src/plugins/config.rs
Normal file
99
src/plugins/config.rs
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
use regex::Regex;
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub struct PluginConfig {
|
||||
pub name: Cow<'static, str>,
|
||||
pub description: Cow<'static, str>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "::serde_with::rust::unwrap_or_skip"
|
||||
)]
|
||||
pub bin: Option<PluginBinary>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "::serde_with::rust::unwrap_or_skip"
|
||||
)]
|
||||
pub icon: Option<crate::IconSource>,
|
||||
|
||||
#[serde(default)]
|
||||
pub query: PluginQuery,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub struct PluginBinary {
|
||||
path: Cow<'static, str>,
|
||||
|
||||
#[serde(default)]
|
||||
args: Vec<Cow<'static, str>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub struct PluginQuery {
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "::serde_with::rust::unwrap_or_skip"
|
||||
)]
|
||||
pub help: Option<Cow<'static, str>>,
|
||||
|
||||
#[serde(default)]
|
||||
pub isolate: bool,
|
||||
|
||||
#[serde(default)]
|
||||
pub no_sort: bool,
|
||||
|
||||
#[serde(default)]
|
||||
pub persistent: bool,
|
||||
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
with = "::serde_with::rust::unwrap_or_skip"
|
||||
)]
|
||||
pub regex: Option<Cow<'static, str>>,
|
||||
}
|
||||
|
||||
pub fn load(source: &Path, config_path: &Path) -> Option<(PathBuf, PluginConfig, Option<Regex>)> {
|
||||
if let Ok(config_bytes) = std::fs::read_to_string(&config_path) {
|
||||
let config = match ron::from_str::<PluginConfig>(&config_bytes) {
|
||||
Ok(config) => config,
|
||||
Err(why) => {
|
||||
tracing::error!("malformed config at {}: {}", config_path.display(), why);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let exec = if let Some(bin) = config.bin.as_ref() {
|
||||
if bin.path.starts_with('/') {
|
||||
PathBuf::from((*bin.path).to_owned())
|
||||
} else {
|
||||
source.join(bin.path.as_ref())
|
||||
}
|
||||
} else {
|
||||
tracing::error!(
|
||||
"bin field is missing from config at {}",
|
||||
config_path.display()
|
||||
);
|
||||
return None;
|
||||
};
|
||||
|
||||
let regex = config
|
||||
.query
|
||||
.regex
|
||||
.as_ref()
|
||||
.and_then(|p| Regex::new(&*p).ok());
|
||||
|
||||
return Some((exec, config, regex));
|
||||
}
|
||||
|
||||
tracing::error!("I/O error reading config at {}", config_path.display());
|
||||
|
||||
None
|
||||
}
|
||||
76
src/plugins/external/load.rs
vendored
Normal file
76
src/plugins/external/load.rs
vendored
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
use crate::PluginConfig;
|
||||
|
||||
use flume::Sender;
|
||||
use futures_lite::{Stream, StreamExt};
|
||||
use regex::Regex;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Fetches plugins installed on the system in parallel.
|
||||
pub async fn from_paths(tx: Sender<(PathBuf, PluginConfig, Option<Regex>)>) {
|
||||
const PLUGIN_PATHS: &[&str] = &[
|
||||
// User plugins
|
||||
".local/share/pop-launcher/plugins/",
|
||||
// System plugins configured by admin
|
||||
"/etc/pop-launcher/plugins/",
|
||||
// Distribution plugins
|
||||
"/usr/lib/pop-launcher/plugins/",
|
||||
];
|
||||
|
||||
let mut futures = Vec::new();
|
||||
|
||||
// Searches plugin paths from highest to least priority.
|
||||
// User plugins will override distribution plugins.
|
||||
for path in PLUGIN_PATHS {
|
||||
let path_buf;
|
||||
#[allow(deprecated)]
|
||||
let path = if !path.starts_with('/') {
|
||||
path_buf = std::env::home_dir()
|
||||
.expect("user does not have home dir")
|
||||
.join(path);
|
||||
path_buf.as_path()
|
||||
} else {
|
||||
Path::new(&path)
|
||||
};
|
||||
|
||||
let loadable_plugins = from_path(path);
|
||||
futures_lite::pin!(loadable_plugins);
|
||||
|
||||
// Spawn a background task to parse the config for each plugin found.
|
||||
while let Some((source, config)) = loadable_plugins.next().await {
|
||||
let tx = tx.clone();
|
||||
let future = smol::unblock(move || {
|
||||
if let Some(plugin) = crate::plugins::config::load(&source, &config) {
|
||||
let _ = tx.send(plugin);
|
||||
}
|
||||
});
|
||||
|
||||
futures.push(smol::spawn(future))
|
||||
}
|
||||
|
||||
// Ensures that plugins are loaded in the order that they were spawned.
|
||||
for future in futures.drain(..) {
|
||||
future.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads all plugin information found in the given path.
|
||||
pub fn from_path(path: &Path) -> impl Stream<Item = (PathBuf, PathBuf)> + '_ {
|
||||
gen_z::gen_z(move |mut z| async move {
|
||||
if let Ok(readdir) = path.read_dir() {
|
||||
for entry in readdir.filter_map(Result::ok) {
|
||||
let source = entry.path();
|
||||
if !source.is_dir() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let config = source.join("plugin.ron");
|
||||
if !config.exists() {
|
||||
continue;
|
||||
}
|
||||
|
||||
z.send((source, config)).await;
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
192
src/plugins/external/mod.rs
vendored
Normal file
192
src/plugins/external/mod.rs
vendored
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
pub mod load;
|
||||
|
||||
use std::{
|
||||
io,
|
||||
path::PathBuf,
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
},
|
||||
};
|
||||
|
||||
use crate::{Plugin, PluginResponse, Request};
|
||||
use async_oneshot::oneshot;
|
||||
use flume::Sender;
|
||||
use futures_lite::{AsyncWriteExt, FutureExt, StreamExt};
|
||||
use smol::{
|
||||
process::{Child, Command, Stdio},
|
||||
Task,
|
||||
};
|
||||
use tracing::{event, Level};
|
||||
|
||||
pub struct ExternalPlugin {
|
||||
tx: Sender<PluginResponse>,
|
||||
name: String,
|
||||
pub cmd: PathBuf,
|
||||
pub args: Vec<String>,
|
||||
process: Option<(Task<()>, Child, async_oneshot::Sender<()>)>,
|
||||
detached: Arc<AtomicBool>,
|
||||
searching: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl ExternalPlugin {
|
||||
pub fn new(name: String, cmd: PathBuf, args: Vec<String>, tx: Sender<PluginResponse>) -> Self {
|
||||
Self {
|
||||
name,
|
||||
tx,
|
||||
cmd,
|
||||
args,
|
||||
process: None,
|
||||
detached: Arc::default(),
|
||||
searching: Arc::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn launch(&mut self) -> Option<&mut (Task<()>, Child, async_oneshot::Sender<()>)> {
|
||||
event!(Level::DEBUG, "{}: launching plugin", self.name());
|
||||
|
||||
let child = Command::new(&self.cmd)
|
||||
.args(&self.args)
|
||||
.stdout(Stdio::piped())
|
||||
.stdin(Stdio::piped())
|
||||
.stderr(Stdio::inherit())
|
||||
.spawn()
|
||||
.ok();
|
||||
|
||||
if let Some(mut child) = child {
|
||||
if let Some(stdout) = child.stdout.take() {
|
||||
let detached = self.detached.clone();
|
||||
let searching = self.searching.clone();
|
||||
let (trip_tx, trip_rx) = oneshot::<()>();
|
||||
let tx = self.tx.clone();
|
||||
let name = self.name().to_owned();
|
||||
|
||||
// Spawn a background task to forward JSON responses from the child process.
|
||||
let task = smol::spawn(async move {
|
||||
let tx_ = tx.clone();
|
||||
let searching_ = searching.clone();
|
||||
let name_ = name.clone();
|
||||
|
||||
// Future for directly handling the JSON output from the process.
|
||||
let responder = async move {
|
||||
let mut requests = crate::json_input_stream(stdout);
|
||||
|
||||
while let Some(result) = requests.next().await {
|
||||
match result {
|
||||
Ok(response) => {
|
||||
if let PluginResponse::Finished = response {
|
||||
searching_.store(false, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
tracing::debug!("{}: responding with {:?}", name_, response);
|
||||
let _ = tx_.send(response);
|
||||
}
|
||||
Err(why) => {
|
||||
event!(Level::ERROR, "{}: serde error: {:?}", name_, why);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracing::debug!("{}: exiting from responder", name_);
|
||||
};
|
||||
|
||||
let trip = async move {
|
||||
let _ = trip_rx.await;
|
||||
};
|
||||
|
||||
let _ = responder.or(trip).await;
|
||||
|
||||
// Ensure that a task that was searching sends a finished signal if it dies.
|
||||
if searching.swap(false, Ordering::SeqCst) {
|
||||
let _ = tx.send(PluginResponse::Finished);
|
||||
}
|
||||
|
||||
detached.store(true, Ordering::SeqCst);
|
||||
|
||||
event!(Level::DEBUG, "{}: detached plugin", name);
|
||||
});
|
||||
|
||||
self.process = Some((task, child, trip_tx));
|
||||
}
|
||||
}
|
||||
|
||||
self.process.as_mut()
|
||||
}
|
||||
|
||||
pub async fn process_check(&mut self) {
|
||||
if let Some(mut child) = self.process.take() {
|
||||
match child.1.try_status() {
|
||||
Err(_) | Ok(Some(_)) => {
|
||||
child.0.cancel().await;
|
||||
}
|
||||
Ok(None) => self.process = Some(child),
|
||||
}
|
||||
|
||||
if self.detached.swap(false, Ordering::SeqCst) {
|
||||
self.process = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn query(&mut self, event: &Request) -> io::Result<()> {
|
||||
self.process_check().await;
|
||||
|
||||
if self.process.is_none() {
|
||||
tracing::debug!("{}: relaunching process", self.name());
|
||||
self.launch();
|
||||
}
|
||||
|
||||
if let Some((_, child, _)) = self.process.as_mut() {
|
||||
if let Some(stdin) = child.stdin.as_mut() {
|
||||
if let Ok(mut serialized) = serde_json::to_vec(event) {
|
||||
serialized.push(b'\n');
|
||||
let _ = stdin.write_all(&serialized).await?;
|
||||
tracing::debug!("{}: sent message to external process", self.name());
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::NotConnected,
|
||||
"child process could not be reached",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Plugin for ExternalPlugin {
|
||||
async fn activate(&mut self, id: u32) {
|
||||
let _ = self.query(&Request::Activate(id)).await;
|
||||
}
|
||||
|
||||
async fn complete(&mut self, id: u32) {
|
||||
let _ = self.query(&Request::Complete(id)).await;
|
||||
}
|
||||
|
||||
fn exit(&mut self) {
|
||||
if let Some((_, _, mut trigger)) = self.process.take() {
|
||||
let _ = trigger.send(());
|
||||
}
|
||||
}
|
||||
|
||||
async fn interrupt(&mut self) {
|
||||
let _ = self.query(&Request::Interrupt).await;
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
async fn search(&mut self, query: &str) {
|
||||
if self.query(&Request::Search(query.to_owned())).await.is_ok() {
|
||||
self.searching.store(true, Ordering::SeqCst);
|
||||
} else {
|
||||
let _ = self.tx.send_async(PluginResponse::Finished).await;
|
||||
}
|
||||
}
|
||||
async fn quit(&mut self, id: u32) {
|
||||
let _ = self.query(&Request::Quit(id)).await;
|
||||
}
|
||||
}
|
||||
95
src/plugins/help.rs
Normal file
95
src/plugins/help.rs
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
use crate::{Event, IconSource, Plugin, PluginConfig, PluginQuery, PluginResponse, SearchMeta};
|
||||
|
||||
use flume::Sender;
|
||||
use slab::Slab;
|
||||
use std::borrow::Cow;
|
||||
|
||||
pub const REGEX: Cow<'static, str> = Cow::Borrowed("^(\\?).*");
|
||||
|
||||
pub const CONFIG: PluginConfig = PluginConfig {
|
||||
name: Cow::Borrowed("Help"),
|
||||
description: Cow::Borrowed("Show available plugin prefixes"),
|
||||
bin: None,
|
||||
query: PluginQuery {
|
||||
help: None,
|
||||
isolate: true,
|
||||
no_sort: true,
|
||||
persistent: false,
|
||||
regex: None,
|
||||
},
|
||||
icon: Some(IconSource::Name(Cow::Borrowed("system-help-symbolic"))),
|
||||
};
|
||||
|
||||
pub struct PluginHelp {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub help: Option<String>,
|
||||
}
|
||||
|
||||
pub struct HelpPlugin {
|
||||
pub details: Slab<PluginHelp>,
|
||||
pub internal: Sender<Event>,
|
||||
pub tx: Sender<PluginResponse>,
|
||||
}
|
||||
|
||||
impl HelpPlugin {
|
||||
pub fn new(internal: Sender<Event>, tx: Sender<PluginResponse>) -> Self {
|
||||
Self {
|
||||
details: Slab::new(),
|
||||
internal,
|
||||
tx,
|
||||
}
|
||||
}
|
||||
|
||||
async fn reload(&mut self) {
|
||||
let (tx, rx) = async_oneshot::oneshot();
|
||||
let _ = self.internal.send_async(Event::Help(tx)).await;
|
||||
self.details = rx.await.expect("internal error fetching help info");
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl Plugin for HelpPlugin {
|
||||
async fn activate(&mut self, id: u32) {
|
||||
if let Some(detail) = self.details.get(id as usize) {
|
||||
if let Some(help) = detail.help.as_ref() {
|
||||
let _ = self.tx.send_async(PluginResponse::Fill(help.clone())).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn complete(&mut self, id: u32) {
|
||||
self.activate(id).await
|
||||
}
|
||||
|
||||
fn exit(&mut self) {}
|
||||
|
||||
async fn interrupt(&mut self) {}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
"help"
|
||||
}
|
||||
|
||||
async fn search(&mut self, _query: &str) {
|
||||
if self.details.is_empty() {
|
||||
self.reload().await;
|
||||
}
|
||||
for (id, detail) in self.details.iter() {
|
||||
if detail.help.is_some() {
|
||||
let _ = self
|
||||
.tx
|
||||
.send_async(PluginResponse::Append(SearchMeta {
|
||||
id: id as u32,
|
||||
name: detail.name.clone(),
|
||||
description: detail.description.clone(),
|
||||
..Default::default()
|
||||
}))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
let _ = self.tx.send_async(PluginResponse::Finished).await;
|
||||
}
|
||||
|
||||
async fn quit(&mut self, _id: u32) {}
|
||||
}
|
||||
124
src/plugins/mod.rs
Normal file
124
src/plugins/mod.rs
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
mod config;
|
||||
pub(crate) mod external;
|
||||
pub mod help;
|
||||
|
||||
pub use self::config::{PluginBinary, PluginConfig, PluginQuery};
|
||||
pub use self::external::ExternalPlugin;
|
||||
pub use self::help::{HelpPlugin, PluginHelp};
|
||||
|
||||
use crate::Request;
|
||||
use async_trait::async_trait;
|
||||
use flume::{Receiver, Sender};
|
||||
use regex::Regex;
|
||||
|
||||
#[async_trait]
|
||||
pub trait Plugin
|
||||
where
|
||||
Self: Sized + Send,
|
||||
{
|
||||
/// Activate the selected ID from this plugin
|
||||
async fn activate(&mut self, id: u32);
|
||||
|
||||
async fn complete(&mut self, id: u32);
|
||||
|
||||
fn exit(&mut self);
|
||||
|
||||
async fn interrupt(&mut self);
|
||||
|
||||
fn name(&self) -> &str;
|
||||
|
||||
async fn search(&mut self, query: &str);
|
||||
|
||||
async fn quit(&mut self, id: u32);
|
||||
|
||||
async fn run(&mut self, rx: Receiver<Request>) {
|
||||
while let Ok(request) = rx.recv_async().await {
|
||||
tracing::event!(
|
||||
tracing::Level::DEBUG,
|
||||
"{}: received {:?}",
|
||||
self.name(),
|
||||
request
|
||||
);
|
||||
match request {
|
||||
Request::Search(query) => self.search(&query).await,
|
||||
Request::Interrupt => self.interrupt().await,
|
||||
Request::Activate(id) => self.activate(id).await,
|
||||
Request::Complete(id) => self.complete(id).await,
|
||||
Request::Quit(id) => self.quit(id).await,
|
||||
Request::Exit => {
|
||||
self.exit();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracing::event!(tracing::Level::DEBUG, "{}: exiting plugin", self.name());
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores all information relevant for communicating with a plugin
|
||||
///
|
||||
/// Plugins may be requested to exit, and relaunched at any point in the future.
|
||||
pub struct PluginConnector {
|
||||
/// The deserialized configuration file for this plugin
|
||||
pub config: PluginConfig,
|
||||
|
||||
/// Code that is executed to prepare a new instance of
|
||||
/// this plugin to spawn as a background service
|
||||
pub init: Box<dyn Fn() -> Sender<Request>>,
|
||||
|
||||
/// A compiled regular expression that a query must match
|
||||
/// for the launcher service to justify spawning and sending
|
||||
/// queries to this plugin
|
||||
pub regex: Option<Regex>,
|
||||
|
||||
/// The sender of the spawned background service that will be
|
||||
/// forwarded to the launncher service
|
||||
pub sender: Option<Sender<Request>>,
|
||||
}
|
||||
|
||||
impl PluginConnector {
|
||||
pub fn new(
|
||||
config: PluginConfig,
|
||||
regex: Option<Regex>,
|
||||
init: Box<dyn Fn() -> Sender<Request> + Send>,
|
||||
) -> Self {
|
||||
Self {
|
||||
config,
|
||||
init,
|
||||
regex,
|
||||
sender: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn details(&self) -> PluginHelp {
|
||||
PluginHelp {
|
||||
name: self.config.name.as_ref().to_owned(),
|
||||
description: self.config.description.as_ref().to_owned(),
|
||||
help: self
|
||||
.config
|
||||
.query
|
||||
.help
|
||||
.as_ref()
|
||||
.map(|x| x.as_ref().to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Obtains the sender for sending messages to this plugin.
|
||||
///
|
||||
/// If the sender is absent, the plugin is relaunched with a new one.
|
||||
pub fn sender_exec(&mut self) -> &mut Sender<Request> {
|
||||
let &mut Self {
|
||||
ref mut sender,
|
||||
ref init,
|
||||
..
|
||||
} = self;
|
||||
|
||||
sender.get_or_insert_with(|| init())
|
||||
}
|
||||
|
||||
/// Drops the sender, which will subsequently drop the plugin forwarder attached to it
|
||||
pub fn sender_drop(&mut self) {
|
||||
self.sender = None;
|
||||
}
|
||||
}
|
||||
472
src/service.rs
Normal file
472
src/service.rs
Normal file
|
|
@ -0,0 +1,472 @@
|
|||
use crate::*;
|
||||
use flume::{unbounded, Receiver, Sender};
|
||||
use futures_lite::{future, StreamExt};
|
||||
use regex::Regex;
|
||||
use slab::Slab;
|
||||
use std::io::Write;
|
||||
|
||||
pub struct Service<O> {
|
||||
active_search: Vec<(PluginKey, SearchMeta)>,
|
||||
awaiting_results: usize,
|
||||
last_query: String,
|
||||
output: O,
|
||||
plugins: Slab<PluginConnector>,
|
||||
no_sort: bool,
|
||||
search_scheduled: bool,
|
||||
}
|
||||
|
||||
impl<O: Write> Service<O> {
|
||||
pub fn new(output: O) -> Self {
|
||||
Self {
|
||||
active_search: Vec::new(),
|
||||
awaiting_results: 0,
|
||||
last_query: String::new(),
|
||||
output,
|
||||
plugins: Slab::new(),
|
||||
no_sort: false,
|
||||
search_scheduled: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn exec(mut self) {
|
||||
let (service_tx, service_rx) = unbounded();
|
||||
|
||||
{
|
||||
let (plugins_tx, plugins_rx) = unbounded();
|
||||
let plugin_loader = plugins::external::load::from_paths(plugins_tx);
|
||||
let plugin_receiver = async {
|
||||
while let Ok((exec, config, regex)) = plugins_rx.recv_async().await {
|
||||
tracing::info!("found plugin \"{}\"", exec.display());
|
||||
if self
|
||||
.plugins
|
||||
.iter()
|
||||
.any(|(_, p)| p.config.name == config.name)
|
||||
{
|
||||
tracing::info!("ignoring plugin");
|
||||
continue;
|
||||
}
|
||||
|
||||
let name = String::from(config.name.as_ref());
|
||||
|
||||
self.register_plugin(service_tx.clone(), config, regex, move |tx| {
|
||||
ExternalPlugin::new(name.clone(), exec.clone(), Vec::new(), tx)
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
future::zip(plugin_loader, plugin_receiver).await;
|
||||
}
|
||||
|
||||
let internal = service_tx.clone();
|
||||
|
||||
self.register_plugin(
|
||||
service_tx.clone(),
|
||||
plugins::help::CONFIG,
|
||||
Some(Regex::new(plugins::help::REGEX.as_ref()).expect("failed to compile help regex")),
|
||||
move |tx| HelpPlugin::new(internal.clone(), tx),
|
||||
);
|
||||
|
||||
let f1 = request_handler(service_tx);
|
||||
let f2 = self.response_handler(service_rx);
|
||||
|
||||
future::zip(f1, f2).await;
|
||||
}
|
||||
|
||||
async fn response_handler(&mut self, service_rx: Receiver<Event>) {
|
||||
while let Ok(event) = service_rx.recv_async().await {
|
||||
match event {
|
||||
Event::Request(request) => {
|
||||
match request {
|
||||
Request::Search(query) => self.search(query),
|
||||
Request::Interrupt => self.interrupt(),
|
||||
Request::Activate(id) => self.activate(id),
|
||||
Request::Complete(id) => self.complete(id),
|
||||
Request::Quit(id) => self.quit(id),
|
||||
|
||||
// When requested to exit, the service will forward that
|
||||
// request to all of its plugins before exiting itself
|
||||
Request::Exit => {
|
||||
for (_key, plugin) in self.plugins.iter_mut() {
|
||||
let tx = plugin.sender_exec();
|
||||
let _ = tx.send(Request::Exit);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Event::Response((plugin, response)) => match response {
|
||||
PluginResponse::Append(item) => self.append(plugin, item),
|
||||
PluginResponse::Clear => self.clear(),
|
||||
PluginResponse::Close => self.close(),
|
||||
PluginResponse::Fill(text) => self.fill(text),
|
||||
PluginResponse::Finished => self.finished(plugin),
|
||||
PluginResponse::DesktopEntry(path) => {
|
||||
self.respond(&Response::DesktopEntry(path));
|
||||
}
|
||||
},
|
||||
|
||||
// When a plugin has exited, the sender attached to the plugin will be dropped
|
||||
Event::PluginExit(plugin_id) => {
|
||||
if let Some(plugin) = self.plugins.get_mut(plugin_id) {
|
||||
plugin.sender_drop();
|
||||
}
|
||||
}
|
||||
|
||||
Event::Help(mut sender) => {
|
||||
let mut details = Slab::new();
|
||||
|
||||
for (_, plugin) in self.plugins.iter() {
|
||||
details.insert(plugin.details());
|
||||
}
|
||||
|
||||
let _ = sender.send(details);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn register_plugin<P: Plugin, I: Fn(Sender<PluginResponse>) -> P + Send + Sync + 'static>(
|
||||
&mut self,
|
||||
service_tx: Sender<Event>,
|
||||
config: PluginConfig,
|
||||
regex: Option<regex::Regex>,
|
||||
init: I,
|
||||
) {
|
||||
let (plugin_tx, plugin_rx) = unbounded();
|
||||
|
||||
let entry = self.plugins.vacant_entry();
|
||||
let id = entry.key();
|
||||
|
||||
let init = std::sync::Arc::new(init);
|
||||
|
||||
entry.insert(PluginConnector::new(
|
||||
config,
|
||||
regex,
|
||||
Box::new(move || {
|
||||
let (request_tx, request_rx) = unbounded();
|
||||
|
||||
let init = init.clone();
|
||||
let plugin_tx = plugin_tx.clone();
|
||||
let plugin_rx = plugin_rx.clone();
|
||||
let service_tx = service_tx.clone();
|
||||
smol::spawn(async move {
|
||||
let mut plugin = init(plugin_tx);
|
||||
|
||||
let f1 = plugin.run(request_rx);
|
||||
let f2 = plugin_forwarder(id, plugin_rx, service_tx);
|
||||
|
||||
future::zip(f1, f2).await;
|
||||
})
|
||||
.detach();
|
||||
|
||||
request_tx
|
||||
}),
|
||||
));
|
||||
}
|
||||
|
||||
fn activate(&mut self, id: u32) {
|
||||
if let Some((plugin, meta)) = self.search_result(id as usize) {
|
||||
let _ = plugin.sender_exec().send(Request::Activate(meta.id));
|
||||
}
|
||||
}
|
||||
|
||||
fn append(&mut self, plugin: PluginKey, append: SearchMeta) {
|
||||
self.active_search.push((plugin, append));
|
||||
}
|
||||
|
||||
fn clear(&mut self) {
|
||||
self.active_search.clear();
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.respond(&Response::Close);
|
||||
}
|
||||
|
||||
fn complete(&mut self, id: u32) {
|
||||
if let Some((plugin, meta)) = self.search_result(id as usize) {
|
||||
let _ = plugin.sender_exec().send(Request::Complete(meta.id));
|
||||
}
|
||||
}
|
||||
|
||||
fn fill(&mut self, text: String) {
|
||||
self.respond(&Response::Fill(text));
|
||||
}
|
||||
|
||||
fn finished(&mut self, _plugin: PluginKey) {
|
||||
self.awaiting_results -= 1;
|
||||
if self.awaiting_results == 0 {
|
||||
if self.search_scheduled {
|
||||
self.search(String::new());
|
||||
return;
|
||||
}
|
||||
|
||||
let search_list = self.sort();
|
||||
self.respond(&Response::Update(search_list))
|
||||
}
|
||||
}
|
||||
|
||||
fn interrupt(&mut self) {
|
||||
for (_, plugin) in self.plugins.iter_mut() {
|
||||
if let Some(sender) = plugin.sender.as_mut() {
|
||||
let _ = sender.send(Request::Interrupt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn quit(&mut self, id: u32) {
|
||||
if let Some((plugin, meta)) = self.search_result(id as usize) {
|
||||
let _ = plugin.sender_exec().send(Request::Quit(meta.id));
|
||||
}
|
||||
}
|
||||
|
||||
/// Serializes the launcher's response to stdout
|
||||
fn respond<E: serde::Serialize>(&mut self, event: &E) {
|
||||
if let Ok(mut vec) = serde_json::to_vec(event) {
|
||||
vec.push(b'\n');
|
||||
let _ = self.output.write_all(&vec);
|
||||
}
|
||||
}
|
||||
|
||||
fn search(&mut self, query: String) {
|
||||
if self.awaiting_results > 0 {
|
||||
tracing::debug!("backing off from search until plugins are ready");
|
||||
if !self.search_scheduled {
|
||||
self.interrupt();
|
||||
self.search_scheduled = true;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
self.active_search.clear();
|
||||
|
||||
if !self.search_scheduled {
|
||||
self.last_query = query;
|
||||
}
|
||||
|
||||
self.search_scheduled = false;
|
||||
let query = self.last_query.as_str();
|
||||
|
||||
let mut query_queue = Vec::new();
|
||||
let mut isolated = None;
|
||||
|
||||
let requires_persistence = query.is_empty();
|
||||
|
||||
for (key, plugin) in self.plugins.iter_mut() {
|
||||
// Avoid sending queries to plugins which are not matched
|
||||
if let Some(regex) = plugin.regex.as_ref() {
|
||||
if !regex.is_match(query) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if requires_persistence && !plugin.config.query.persistent {
|
||||
continue;
|
||||
}
|
||||
|
||||
if plugin.config.query.isolate {
|
||||
isolated = Some(key);
|
||||
break;
|
||||
}
|
||||
|
||||
query_queue.push(key);
|
||||
}
|
||||
|
||||
if let Some(isolated) = isolated {
|
||||
if let Some(plugin) = self.plugins.get_mut(isolated) {
|
||||
if plugin
|
||||
.sender_exec()
|
||||
.send(Request::Search(query.to_owned()))
|
||||
.is_ok()
|
||||
{
|
||||
tracing::debug!("submitted query to {}", plugin.config.name);
|
||||
self.awaiting_results += 1;
|
||||
self.no_sort = plugin.config.query.no_sort;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for plugin in query_queue {
|
||||
if let Some(plugin) = self.plugins.get_mut(plugin) {
|
||||
if plugin
|
||||
.sender_exec()
|
||||
.send(Request::Search(query.to_owned()))
|
||||
.is_ok()
|
||||
{
|
||||
tracing::debug!("submitted query to {}", plugin.config.name);
|
||||
self.awaiting_results += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// From a given position ID, fetch the search result and its associated plugin
|
||||
fn search_result(&mut self, id: usize) -> Option<(&mut PluginConnector, &mut SearchMeta)> {
|
||||
let &mut Self {
|
||||
ref mut active_search,
|
||||
ref mut plugins,
|
||||
..
|
||||
} = self;
|
||||
|
||||
active_search
|
||||
.get_mut(id)
|
||||
.and_then(move |(plugin_id, meta)| {
|
||||
plugins.get_mut(*plugin_id).map(|plugin| (plugin, meta))
|
||||
})
|
||||
}
|
||||
|
||||
fn sort(&mut self) -> Vec<SearchResult> {
|
||||
let &mut Self {
|
||||
ref mut active_search,
|
||||
ref mut no_sort,
|
||||
ref last_query,
|
||||
ref plugins,
|
||||
..
|
||||
} = self;
|
||||
|
||||
let query = &last_query.to_ascii_lowercase();
|
||||
|
||||
use std::cmp::Ordering;
|
||||
|
||||
if *no_sort {
|
||||
*no_sort = false;
|
||||
} else {
|
||||
active_search.sort_by(|a, b| {
|
||||
fn calculate_weight(meta: &SearchMeta, query: &str) -> usize {
|
||||
let mut weight = 0;
|
||||
|
||||
let name = meta.name.to_ascii_lowercase();
|
||||
let description = meta.description.to_ascii_lowercase();
|
||||
let exec = meta
|
||||
.exec
|
||||
.as_ref()
|
||||
.map(|exec| exec.to_ascii_lowercase())
|
||||
.unwrap_or_default();
|
||||
|
||||
if !name.starts_with(query) {
|
||||
weight = 1;
|
||||
|
||||
if !name.contains(query) {
|
||||
weight = strsim::damerau_levenshtein(&name, query)
|
||||
.min(strsim::damerau_levenshtein(&description, query));
|
||||
|
||||
if let Some(keywords) = meta.keywords.as_ref() {
|
||||
for keyword in keywords.iter() {
|
||||
let keyword = keyword.to_ascii_lowercase();
|
||||
weight = if keyword.starts_with(query)
|
||||
|| keyword.contains(query)
|
||||
{
|
||||
1
|
||||
} else {
|
||||
weight.min(strsim::damerau_levenshtein(query, &keyword) + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if exec.contains(query) {
|
||||
weight = if exec.starts_with(query) {
|
||||
weight.min(2)
|
||||
} else {
|
||||
weight.min(strsim::damerau_levenshtein(query, &exec))
|
||||
}
|
||||
}
|
||||
|
||||
weight
|
||||
}
|
||||
|
||||
let a_weight = calculate_weight(&a.1, query);
|
||||
let b_weight = calculate_weight(&b.1, query);
|
||||
|
||||
match a_weight.cmp(&b_weight) {
|
||||
Ordering::Equal => {
|
||||
let a_len = a.1.name.len();
|
||||
let b_len = b.1.name.len();
|
||||
|
||||
a_len.cmp(&b_len)
|
||||
}
|
||||
other => other,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let take = if last_query.starts_with('/') | last_query.starts_with('~') {
|
||||
100
|
||||
} else {
|
||||
8
|
||||
};
|
||||
|
||||
let mut windows = Vec::with_capacity(take);
|
||||
let mut non_windows = Vec::with_capacity(take);
|
||||
|
||||
let search_results =
|
||||
active_search
|
||||
.iter()
|
||||
.take(take)
|
||||
.enumerate()
|
||||
.map(|(id, (plugin, meta))| SearchResult {
|
||||
id: id as u32,
|
||||
name: meta.name.clone(),
|
||||
description: meta.description.clone(),
|
||||
icon: meta.icon.clone(),
|
||||
category_icon: plugins
|
||||
.get(*plugin)
|
||||
.and_then(|conn| conn.config.icon.clone()),
|
||||
window: meta.window,
|
||||
});
|
||||
|
||||
for result in search_results {
|
||||
if result.window.is_some() {
|
||||
windows.push(result);
|
||||
} else {
|
||||
non_windows.push(result)
|
||||
}
|
||||
}
|
||||
|
||||
windows.append(&mut non_windows);
|
||||
windows
|
||||
}
|
||||
}
|
||||
|
||||
async fn plugin_forwarder(
|
||||
plugin_id: PluginKey,
|
||||
receiver: Receiver<PluginResponse>,
|
||||
forwarder: Sender<Event>,
|
||||
) {
|
||||
while let Ok(response) = receiver.recv_async().await {
|
||||
let _ = forwarder.send(Event::Response((plugin_id, response)));
|
||||
}
|
||||
|
||||
let _ = forwarder.send(Event::PluginExit(plugin_id));
|
||||
}
|
||||
|
||||
/// Handles Requests received from a frontend
|
||||
async fn request_handler(tx: Sender<Event>) {
|
||||
let mut requested_to_exit = false;
|
||||
let mut request_stream = json_input_stream(async_stdin());
|
||||
|
||||
while let Some(result) = request_stream.next().await {
|
||||
match result {
|
||||
Ok(request) => {
|
||||
if let Request::Exit = request {
|
||||
requested_to_exit = true
|
||||
}
|
||||
|
||||
let _ = tx.send(Event::Request(request));
|
||||
|
||||
if requested_to_exit {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Err(why) => {
|
||||
tracing::error!("Request JSON is malformed: {}", why);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracing::debug!("no longer listening for requests")
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue