Initial commit.
4
.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
.DS_Store
|
||||
arm64
|
||||
x86_64
|
||||
build
|
||||
674
COPYING
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>.
|
||||
35
Makefile
Normal file
@@ -0,0 +1,35 @@
|
||||
CmdBar.app:
|
||||
$(MAKE) -C src FLAGS=-O CFLAGS=-O3 all
|
||||
|
||||
container:
|
||||
ditto -c -k --keepParent ./src/CmdBar.app ./build/CmdBar.zip
|
||||
|
||||
notarize:
|
||||
xcrun notarytool submit ./build/CmdBar.zip \
|
||||
--keychain-profile "notarytool-password" --wait
|
||||
|
||||
staple:
|
||||
cd build && \
|
||||
ditto -xk CmdBar.zip . && \
|
||||
rm CmdBar.zip && \
|
||||
xcrun stapler staple CmdBar.app
|
||||
|
||||
zip:
|
||||
cd build && \
|
||||
ditto -c -k --keepParent CmdBar.app CmdBar.zip
|
||||
|
||||
dmg:
|
||||
cp background.png build && cd build && \
|
||||
create-dmg --volname "CmdBar Installer" --window-size 600 400 \
|
||||
--background "background.png" --icon "CmdBar.app" 200 170 \
|
||||
--app-drop-link 400 170 --icon-size 100 "CmdBar.dmg" "CmdBar"
|
||||
rm build/background.png
|
||||
|
||||
all: CmdBar.app container notarize staple zip dmg
|
||||
|
||||
clean:
|
||||
rm -rf build
|
||||
|
||||
clean-all: clean
|
||||
mkdir build
|
||||
@$(MAKE) -C src clean-all
|
||||
10
README.md
Normal file
@@ -0,0 +1,10 @@
|
||||
# About CmdBar
|
||||
CmdBar allows you to display an output of scripts (or executables) in the
|
||||
MacOS's menu bar. Read more at [cmdbar.app](https://cmdbar.app/).
|
||||
|
||||
# Documentation
|
||||
You can read documentation at
|
||||
[cmdbar.app/documentation](https://cmdbar.app/documentation).
|
||||
|
||||
# Compiled Binary
|
||||
Download CmdBar at [cmdbar.app/download](https://cmdbar.app/download).
|
||||
BIN
background.png
Normal file
|
After Width: | Height: | Size: 23 KiB |
374
src/AboutViewController.swift
Normal file
@@ -0,0 +1,374 @@
|
||||
//
|
||||
// AboutLicenseView.swift
|
||||
// CmdBar
|
||||
//
|
||||
// Created by Igor Kolokolnikov on 8/16/23.
|
||||
//
|
||||
|
||||
import Cocoa
|
||||
|
||||
// MARK: - Constants
|
||||
fileprivate enum AboutLinks {
|
||||
static let privacyLink = "https://cmdbar.app/#privacy-policy"
|
||||
static let purchaseLink = "https://cmdbar.app/purchase"
|
||||
}
|
||||
|
||||
enum Strings {
|
||||
static let copyright = "Copyright © 2024 GarikMI. All rights reserved."
|
||||
static let evaluationTitle = "License - Evaluation"
|
||||
static let evaluationMessage = "You are currently using evaluation license. CmdBar will quit after 20 minutes. If you already own a license, enter it below or purchase a license."
|
||||
static let activate = "Activate"
|
||||
static let proTitle = "License - Activated"
|
||||
static let proMessage = "Thank you for purchasing CmdBar! Enjoy!"
|
||||
static let deactivate = "Deactivate"
|
||||
static let activating = "Activating..."
|
||||
}
|
||||
|
||||
fileprivate enum ViewConstants {
|
||||
static let spacing2: CGFloat = 2
|
||||
static let spacing10: CGFloat = 10
|
||||
static let spacing20: CGFloat = 20
|
||||
}
|
||||
|
||||
// MARK: - Controller
|
||||
class AboutViewController: NSViewController, NSTextFieldDelegate {
|
||||
// MARK: - Views
|
||||
private var appIconImage: NSImageView = {
|
||||
//let image = NSImageView(image: NSApp.applicationIconImage)
|
||||
let image = NSImageView()
|
||||
image.image = NSWorkspace.shared.icon(forFile: Bundle.main.bundlePath)
|
||||
image.imageScaling = .scaleAxesIndependently
|
||||
image.translatesAutoresizingMaskIntoConstraints = false
|
||||
return image
|
||||
}()
|
||||
|
||||
private var appNameLabel: NSTextField = {
|
||||
let textField = NSTextField()
|
||||
textField.stringValue = (Bundle.main.infoDictionary?["CFBundleName"] as? String) ?? "NOT FOUND"
|
||||
textField.isEditable = false
|
||||
textField.isBezeled = false
|
||||
textField.drawsBackground = false
|
||||
textField.alignment = .left
|
||||
textField.font = NSFont.systemFont(ofSize: NSFontDescriptor.preferredFontDescriptor(forTextStyle: .body).pointSize, weight: .bold)
|
||||
textField.translatesAutoresizingMaskIntoConstraints = false
|
||||
return textField
|
||||
}()
|
||||
|
||||
private var versionLabel: NSTextField = {
|
||||
let textField = NSTextField()
|
||||
textField.stringValue = "Version \((Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String) ?? "-.--")"
|
||||
textField.isEditable = false
|
||||
textField.isBezeled = false
|
||||
textField.drawsBackground = false
|
||||
textField.alignment = .left
|
||||
textField.textColor = NSColor.systemGray
|
||||
textField.font = NSFont.systemFont(ofSize: NSFontDescriptor.preferredFontDescriptor(forTextStyle: .subheadline).pointSize, weight: .regular)
|
||||
textField.translatesAutoresizingMaskIntoConstraints = false
|
||||
return textField
|
||||
}()
|
||||
|
||||
private var copyrightLabel: NSTextField = {
|
||||
let textField = NSTextField()
|
||||
textField.stringValue = Strings.copyright
|
||||
textField.maximumNumberOfLines = 4
|
||||
textField.cell?.truncatesLastVisibleLine = true
|
||||
textField.isEditable = false
|
||||
textField.isBezeled = false
|
||||
textField.drawsBackground = false
|
||||
textField.alignment = .left
|
||||
textField.textColor = NSColor.systemGray
|
||||
textField.font = NSFont.systemFont(ofSize: NSFontDescriptor.preferredFontDescriptor(forTextStyle: .subheadline).pointSize, weight: .regular)
|
||||
textField.translatesAutoresizingMaskIntoConstraints = false
|
||||
return textField
|
||||
}()
|
||||
|
||||
private var licenseLabel: NSTextField = {
|
||||
let textField = NSTextField()
|
||||
textField.stringValue = Strings.evaluationTitle
|
||||
textField.isEditable = false
|
||||
textField.isBezeled = false
|
||||
textField.drawsBackground = false
|
||||
textField.alignment = .left
|
||||
textField.font = NSFont.systemFont(ofSize: NSFontDescriptor.preferredFontDescriptor(forTextStyle: .title2).pointSize, weight: .bold)
|
||||
textField.translatesAutoresizingMaskIntoConstraints = false
|
||||
return textField
|
||||
}()
|
||||
|
||||
private var licenseInfoLabel: NSTextField = {
|
||||
let textField = NSTextField()
|
||||
textField.stringValue = Strings.evaluationMessage
|
||||
textField.cell?.truncatesLastVisibleLine = true
|
||||
textField.maximumNumberOfLines = 6
|
||||
textField.isEditable = false
|
||||
textField.isBezeled = false
|
||||
textField.drawsBackground = false
|
||||
textField.alignment = .left
|
||||
textField.textColor = NSColor.systemGray
|
||||
textField.font = NSFont.systemFont(ofSize: NSFontDescriptor.preferredFontDescriptor(forTextStyle: .subheadline).pointSize, weight: .regular)
|
||||
textField.translatesAutoresizingMaskIntoConstraints = false
|
||||
return textField
|
||||
}()
|
||||
|
||||
private var emailInput: EditableNSTextField = {
|
||||
let textField = EditableNSTextField()
|
||||
textField.placeholderString = "Email"
|
||||
textField.bezelStyle = .roundedBezel
|
||||
textField.translatesAutoresizingMaskIntoConstraints = false
|
||||
return textField
|
||||
}()
|
||||
|
||||
private var licenseKeyInput: EditableNSTextField = {
|
||||
let textField = EditableNSTextField()
|
||||
textField.placeholderString = "License Key"
|
||||
textField.bezelStyle = .roundedBezel
|
||||
textField.translatesAutoresizingMaskIntoConstraints = false
|
||||
return textField
|
||||
}()
|
||||
|
||||
private var privacyButton: NSButton = {
|
||||
let button = NSButton()
|
||||
button.title = "Privacy Policy"
|
||||
button.sizeToFit()
|
||||
button.bezelStyle = .rounded
|
||||
button.action = #selector(privacy)
|
||||
button.translatesAutoresizingMaskIntoConstraints = false
|
||||
return button
|
||||
}()
|
||||
|
||||
private var closeButton: NSButton = {
|
||||
let button = NSButton()
|
||||
button.title = "Close"
|
||||
button.sizeToFit()
|
||||
button.bezelStyle = .rounded
|
||||
button.action = #selector(close)
|
||||
button.translatesAutoresizingMaskIntoConstraints = false
|
||||
return button
|
||||
}()
|
||||
|
||||
private var purchaseButton: NSButton = {
|
||||
let button = NSButton()
|
||||
button.title = "Purchase"
|
||||
button.sizeToFit()
|
||||
button.bezelStyle = .rounded
|
||||
button.action = #selector(purchase)
|
||||
button.translatesAutoresizingMaskIntoConstraints = false
|
||||
return button
|
||||
}()
|
||||
|
||||
private var activateButton: NSButton = {
|
||||
let button = NSButton()
|
||||
button.isEnabled = false
|
||||
button.title = "Activate"
|
||||
button.keyEquivalent = "\r"
|
||||
button.sizeToFit()
|
||||
button.bezelStyle = .rounded
|
||||
button.action = #selector(activate)
|
||||
button.translatesAutoresizingMaskIntoConstraints = false
|
||||
return button
|
||||
}()
|
||||
|
||||
private var dividerBox: NSBox = {
|
||||
let box = NSBox()
|
||||
box.boxType = .separator
|
||||
box.translatesAutoresizingMaskIntoConstraints = false
|
||||
return box
|
||||
}()
|
||||
|
||||
// MARK: - Lifecycle
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
// Input delegates
|
||||
emailInput.delegate = self
|
||||
licenseKeyInput.delegate = self
|
||||
|
||||
// Program info
|
||||
view.addSubview(appIconImage)
|
||||
view.addSubview(appNameLabel)
|
||||
view.addSubview(versionLabel)
|
||||
view.addSubview(copyrightLabel)
|
||||
view.addSubview(privacyButton)
|
||||
|
||||
// Divider
|
||||
view.addSubview(dividerBox)
|
||||
|
||||
// License
|
||||
view.addSubview(licenseLabel)
|
||||
view.addSubview(licenseInfoLabel)
|
||||
view.addSubview(emailInput)
|
||||
view.addSubview(licenseKeyInput)
|
||||
|
||||
// Action buttons
|
||||
view.addSubview(closeButton)
|
||||
view.addSubview(purchaseButton)
|
||||
view.addSubview(activateButton)
|
||||
|
||||
setupConstraints()
|
||||
}
|
||||
|
||||
override func viewDidAppear() {
|
||||
super.viewDidAppear()
|
||||
self.view.window?.center()
|
||||
checkLicense()
|
||||
}
|
||||
|
||||
override func loadView() {
|
||||
self.view = NSView()
|
||||
}
|
||||
|
||||
// MARK: - Constraints
|
||||
private func setupConstraints() {
|
||||
// View.
|
||||
NSLayoutConstraint.activate([
|
||||
view.widthAnchor.constraint(equalToConstant: 600),
|
||||
view.heightAnchor.constraint(lessThanOrEqualToConstant: 500),
|
||||
])
|
||||
|
||||
// App image.
|
||||
NSLayoutConstraint.activate([
|
||||
appIconImage.widthAnchor.constraint(equalToConstant: 60),
|
||||
appIconImage.heightAnchor.constraint(equalTo: appIconImage.widthAnchor, multiplier: 1),
|
||||
|
||||
appIconImage.topAnchor.constraint(equalTo: view.topAnchor, constant: ViewConstants.spacing20),
|
||||
appIconImage.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: ViewConstants.spacing20),
|
||||
])
|
||||
|
||||
// Title
|
||||
NSLayoutConstraint.activate([
|
||||
appNameLabel.topAnchor.constraint(equalTo: appIconImage.topAnchor),
|
||||
appNameLabel.leadingAnchor.constraint(equalTo: appIconImage.trailingAnchor, constant: ViewConstants.spacing10),
|
||||
appNameLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -ViewConstants.spacing20),
|
||||
|
||||
versionLabel.topAnchor.constraint(equalTo: appNameLabel.bottomAnchor, constant: ViewConstants.spacing2),
|
||||
versionLabel.leadingAnchor.constraint(equalTo: appNameLabel.leadingAnchor),
|
||||
versionLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -ViewConstants.spacing20),
|
||||
|
||||
copyrightLabel.topAnchor.constraint(equalTo: versionLabel.bottomAnchor, constant: ViewConstants.spacing2),
|
||||
copyrightLabel.leadingAnchor.constraint(equalTo: appNameLabel.leadingAnchor),
|
||||
copyrightLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -ViewConstants.spacing20),
|
||||
|
||||
privacyButton.topAnchor.constraint(equalTo: copyrightLabel.bottomAnchor, constant: ViewConstants.spacing10),
|
||||
privacyButton.leadingAnchor.constraint(equalTo: appNameLabel.leadingAnchor),
|
||||
])
|
||||
|
||||
NSLayoutConstraint.activate([
|
||||
dividerBox.topAnchor.constraint(equalTo: privacyButton.bottomAnchor, constant: ViewConstants.spacing10),
|
||||
dividerBox.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: ViewConstants.spacing20),
|
||||
dividerBox.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -ViewConstants.spacing20),
|
||||
])
|
||||
|
||||
// License labels.
|
||||
NSLayoutConstraint.activate([
|
||||
licenseLabel.topAnchor.constraint(equalTo: dividerBox.bottomAnchor, constant: ViewConstants.spacing10),
|
||||
licenseLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: ViewConstants.spacing20),
|
||||
licenseLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -ViewConstants.spacing20),
|
||||
|
||||
licenseInfoLabel.topAnchor.constraint(equalTo: licenseLabel.bottomAnchor, constant: ViewConstants.spacing2),
|
||||
licenseInfoLabel.leadingAnchor.constraint(equalTo: licenseLabel.leadingAnchor),
|
||||
licenseInfoLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -ViewConstants.spacing20),
|
||||
])
|
||||
|
||||
// License inputs.
|
||||
NSLayoutConstraint.activate([
|
||||
emailInput.topAnchor.constraint(equalTo: licenseInfoLabel.bottomAnchor, constant: ViewConstants.spacing10),
|
||||
emailInput.leadingAnchor.constraint(equalTo: licenseInfoLabel.leadingAnchor),
|
||||
emailInput.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -ViewConstants.spacing20),
|
||||
|
||||
licenseKeyInput.topAnchor.constraint(equalTo: emailInput.bottomAnchor, constant: ViewConstants.spacing10),
|
||||
licenseKeyInput.leadingAnchor.constraint(equalTo: licenseInfoLabel.leadingAnchor),
|
||||
licenseKeyInput.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -ViewConstants.spacing20),
|
||||
])
|
||||
|
||||
// License buttons.
|
||||
NSLayoutConstraint.activate([
|
||||
activateButton.topAnchor.constraint(equalTo: licenseKeyInput.bottomAnchor, constant: ViewConstants.spacing20),
|
||||
activateButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -ViewConstants.spacing20),
|
||||
activateButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -ViewConstants.spacing20),
|
||||
|
||||
purchaseButton.trailingAnchor.constraint(equalTo: activateButton.leadingAnchor, constant: -ViewConstants.spacing10),
|
||||
purchaseButton.lastBaselineAnchor.constraint(equalTo: activateButton.lastBaselineAnchor),
|
||||
|
||||
closeButton.trailingAnchor.constraint(equalTo: purchaseButton.leadingAnchor, constant: -ViewConstants.spacing10),
|
||||
closeButton.lastBaselineAnchor.constraint(equalTo: purchaseButton.lastBaselineAnchor),
|
||||
])
|
||||
}
|
||||
|
||||
// MARK: - Button Functions
|
||||
@objc private func privacy() {
|
||||
NSWorkspace.shared.open(URL(string: AboutLinks.privacyLink)!)
|
||||
}
|
||||
|
||||
@objc private func close() {
|
||||
view.window?.orderOut(nil)
|
||||
}
|
||||
|
||||
@objc private func purchase() {
|
||||
guard let url = URL(string: AboutLinks.purchaseLink) else { return }
|
||||
NSWorkspace.shared.open(url)
|
||||
}
|
||||
|
||||
@objc private func activate() {
|
||||
let email = emailInput.stringValue
|
||||
let key = licenseKeyInput.stringValue
|
||||
if email.isEmpty || key.isEmpty { return }
|
||||
|
||||
activateButton.isEnabled = false
|
||||
activateButton.title = Strings.activating
|
||||
|
||||
// TODO: Notify the user if registration failed.
|
||||
LicenseManager.standard.activateLicense(email: email, key: key) { [weak self] _ in
|
||||
DispatchQueue.main.async { self?.checkLicense() }
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func deactivate() {
|
||||
LicenseManager.standard.deactivateLicense()
|
||||
checkLicense()
|
||||
}
|
||||
|
||||
private func checkLicense() {
|
||||
if LicenseManager.standard.isRegistered() {
|
||||
activateButton.isEnabled = true
|
||||
activateButton.title = Strings.deactivate
|
||||
activateButton.action = #selector(deactivate)
|
||||
|
||||
licenseLabel.stringValue = Strings.proTitle
|
||||
licenseInfoLabel.stringValue = Strings.proMessage
|
||||
|
||||
emailInput.isEnabled = false
|
||||
licenseKeyInput.isEnabled = false
|
||||
|
||||
let license = LicenseManager.standard.getLicense()
|
||||
emailInput.stringValue = license.email
|
||||
licenseKeyInput.stringValue =
|
||||
"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXX" +
|
||||
license.key.dropFirst(license.key.count - 5)
|
||||
} else {
|
||||
activateButton.isEnabled = false
|
||||
activateButton.title = Strings.activate
|
||||
activateButton.action = #selector(activate)
|
||||
|
||||
licenseLabel.stringValue = Strings.evaluationTitle
|
||||
licenseInfoLabel.stringValue = Strings.evaluationMessage
|
||||
|
||||
emailInput.isEnabled = true
|
||||
licenseKeyInput.isEnabled = true
|
||||
|
||||
emailInput.stringValue = ""
|
||||
licenseKeyInput.stringValue = ""
|
||||
|
||||
emailInput.becomeFirstResponder()
|
||||
}
|
||||
|
||||
#if(DEBUG)
|
||||
emailInput.stringValue = "igorkolokolnikov@icloud.com"
|
||||
licenseKeyInput.stringValue = "137A5010-A95A-4A8C-A037-6DF16B6CA666"
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
extension AboutViewController {
|
||||
func controlTextDidChange(_ obj: Notification) {
|
||||
activateButton.isEnabled = !(emailInput.stringValue.isEmpty || licenseKeyInput.stringValue.isEmpty)
|
||||
}
|
||||
}
|
||||
92
src/AppDelegate.swift
Normal file
@@ -0,0 +1,92 @@
|
||||
import Cocoa
|
||||
import ServiceManagement
|
||||
|
||||
class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
// MARK: - State
|
||||
private var aboutWindow: MenulessWindow!
|
||||
private var updateWindow: MenulessWindow!
|
||||
|
||||
// MARK: - Lifecycle
|
||||
func applicationDidFinishLaunching(_ notification: Notification) {
|
||||
setupAboutWindow()
|
||||
setupUpdateWindow()
|
||||
setupNotifications()
|
||||
|
||||
setupLicense()
|
||||
|
||||
CmdManager.standard.configure()
|
||||
}
|
||||
|
||||
private func setupLicense() {
|
||||
let licenseManager = LicenseManager.standard
|
||||
if !licenseManager.isRegistered() {
|
||||
showAbout()
|
||||
licenseManager.clearLicense()
|
||||
licenseManager.startTimer()
|
||||
}
|
||||
}
|
||||
|
||||
private func setupUpdateWindow() {
|
||||
let controller = UpdateViewController()
|
||||
controller.setUpdateDelegate()
|
||||
|
||||
updateWindow = MenulessWindow(viewController: controller)
|
||||
updateWindow.title = "Software Update"
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ notification: Notification) {
|
||||
persistMenuBar(false)
|
||||
CmdManager.standard.clearItems()
|
||||
}
|
||||
|
||||
// MARK: - Notifications
|
||||
private func setupNotifications() {
|
||||
NSWorkspace.shared.notificationCenter.addObserver(
|
||||
self,
|
||||
selector: #selector(wakeUp),
|
||||
name: NSWorkspace.didWakeNotification,
|
||||
object: nil)
|
||||
}
|
||||
|
||||
@objc private func wakeUp() {
|
||||
CmdManager.standard.resetTimers()
|
||||
}
|
||||
|
||||
// MARK: - Status Items
|
||||
@objc func reloadWidgets() {
|
||||
CmdManager.standard.reloadItems()
|
||||
}
|
||||
|
||||
@objc func terminateApp() {
|
||||
DispatchQueue.main.async {
|
||||
NSApplication.shared.terminate(self)
|
||||
}
|
||||
}
|
||||
|
||||
@objc func checkForUpdates() {
|
||||
NSApplication.shared.activate(ignoringOtherApps: true)
|
||||
updateWindow.makeKeyAndOrderFront(nil)
|
||||
updateWindow.center()
|
||||
}
|
||||
|
||||
// MARK: - Setup About Window
|
||||
private func setupAboutWindow() {
|
||||
aboutWindow = MenulessWindow(viewController: AboutViewController())
|
||||
}
|
||||
|
||||
// MARK: - Show About Window
|
||||
@objc func showAbout() {
|
||||
NSApplication.shared.activate(ignoringOtherApps: true)
|
||||
aboutWindow.makeKeyAndOrderFront(nil)
|
||||
}
|
||||
|
||||
// MARK: - Launch at Login
|
||||
func toggleLaunchAtLogin() {
|
||||
let service = SMAppService.mainApp
|
||||
if service.status == .enabled {
|
||||
try? service.unregister()
|
||||
} else {
|
||||
try? service.register()
|
||||
}
|
||||
}
|
||||
}
|
||||
217
src/CBMenuBarItem.swift
Normal file
@@ -0,0 +1,217 @@
|
||||
//
|
||||
// MIT License
|
||||
//
|
||||
// Copyright (c) 2022 Lukas Romsicki
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
// of this software and associated documentation files (the "Software"), to deal
|
||||
// in the Software without restriction, including without limitation the rights
|
||||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
// copies of the Software, and to permit persons to whom the Software is
|
||||
// furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all
|
||||
// copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
// SOFTWARE.
|
||||
//
|
||||
// Source Code: https://github.com/lfroms/fluid-menu-bar-extra
|
||||
// Some parts of the code were altered to fit the needs of this application.
|
||||
// Any modifications that were made are still licensed under the author's
|
||||
// original license (aka MIT license). Contents of this file are excluded
|
||||
// from the coverage of the license being applied to the rest of the code.
|
||||
//
|
||||
|
||||
import Cocoa
|
||||
import os
|
||||
|
||||
final class CBMenuBarItem: NSObject, NSWindowDelegate {
|
||||
private var statusItem: NSStatusItem
|
||||
var panel: NSPanel
|
||||
|
||||
private var localEventMonitor: EventMonitor?
|
||||
private var localDragEventMonitor: EventMonitor?
|
||||
private var globalEventMonitor: EventMonitor?
|
||||
|
||||
override init() {
|
||||
self.statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
|
||||
self.statusItem.isVisible = true
|
||||
self.panel = PopoverPanel(viewController: CmdViewController())
|
||||
|
||||
super.init()
|
||||
|
||||
// Events
|
||||
// Shows panel and keeps the button highlighted.
|
||||
localEventMonitor = LocalEventMonitor(mask: [.leftMouseDown]) { [weak self] event in
|
||||
if let button = self?.statusItem.button, event.window == button.window, !event.modifierFlags.contains(.command) {
|
||||
self?.statusButtonPressed(button)
|
||||
return nil
|
||||
}
|
||||
|
||||
return event
|
||||
}
|
||||
|
||||
// On click and drag, the button should panel should desappear and
|
||||
// un-highlight.
|
||||
localDragEventMonitor = LocalEventMonitor(mask: [.leftMouseDragged, .keyDown]) { [weak self] event in
|
||||
if let panel = self?.panel, panel.isKeyWindow {
|
||||
if event.modifierFlags.contains(.command) && event.type == .leftMouseDragged {
|
||||
self?.panel.resignKey()
|
||||
}
|
||||
}
|
||||
|
||||
return event
|
||||
}
|
||||
|
||||
// NOTE: The need for this seems a bit questionable. Maybe, this
|
||||
// works properly without global event monitor in MacOS Sequoia?
|
||||
// Resign key whenever clicking outside of panel, thus hiding the
|
||||
// panel and un-highlighting the button.
|
||||
// In order to receive events, the program needs to be codesigned.
|
||||
globalEventMonitor = GlobalEventMonitor(mask: [.leftMouseDown, .rightMouseDown]) { [weak self] event in
|
||||
if let panel = self?.panel, panel.isKeyWindow {
|
||||
panel.resignKey()
|
||||
}
|
||||
}
|
||||
|
||||
if let statusButton = statusItem.button,
|
||||
let statusButtonWindow = statusButton.window {
|
||||
statusButtonWindow.delegate = self
|
||||
}
|
||||
|
||||
self.panel.delegate = self
|
||||
localEventMonitor?.start()
|
||||
localDragEventMonitor?.start()
|
||||
}
|
||||
|
||||
deinit {
|
||||
persistMenuBar(false)
|
||||
localEventMonitor?.stop()
|
||||
localDragEventMonitor?.stop()
|
||||
globalEventMonitor?.stop()
|
||||
panel.close()
|
||||
NSStatusBar.system.removeStatusItem(statusItem)
|
||||
}
|
||||
|
||||
@objc private func statusButtonPressed(_ sender: NSButton) {
|
||||
if panel.isVisible {
|
||||
panel.resignKey()
|
||||
return
|
||||
}
|
||||
showPanel()
|
||||
}
|
||||
|
||||
private func showPanel() {
|
||||
setButtonHighlighted(to: true)
|
||||
persistMenuBar(true)
|
||||
setPanelPosition()
|
||||
panel.makeKeyAndOrderFront(nil)
|
||||
}
|
||||
|
||||
private func dismissPanel() {
|
||||
NSAnimationContext.runAnimationGroup { context in
|
||||
context.duration = 0.3
|
||||
context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
|
||||
panel.animator().alphaValue = 0
|
||||
} completionHandler: { [weak self] in
|
||||
self?.panel.orderOut(nil)
|
||||
self?.panel.alphaValue = 1
|
||||
self?.setButtonHighlighted(to: false)
|
||||
persistMenuBar(false)
|
||||
}
|
||||
}
|
||||
|
||||
private func setPanelPosition() {
|
||||
guard let statusItemView = statusItem.button?.window else {
|
||||
panel.center()
|
||||
return
|
||||
}
|
||||
|
||||
var targetRect = statusItemView.frame
|
||||
|
||||
if let screen = statusItemView.screen {
|
||||
let panelWidth = panel.frame.width
|
||||
|
||||
if statusItemView.frame.origin.x + panelWidth > screen.visibleFrame.width {
|
||||
targetRect.origin.x += statusItemView.frame.width
|
||||
targetRect.origin.x -= panelWidth
|
||||
targetRect.origin.x += Metrics.windowBorderSize
|
||||
} else {
|
||||
targetRect.origin.x -= Metrics.windowBorderSize
|
||||
}
|
||||
} else {
|
||||
targetRect.origin.x -= Metrics.windowBorderSize
|
||||
}
|
||||
|
||||
if targetRect.origin.x < 0 {
|
||||
targetRect.origin.x = 0
|
||||
}
|
||||
|
||||
panel.setFrameTopLeftPoint(targetRect.origin)
|
||||
}
|
||||
|
||||
private func setButtonHighlighted(to highlight: Bool) {
|
||||
self.statusItem.button!.highlight(highlight)
|
||||
}
|
||||
|
||||
func setImage(title: String?, description: String) {
|
||||
if title != nil {
|
||||
statusItem.button!.image = NSImage(systemSymbolName: title!, accessibilityDescription: description)
|
||||
return
|
||||
}
|
||||
statusItem.button!.image = nil
|
||||
}
|
||||
|
||||
func setTitle(_ title: String) {
|
||||
statusItem.button!.title = title
|
||||
}
|
||||
|
||||
func setAutosaveName(_ name: String) {
|
||||
statusItem.autosaveName = name
|
||||
}
|
||||
|
||||
func setContents(to text: String) {
|
||||
guard let viewContoller = panel.contentViewController as? CmdViewController else { return }
|
||||
viewContoller.setText(text)
|
||||
}
|
||||
|
||||
func setFile(_ file: CmdFile) {
|
||||
guard let viewContoller = panel.contentViewController as? CmdViewController else { return }
|
||||
viewContoller.setFile(file)
|
||||
}
|
||||
|
||||
func windowDidResize(_ notification: Notification) {
|
||||
if let cmdPanel = notification.object as? NSPanel, panel == cmdPanel {
|
||||
setPanelPosition()
|
||||
}
|
||||
}
|
||||
|
||||
func windowDidMove(_ notification: Notification) {
|
||||
if let statusBarButtonWindow = notification.object as? NSWindow,
|
||||
let buttonWindow = statusItem.button?.window,
|
||||
buttonWindow == statusBarButtonWindow
|
||||
{
|
||||
setPanelPosition()
|
||||
}
|
||||
}
|
||||
|
||||
func windowDidBecomeKey(_ notification: Notification) {
|
||||
globalEventMonitor?.start()
|
||||
}
|
||||
|
||||
func windowDidResignKey(_ notification: Notification) {
|
||||
globalEventMonitor?.stop()
|
||||
dismissPanel()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Metrics
|
||||
fileprivate enum Metrics {
|
||||
static let windowBorderSize: CGFloat = 2
|
||||
}
|
||||
81
src/CircularProgressView.swift
Normal file
@@ -0,0 +1,81 @@
|
||||
import AppKit
|
||||
|
||||
class CircularProgressView: NSView {
|
||||
private var _value: CGFloat = 0.0
|
||||
var value: CGFloat {
|
||||
get { _value }
|
||||
set {
|
||||
if newValue > maxValue {
|
||||
_value = 1.0
|
||||
} else if newValue < minValue {
|
||||
_value = 0.0
|
||||
} else {
|
||||
_value = newValue / maxValue
|
||||
}
|
||||
advanceProgress(to: _value)
|
||||
}
|
||||
}
|
||||
var minValue: Double = 0
|
||||
var maxValue: Double = 1
|
||||
|
||||
var animationSpeed: Double = 0.5
|
||||
var backgroundColor: NSColor = NSColor.darkGray
|
||||
var foregroundColor: NSColor = NSColor.systemBlue
|
||||
|
||||
private let backgroundLayer = CAShapeLayer()
|
||||
private let foregroundLayer = CAShapeLayer()
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
super.draw(dirtyRect)
|
||||
drawCirlces()
|
||||
}
|
||||
|
||||
override func layout() {
|
||||
super.layout()
|
||||
foregroundLayer.frame = bounds
|
||||
}
|
||||
|
||||
private func drawCirlces() {
|
||||
let lineWidth = bounds.width * 0.3
|
||||
|
||||
let bgMutablePath = CGMutablePath()
|
||||
bgMutablePath.addArc(
|
||||
center: CGPoint(x: bounds.midX, y: bounds.midY),
|
||||
radius: min(bounds.width, bounds.height) / 2 - (lineWidth / 2),
|
||||
startAngle: CGFloat.zero, endAngle: CGFloat(2 * Double.pi),
|
||||
clockwise: true
|
||||
)
|
||||
backgroundLayer.path = bgMutablePath
|
||||
backgroundLayer.fillColor = NSColor.clear.cgColor
|
||||
// backgroundLayer.strokeColor = NSColor(name: nil) { getColors(.lightGray, .darkGray, for: $0) }.cgColor
|
||||
backgroundLayer.strokeColor = backgroundColor.cgColor
|
||||
backgroundLayer.lineWidth = lineWidth
|
||||
|
||||
let fgMutablePath = CGMutablePath()
|
||||
fgMutablePath.addArc(
|
||||
center: CGPoint(x: bounds.midX, y: bounds.midY),
|
||||
radius: min(bounds.width, bounds.height) / 2 - (lineWidth / 2),
|
||||
startAngle: CGFloat.zero, endAngle: CGFloat(2 * Double.pi),
|
||||
clockwise: true
|
||||
)
|
||||
foregroundLayer.path = fgMutablePath
|
||||
foregroundLayer.fillColor = NSColor.clear.cgColor
|
||||
foregroundLayer.strokeColor = foregroundColor.cgColor
|
||||
foregroundLayer.lineCap = .round
|
||||
foregroundLayer.lineWidth = lineWidth
|
||||
foregroundLayer.strokeEnd = value
|
||||
foregroundLayer.transform = CATransform3DMakeRotation(CGFloat(Double.pi / 2), 0, 0, 1)
|
||||
|
||||
layer?.addSublayer(backgroundLayer)
|
||||
layer?.addSublayer(foregroundLayer)
|
||||
}
|
||||
|
||||
private func advanceProgress(to value: Double) {
|
||||
let animation = CABasicAnimation(keyPath: "strokeEnd")
|
||||
animation.duration = animationSpeed
|
||||
animation.fromValue = foregroundLayer.presentation()?.value(forKeyPath: "strokeEnd") ?? value
|
||||
animation.toValue = value
|
||||
foregroundLayer.strokeEnd = CGFloat(value)
|
||||
foregroundLayer.add(animation, forKey: "pathAnimation")
|
||||
}
|
||||
}
|
||||
5
src/CmdBar.entitlements
Normal file
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict/>
|
||||
</plist>
|
||||
175
src/CmdManager.swift
Normal file
@@ -0,0 +1,175 @@
|
||||
import Foundation
|
||||
import Cocoa
|
||||
|
||||
// MARK: - CmdFile
|
||||
class CmdFile {
|
||||
// MARK: - State
|
||||
private var timer: DispatchSourceTimer?
|
||||
private(set) var lastExec = Int(Date().timeIntervalSince1970)
|
||||
var untilNextExec: Int {
|
||||
get {
|
||||
let res = reloadTime - (Int(Date().timeIntervalSince1970) - lastExec)
|
||||
if res <= 0 { return reloadTime }
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
private(set) var url: URL
|
||||
private(set) var reloadTime: Int
|
||||
private var statusItem: CBMenuBarItem = CBMenuBarItem()
|
||||
|
||||
private var shouldWait = false
|
||||
|
||||
// MARK: - Initializers
|
||||
init(url: URL, reloadTime: Int) {
|
||||
self.url = url
|
||||
self.reloadTime = reloadTime
|
||||
|
||||
statusItem.setAutosaveName(url.lastPathComponent)
|
||||
statusItem.setImage(title: "clock.fill", description: "Clock")
|
||||
statusItem.setFile(self)
|
||||
|
||||
setupTimer()
|
||||
resumeTimer()
|
||||
}
|
||||
|
||||
deinit {
|
||||
cancelTimer()
|
||||
}
|
||||
|
||||
// MARK: - Reload Widget
|
||||
private func reloadWidget() {
|
||||
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
|
||||
if let url = self?.url {
|
||||
self?.shouldWait = true
|
||||
let execResult = execute(atPath: url)
|
||||
DispatchQueue.main.async {
|
||||
if execResult.title.isEmpty {
|
||||
self?.statusItem.setImage(title: "exclamationmark.triangle.fill", description: "Warning")
|
||||
self?.statusItem.setTitle("")
|
||||
} else {
|
||||
self?.statusItem.setImage(title: nil, description: "")
|
||||
self?.statusItem.setTitle(execResult.0)
|
||||
}
|
||||
self?.statusItem.setContents(to: execResult.body)
|
||||
}
|
||||
self?.shouldWait = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Timer
|
||||
private func setupTimer() {
|
||||
timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
|
||||
timer?.schedule(deadline: .now(), repeating: .seconds(reloadTime))
|
||||
timer?.setEventHandler { [weak self] in
|
||||
guard let file = self, !file.shouldWait else { return }
|
||||
file.reloadWidget()
|
||||
file.lastExec = Int(Date().timeIntervalSince1970)
|
||||
}
|
||||
}
|
||||
|
||||
private func resumeTimer() {
|
||||
timer?.schedule(deadline: .now(), repeating: .seconds(reloadTime))
|
||||
timer?.resume()
|
||||
}
|
||||
|
||||
private func pauseTimer() {
|
||||
timer?.suspend()
|
||||
}
|
||||
|
||||
private func cancelTimer() {
|
||||
if timer != nil {
|
||||
timer?.cancel()
|
||||
timer = nil
|
||||
}
|
||||
}
|
||||
|
||||
func restartTimer() {
|
||||
pauseTimer()
|
||||
resumeTimer()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CmdManager
|
||||
class CmdManager {
|
||||
//MARK: - State
|
||||
static let standard = CmdManager()
|
||||
|
||||
var paths: [CmdFile] = []
|
||||
private var defaultStatusItem: NSStatusItem?
|
||||
|
||||
// MARK: - Configure
|
||||
func configure() {
|
||||
getPaths()
|
||||
if paths.isEmpty {
|
||||
setupMenu()
|
||||
} else {
|
||||
defaultStatusItem = nil
|
||||
}
|
||||
}
|
||||
|
||||
private func getPaths() {
|
||||
let manager = FileManager.default
|
||||
let path = manager.homeDirectoryForCurrentUser.appending(path: ".cmdbar")
|
||||
if let contents = try? manager.contentsOfDirectory(atPath: path.path()) {
|
||||
for content in contents {
|
||||
let filePath = path.appending(path: content)
|
||||
|
||||
let domains = filePath.path().components(separatedBy: ".")
|
||||
if (isValidTimeFormat(domains[domains.count - 1])) {
|
||||
paths.append(CmdFile(url: filePath, reloadTime: intervalToSeconds(from: domains[domains.count - 1])))
|
||||
} else if (domains.last == "sh" && isValidTimeFormat(domains[domains.count - 2])) {
|
||||
paths.append(CmdFile(url: filePath, reloadTime: intervalToSeconds(from: domains[domains.count - 2])))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func setupMenu() {
|
||||
defaultStatusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
|
||||
if let btn = defaultStatusItem?.button {
|
||||
let image = NSApp.applicationIconImage
|
||||
image!.size = NSSize(width: 22, height: 22)
|
||||
btn.image = image
|
||||
}
|
||||
guard defaultStatusItem != nil else { return }
|
||||
let menu = NSMenu()
|
||||
menu.addItem(NSMenuItem(title: "Reload", action: #selector(reloadWidgets), keyEquivalent: ""))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "About", action: #selector(showAbout), keyEquivalent: ""))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Check for Updates...", action: #selector(checkForUpdates), keyEquivalent: ""))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(NSMenuItem(title: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))
|
||||
defaultStatusItem!.menu = menu
|
||||
}
|
||||
|
||||
func clearItems() {
|
||||
paths.removeAll()
|
||||
}
|
||||
|
||||
func reloadItems() {
|
||||
clearItems()
|
||||
configure()
|
||||
}
|
||||
|
||||
func resetTimers() {
|
||||
for item in paths {
|
||||
item.restartTimer()
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func reloadWidgets() {
|
||||
reloadItems()
|
||||
}
|
||||
|
||||
// MARK: - NSMenu Functions
|
||||
@objc private func showAbout() {
|
||||
delegate.showAbout()
|
||||
}
|
||||
|
||||
@objc private func checkForUpdates() {
|
||||
delegate.checkForUpdates()
|
||||
}
|
||||
}
|
||||
452
src/CmdViewController.swift
Normal file
@@ -0,0 +1,452 @@
|
||||
import Cocoa
|
||||
import ServiceManagement
|
||||
|
||||
fileprivate enum Metrics {
|
||||
static let contentMinWidth = 400.0
|
||||
static let contentMaxWidth = /*600.0*/ NSScreen.main!.visibleFrame.size.width * 0.7 // REVIEW: Under what circumstances can NSScreen return nil?
|
||||
static let contentMinHeight = 160.0
|
||||
static let contentMaxHeight = /*800.0*/ NSScreen.main!.visibleFrame.size.height * 0.8 // REVIEW: Under what circumstances can NSScreen return nil?
|
||||
static let padding = 10.0
|
||||
static let buttonSpacing = 2.0
|
||||
}
|
||||
|
||||
class CmdViewController: NSViewController {
|
||||
private weak var cmdFile: CmdFile?
|
||||
private var timer: DispatchSourceTimer?
|
||||
private var keyboardEvents: EventMonitor?
|
||||
|
||||
private var visualEffectView: NSView = {
|
||||
let visualEffect = NSVisualEffectView()
|
||||
visualEffect.blendingMode = .behindWindow
|
||||
visualEffect.material = .popover
|
||||
visualEffect.state = .active
|
||||
visualEffect.translatesAutoresizingMaskIntoConstraints = false
|
||||
return visualEffect
|
||||
}()
|
||||
|
||||
private var textLabelScrollView: NSScrollView = {
|
||||
let scrollView = NSScrollView()
|
||||
scrollView.automaticallyAdjustsContentInsets = false
|
||||
scrollView.hasVerticalScroller = true
|
||||
scrollView.hasHorizontalScroller = true
|
||||
scrollView.scrollerStyle = .overlay
|
||||
scrollView.drawsBackground = false
|
||||
scrollView.translatesAutoresizingMaskIntoConstraints = false
|
||||
return scrollView
|
||||
}()
|
||||
|
||||
private var textLabel: NSTextField = {
|
||||
let textField = NSTextField()
|
||||
textField.backgroundColor = .clear // NOTE: Setting drawsBackground = false messes with geometry. Also, setting a custom cell, messes up, too.
|
||||
textField.isSelectable = true
|
||||
textField.isHidden = false
|
||||
textField.isEditable = false
|
||||
textField.isBezeled = false
|
||||
textField.alignment = .left
|
||||
textField.textColor = NSColor(name: nil) { getColors(.black, .white, for: $0) }
|
||||
textField.font = NSFont.monospacedSystemFont(ofSize: NSFontDescriptor.preferredFontDescriptor(forTextStyle: .body).pointSize, weight: .regular)
|
||||
textField.translatesAutoresizingMaskIntoConstraints = false
|
||||
return textField
|
||||
}()
|
||||
|
||||
private var reloadsText: NSTextField = {
|
||||
let textField = NSTextField()
|
||||
textField.isHidden = false
|
||||
textField.stringValue = "--"
|
||||
textField.lineBreakMode = .byTruncatingTail
|
||||
textField.maximumNumberOfLines = 1
|
||||
textField.isEditable = false
|
||||
textField.isBezeled = false
|
||||
textField.drawsBackground = false
|
||||
textField.alignment = .left
|
||||
textField.textColor = NSColor(name: nil) { getColors(.darkGray, .lightGray, for: $0) }
|
||||
textField.font = NSFont.systemFont(ofSize: NSFontDescriptor.preferredFontDescriptor(forTextStyle: .subheadline).pointSize, weight: .bold)
|
||||
textField.translatesAutoresizingMaskIntoConstraints = false
|
||||
return textField
|
||||
}()
|
||||
|
||||
private var progressView: CircularProgressView = {
|
||||
let progress = CircularProgressView()
|
||||
progress.translatesAutoresizingMaskIntoConstraints = false
|
||||
return progress
|
||||
}()
|
||||
|
||||
private var statusText: NSTextField = {
|
||||
let textField = NSTextField()
|
||||
textField.isHidden = false
|
||||
textField.stringValue = "Loading..."
|
||||
textField.isEditable = false
|
||||
textField.isBezeled = false
|
||||
textField.drawsBackground = false
|
||||
textField.alignment = .center
|
||||
textField.textColor = NSColor(name: nil) { getColors(.darkGray, .lightGray, for: $0) }
|
||||
textField.font = NSFont(descriptor: NSFontDescriptor.preferredFontDescriptor(forTextStyle: .body), size: 0)
|
||||
textField.translatesAutoresizingMaskIntoConstraints = false
|
||||
return textField
|
||||
}()
|
||||
|
||||
private var quitButton: NSButton = {
|
||||
let button = NSButton()
|
||||
button.image = systemImage("xmark.circle.fill", .title2, .large, .init(paletteColors: [.white, .systemRed]))
|
||||
button.isBordered = false
|
||||
button.action = #selector(terminateApp)
|
||||
button.sizeToFit()
|
||||
button.toolTip = "Quit"
|
||||
button.translatesAutoresizingMaskIntoConstraints = false
|
||||
return button
|
||||
}()
|
||||
|
||||
private var reloadButton: NSButton = {
|
||||
let button = NSButton()
|
||||
button.image = systemImage("arrow.clockwise.circle.fill", .title2, .large, .init(paletteColors: [.white, .systemBlue]))
|
||||
button.isBordered = false
|
||||
button.action = #selector(reloadWidget)
|
||||
button.sizeToFit()
|
||||
button.toolTip = "Reload Current"
|
||||
button.translatesAutoresizingMaskIntoConstraints = false
|
||||
return button
|
||||
}()
|
||||
|
||||
private var startButton: NSButton = {
|
||||
let button = NSButton()
|
||||
button.image = systemImage("sun.max.circle.fill", .title2, .large, .init(paletteColors: [.white, .systemOrange]))
|
||||
button.isBordered = false
|
||||
button.action = #selector(openAtLogin)
|
||||
button.sizeToFit()
|
||||
button.toolTip = "Open at Login — OFF"
|
||||
button.translatesAutoresizingMaskIntoConstraints = false
|
||||
return button
|
||||
}()
|
||||
|
||||
private var aboutButton: NSButton = {
|
||||
let button = NSButton()
|
||||
button.image = systemImage("info.circle.fill", .title2, .large, .init(paletteColors: [.white, .systemGray]))
|
||||
button.isBordered = false
|
||||
button.action = #selector(showAbout)
|
||||
button.sizeToFit()
|
||||
button.toolTip = "About"
|
||||
button.translatesAutoresizingMaskIntoConstraints = false
|
||||
return button
|
||||
}()
|
||||
|
||||
private var updateButton: NSButton = {
|
||||
let button = NSButton()
|
||||
button.image = NSImage(systemSymbolName: "arrow.down.circle.fill", accessibilityDescription: nil)?
|
||||
.withSymbolConfiguration(
|
||||
NSImage.SymbolConfiguration(textStyle: .title2, scale: .large)
|
||||
.applying(.init(paletteColors: [.white, .systemGreen]))
|
||||
)
|
||||
button.isBordered = false
|
||||
button.action = #selector(updateApp)
|
||||
button.sizeToFit()
|
||||
button.toolTip = "About"
|
||||
button.toolTip = "Update"
|
||||
button.translatesAutoresizingMaskIntoConstraints = false
|
||||
return button
|
||||
}()
|
||||
|
||||
private var buttonsBackground: NSView = {
|
||||
let blurView = NSVisualEffectView()
|
||||
blurView.blendingMode = .behindWindow
|
||||
blurView.material = .sheet
|
||||
blurView.state = .active
|
||||
blurView.wantsLayer = true
|
||||
blurView.layer?.borderColor = NSColor.systemGray.withAlphaComponent(0.05).cgColor
|
||||
blurView.layer?.borderWidth = 1.5
|
||||
blurView.translatesAutoresizingMaskIntoConstraints = false
|
||||
return blurView
|
||||
}()
|
||||
|
||||
private var buttonsContainer: NSLayoutGuide = {
|
||||
let container = NSLayoutGuide()
|
||||
return container
|
||||
}()
|
||||
|
||||
private func addSubviews() {
|
||||
view.addSubview(visualEffectView)
|
||||
|
||||
view.addSubview(statusText)
|
||||
|
||||
textLabelScrollView.documentView = textLabel
|
||||
view.addSubview(textLabelScrollView)
|
||||
|
||||
view.addLayoutGuide(buttonsContainer)
|
||||
view.addSubview(buttonsBackground)
|
||||
view.addSubview(quitButton)
|
||||
view.addSubview(reloadButton)
|
||||
view.addSubview(startButton)
|
||||
view.addSubview(aboutButton)
|
||||
view.addSubview(reloadsText)
|
||||
view.addSubview(updateButton)
|
||||
view.addSubview(progressView)
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
addSubviews()
|
||||
setup()
|
||||
setContraints()
|
||||
}
|
||||
|
||||
override func loadView() {
|
||||
self.view = QuietView()
|
||||
}
|
||||
|
||||
override func viewDidAppear() {
|
||||
super.viewDidAppear()
|
||||
|
||||
startReloadTextTimer()
|
||||
keyboardEvents?.start()
|
||||
|
||||
resetReloadButton()
|
||||
}
|
||||
|
||||
override func viewDidDisappear() {
|
||||
super.viewDidDisappear()
|
||||
|
||||
timer?.cancel()
|
||||
timer = nil
|
||||
|
||||
keyboardEvents?.stop()
|
||||
|
||||
if let editor = textLabel.currentEditor() { textLabel.endEditing(editor) }
|
||||
}
|
||||
|
||||
private func setContraints() {
|
||||
setViewConstraints()
|
||||
setTextConstraints()
|
||||
setReloadConstrains()
|
||||
setButtonConstraints()
|
||||
}
|
||||
|
||||
func setup() {
|
||||
openAtLoginToggle()
|
||||
|
||||
buttonsBackground.layer?.cornerRadius = quitButton.bounds.height / Metrics.buttonSpacing + Metrics.buttonSpacing
|
||||
|
||||
setupKeyEvents()
|
||||
}
|
||||
|
||||
private func setReloadConstrains() {
|
||||
NSLayoutConstraint.activate([
|
||||
progressView.widthAnchor.constraint(equalToConstant: 16),
|
||||
progressView.heightAnchor.constraint(equalToConstant: 16),
|
||||
|
||||
progressView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: Metrics.padding),
|
||||
progressView.centerYAnchor.constraint(equalTo: reloadsText.centerYAnchor),
|
||||
])
|
||||
|
||||
NSLayoutConstraint.activate([
|
||||
reloadsText.leadingAnchor.constraint(equalTo: progressView.trailingAnchor, constant: Metrics.buttonSpacing),
|
||||
reloadsText.centerYAnchor.constraint(equalTo: buttonsBackground.centerYAnchor),
|
||||
reloadsText.trailingAnchor.constraint(equalTo: buttonsBackground.leadingAnchor, constant: -Metrics.buttonSpacing),
|
||||
])
|
||||
}
|
||||
|
||||
private func setViewConstraints() {
|
||||
NSLayoutConstraint.activate([
|
||||
visualEffectView.topAnchor.constraint(equalTo: view.topAnchor),
|
||||
visualEffectView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
|
||||
visualEffectView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
|
||||
visualEffectView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
|
||||
])
|
||||
}
|
||||
|
||||
private func setButtonConstraints() {
|
||||
NSLayoutConstraint.activate([
|
||||
quitButton.widthAnchor.constraint(equalToConstant: quitButton.bounds.width),
|
||||
quitButton.heightAnchor.constraint(equalToConstant: quitButton.bounds.height),
|
||||
reloadButton.widthAnchor.constraint(equalToConstant: reloadButton.bounds.width),
|
||||
reloadButton.heightAnchor.constraint(equalToConstant: reloadButton.bounds.height),
|
||||
startButton.widthAnchor.constraint(equalToConstant: startButton.bounds.width),
|
||||
startButton.heightAnchor.constraint(equalToConstant: startButton.bounds.height),
|
||||
aboutButton.widthAnchor.constraint(equalToConstant: aboutButton.bounds.width),
|
||||
aboutButton.heightAnchor.constraint(equalToConstant: aboutButton.bounds.height),
|
||||
updateButton.widthAnchor.constraint(equalToConstant: updateButton.bounds.width),
|
||||
updateButton.heightAnchor.constraint(equalToConstant: updateButton.bounds.height),
|
||||
|
||||
buttonsContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -Metrics.padding),
|
||||
buttonsContainer.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -Metrics.padding),
|
||||
|
||||
buttonsBackground.leadingAnchor.constraint(equalTo: buttonsContainer.leadingAnchor),
|
||||
buttonsBackground.trailingAnchor.constraint(equalTo: buttonsContainer.trailingAnchor),
|
||||
buttonsBackground.topAnchor.constraint(equalTo: buttonsContainer.topAnchor),
|
||||
buttonsBackground.bottomAnchor.constraint(equalTo: buttonsContainer.bottomAnchor),
|
||||
|
||||
quitButton.trailingAnchor.constraint(equalTo: buttonsContainer.trailingAnchor, constant: -Metrics.buttonSpacing),
|
||||
quitButton.topAnchor.constraint(equalTo: buttonsContainer.topAnchor, constant: Metrics.buttonSpacing),
|
||||
quitButton.bottomAnchor.constraint(equalTo: buttonsContainer.bottomAnchor, constant: -Metrics.buttonSpacing),
|
||||
|
||||
reloadButton.firstBaselineAnchor.constraint(equalTo: quitButton.firstBaselineAnchor),
|
||||
reloadButton.trailingAnchor.constraint(equalTo: quitButton.leadingAnchor, constant: -Metrics.buttonSpacing),
|
||||
|
||||
startButton.firstBaselineAnchor.constraint(equalTo: reloadButton.firstBaselineAnchor),
|
||||
startButton.trailingAnchor.constraint(equalTo: reloadButton.leadingAnchor, constant: -Metrics.buttonSpacing),
|
||||
|
||||
aboutButton.firstBaselineAnchor.constraint(equalTo: startButton.firstBaselineAnchor),
|
||||
aboutButton.trailingAnchor.constraint(equalTo: startButton.leadingAnchor, constant: -Metrics.buttonSpacing),
|
||||
|
||||
updateButton.firstBaselineAnchor.constraint(equalTo: startButton.firstBaselineAnchor),
|
||||
updateButton.leadingAnchor.constraint(equalTo: buttonsContainer.leadingAnchor, constant: Metrics.buttonSpacing),
|
||||
updateButton.trailingAnchor.constraint(equalTo: aboutButton.leadingAnchor, constant: -Metrics.buttonSpacing),
|
||||
])
|
||||
}
|
||||
|
||||
private func setTextConstraints() {
|
||||
NSLayoutConstraint.activate([
|
||||
statusText.centerXAnchor.constraint(equalTo: view.centerXAnchor),
|
||||
statusText.centerYAnchor.constraint(equalTo: view.centerYAnchor),
|
||||
])
|
||||
|
||||
let trailing = textLabel.trailingAnchor.constraint(equalTo: textLabelScrollView.trailingAnchor)
|
||||
trailing.priority = .init(600)
|
||||
|
||||
let bottom = textLabel.bottomAnchor.constraint(equalTo: textLabelScrollView.bottomAnchor)
|
||||
bottom.priority = .init(600)
|
||||
|
||||
textLabel.setContentHuggingPriority(.required, for: .horizontal)
|
||||
NSLayoutConstraint.activate([
|
||||
textLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: Metrics.contentMinWidth),
|
||||
textLabelScrollView.widthAnchor.constraint(lessThanOrEqualToConstant: Metrics.contentMaxWidth),
|
||||
|
||||
textLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: Metrics.contentMinHeight),
|
||||
textLabelScrollView.heightAnchor.constraint(lessThanOrEqualToConstant: Metrics.contentMaxHeight),
|
||||
|
||||
textLabel.topAnchor.constraint(equalTo: textLabelScrollView.topAnchor),
|
||||
bottom,
|
||||
textLabel.leadingAnchor.constraint(equalTo: textLabelScrollView.leadingAnchor),
|
||||
trailing,
|
||||
|
||||
textLabelScrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10),
|
||||
textLabelScrollView.bottomAnchor.constraint(equalTo: buttonsContainer.topAnchor, constant: -10),
|
||||
textLabelScrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10),
|
||||
textLabelScrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10),
|
||||
])
|
||||
}
|
||||
|
||||
private func resetReloadButton() {
|
||||
reloadButton.image = systemImage("arrow.clockwise.circle.fill", .title2, .large, .init(paletteColors: [.white, .systemBlue]))
|
||||
reloadButton.action = #selector(reloadWidget)
|
||||
reloadButton.toolTip = "Reload Current"
|
||||
}
|
||||
|
||||
private func startReloadTextTimer() {
|
||||
timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
|
||||
timer?.schedule(deadline: .now(), repeating: .seconds(1))
|
||||
timer?.setEventHandler { [weak self] in
|
||||
DispatchQueue.main.async {
|
||||
guard let controller = self, let file = controller.cmdFile else { return }
|
||||
controller.setUntil("\(stringifySeconds(file.untilNextExec))")
|
||||
controller.progressView.value = Double(file.untilNextExec)
|
||||
}
|
||||
}
|
||||
timer?.resume()
|
||||
}
|
||||
|
||||
private func setupKeyEvents() {
|
||||
keyboardEvents = LocalEventMonitor(mask: [.flagsChanged, .keyDown], handler: { [weak self] event in
|
||||
if event.modifierFlags.contains(.shift) {
|
||||
self?.reloadButton.image = systemImage("arrow.clockwise.circle.fill", .title2, .large, .init(paletteColors: [.white, .systemCyan]))
|
||||
self?.reloadButton.action = #selector(self?.reloadWidgets)
|
||||
self?.reloadButton.toolTip = "Reload All"
|
||||
} else {
|
||||
self?.reloadButton.image = systemImage("arrow.clockwise.circle.fill", .title2, .large, .init(paletteColors: [.white, .systemBlue]))
|
||||
self?.reloadButton.action = #selector(self?.reloadWidget)
|
||||
self?.reloadButton.toolTip = "Reload Current"
|
||||
}
|
||||
|
||||
if event.modifierFlags.contains(.command) && event.keyCode == 15 { // r
|
||||
self?.reloadWidget()
|
||||
}
|
||||
|
||||
if event.modifierFlags.contains(.shift) && event.modifierFlags.contains(.command) && event.keyCode == 15 { // r
|
||||
self?.reloadWidgets()
|
||||
}
|
||||
|
||||
if (event.modifierFlags.contains(.command) && event.keyCode == 13) || event.keyCode == 12 || event.keyCode == 53 { // w, q, esc
|
||||
self?.view.superview?.window?.resignKey()
|
||||
}
|
||||
|
||||
if event.modifierFlags.contains(.command) && event.keyCode == 12 { // q
|
||||
self?.terminateApp()
|
||||
}
|
||||
|
||||
if event.modifierFlags.contains(.command) && event.keyCode == 8 { // c
|
||||
self?.textLabel.currentEditor()?.copy(nil)
|
||||
}
|
||||
|
||||
return event
|
||||
})
|
||||
}
|
||||
|
||||
func setFile(_ file: CmdFile) {
|
||||
self.cmdFile = file
|
||||
progressView.minValue = 0.0
|
||||
progressView.maxValue = Double(file.reloadTime)
|
||||
progressView.value = Double(file.reloadTime)
|
||||
}
|
||||
|
||||
func setText(_ text: String) {
|
||||
if text.isEmpty {
|
||||
statusText.stringValue = "Empty"
|
||||
textLabel.stringValue = ""
|
||||
statusText.isHidden = false
|
||||
textLabel.isHidden = true
|
||||
} else {
|
||||
textLabel.stringValue = text
|
||||
statusText.isHidden = true
|
||||
textLabel.isHidden = false
|
||||
}
|
||||
}
|
||||
|
||||
func setUntil(_ text: String) {
|
||||
reloadsText.stringValue = text
|
||||
}
|
||||
|
||||
@objc private func reloadWidgets() {
|
||||
delegate.reloadWidgets()
|
||||
}
|
||||
|
||||
@objc private func reloadWidget() {
|
||||
cmdFile?.restartTimer()
|
||||
statusText.stringValue = "Loading..."
|
||||
textLabel.isHidden = true
|
||||
statusText.isHidden = false
|
||||
}
|
||||
|
||||
@objc private func showAbout() {
|
||||
delegate.showAbout()
|
||||
}
|
||||
|
||||
@objc private func openAtLogin() {
|
||||
delegate.toggleLaunchAtLogin()
|
||||
openAtLoginToggle()
|
||||
}
|
||||
|
||||
@objc func terminateApp() {
|
||||
delegate.terminateApp()
|
||||
}
|
||||
|
||||
@objc func updateApp() {
|
||||
delegate.checkForUpdates()
|
||||
}
|
||||
|
||||
private func openAtLoginToggle() {
|
||||
if SMAppService.mainApp.status == .enabled {
|
||||
startButton.toolTip = "Open at Login — ON"
|
||||
startButton.image = systemImage("sunrise.circle.fill", .title2, .large, .init(paletteColors: [.white, .systemOrange]))
|
||||
} else {
|
||||
startButton.toolTip = "Open at Login — OFF"
|
||||
startButton.image = systemImage("sun.max.circle.fill", .title2, .large, .init(paletteColors: [.white, .systemOrange]))
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
if timer != nil {
|
||||
timer!.cancel()
|
||||
timer = nil
|
||||
}
|
||||
keyboardEvents?.stop()
|
||||
}
|
||||
}
|
||||
17
src/CopyableTextView.swift
Normal file
@@ -0,0 +1,17 @@
|
||||
import AppKit
|
||||
|
||||
class CopyableTextView: NSTextView, NSTextViewDelegate {
|
||||
func clearSelection() {
|
||||
setSelectedRange(NSRange(location: 0, length: 0))
|
||||
}
|
||||
|
||||
func copyRange() {
|
||||
let range = selectedRange()
|
||||
let start = string.index(string.startIndex, offsetBy: range.location)
|
||||
let end = string.index(start, offsetBy: range.length)
|
||||
|
||||
let pasteboard = NSPasteboard.general
|
||||
pasteboard.prepareForNewContents()
|
||||
pasteboard.setString(String(string[start..<end]), forType: .string)
|
||||
}
|
||||
}
|
||||
32
src/EditableNSTextField.swift
Normal file
@@ -0,0 +1,32 @@
|
||||
import Cocoa
|
||||
|
||||
final class EditableNSTextField: NSTextField {
|
||||
private let commandKey = NSEvent.ModifierFlags.command.rawValue
|
||||
private let commandShiftKey = NSEvent.ModifierFlags.command.rawValue | NSEvent.ModifierFlags.shift.rawValue
|
||||
|
||||
override func performKeyEquivalent(with event: NSEvent) -> Bool {
|
||||
if event.type == NSEvent.EventType.keyDown {
|
||||
if (event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) == commandKey {
|
||||
switch event.charactersIgnoringModifiers! {
|
||||
case "x":
|
||||
if NSApp.sendAction(#selector(NSText.cut(_:)), to: nil, from: self) { return true }
|
||||
case "c":
|
||||
if NSApp.sendAction(#selector(NSText.copy(_:)), to: nil, from: self) { return true }
|
||||
case "v":
|
||||
if NSApp.sendAction(#selector(NSText.paste(_:)), to: nil, from: self) { return true }
|
||||
case "z":
|
||||
if NSApp.sendAction(Selector(("undo:")), to: nil, from: self) { return true }
|
||||
case "a":
|
||||
if NSApp.sendAction(#selector(NSResponder.selectAll(_:)), to: nil, from: self) { return true }
|
||||
default:
|
||||
break
|
||||
}
|
||||
} else if (event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) == commandShiftKey {
|
||||
if event.charactersIgnoringModifiers == "Z" {
|
||||
if NSApp.sendAction(Selector(("redo:")), to: nil, from: self) { return true }
|
||||
}
|
||||
}
|
||||
}
|
||||
return super.performKeyEquivalent(with: event)
|
||||
}
|
||||
}
|
||||
55
src/EventMonitor.swift
Normal file
@@ -0,0 +1,55 @@
|
||||
import Cocoa
|
||||
|
||||
class EventMonitor {
|
||||
fileprivate let mask: NSEvent.EventTypeMask
|
||||
fileprivate var monitor: Any?
|
||||
|
||||
fileprivate init(mask: NSEvent.EventTypeMask) {
|
||||
self.mask = mask
|
||||
}
|
||||
|
||||
deinit {
|
||||
stop()
|
||||
}
|
||||
|
||||
func start() {
|
||||
fatalError("start must be implemented by a subclass of EventMonitor")
|
||||
}
|
||||
|
||||
func stop() {
|
||||
if monitor != nil {
|
||||
NSEvent.removeMonitor(monitor!)
|
||||
monitor = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class LocalEventMonitor: EventMonitor {
|
||||
typealias Handler = (NSEvent) -> NSEvent?
|
||||
|
||||
private let handler: Handler
|
||||
|
||||
init(mask: NSEvent.EventTypeMask, handler: @escaping Handler) {
|
||||
self.handler = handler
|
||||
super.init(mask: mask)
|
||||
}
|
||||
|
||||
override func start() {
|
||||
monitor = NSEvent.addLocalMonitorForEvents(matching: mask, handler: handler)
|
||||
}
|
||||
}
|
||||
|
||||
final class GlobalEventMonitor: EventMonitor {
|
||||
typealias Handler = (NSEvent) -> Void
|
||||
|
||||
private let handler: Handler
|
||||
|
||||
init(mask: NSEvent.EventTypeMask, handler: @escaping Handler) {
|
||||
self.handler = handler
|
||||
super.init(mask: mask)
|
||||
}
|
||||
|
||||
override func start() {
|
||||
monitor = NSEvent.addGlobalMonitorForEvents(matching: mask, handler: handler)
|
||||
}
|
||||
}
|
||||
178
src/Helpers.swift
Normal file
@@ -0,0 +1,178 @@
|
||||
import AppKit
|
||||
|
||||
// MARK: - Tracking Notifications
|
||||
fileprivate extension Notification.Name {
|
||||
static let beginMenuTracking = Notification.Name("com.apple.HIToolbox.beginMenuTrackingNotification")
|
||||
static let endMenuTracking = Notification.Name("com.apple.HIToolbox.endMenuTrackingNotification")
|
||||
}
|
||||
|
||||
#if(DEBUG)
|
||||
struct EndpointConstants {
|
||||
static var versionURL = "http://localhost:8081/version"
|
||||
static var appURL = "http://localhost:8081/download"
|
||||
static var appURLZip = "http://localhost:8081/static/app/CmdBar.zip"
|
||||
static var changelog = "http://localhost:8081/changelog"
|
||||
static var validateURL = "http://localhost:8081/validate"
|
||||
}
|
||||
#else
|
||||
struct EndpointConstants {
|
||||
static var versionURL = "http://cmdbar.app/version"
|
||||
static var appURL = "http://cmdbar.app/download"
|
||||
static var appURLZip = "http://cmdbar.app/static/app/CmdBar.zip"
|
||||
static var changelog = "http://cmdbar.app/changelog"
|
||||
static var validateURL = "https://cmdbar.app/validate"
|
||||
}
|
||||
#endif
|
||||
|
||||
//
|
||||
enum Resulting<Success, Failure> {
|
||||
case success
|
||||
case failure
|
||||
}
|
||||
|
||||
// Parse time string into seconds.
|
||||
func intervalToSeconds(from timeString: String) -> Int {
|
||||
guard let value = Int(timeString.dropLast()) else { return 0 }
|
||||
let unit = timeString.suffix(1)
|
||||
switch unit {
|
||||
case "s":
|
||||
return value
|
||||
case "m":
|
||||
return value * 60
|
||||
case "h":
|
||||
return value * 60 * 60
|
||||
case "d":
|
||||
return value * 60 * 60 * 24
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// Regex check if string is in the right format.
|
||||
// Regular expression pattern to match "1s", "5m", "1h", "1d"
|
||||
func isValidTimeFormat(_ timeString: String) -> Bool {
|
||||
let pattern = #"^\d+[smhd]$"#
|
||||
return NSPredicate(format: "SELF MATCHES %@", pattern).evaluate(with: timeString)
|
||||
}
|
||||
|
||||
// Turn seconds into a time string.
|
||||
func stringifySeconds(_ seconds: Int) -> String {
|
||||
if seconds >= 60 && seconds < 3600 {
|
||||
return "\(String(format: "%.1f", Double(seconds) / 60.0))m"
|
||||
} else if seconds >= 3600 && seconds < 86400 {
|
||||
return "\(String(format: "%.1f", Double(seconds) / 3600.0))h"
|
||||
} else if seconds >= 86400 {
|
||||
return "\(String(format: "%.1f", Double(seconds) / 86400.0))h"
|
||||
}
|
||||
return "\(seconds)s"
|
||||
}
|
||||
|
||||
// Execution errors.
|
||||
private enum ExecError: Error {
|
||||
case doesntExist
|
||||
case noPermission
|
||||
case failed
|
||||
case error(err: String)
|
||||
}
|
||||
|
||||
// Executes file and parses its output.
|
||||
func execute(atPath path: URL) -> (title: String, body: String) {
|
||||
let stringPath = path.path()
|
||||
|
||||
do {
|
||||
let output = try executeFile(path: path)
|
||||
if !output.isEmpty {
|
||||
let result = output.components(separatedBy: "\n")
|
||||
if result.count >= 1 {
|
||||
return (result.first!, result.dropFirst().joined(separator: "\n"))
|
||||
}
|
||||
}
|
||||
} catch ExecError.failed {
|
||||
return ("", "execution failed: \(stringPath)")
|
||||
} catch ExecError.doesntExist {
|
||||
return ("", "doesn't exist: \(stringPath)")
|
||||
} catch ExecError.noPermission {
|
||||
return ("", "permission denied: \(stringPath)")
|
||||
} catch ExecError.error(let error) {
|
||||
return ("", "\(error)")
|
||||
} catch {
|
||||
return ("", "\(error)")
|
||||
}
|
||||
|
||||
return ("", "")
|
||||
}
|
||||
|
||||
// Executes a file.
|
||||
private func executeFile(path: URL) throws -> String {
|
||||
if !FileManager.default.fileExists(atPath: path.path()) { throw ExecError.doesntExist }
|
||||
if !FileManager.default.isExecutableFile(atPath: path.path()) { throw ExecError.noPermission }
|
||||
|
||||
let process = Process()
|
||||
process.executableURL = path
|
||||
|
||||
let outputPipe = Pipe()
|
||||
let errorPipe = Pipe()
|
||||
process.standardOutput = outputPipe
|
||||
process.standardError = errorPipe
|
||||
|
||||
do {
|
||||
try process.run()
|
||||
} catch {
|
||||
throw ExecError.failed
|
||||
}
|
||||
process.waitUntilExit()
|
||||
|
||||
let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()
|
||||
let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()
|
||||
|
||||
let output = String(data: outputData, encoding: .utf8)
|
||||
let error = String(data: errorData, encoding: .utf8)
|
||||
|
||||
if process.terminationStatus != 0 {
|
||||
if let err = error {
|
||||
throw ExecError.error(err: err)
|
||||
}
|
||||
}
|
||||
|
||||
if let out = output, !out.isEmpty {
|
||||
var result = ""
|
||||
if out.hasSuffix("\n") {
|
||||
result = out.trimmingCharacters(in: .newlines)
|
||||
}
|
||||
return result
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func getColors(_ light: NSColor, _ dark: NSColor, for appearance: NSAppearance) -> NSColor {
|
||||
switch appearance.name {
|
||||
case .aqua, .vibrantLight, .accessibilityHighContrastAqua, .accessibilityHighContrastVibrantLight:
|
||||
return light
|
||||
case .darkAqua, .vibrantDark, .accessibilityHighContrastDarkAqua, .accessibilityHighContrastVibrantDark:
|
||||
return dark
|
||||
default:
|
||||
return NSColor.white
|
||||
}
|
||||
}
|
||||
|
||||
// ex: systemImage("sunrise.circle.fill", .title2, .large, .init(paletteColors: [.white, .systemOrange]))
|
||||
func systemImage(_ name: String, _ size: NSFont.TextStyle, _ scale: NSImage.SymbolScale, _ configuration: NSImage.SymbolConfiguration) -> NSImage? {
|
||||
return NSImage(systemSymbolName: name, accessibilityDescription: nil)?
|
||||
.withSymbolConfiguration(
|
||||
NSImage.SymbolConfiguration(textStyle: size, scale: scale)
|
||||
.applying(configuration)
|
||||
)
|
||||
}
|
||||
|
||||
func openLink(_ url: String) {
|
||||
guard let url = URL(string: url) else { return }
|
||||
NSWorkspace.shared.open(url)
|
||||
}
|
||||
|
||||
func persistMenuBar(_ state: Bool) {
|
||||
if state {
|
||||
DistributedNotificationCenter.default().post(name: .beginMenuTracking, object: nil)
|
||||
} else {
|
||||
DistributedNotificationCenter.default().post(name: .endMenuTracking, object: nil)
|
||||
}
|
||||
}
|
||||
44
src/Info.plist
Normal file
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>CmdBar</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>AppIcon</string>
|
||||
<key>CFBundleIconName</key>
|
||||
<string>AppIcon</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.garikme.CmdBar</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>CmdBar</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.93</string>
|
||||
<key>CFBundleSupportedPlatforms</key>
|
||||
<array>
|
||||
<string>MacOSX</string>
|
||||
</array>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1.93</string>
|
||||
<key>DTPlatformName</key>
|
||||
<string>macosx</string>
|
||||
<key>DTPlatformVersion</key>
|
||||
<string>15.0</string>
|
||||
<key>DTSDKName</key>
|
||||
<string>macosx15.0</string>
|
||||
<key>LSApplicationCategoryType</key>
|
||||
<string>public.app-category.utilities</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>13.0</string>
|
||||
<key>LSUIElement</key>
|
||||
<true/>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
</dict>
|
||||
</plist>
|
||||
129
src/LicenseManager.swift
Normal file
@@ -0,0 +1,129 @@
|
||||
//
|
||||
// LicenseManager.swift
|
||||
// CmdBar
|
||||
//
|
||||
// Created by Igor Kolokolnikov on 8/26/23.
|
||||
//
|
||||
|
||||
import Cocoa
|
||||
import CryptoKit
|
||||
|
||||
fileprivate struct LicenseModel: Codable {
|
||||
let valid: Bool
|
||||
let error: String
|
||||
let email: String
|
||||
let key: String
|
||||
}
|
||||
|
||||
// Converts string to a hash.
|
||||
fileprivate func hashString(_ string: String) -> String {
|
||||
return SHA256.hash(data: Data(string.utf8)).compactMap { String(format: "%02x", $0) }.joined()
|
||||
}
|
||||
|
||||
// Converts passphrase to a SymmetricKey.
|
||||
fileprivate func passToKey(from passphrase: String) -> SymmetricKey {
|
||||
let passphraseData = Data(passphrase.utf8)
|
||||
let keyData = SHA256.hash(data: passphraseData).withUnsafeBytes { buffer in
|
||||
return Data(buffer)
|
||||
}
|
||||
return SymmetricKey(data: keyData)
|
||||
}
|
||||
|
||||
final class LicenseManager {
|
||||
static let standard = LicenseManager()
|
||||
|
||||
private let passkey = passToKey(from: "B2B67FB0E22B814CE5A6E7DA729A068BF21C9490919EA0B42FCEB322F9C9BA82")
|
||||
private let defaults = UserDefaults.standard
|
||||
private var timer: DispatchSourceTimer?
|
||||
private var quitAfterMinutes = 20.0 * 60.0 // quit after 20 minutes
|
||||
|
||||
func isRegistered() -> Bool {
|
||||
guard let email = defaults.object(forKey: "Email") as? String,
|
||||
let key = defaults.object(forKey: "Key") as? String,
|
||||
let licenseData = defaults.object(forKey: "License") as? Data,
|
||||
let unsealedBox = try? AES.GCM.SealedBox(combined: licenseData),
|
||||
let licenseHashData = try? AES.GCM.open(unsealedBox, using: passkey),
|
||||
!email.isEmpty,
|
||||
!key.isEmpty
|
||||
else { return false }
|
||||
|
||||
let currentHashData = Data(SHA256.hash(data: Data(hashString("\(email)\(key)\(NSUserName())").utf8))
|
||||
.compactMap { String(format: "%02x", $0) }.joined().utf8)
|
||||
|
||||
return licenseHashData == currentHashData
|
||||
}
|
||||
|
||||
func activateLicense(email: String, key: String, completionHandler: @escaping (_ data: Resulting<Bool, String>) -> Void) {
|
||||
guard let url = URL(string: EndpointConstants.validateURL)?.appending(component: key)
|
||||
else { completionHandler(.failure); return }
|
||||
|
||||
URLSession.shared.dataTask(with: url) { [weak self] (data, response, error) in
|
||||
guard
|
||||
let data = data,
|
||||
error == nil,
|
||||
let response = response as? HTTPURLResponse,
|
||||
(200...299).contains(response.statusCode)
|
||||
else { completionHandler(.failure); return }
|
||||
|
||||
guard let jsonResponse = try? JSONDecoder().decode(LicenseModel.self, from: data)
|
||||
else { completionHandler(.failure); return }
|
||||
|
||||
if jsonResponse.email == email && jsonResponse.key == key {
|
||||
self?.saveLicense(with: email, and: key)
|
||||
self?.stopTimer()
|
||||
completionHandler(.success)
|
||||
} else {
|
||||
completionHandler(.failure)
|
||||
}
|
||||
}.resume()
|
||||
}
|
||||
|
||||
func deactivateLicense() {
|
||||
clearLicense()
|
||||
startTimer()
|
||||
}
|
||||
|
||||
func getLicense() -> (email: String, key: String) {
|
||||
guard
|
||||
let email = defaults.object(forKey: "Email") as? String,
|
||||
let key = defaults.object(forKey: "Key") as? String
|
||||
else { return ("", "") }
|
||||
return (email, key)
|
||||
}
|
||||
|
||||
private func saveLicense(with email: String, and key: String) {
|
||||
let defaults = UserDefaults.standard
|
||||
|
||||
let licenseHashData = Data(SHA256.hash(data: Data(hashString("\(email)\(key)\(NSUserName())").utf8))
|
||||
.compactMap { String(format: "%02x", $0) }.joined().utf8)
|
||||
|
||||
guard let sealedBoxData = try? AES.GCM.seal(licenseHashData, using: passkey).combined else { return }
|
||||
defaults.set(email, forKey: "Email")
|
||||
defaults.set(key, forKey: "Key")
|
||||
defaults.set(sealedBoxData, forKey: "License")
|
||||
}
|
||||
|
||||
func clearLicense() {
|
||||
defaults.set(nil, forKey: "Email")
|
||||
defaults.set(nil, forKey: "Key")
|
||||
defaults.set(nil, forKey: "License")
|
||||
}
|
||||
|
||||
// MARK: - Timer
|
||||
func startTimer() {
|
||||
timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
|
||||
timer?.schedule(
|
||||
deadline: .now() + quitAfterMinutes,
|
||||
repeating: DispatchTimeInterval.never
|
||||
)
|
||||
timer?.setEventHandler {
|
||||
DispatchQueue.main.async { NSApplication.shared.terminate(self) }
|
||||
}
|
||||
timer?.resume()
|
||||
}
|
||||
|
||||
func stopTimer() {
|
||||
timer?.cancel()
|
||||
timer = nil
|
||||
}
|
||||
}
|
||||
103
src/Makefile
Normal file
@@ -0,0 +1,103 @@
|
||||
FLAGS = -g
|
||||
CFLAGS = -g
|
||||
#-O
|
||||
MACOS_VERSION = 13.0
|
||||
SDK = $(shell xcrun --show-sdk-path)
|
||||
XCODE_PATH = $(shell xcode-select --print-path)
|
||||
|
||||
EXEC = CmdBar
|
||||
|
||||
SRCMODULES = UpdateManager.swift LicenseManager.swift \
|
||||
AboutViewController.swift AppDelegate.swift CBMenuBarItem.swift \
|
||||
CircularProgressView.swift CmdManager.swift CmdViewController.swift \
|
||||
CopyableTextView.swift EditableNSTextField.swift EventMonitor.swift \
|
||||
Helpers.swift MenulessWindow.swift PopoverPanel.swift \
|
||||
QuietView.swift UpdateViewController.swift main.swift
|
||||
ARMOBJMODULES = $(addprefix ./arm64/,$(SRCMODULES:.swift=.o))
|
||||
X86OBJMODULES = $(addprefix ./x86_64/,$(SRCMODULES:.swift=.o))
|
||||
|
||||
FRAMEWORKS = -framework AppKit -framework ServiceManagement
|
||||
#-emit-module-path
|
||||
|
||||
LIBS = -lzip
|
||||
|
||||
zip:
|
||||
@$(MAKE) -C libs/Zip/Zip FLAGS=$(FLAGS) CFLAGS=$(CFLAGS) \
|
||||
MACOS_VERSION=$(MACOS_VERSION) all
|
||||
|
||||
cmdbar_updater:
|
||||
@$(MAKE) -C updater FLAGS=$(FLAGS) all
|
||||
@cp updater/$@ .
|
||||
|
||||
./arm64/%.o: %.swift
|
||||
@echo $<
|
||||
swift -frontend -c $(if $(DEBUG), -D DEBUG,) \
|
||||
-target arm64-apple-macos$(MACOS_VERSION) $(FLAGS) \
|
||||
-I./libs/Zip/Zip -I./libs/Zip/Zip/arm64 -L./libs/Zip/Zip/arm64 \
|
||||
-primary-file $< $(filter-out $<, $(SRCMODULES)) $(LIBS) \
|
||||
-sdk $(SDK) -module-name $(EXEC) -o $@ -emit-module
|
||||
|
||||
ifdef UNIVERSAL
|
||||
./x86_64/%.o: %.swift
|
||||
@swift -frontend -c $(if $(DEBUG), -D DEBUG,) \
|
||||
-target x86_64-apple-macos$(MACOS_VERSION) $(FLAGS) \
|
||||
-I./libs/Zip/Zip -I./libs/Zip/Zip/x86_64 -L./libs/Zip/Zip/x86_64 \
|
||||
-primary-file $< $(filter-out $<, $(SRCMODULES)) $(LIBS) \
|
||||
-sdk $(SDK) -module-name $(EXEC) -o $@ -emit-module
|
||||
endif
|
||||
./arm64/$(EXEC): $(ARMOBJMODULES)
|
||||
@ld -syslibroot $(SDK) -lSystem -arch arm64 -macos_version_min \
|
||||
$(MACOS_VERSION).0 \
|
||||
/Library/Developer/CommandLineTools/usr/lib/swift/macosx/libswiftCompatibilityPacks.a \
|
||||
-sectcreate __TEXT __info_plist Info.plist \
|
||||
-L /Library/Developer/CommandLineTools/usr/lib/swift/macosx -L \
|
||||
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib/swift \
|
||||
-no_objc_category_merging -L $(XCODE_PATH) -rpath \
|
||||
Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx \
|
||||
./arm64/main.o $(filter-out ./arm64/main.o, $(ARMOBJMODULES)) \
|
||||
./libs/Zip/Zip/arm64/libzip.a -o $@
|
||||
|
||||
ifdef UNIVERSAL
|
||||
./x86_64/$(EXEC): $(X86OBJMODULES)
|
||||
@ld -syslibroot $(SDK) -lSystem -arch x86_64 -macos_version_min \
|
||||
$(MACOS_VERSION).0 \
|
||||
/Library/Developer/CommandLineTools/usr/lib/swift/macosx/libswiftCompatibilityPacks.a \
|
||||
-sectcreate __TEXT __info_plist Info.plist \
|
||||
-L /Library/Developer/CommandLineTools/usr/lib/swift/macosx -L \
|
||||
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib/swift \
|
||||
-no_objc_category_merging -L $(XCODE_PATH) -rpath \
|
||||
Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx \
|
||||
./x86_64/main.o $(filter-out ./x86_64/main.o, $(X86OBJMODULES)) \
|
||||
./libs/Zip/Zip/x86_64/libzip.a -o $@
|
||||
endif
|
||||
|
||||
ifdef UNIVERSAL
|
||||
$(EXEC): ./arm64/$(EXEC) ./x86_64/$(EXEC)
|
||||
@lipo -create -output $(EXEC) $^
|
||||
else
|
||||
$(EXEC): ./arm64/$(EXEC)
|
||||
lipo -create -output $(EXEC) $^
|
||||
endif
|
||||
|
||||
$(EXEC).app: $(EXEC)
|
||||
@rm -rf $@
|
||||
@mkdir -p $@/Contents/MacOS/ && \
|
||||
mkdir -p $@/Contents/Resources/ && \
|
||||
cp Info.plist $@/Contents/ && \
|
||||
cp resources/AppIcon.icns $@/Contents/Resources/ && \
|
||||
cp $(EXEC) $@/Contents/MacOS/ && \
|
||||
cp cmdbar_updater $@/Contents/MacOS/ && \
|
||||
codesign -s ${DEVELOPER_ID} -f --timestamp -o runtime $(EXEC).app
|
||||
|
||||
all: zip cmdbar_updater $(EXEC).app
|
||||
|
||||
run: all
|
||||
@open $(EXEC).app
|
||||
|
||||
clean:
|
||||
rm -rf $(EXEC) $(EXEC).app cmdbar_updater arm64 x86_64
|
||||
mkdir arm64 x86_64
|
||||
|
||||
clean-all: clean
|
||||
$(MAKE) -C libs/Zip/Zip clean-all
|
||||
$(MAKE) -C updater clean
|
||||
31
src/MenulessWindow.swift
Normal file
@@ -0,0 +1,31 @@
|
||||
import Cocoa
|
||||
|
||||
class MenulessWindow: NSWindow {
|
||||
init(viewController: NSViewController) {
|
||||
super.init(
|
||||
contentRect: CGRect(x: 0, y: 0, width: 100, height: 100),
|
||||
styleMask: [.titled, .closable],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
)
|
||||
super.contentViewController = viewController
|
||||
|
||||
title = ""
|
||||
titlebarAppearsTransparent = true
|
||||
collectionBehavior = [.managed, .fullScreenNone]
|
||||
isReleasedWhenClosed = false
|
||||
hidesOnDeactivate = false
|
||||
}
|
||||
|
||||
override func performKeyEquivalent(with event: NSEvent) -> Bool {
|
||||
let commandKey = NSEvent.ModifierFlags.command.rawValue
|
||||
|
||||
if event.type == NSEvent.EventType.keyDown {
|
||||
if (event.modifierFlags.rawValue & NSEvent.ModifierFlags.deviceIndependentFlagsMask.rawValue) == commandKey,
|
||||
event.charactersIgnoringModifiers! == "w" {
|
||||
performClose(nil)
|
||||
}
|
||||
}
|
||||
return super.performKeyEquivalent(with: event)
|
||||
}
|
||||
}
|
||||
37
src/PopoverPanel.swift
Normal file
@@ -0,0 +1,37 @@
|
||||
import Cocoa
|
||||
|
||||
class PopoverPanel: NSPanel {
|
||||
override var canBecomeKey: Bool { true }
|
||||
|
||||
init(viewController: NSViewController) {
|
||||
super.init(
|
||||
contentRect: CGRect(x: 0, y: 0, width: 100, height: 100),
|
||||
styleMask: [.titled, .nonactivatingPanel, .utilityWindow, .fullSizeContentView],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
)
|
||||
super.contentViewController = viewController
|
||||
|
||||
title = ""
|
||||
isMovable = false
|
||||
isMovableByWindowBackground = false
|
||||
isFloatingPanel = true
|
||||
isOpaque = false
|
||||
level = .statusBar
|
||||
titleVisibility = .hidden
|
||||
titlebarAppearsTransparent = true
|
||||
|
||||
animationBehavior = .none
|
||||
collectionBehavior = [.moveToActiveSpace, .fullScreenAuxiliary, .transient]
|
||||
isReleasedWhenClosed = false
|
||||
hidesOnDeactivate = false
|
||||
|
||||
standardWindowButton(.closeButton)?.isHidden = true
|
||||
standardWindowButton(.miniaturizeButton)?.isHidden = true
|
||||
standardWindowButton(.zoomButton)?.isHidden = true
|
||||
}
|
||||
|
||||
override func performKeyEquivalent(with event: NSEvent) -> Bool {
|
||||
return super.performKeyEquivalent(with: event)
|
||||
}
|
||||
}
|
||||
12
src/QuietView.swift
Normal file
@@ -0,0 +1,12 @@
|
||||
import AppKit
|
||||
|
||||
class QuietView: NSView {
|
||||
override func performKeyEquivalent(with event: NSEvent) -> Bool {
|
||||
if event.keyCode == 53 { // esc
|
||||
event.window?.resignKey()
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
143
src/UpdateManager.swift
Normal file
@@ -0,0 +1,143 @@
|
||||
//
|
||||
// UpdateManager.swift
|
||||
// CmdBar
|
||||
//
|
||||
// Created by Igor Kolokolnikov on 5/23/24.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Zip
|
||||
|
||||
struct VersionModel: Codable {
|
||||
let ok: Bool
|
||||
let version: Double
|
||||
let changes: [String]
|
||||
}
|
||||
|
||||
protocol UpdateManagerDelegate: AnyObject {
|
||||
func downloadProgressChanged(_ value: Double)
|
||||
func unzipProgressChanged(_ value: Double)
|
||||
}
|
||||
|
||||
final class UpdateManager {
|
||||
static let shared = UpdateManager()
|
||||
weak var delegate: UpdateManagerDelegate?
|
||||
|
||||
private var observation: NSKeyValueObservation?
|
||||
|
||||
func currentVersion() -> Double? {
|
||||
guard let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String else { return nil }
|
||||
if let version = Double(version) {
|
||||
return version
|
||||
} else { return nil }
|
||||
}
|
||||
|
||||
func latestVersion() async -> VersionModel? {
|
||||
guard let url = URL(string: EndpointConstants.versionURL) else { return nil }
|
||||
do {
|
||||
let config = URLSessionConfiguration.default
|
||||
config.timeoutIntervalForResource = 5.0
|
||||
let session = URLSession(configuration: config)
|
||||
let (data, _) = try await session.data(from: url)
|
||||
|
||||
// let (data, _) = try await URLSession.shared.data(from: url)
|
||||
let response = try JSONDecoder().decode(VersionModel.self, from: data)
|
||||
return response.ok ? response : nil
|
||||
} catch { return nil }
|
||||
}
|
||||
|
||||
func isUpdateAvailable() async -> (available: Bool?, model: VersionModel?) {
|
||||
guard let curVersion = currentVersion(),
|
||||
let fetVersion = await latestVersion()
|
||||
else { return (nil, nil) }
|
||||
|
||||
if fetVersion.version > curVersion {
|
||||
return (true, fetVersion)
|
||||
}
|
||||
return (false, nil)
|
||||
}
|
||||
|
||||
func downloadUpdate(completionHandler: @escaping (_ data: Resulting<Bool, String>) -> Void) {
|
||||
guard let url = URL(string: EndpointConstants.appURLZip) else { completionHandler(.failure); return }
|
||||
|
||||
let task = URLSession.shared.downloadTask(with: url) { (tempURL, response, error) in
|
||||
guard
|
||||
let tempURL = tempURL,
|
||||
error == nil,
|
||||
let response = response as? HTTPURLResponse,
|
||||
(200...299).contains(response.statusCode)
|
||||
else {
|
||||
completionHandler(.failure)
|
||||
return
|
||||
}
|
||||
|
||||
let fileManager = FileManager.default
|
||||
var userTmpURL = FileManager.default.temporaryDirectory
|
||||
|
||||
var isDirectory = ObjCBool(true)
|
||||
guard fileManager.fileExists(atPath: userTmpURL.path(), isDirectory: &isDirectory) else { completionHandler(.failure); return }
|
||||
userTmpURL = userTmpURL.appendingPathComponent("CmdBar.zip")
|
||||
if fileManager.fileExists(atPath: userTmpURL.path()) {
|
||||
do {
|
||||
try fileManager.removeItem(at: userTmpURL)
|
||||
} catch {
|
||||
completionHandler(.failure)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try fileManager.moveItem(at: tempURL, to: userTmpURL)
|
||||
completionHandler(.success)
|
||||
} catch {
|
||||
completionHandler(.failure)
|
||||
return
|
||||
}
|
||||
}
|
||||
observation = task.progress.observe(\.fractionCompleted, changeHandler: { [weak self] progress, _ in
|
||||
guard let delegate = self?.delegate else { return }
|
||||
delegate.downloadProgressChanged(progress.fractionCompleted)
|
||||
})
|
||||
task.resume()
|
||||
}
|
||||
|
||||
func extractUpdate(completionHandler: @escaping (_ data: Resulting<Bool, String>) -> Void) {
|
||||
let fileManager = FileManager.default
|
||||
let userTmpURL = fileManager.temporaryDirectory.appending(path: "CmdBar.zip")
|
||||
do {
|
||||
try Zip.unzipFile(userTmpURL, destination: FileManager.default.temporaryDirectory, overwrite: true, password: nil) { [weak self] progress in
|
||||
guard let delegate = self?.delegate else { return }
|
||||
delegate.unzipProgressChanged(progress)
|
||||
}
|
||||
try fileManager.removeItem(at: userTmpURL)
|
||||
completionHandler(.success)
|
||||
} catch {
|
||||
completionHandler(.failure)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func removeUpdate() {
|
||||
let tmp = FileManager.default.temporaryDirectory.appending(path: "CmdBar.app")
|
||||
if !existsAtPath(tmp.path()) { return }
|
||||
try? FileManager.default.removeItem(at: tmp)
|
||||
}
|
||||
|
||||
func installUpdate() {
|
||||
if let url = Bundle.main.url(forAuxiliaryExecutable: "cmdbar_updater") {
|
||||
let task = Process()
|
||||
task.executableURL = url
|
||||
try? task.run()
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
observation?.invalidate()
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func existsAtPath(_ path: String, isDirectory: Bool = false) -> Bool {
|
||||
var isDirectory: ObjCBool = ObjCBool(isDirectory)
|
||||
let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
|
||||
return exists
|
||||
}
|
||||
302
src/UpdateViewController.swift
Normal file
@@ -0,0 +1,302 @@
|
||||
//
|
||||
// UpdateViewController.swift
|
||||
// CmdBar
|
||||
//
|
||||
// Created by Igor Kolokolnikov on 5/23/24.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
|
||||
fileprivate enum ViewConstants {
|
||||
static let spacing2: CGFloat = 2
|
||||
static let spacing10: CGFloat = 10
|
||||
static let spacing20: CGFloat = 20
|
||||
static let spacing40: CGFloat = 40
|
||||
}
|
||||
|
||||
fileprivate enum UpdateStatus: String {
|
||||
case check = "Check for updates..."
|
||||
case latest = "You're up-to-date!"
|
||||
case checking = "Checking for udpates..."
|
||||
case available = "A new version is available!"
|
||||
case downloading = "Downloading update..."
|
||||
case extracting = "Extracting update..."
|
||||
case install = "Ready to Install"
|
||||
case checkFailed = "Failed to Check for Updates"
|
||||
case installFailed = "Failed to Install Update"
|
||||
}
|
||||
|
||||
class UpdateViewController: NSViewController, UpdateManagerDelegate {
|
||||
private weak var updaterDelegate: UpdateManagerDelegate?
|
||||
|
||||
private var appIconImage: NSImageView = {
|
||||
//let image = NSImageView(image: NSApp.applicationIconImage)
|
||||
let image = NSImageView()
|
||||
image.image = NSWorkspace.shared.icon(forFile: Bundle.main.bundlePath)
|
||||
image.imageScaling = .scaleAxesIndependently
|
||||
image.translatesAutoresizingMaskIntoConstraints = false
|
||||
return image
|
||||
}()
|
||||
|
||||
private var statusLabel: NSTextField = {
|
||||
let textField = NSTextField()
|
||||
textField.isEditable = false
|
||||
textField.isBezeled = false
|
||||
textField.drawsBackground = false
|
||||
textField.alignment = .left
|
||||
textField.textColor = NSColor(name: nil) { getColors(.black, .white, for: $0) }
|
||||
textField.font = NSFont.systemFont(ofSize: NSFontDescriptor.preferredFontDescriptor(forTextStyle: .body).pointSize, weight: .bold)
|
||||
textField.translatesAutoresizingMaskIntoConstraints = false
|
||||
return textField
|
||||
}()
|
||||
|
||||
private var subStatusLabel: NSTextField = {
|
||||
let textField = NSTextField()
|
||||
textField.stringValue = "CHANGELOG"
|
||||
textField.isHidden = true
|
||||
textField.isEditable = false
|
||||
textField.isBezeled = false
|
||||
textField.drawsBackground = false
|
||||
textField.alignment = .left
|
||||
textField.textColor = .gray
|
||||
textField.font = NSFont.systemFont(ofSize: NSFontDescriptor.preferredFontDescriptor(forTextStyle: .body).pointSize, weight: .bold)
|
||||
textField.translatesAutoresizingMaskIntoConstraints = false
|
||||
return textField
|
||||
}()
|
||||
|
||||
private var changelogLabel: NSScrollView = { // TODO: Improve some more. Maybe make it scrollable.
|
||||
let scrollableTextView = NSTextView.scrollableTextView()
|
||||
scrollableTextView.isHidden = true
|
||||
(scrollableTextView.documentView as? NSTextView)?.isEditable = false
|
||||
// (scrollableTextView.documentView as? NSTextView)?.drawsBackground = false
|
||||
(scrollableTextView.documentView as? NSTextView)?.textColor = .gray
|
||||
(scrollableTextView.documentView as? NSTextView)?.font = NSFont.systemFont(ofSize: NSFontDescriptor.preferredFontDescriptor(forTextStyle: .body).pointSize, weight: .regular)
|
||||
scrollableTextView.translatesAutoresizingMaskIntoConstraints = false
|
||||
return scrollableTextView
|
||||
}()
|
||||
|
||||
private var progressIndicator: NSProgressIndicator = {
|
||||
let progress = NSProgressIndicator()
|
||||
progress.maxValue = 1.0
|
||||
progress.isIndeterminate = false
|
||||
progress.translatesAutoresizingMaskIntoConstraints = false
|
||||
return progress
|
||||
}()
|
||||
|
||||
private var updateButton: NSButton = {
|
||||
let button = NSButton()
|
||||
button.title = "Check for Updates"
|
||||
button.sizeToFit()
|
||||
button.bezelStyle = .rounded
|
||||
button.action = #selector(checkForUpdate)
|
||||
button.isEnabled = false
|
||||
button.translatesAutoresizingMaskIntoConstraints = false
|
||||
return button
|
||||
}()
|
||||
|
||||
private var changelogButton: NSButton = {
|
||||
let button = NSButton()
|
||||
button.title = "Changelog"
|
||||
button.sizeToFit()
|
||||
button.bezelStyle = .rounded
|
||||
button.action = #selector(openChangelog)
|
||||
button.translatesAutoresizingMaskIntoConstraints = false
|
||||
return button
|
||||
}()
|
||||
|
||||
private var stackView: NSStackView = {
|
||||
let stack = NSStackView()
|
||||
stack.orientation = .vertical
|
||||
stack.alignment = .trailing
|
||||
stack.spacing = ViewConstants.spacing10
|
||||
stack.translatesAutoresizingMaskIntoConstraints = false
|
||||
return stack
|
||||
}()
|
||||
|
||||
private var buttonsStackView: NSStackView = {
|
||||
let stack = NSStackView()
|
||||
stack.orientation = .horizontal
|
||||
stack.translatesAutoresizingMaskIntoConstraints = false
|
||||
return stack
|
||||
}()
|
||||
|
||||
private func addSubviews() {
|
||||
view.addSubview(appIconImage)
|
||||
|
||||
view.addSubview(statusLabel)
|
||||
view.addSubview(subStatusLabel)
|
||||
|
||||
view.addSubview(stackView)
|
||||
stackView.addArrangedSubview(changelogLabel)
|
||||
stackView.addArrangedSubview(progressIndicator)
|
||||
stackView.addArrangedSubview(buttonsStackView)
|
||||
buttonsStackView.addArrangedSubview(changelogButton)
|
||||
buttonsStackView.addArrangedSubview(updateButton)
|
||||
}
|
||||
|
||||
private func setConstraints() {
|
||||
stackView.setHuggingPriority(.required, for: .vertical)
|
||||
|
||||
NSLayoutConstraint.activate([
|
||||
appIconImage.widthAnchor.constraint(equalToConstant: 70),
|
||||
appIconImage.heightAnchor.constraint(equalTo: appIconImage.widthAnchor, multiplier: 1),
|
||||
|
||||
appIconImage.topAnchor.constraint(equalTo: view.topAnchor, constant: ViewConstants.spacing10),
|
||||
appIconImage.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: ViewConstants.spacing10),
|
||||
|
||||
statusLabel.topAnchor.constraint(equalTo: appIconImage.topAnchor, constant: ViewConstants.spacing2),
|
||||
statusLabel.leadingAnchor.constraint(equalTo: appIconImage.trailingAnchor, constant: ViewConstants.spacing10),
|
||||
|
||||
subStatusLabel.topAnchor.constraint(equalTo: statusLabel.bottomAnchor, constant: ViewConstants.spacing10),
|
||||
subStatusLabel.leadingAnchor.constraint(equalTo: statusLabel.leadingAnchor),
|
||||
|
||||
changelogLabel.widthAnchor.constraint(equalTo: stackView.widthAnchor),
|
||||
changelogLabel.heightAnchor.constraint(equalToConstant: 150),
|
||||
|
||||
stackView.topAnchor.constraint(equalTo: subStatusLabel.bottomAnchor, constant: ViewConstants.spacing2),
|
||||
stackView.leadingAnchor.constraint(equalTo: statusLabel.leadingAnchor),
|
||||
view.trailingAnchor.constraint(equalTo: stackView.trailingAnchor, constant: ViewConstants.spacing20),
|
||||
view.bottomAnchor.constraint(equalTo: stackView.bottomAnchor, constant: ViewConstants.spacing20),
|
||||
|
||||
buttonsStackView.heightAnchor.constraint(equalTo: updateButton.heightAnchor),
|
||||
])
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
addSubviews()
|
||||
setConstraints()
|
||||
}
|
||||
|
||||
override func viewDidAppear() {
|
||||
super.viewDidAppear()
|
||||
|
||||
(changelogLabel.documentView as? NSTextView)?.string = ""
|
||||
subStatusLabel.isHidden = true
|
||||
changelogLabel.isHidden = true
|
||||
updateStatus(.checking)
|
||||
checkForUpdate()
|
||||
}
|
||||
|
||||
private func updateStatus(_ status: UpdateStatus) {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.updateButton.isEnabled = true
|
||||
self?.updateButton.title = "Check for Update"
|
||||
self?.updateButton.keyEquivalent = "\r"
|
||||
self?.progressIndicator.isHidden = true
|
||||
self?.statusLabel.stringValue = UpdateStatus.check.rawValue
|
||||
self?.updateButton.action = #selector(self!.checkForUpdate)
|
||||
|
||||
switch status {
|
||||
case .check:
|
||||
break
|
||||
case .latest:
|
||||
self?.statusLabel.stringValue = UpdateStatus.latest.rawValue
|
||||
break
|
||||
case .checking:
|
||||
self?.statusLabel.stringValue = UpdateStatus.checking.rawValue
|
||||
self?.updateButton.keyEquivalent = ""
|
||||
self?.updateButton.isEnabled = false
|
||||
case .available:
|
||||
self?.updateButton.title = "Download"
|
||||
self?.updateButton.keyEquivalent = ""
|
||||
self?.statusLabel.stringValue = UpdateStatus.available.rawValue
|
||||
self?.updateButton.action = #selector(self!.downloadUpdate)
|
||||
case .downloading:
|
||||
self?.updateButton.isEnabled = false
|
||||
self?.updateButton.title = "Install"
|
||||
self?.progressIndicator.isHidden = false
|
||||
self?.statusLabel.stringValue = UpdateStatus.downloading.rawValue
|
||||
case .extracting:
|
||||
self?.updateButton.isEnabled = false
|
||||
self?.updateButton.title = "Install"
|
||||
self?.progressIndicator.isHidden = false
|
||||
self?.statusLabel.stringValue = UpdateStatus.extracting.rawValue
|
||||
case .install:
|
||||
self?.updateButton.title = "Install"
|
||||
self?.progressIndicator.isHidden = false
|
||||
self?.statusLabel.stringValue = UpdateStatus.install.rawValue
|
||||
self?.updateButton.action = #selector(self!.installUpdate)
|
||||
case .checkFailed:
|
||||
self?.statusLabel.stringValue = UpdateStatus.checkFailed.rawValue
|
||||
case .installFailed:
|
||||
self?.statusLabel.stringValue = UpdateStatus.installFailed.rawValue
|
||||
self?.updateButton.action = #selector(self!.checkForUpdate)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func checkForUpdate() {
|
||||
updateStatus(.checking)
|
||||
Task { [weak self] in
|
||||
let status = await UpdateManager.shared.isUpdateAvailable()
|
||||
if status.available == nil {
|
||||
self?.updateStatus(.checkFailed)
|
||||
} else {
|
||||
if status.available! {
|
||||
self?.updateStatus(.available)
|
||||
if let model = status.model, model.changes.count > 0 {
|
||||
DispatchQueue.main.async {
|
||||
self?.subStatusLabel.isHidden = false
|
||||
self?.changelogLabel.isHidden = false
|
||||
for (i, change) in model.changes.enumerated() {
|
||||
(self?.changelogLabel.documentView as? NSTextView)?.string += "\u{2022} \(change)"
|
||||
if i < model.changes.count-1 { (self?.changelogLabel.documentView as? NSTextView)?.string += "\n" }
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
self?.updateStatus(.latest)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func downloadUpdate() {
|
||||
updateStatus(.downloading)
|
||||
|
||||
UpdateManager.shared.downloadUpdate { [weak self] data in
|
||||
switch data {
|
||||
case .success:
|
||||
self?.updateStatus(.extracting)
|
||||
UpdateManager.shared.extractUpdate { [weak self] idata in
|
||||
switch idata {
|
||||
case .success:
|
||||
self?.updateStatus(.install)
|
||||
case .failure:
|
||||
self?.updateStatus(.installFailed)
|
||||
}
|
||||
}
|
||||
case .failure:
|
||||
self?.updateStatus(.installFailed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func installUpdate() {
|
||||
updateButton.isEnabled = false
|
||||
UpdateManager.shared.installUpdate()
|
||||
delegate.terminateApp()
|
||||
}
|
||||
|
||||
@objc private func openChangelog() {
|
||||
openLink(EndpointConstants.changelog)
|
||||
}
|
||||
|
||||
public func setUpdateDelegate() {
|
||||
UpdateManager.shared.delegate = self
|
||||
}
|
||||
|
||||
public func downloadProgressChanged(_ value: Double) {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.progressIndicator.doubleValue = value
|
||||
}
|
||||
}
|
||||
|
||||
public func unzipProgressChanged(_ value: Double) {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.progressIndicator.doubleValue = value
|
||||
}
|
||||
}
|
||||
}
|
||||
41
src/libs/Zip/CHANGELOG.md
Normal file
@@ -0,0 +1,41 @@
|
||||
# Change Log
|
||||
|
||||
## [0.3.0](https://github.com/marmelroy/Zip/tree/0.3.0) (2016-03-07)
|
||||
[Full Changelog](https://github.com/marmelroy/Zip/compare/0.2.0...0.3.0)
|
||||
|
||||
**Closed issues:**
|
||||
|
||||
- No Mac platform support [\#6](https://github.com/marmelroy/Zip/issues/6)
|
||||
|
||||
## [0.2.0](https://github.com/marmelroy/Zip/tree/0.2.0) (2016-01-27)
|
||||
[Full Changelog](https://github.com/marmelroy/Zip/compare/0.1.5...0.2.0)
|
||||
|
||||
**Closed issues:**
|
||||
|
||||
- iOS SDK Requirement [\#4](https://github.com/marmelroy/Zip/issues/4)
|
||||
- Zipping a folder [\#3](https://github.com/marmelroy/Zip/issues/3)
|
||||
|
||||
## [0.1.5](https://github.com/marmelroy/Zip/tree/0.1.5) (2016-01-25)
|
||||
[Full Changelog](https://github.com/marmelroy/Zip/compare/0.1.4...0.1.5)
|
||||
|
||||
**Closed issues:**
|
||||
|
||||
- how to adding some new file to current ziped file? [\#2](https://github.com/marmelroy/Zip/issues/2)
|
||||
|
||||
## [0.1.4](https://github.com/marmelroy/Zip/tree/0.1.4) (2016-01-19)
|
||||
[Full Changelog](https://github.com/marmelroy/Zip/compare/0.1.3...0.1.4)
|
||||
|
||||
## [0.1.3](https://github.com/marmelroy/Zip/tree/0.1.3) (2016-01-18)
|
||||
[Full Changelog](https://github.com/marmelroy/Zip/compare/0.1.2...0.1.3)
|
||||
|
||||
## [0.1.2](https://github.com/marmelroy/Zip/tree/0.1.2) (2016-01-17)
|
||||
[Full Changelog](https://github.com/marmelroy/Zip/compare/0.1.0...0.1.2)
|
||||
|
||||
## [0.1.0](https://github.com/marmelroy/Zip/tree/0.1.0) (2016-01-17)
|
||||
**Closed issues:**
|
||||
|
||||
- Images for README [\#1](https://github.com/marmelroy/Zip/issues/1)
|
||||
|
||||
|
||||
|
||||
\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*
|
||||
22
src/libs/Zip/LICENSE
Normal file
@@ -0,0 +1,22 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Roy Marmelstein
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
78
src/libs/Zip/README.md
Normal file
@@ -0,0 +1,78 @@
|
||||

|
||||
|
||||
[](https://travis-ci.org/marmelroy/Zip) [](http://cocoapods.org/?q=Zip) [](https://github.com/Carthage/Carthage) [](https://swift.org/package-manager)
|
||||
|
||||
|
||||
# Zip
|
||||
A Swift framework for zipping and unzipping files. Simple and quick to use. Built on top of [minizip](https://github.com/nmoinvaz/minizip).
|
||||
|
||||
## Usage
|
||||
|
||||
Import Zip at the top of the Swift file.
|
||||
|
||||
```swift
|
||||
import Zip
|
||||
```
|
||||
|
||||
## Quick functions
|
||||
|
||||
The easiest way to use Zip is through quick functions. Both take local file paths as NSURLs, throw if an error is encountered and return an NSURL to the destination if successful.
|
||||
```swift
|
||||
do {
|
||||
let filePath = Bundle.main.url(forResource: "file", withExtension: "zip")!
|
||||
let unzipDirectory = try Zip.quickUnzipFile(filePath) // Unzip
|
||||
let zipFilePath = try Zip.quickZipFiles([filePath], fileName: "archive") // Zip
|
||||
}
|
||||
catch {
|
||||
print("Something went wrong")
|
||||
}
|
||||
```
|
||||
|
||||
## Advanced Zip
|
||||
|
||||
For more advanced usage, Zip has functions that let you set custom destination paths, work with password protected zips and use a progress handling closure. These functions throw if there is an error but don't return.
|
||||
```swift
|
||||
do {
|
||||
let filePath = Bundle.main.url(forResource: "file", withExtension: "zip")!
|
||||
let documentsDirectory = FileManager.default.urls(for:.documentDirectory, in: .userDomainMask)[0]
|
||||
try Zip.unzipFile(filePath, destination: documentsDirectory, overwrite: true, password: "password", progress: { (progress) -> () in
|
||||
print(progress)
|
||||
}) // Unzip
|
||||
|
||||
let zipFilePath = documentsFolder.appendingPathComponent("archive.zip")
|
||||
try Zip.zipFiles([filePath], zipFilePath: zipFilePath, password: "password", progress: { (progress) -> () in
|
||||
print(progress)
|
||||
}) //Zip
|
||||
|
||||
}
|
||||
catch {
|
||||
print("Something went wrong")
|
||||
}
|
||||
```
|
||||
|
||||
## Custom File Extensions
|
||||
|
||||
Zip supports '.zip' and '.cbz' files out of the box. To support additional zip-derivative file extensions:
|
||||
```swift
|
||||
Zip.addCustomFileExtension("file-extension-here")
|
||||
```
|
||||
|
||||
### [Preferred] Setting up with [Swift Package Manager](https://swift.org/package-manager)
|
||||
To use Zip with Swift Package Manager, add it to your package's dependencies:
|
||||
```swift
|
||||
.package(url: "https://github.com/marmelroy/Zip.git", .upToNextMinor(from: "2.1"))
|
||||
```
|
||||
|
||||
### Setting up with [CocoaPods](http://cocoapods.org/?q=Zip)
|
||||
```ruby
|
||||
source 'https://github.com/CocoaPods/Specs.git'
|
||||
pod 'Zip', '~> 2.1'
|
||||
```
|
||||
|
||||
### Setting up with [Carthage](https://github.com/Carthage/Carthage)
|
||||
To integrate Zip into your Xcode project using Carthage, specify it in your `Cartfile`:
|
||||
|
||||
```ogdl
|
||||
github "marmelroy/Zip" ~> 2.1
|
||||
```
|
||||
|
||||
33
src/libs/Zip/Zip/Makefile
Normal file
@@ -0,0 +1,33 @@
|
||||
CC = swiftc
|
||||
CFLAGS = -g
|
||||
FLAGS = -g
|
||||
|
||||
build_minizip:
|
||||
@:$(if $(value MACOS_VERSION),,$(error MACOS_VERSION is not defined))
|
||||
@$(MAKE) -C minizip CFLAGS=$(CFLAGS) MACOS_VERSION=$(MACOS_VERSION) all
|
||||
|
||||
./arm64/libzip.a: Zip.swift QuickZip.swift ZipUtilities.swift \
|
||||
./minizip/arm64/zip.o ./minizip/arm64/unzip.o ./minizip/arm64/ioapi.o
|
||||
@:$(if $(value MACOS_VERSION),,$(error MACOS_VERSION is not defined))
|
||||
swiftc -target arm64-apple-macos$(MACOS_VERSION) -I./minizip/module \
|
||||
-I./minizip/include -L./minizip/arm64 $(FLAGS) -static \
|
||||
-module-name Zip -emit-library -emit-module -parse-as-library \
|
||||
$^ -o $@
|
||||
|
||||
./x86_64/libzip.a: Zip.swift QuickZip.swift ZipUtilities.swift \
|
||||
./minizip/x86_64/zip.o ./minizip/x86_64/unzip.o \
|
||||
./minizip/x86_64/ioapi.o
|
||||
@:$(if $(value MACOS_VERSION),,$(error MACOS_VERSION is not defined))
|
||||
@swiftc -target x86_64-apple-macos$(MACOS_VERSION) -I./minizip/module \
|
||||
-I./minizip/include -L./minizip/x86_64 $(FLAGS) -static \
|
||||
-module-name Zip -emit-library -emit-module -parse-as-library \
|
||||
$^ -o $@
|
||||
|
||||
all: build_minizip ./arm64/libzip.a ./x86_64/libzip.a
|
||||
|
||||
clean:
|
||||
rm -rf arm64 x86_64
|
||||
mkdir arm64 x86_64
|
||||
|
||||
clean-all: clean
|
||||
$(MAKE) -C minizip clean
|
||||
125
src/libs/Zip/Zip/QuickZip.swift
Normal file
@@ -0,0 +1,125 @@
|
||||
//
|
||||
// QuickZip.swift
|
||||
// Zip
|
||||
//
|
||||
// Created by Roy Marmelstein on 16/01/2016.
|
||||
// Copyright © 2016 Roy Marmelstein. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
extension Zip {
|
||||
|
||||
/**
|
||||
Get search path directory. For tvOS Documents directory doesn't exist.
|
||||
|
||||
- returns: Search path directory
|
||||
*/
|
||||
fileprivate class func searchPathDirectory() -> FileManager.SearchPathDirectory {
|
||||
var searchPathDirectory: FileManager.SearchPathDirectory = .documentDirectory
|
||||
|
||||
#if os(tvOS)
|
||||
searchPathDirectory = .cachesDirectory
|
||||
#endif
|
||||
|
||||
return searchPathDirectory
|
||||
}
|
||||
|
||||
//MARK: Quick Unzip
|
||||
|
||||
/**
|
||||
Quick unzip a file. Unzips to a new folder inside the app's documents folder with the zip file's name.
|
||||
|
||||
- parameter path: Path of zipped file. NSURL.
|
||||
|
||||
- throws: Error if unzipping fails or if file is not found. Can be printed with a description variable.
|
||||
|
||||
- returns: NSURL of the destination folder.
|
||||
*/
|
||||
public class func quickUnzipFile(_ path: URL) throws -> URL {
|
||||
return try quickUnzipFile(path, progress: nil)
|
||||
}
|
||||
|
||||
/**
|
||||
Quick unzip a file. Unzips to a new folder inside the app's documents folder with the zip file's name.
|
||||
|
||||
- parameter path: Path of zipped file. NSURL.
|
||||
- parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1.
|
||||
|
||||
- throws: Error if unzipping fails or if file is not found. Can be printed with a description variable.
|
||||
|
||||
- notes: Supports implicit progress composition
|
||||
|
||||
- returns: NSURL of the destination folder.
|
||||
*/
|
||||
public class func quickUnzipFile(_ path: URL, progress: ((_ progress: Double) -> ())?) throws -> URL {
|
||||
let fileManager = FileManager.default
|
||||
|
||||
let fileExtension = path.pathExtension
|
||||
let fileName = path.lastPathComponent
|
||||
|
||||
let directoryName = fileName.replacingOccurrences(of: ".\(fileExtension)", with: "")
|
||||
|
||||
#if os(Linux)
|
||||
// urls(for:in:) is not yet implemented on Linux
|
||||
// See https://github.com/apple/swift-corelibs-foundation/blob/swift-4.2-branch/Foundation/FileManager.swift#L125
|
||||
let documentsUrl = fileManager.temporaryDirectory
|
||||
#else
|
||||
let documentsUrl = fileManager.urls(for: self.searchPathDirectory(), in: .userDomainMask)[0]
|
||||
#endif
|
||||
do {
|
||||
let destinationUrl = documentsUrl.appendingPathComponent(directoryName, isDirectory: true)
|
||||
try self.unzipFile(path, destination: destinationUrl, overwrite: true, password: nil, progress: progress)
|
||||
return destinationUrl
|
||||
}catch{
|
||||
throw(ZipError.unzipFail)
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: Quick Zip
|
||||
|
||||
/**
|
||||
Quick zip files.
|
||||
|
||||
- parameter paths: Array of NSURL filepaths.
|
||||
- parameter fileName: File name for the resulting zip file.
|
||||
|
||||
- throws: Error if zipping fails.
|
||||
|
||||
- notes: Supports implicit progress composition
|
||||
|
||||
- returns: NSURL of the destination folder.
|
||||
*/
|
||||
public class func quickZipFiles(_ paths: [URL], fileName: String) throws -> URL {
|
||||
return try quickZipFiles(paths, fileName: fileName, progress: nil)
|
||||
}
|
||||
|
||||
/**
|
||||
Quick zip files.
|
||||
|
||||
- parameter paths: Array of NSURL filepaths.
|
||||
- parameter fileName: File name for the resulting zip file.
|
||||
- parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1.
|
||||
|
||||
- throws: Error if zipping fails.
|
||||
|
||||
- notes: Supports implicit progress composition
|
||||
|
||||
- returns: NSURL of the destination folder.
|
||||
*/
|
||||
public class func quickZipFiles(_ paths: [URL], fileName: String, progress: ((_ progress: Double) -> ())?) throws -> URL {
|
||||
let fileManager = FileManager.default
|
||||
#if os(Linux)
|
||||
// urls(for:in:) is not yet implemented on Linux
|
||||
// See https://github.com/apple/swift-corelibs-foundation/blob/swift-4.2-branch/Foundation/FileManager.swift#L125
|
||||
let documentsUrl = fileManager.temporaryDirectory
|
||||
#else
|
||||
let documentsUrl = fileManager.urls(for: self.searchPathDirectory(), in: .userDomainMask)[0] as URL
|
||||
#endif
|
||||
let destinationUrl = documentsUrl.appendingPathComponent("\(fileName).zip")
|
||||
try self.zipFiles(paths: paths, zipFilePath: destinationUrl, password: nil, progress: progress)
|
||||
return destinationUrl
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
19
src/libs/Zip/Zip/Zip.h
Normal file
@@ -0,0 +1,19 @@
|
||||
//
|
||||
// Zip.h
|
||||
// Zip
|
||||
//
|
||||
// Created by Roy Marmelstein on 13/12/2015.
|
||||
// Copyright © 2015 Roy Marmelstein. All rights reserved.
|
||||
//
|
||||
|
||||
@import Foundation;
|
||||
|
||||
//! Project version number for Zip.
|
||||
FOUNDATION_EXPORT double ZipVersionNumber;
|
||||
|
||||
//! Project version string for Zip.
|
||||
FOUNDATION_EXPORT const unsigned char ZipVersionString[];
|
||||
|
||||
// In this header, you should import all the public headers of your framework using statements like #import <Zip/PublicHeader.h>
|
||||
|
||||
|
||||
541
src/libs/Zip/Zip/Zip.swift
Normal file
@@ -0,0 +1,541 @@
|
||||
//
|
||||
// Zip.swift
|
||||
// Zip
|
||||
//
|
||||
// Created by Roy Marmelstein on 13/12/2015.
|
||||
// Copyright © 2015 Roy Marmelstein. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@_implementationOnly import Minizip
|
||||
|
||||
/// Zip error type
|
||||
public enum ZipError: Error {
|
||||
/// File not found
|
||||
case fileNotFound
|
||||
/// Unzip fail
|
||||
case unzipFail
|
||||
/// Zip fail
|
||||
case zipFail
|
||||
|
||||
/// User readable description
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .fileNotFound: return NSLocalizedString("File not found.", comment: "")
|
||||
case .unzipFail: return NSLocalizedString("Failed to unzip file.", comment: "")
|
||||
case .zipFail: return NSLocalizedString("Failed to zip file.", comment: "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public enum ZipCompression: Int {
|
||||
case NoCompression
|
||||
case BestSpeed
|
||||
case DefaultCompression
|
||||
case BestCompression
|
||||
|
||||
internal var minizipCompression: Int32 {
|
||||
switch self {
|
||||
case .NoCompression:
|
||||
return Z_NO_COMPRESSION
|
||||
case .BestSpeed:
|
||||
return Z_BEST_SPEED
|
||||
case .DefaultCompression:
|
||||
return Z_DEFAULT_COMPRESSION
|
||||
case .BestCompression:
|
||||
return Z_BEST_COMPRESSION
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Data in memory that will be archived as a file.
|
||||
public struct ArchiveFile {
|
||||
var filename:String
|
||||
var data:NSData
|
||||
var modifiedTime:Date?
|
||||
|
||||
public init(filename:String, data:NSData, modifiedTime:Date?) {
|
||||
self.filename = filename
|
||||
self.data = data
|
||||
self.modifiedTime = modifiedTime
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Zip class
|
||||
public class Zip {
|
||||
|
||||
/**
|
||||
Set of vaild file extensions
|
||||
*/
|
||||
internal static var customFileExtensions: Set<String> = []
|
||||
|
||||
// MARK: Lifecycle
|
||||
|
||||
/**
|
||||
Init
|
||||
|
||||
- returns: Zip object
|
||||
*/
|
||||
public init () {
|
||||
}
|
||||
|
||||
// MARK: Unzip
|
||||
|
||||
/**
|
||||
Unzip file
|
||||
|
||||
- parameter zipFilePath: Local file path of zipped file. NSURL.
|
||||
- parameter destination: Local file path to unzip to. NSURL.
|
||||
- parameter overwrite: Overwrite bool.
|
||||
- parameter password: Optional password if file is protected.
|
||||
- parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1.
|
||||
|
||||
- throws: Error if unzipping fails or if fail is not found. Can be printed with a description variable.
|
||||
|
||||
- notes: Supports implicit progress composition
|
||||
*/
|
||||
|
||||
public class func unzipFile(_ zipFilePath: URL, destination: URL, overwrite: Bool, password: String?, progress: ((_ progress: Double) -> ())? = nil, fileOutputHandler: ((_ unzippedFile: URL) -> Void)? = nil) throws {
|
||||
|
||||
// File manager
|
||||
let fileManager = FileManager.default
|
||||
|
||||
// Check whether a zip file exists at path.
|
||||
let path = zipFilePath.path
|
||||
|
||||
if fileManager.fileExists(atPath: path) == false || fileExtensionIsInvalid(zipFilePath.pathExtension) {
|
||||
throw ZipError.fileNotFound
|
||||
}
|
||||
|
||||
// Unzip set up
|
||||
var ret: Int32 = 0
|
||||
var crc_ret: Int32 = 0
|
||||
let bufferSize: UInt32 = 4096
|
||||
var buffer = Array<CUnsignedChar>(repeating: 0, count: Int(bufferSize))
|
||||
|
||||
// Progress handler set up
|
||||
var totalSize: Double = 0.0
|
||||
var currentPosition: Double = 0.0
|
||||
let fileAttributes = try fileManager.attributesOfItem(atPath: path)
|
||||
if let attributeFileSize = fileAttributes[FileAttributeKey.size] as? Double {
|
||||
totalSize += attributeFileSize
|
||||
}
|
||||
|
||||
let progressTracker = Progress(totalUnitCount: Int64(totalSize))
|
||||
progressTracker.isCancellable = false
|
||||
progressTracker.isPausable = false
|
||||
progressTracker.kind = ProgressKind.file
|
||||
|
||||
// Begin unzipping
|
||||
let zip = unzOpen64(path)
|
||||
defer {
|
||||
unzClose(zip)
|
||||
}
|
||||
if unzGoToFirstFile(zip) != UNZ_OK {
|
||||
throw ZipError.unzipFail
|
||||
}
|
||||
repeat {
|
||||
if let cPassword = password?.cString(using: String.Encoding.ascii) {
|
||||
ret = unzOpenCurrentFilePassword(zip, cPassword)
|
||||
}
|
||||
else {
|
||||
ret = unzOpenCurrentFile(zip);
|
||||
}
|
||||
if ret != UNZ_OK {
|
||||
throw ZipError.unzipFail
|
||||
}
|
||||
var fileInfo = unz_file_info64()
|
||||
memset(&fileInfo, 0, MemoryLayout<unz_file_info>.size)
|
||||
ret = unzGetCurrentFileInfo64(zip, &fileInfo, nil, 0, nil, 0, nil, 0)
|
||||
if ret != UNZ_OK {
|
||||
unzCloseCurrentFile(zip)
|
||||
throw ZipError.unzipFail
|
||||
}
|
||||
currentPosition += Double(fileInfo.compressed_size)
|
||||
let fileNameSize = Int(fileInfo.size_filename) + 1
|
||||
//let fileName = UnsafeMutablePointer<CChar>(allocatingCapacity: fileNameSize)
|
||||
let fileName = UnsafeMutablePointer<CChar>.allocate(capacity: fileNameSize)
|
||||
|
||||
unzGetCurrentFileInfo64(zip, &fileInfo, fileName, UInt(fileNameSize), nil, 0, nil, 0)
|
||||
fileName[Int(fileInfo.size_filename)] = 0
|
||||
|
||||
var pathString = String(cString: fileName)
|
||||
|
||||
guard pathString.count > 0 else {
|
||||
throw ZipError.unzipFail
|
||||
}
|
||||
|
||||
var isDirectory = false
|
||||
let fileInfoSizeFileName = Int(fileInfo.size_filename-1)
|
||||
if (fileName[fileInfoSizeFileName] == "/".cString(using: String.Encoding.utf8)?.first || fileName[fileInfoSizeFileName] == "\\".cString(using: String.Encoding.utf8)?.first) {
|
||||
isDirectory = true;
|
||||
}
|
||||
free(fileName)
|
||||
if pathString.rangeOfCharacter(from: CharacterSet(charactersIn: "/\\")) != nil {
|
||||
pathString = pathString.replacingOccurrences(of: "\\", with: "/")
|
||||
}
|
||||
|
||||
let fullPath = destination.appendingPathComponent(pathString).standardized.path
|
||||
// .standardized removes any ".. to move a level up".
|
||||
// If we then check that the fullPath starts with the destination directory we know we are not extracting "outside" te destination.
|
||||
guard fullPath.starts(with: destination.standardized.path) else {
|
||||
throw ZipError.unzipFail
|
||||
}
|
||||
|
||||
let creationDate = Date()
|
||||
|
||||
let directoryAttributes: [FileAttributeKey: Any]?
|
||||
#if os(Linux)
|
||||
// On Linux, setting attributes is not yet really implemented.
|
||||
// In Swift 4.2, the only settable attribute is `.posixPermissions`.
|
||||
// See https://github.com/apple/swift-corelibs-foundation/blob/swift-4.2-branch/Foundation/FileManager.swift#L182-L196
|
||||
directoryAttributes = nil
|
||||
#else
|
||||
directoryAttributes = [.creationDate : creationDate,
|
||||
.modificationDate : creationDate]
|
||||
#endif
|
||||
|
||||
do {
|
||||
if isDirectory {
|
||||
try fileManager.createDirectory(atPath: fullPath, withIntermediateDirectories: true, attributes: directoryAttributes)
|
||||
}
|
||||
else {
|
||||
let parentDirectory = (fullPath as NSString).deletingLastPathComponent
|
||||
try fileManager.createDirectory(atPath: parentDirectory, withIntermediateDirectories: true, attributes: directoryAttributes)
|
||||
}
|
||||
} catch {}
|
||||
if fileManager.fileExists(atPath: fullPath) && !isDirectory && !overwrite {
|
||||
unzCloseCurrentFile(zip)
|
||||
ret = unzGoToNextFile(zip)
|
||||
}
|
||||
|
||||
var writeBytes: UInt64 = 0
|
||||
var filePointer: UnsafeMutablePointer<FILE>?
|
||||
filePointer = fopen(fullPath, "wb")
|
||||
while filePointer != nil {
|
||||
let readBytes = unzReadCurrentFile(zip, &buffer, bufferSize)
|
||||
if readBytes > 0 {
|
||||
guard fwrite(buffer, Int(readBytes), 1, filePointer) == 1 else {
|
||||
throw ZipError.unzipFail
|
||||
}
|
||||
writeBytes += UInt64(readBytes)
|
||||
}
|
||||
else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if let fp = filePointer { fclose(fp) }
|
||||
|
||||
crc_ret = unzCloseCurrentFile(zip)
|
||||
if crc_ret == UNZ_CRCERROR {
|
||||
throw ZipError.unzipFail
|
||||
}
|
||||
guard writeBytes == fileInfo.uncompressed_size else {
|
||||
throw ZipError.unzipFail
|
||||
}
|
||||
|
||||
//Set file permissions from current fileInfo
|
||||
if fileInfo.external_fa != 0 {
|
||||
let permissions = (fileInfo.external_fa >> 16) & 0x1FF
|
||||
//We will devifne a valid permission range between Owner read only to full access
|
||||
if permissions >= 0o400 && permissions <= 0o777 {
|
||||
do {
|
||||
try fileManager.setAttributes([.posixPermissions : permissions], ofItemAtPath: fullPath)
|
||||
} catch {
|
||||
print("Failed to set permissions to file \(fullPath), error: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ret = unzGoToNextFile(zip)
|
||||
|
||||
// Update progress handler
|
||||
if let progressHandler = progress{
|
||||
progressHandler((currentPosition/totalSize))
|
||||
}
|
||||
|
||||
if let fileHandler = fileOutputHandler,
|
||||
let encodedString = fullPath.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
|
||||
let fileUrl = URL(string: encodedString) {
|
||||
fileHandler(fileUrl)
|
||||
}
|
||||
|
||||
progressTracker.completedUnitCount = Int64(currentPosition)
|
||||
|
||||
} while (ret == UNZ_OK && ret != UNZ_END_OF_LIST_OF_FILE)
|
||||
|
||||
// Completed. Update progress handler.
|
||||
if let progressHandler = progress{
|
||||
progressHandler(1.0)
|
||||
}
|
||||
|
||||
progressTracker.completedUnitCount = Int64(totalSize)
|
||||
|
||||
}
|
||||
|
||||
// MARK: Zip
|
||||
|
||||
|
||||
/**
|
||||
Zip files.
|
||||
|
||||
- parameter paths: Array of NSURL filepaths.
|
||||
- parameter zipFilePath: Destination NSURL, should lead to a .zip filepath.
|
||||
- parameter password: Password string. Optional.
|
||||
- parameter compression: Compression strategy
|
||||
- parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1.
|
||||
|
||||
- throws: Error if zipping fails.
|
||||
|
||||
- notes: Supports implicit progress composition
|
||||
*/
|
||||
public class func zipFiles(paths: [URL], zipFilePath: URL, password: String?, compression: ZipCompression = .DefaultCompression, progress: ((_ progress: Double) -> ())?) throws {
|
||||
|
||||
// File manager
|
||||
let fileManager = FileManager.default
|
||||
|
||||
// Check whether a zip file exists at path.
|
||||
let destinationPath = zipFilePath.path
|
||||
|
||||
// Process zip paths
|
||||
let processedPaths = ZipUtilities().processZipPaths(paths)
|
||||
|
||||
// Zip set up
|
||||
let chunkSize: Int = 16384
|
||||
|
||||
// Progress handler set up
|
||||
var currentPosition: Double = 0.0
|
||||
var totalSize: Double = 0.0
|
||||
// Get totalSize for progress handler
|
||||
for path in processedPaths {
|
||||
do {
|
||||
let filePath = path.filePath()
|
||||
let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
|
||||
let fileSize = fileAttributes[FileAttributeKey.size] as? Double
|
||||
if let fileSize = fileSize {
|
||||
totalSize += fileSize
|
||||
}
|
||||
}
|
||||
catch {}
|
||||
}
|
||||
|
||||
let progressTracker = Progress(totalUnitCount: Int64(totalSize))
|
||||
progressTracker.isCancellable = false
|
||||
progressTracker.isPausable = false
|
||||
progressTracker.kind = ProgressKind.file
|
||||
|
||||
// Begin Zipping
|
||||
let zip = zipOpen(destinationPath, APPEND_STATUS_CREATE)
|
||||
for path in processedPaths {
|
||||
let filePath = path.filePath()
|
||||
var isDirectory: ObjCBool = false
|
||||
_ = fileManager.fileExists(atPath: filePath, isDirectory: &isDirectory)
|
||||
if !isDirectory.boolValue {
|
||||
guard let input = fopen(filePath, "r") else {
|
||||
throw ZipError.zipFail
|
||||
}
|
||||
defer { fclose(input) }
|
||||
let fileName = path.fileName
|
||||
var zipInfo: zip_fileinfo = zip_fileinfo(tmz_date: tm_zip(tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0, tm_year: 0), dosDate: 0, internal_fa: 0, external_fa: 0)
|
||||
do {
|
||||
let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
|
||||
if let fileDate = fileAttributes[FileAttributeKey.modificationDate] as? Date {
|
||||
let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: fileDate)
|
||||
zipInfo.tmz_date.tm_sec = UInt32(components.second!)
|
||||
zipInfo.tmz_date.tm_min = UInt32(components.minute!)
|
||||
zipInfo.tmz_date.tm_hour = UInt32(components.hour!)
|
||||
zipInfo.tmz_date.tm_mday = UInt32(components.day!)
|
||||
zipInfo.tmz_date.tm_mon = UInt32(components.month!) - 1
|
||||
zipInfo.tmz_date.tm_year = UInt32(components.year!)
|
||||
}
|
||||
if let fileSize = fileAttributes[FileAttributeKey.size] as? Double {
|
||||
currentPosition += fileSize
|
||||
}
|
||||
}
|
||||
catch {}
|
||||
guard let buffer = malloc(chunkSize) else {
|
||||
throw ZipError.zipFail
|
||||
}
|
||||
if let password = password, let fileName = fileName {
|
||||
zipOpenNewFileInZip3(zip, fileName, &zipInfo, nil, 0, nil, 0, nil,Z_DEFLATED, compression.minizipCompression, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, password, 0)
|
||||
}
|
||||
else if let fileName = fileName {
|
||||
zipOpenNewFileInZip3(zip, fileName, &zipInfo, nil, 0, nil, 0, nil,Z_DEFLATED, compression.minizipCompression, 0, -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, nil, 0)
|
||||
}
|
||||
else {
|
||||
throw ZipError.zipFail
|
||||
}
|
||||
var length: Int = 0
|
||||
while (feof(input) == 0) {
|
||||
length = fread(buffer, 1, chunkSize, input)
|
||||
zipWriteInFileInZip(zip, buffer, UInt32(length))
|
||||
}
|
||||
|
||||
// Update progress handler, only if progress is not 1, because
|
||||
// if we call it when progress == 1, the user will receive
|
||||
// a progress handler call with value 1.0 twice.
|
||||
if let progressHandler = progress, currentPosition / totalSize != 1 {
|
||||
progressHandler(currentPosition/totalSize)
|
||||
}
|
||||
|
||||
progressTracker.completedUnitCount = Int64(currentPosition)
|
||||
|
||||
zipCloseFileInZip(zip)
|
||||
free(buffer)
|
||||
}
|
||||
}
|
||||
zipClose(zip, nil)
|
||||
|
||||
// Completed. Update progress handler.
|
||||
if let progressHandler = progress{
|
||||
progressHandler(1.0)
|
||||
}
|
||||
|
||||
progressTracker.completedUnitCount = Int64(totalSize)
|
||||
}
|
||||
|
||||
/**
|
||||
Zip data in memory.
|
||||
|
||||
- parameter archiveFiles:Array of Archive Files.
|
||||
- parameter zipFilePath: Destination NSURL, should lead to a .zip filepath.
|
||||
- parameter password: Password string. Optional.
|
||||
- parameter compression: Compression strategy
|
||||
- parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1.
|
||||
|
||||
- throws: Error if zipping fails.
|
||||
|
||||
- notes: Supports implicit progress composition
|
||||
*/
|
||||
public class func zipData(archiveFiles:[ArchiveFile], zipFilePath:URL, password: String?, compression: ZipCompression = .DefaultCompression, progress: ((_ progress: Double) -> ())?) throws {
|
||||
|
||||
let destinationPath = zipFilePath.path
|
||||
|
||||
// Progress handler set up
|
||||
var currentPosition: Int = 0
|
||||
var totalSize: Int = 0
|
||||
|
||||
for archiveFile in archiveFiles {
|
||||
totalSize += archiveFile.data.length
|
||||
}
|
||||
|
||||
let progressTracker = Progress(totalUnitCount: Int64(totalSize))
|
||||
progressTracker.isCancellable = false
|
||||
progressTracker.isPausable = false
|
||||
progressTracker.kind = ProgressKind.file
|
||||
|
||||
// Begin Zipping
|
||||
let zip = zipOpen(destinationPath, APPEND_STATUS_CREATE)
|
||||
|
||||
for archiveFile in archiveFiles {
|
||||
|
||||
// Skip empty data
|
||||
if archiveFile.data.length == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
// Setup the zip file info
|
||||
var zipInfo = zip_fileinfo(tmz_date: tm_zip(tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0, tm_year: 0),
|
||||
dosDate: 0,
|
||||
internal_fa: 0,
|
||||
external_fa: 0)
|
||||
|
||||
if let modifiedTime = archiveFile.modifiedTime {
|
||||
let calendar = Calendar.current
|
||||
zipInfo.tmz_date.tm_sec = UInt32(calendar.component(.second, from: modifiedTime))
|
||||
zipInfo.tmz_date.tm_min = UInt32(calendar.component(.minute, from: modifiedTime))
|
||||
zipInfo.tmz_date.tm_hour = UInt32(calendar.component(.hour, from: modifiedTime))
|
||||
zipInfo.tmz_date.tm_mday = UInt32(calendar.component(.day, from: modifiedTime))
|
||||
zipInfo.tmz_date.tm_mon = UInt32(calendar.component(.month, from: modifiedTime))
|
||||
zipInfo.tmz_date.tm_year = UInt32(calendar.component(.year, from: modifiedTime))
|
||||
}
|
||||
|
||||
// Write the data as a file to zip
|
||||
zipOpenNewFileInZip3(zip,
|
||||
archiveFile.filename,
|
||||
&zipInfo,
|
||||
nil,
|
||||
0,
|
||||
nil,
|
||||
0,
|
||||
nil,
|
||||
Z_DEFLATED,
|
||||
compression.minizipCompression,
|
||||
0,
|
||||
-MAX_WBITS,
|
||||
DEF_MEM_LEVEL,
|
||||
Z_DEFAULT_STRATEGY,
|
||||
password,
|
||||
0)
|
||||
zipWriteInFileInZip(zip, archiveFile.data.bytes, UInt32(archiveFile.data.length))
|
||||
zipCloseFileInZip(zip)
|
||||
|
||||
// Update progress handler
|
||||
currentPosition += archiveFile.data.length
|
||||
|
||||
if let progressHandler = progress{
|
||||
progressHandler((Double(currentPosition/totalSize)))
|
||||
}
|
||||
|
||||
progressTracker.completedUnitCount = Int64(currentPosition)
|
||||
}
|
||||
|
||||
zipClose(zip, nil)
|
||||
|
||||
// Completed. Update progress handler.
|
||||
if let progressHandler = progress{
|
||||
progressHandler(1.0)
|
||||
}
|
||||
|
||||
progressTracker.completedUnitCount = Int64(totalSize)
|
||||
}
|
||||
|
||||
/**
|
||||
Check if file extension is invalid.
|
||||
|
||||
- parameter fileExtension: A file extension.
|
||||
|
||||
- returns: false if the extension is a valid file extension, otherwise true.
|
||||
*/
|
||||
internal class func fileExtensionIsInvalid(_ fileExtension: String?) -> Bool {
|
||||
|
||||
guard let fileExtension = fileExtension else { return true }
|
||||
|
||||
return !isValidFileExtension(fileExtension)
|
||||
}
|
||||
|
||||
/**
|
||||
Add a file extension to the set of custom file extensions
|
||||
|
||||
- parameter fileExtension: A file extension.
|
||||
*/
|
||||
public class func addCustomFileExtension(_ fileExtension: String) {
|
||||
customFileExtensions.insert(fileExtension)
|
||||
}
|
||||
|
||||
/**
|
||||
Remove a file extension from the set of custom file extensions
|
||||
|
||||
- parameter fileExtension: A file extension.
|
||||
*/
|
||||
public class func removeCustomFileExtension(_ fileExtension: String) {
|
||||
customFileExtensions.remove(fileExtension)
|
||||
}
|
||||
|
||||
/**
|
||||
Check if a specific file extension is valid
|
||||
|
||||
- parameter fileExtension: A file extension.
|
||||
|
||||
- returns: true if the extension valid, otherwise false.
|
||||
*/
|
||||
public class func isValidFileExtension(_ fileExtension: String) -> Bool {
|
||||
|
||||
let validFileExtensions: Set<String> = customFileExtensions.union(["zip", "cbz"])
|
||||
|
||||
return validFileExtensions.contains(fileExtension)
|
||||
}
|
||||
|
||||
}
|
||||
108
src/libs/Zip/Zip/ZipUtilities.swift
Normal file
@@ -0,0 +1,108 @@
|
||||
//
|
||||
// ZipUtilities.swift
|
||||
// Zip
|
||||
//
|
||||
// Created by Roy Marmelstein on 26/01/2016.
|
||||
// Copyright © 2016 Roy Marmelstein. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
internal class ZipUtilities {
|
||||
|
||||
/*
|
||||
Include root directory.
|
||||
Default is true.
|
||||
|
||||
e.g. The Test directory contains two files A.txt and B.txt.
|
||||
|
||||
As true:
|
||||
$ zip -r Test.zip Test/
|
||||
$ unzip -l Test.zip
|
||||
Test/
|
||||
Test/A.txt
|
||||
Test/B.txt
|
||||
|
||||
As false:
|
||||
$ zip -r Test.zip Test/
|
||||
$ unzip -l Test.zip
|
||||
A.txt
|
||||
B.txt
|
||||
*/
|
||||
let includeRootDirectory = true
|
||||
|
||||
// File manager
|
||||
let fileManager = FileManager.default
|
||||
|
||||
/**
|
||||
* ProcessedFilePath struct
|
||||
*/
|
||||
internal struct ProcessedFilePath {
|
||||
let filePathURL: URL
|
||||
let fileName: String?
|
||||
|
||||
func filePath() -> String {
|
||||
return filePathURL.path
|
||||
}
|
||||
}
|
||||
|
||||
//MARK: Path processing
|
||||
|
||||
/**
|
||||
Process zip paths
|
||||
|
||||
- parameter paths: Paths as NSURL.
|
||||
|
||||
- returns: Array of ProcessedFilePath structs.
|
||||
*/
|
||||
internal func processZipPaths(_ paths: [URL]) -> [ProcessedFilePath]{
|
||||
var processedFilePaths = [ProcessedFilePath]()
|
||||
for path in paths {
|
||||
let filePath = path.path
|
||||
var isDirectory: ObjCBool = false
|
||||
_ = fileManager.fileExists(atPath: filePath, isDirectory: &isDirectory)
|
||||
if !isDirectory.boolValue {
|
||||
let processedPath = ProcessedFilePath(filePathURL: path, fileName: path.lastPathComponent)
|
||||
processedFilePaths.append(processedPath)
|
||||
}
|
||||
else {
|
||||
let directoryContents = expandDirectoryFilePath(path)
|
||||
processedFilePaths.append(contentsOf: directoryContents)
|
||||
}
|
||||
}
|
||||
return processedFilePaths
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
Expand directory contents and parse them into ProcessedFilePath structs.
|
||||
|
||||
- parameter directory: Path of folder as NSURL.
|
||||
|
||||
- returns: Array of ProcessedFilePath structs.
|
||||
*/
|
||||
internal func expandDirectoryFilePath(_ directory: URL) -> [ProcessedFilePath] {
|
||||
var processedFilePaths = [ProcessedFilePath]()
|
||||
let directoryPath = directory.path
|
||||
if let enumerator = fileManager.enumerator(atPath: directoryPath) {
|
||||
while let filePathComponent = enumerator.nextObject() as? String {
|
||||
let path = directory.appendingPathComponent(filePathComponent)
|
||||
let filePath = path.path
|
||||
|
||||
var isDirectory: ObjCBool = false
|
||||
_ = fileManager.fileExists(atPath: filePath, isDirectory: &isDirectory)
|
||||
if !isDirectory.boolValue {
|
||||
var fileName = filePathComponent
|
||||
if includeRootDirectory {
|
||||
let directoryName = directory.lastPathComponent
|
||||
fileName = (directoryName as NSString).appendingPathComponent(filePathComponent)
|
||||
}
|
||||
let processedPath = ProcessedFilePath(filePathURL: path, fileName: fileName)
|
||||
processedFilePaths.append(processedPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
return processedFilePaths
|
||||
}
|
||||
|
||||
}
|
||||
27
src/libs/Zip/Zip/minizip/Makefile
Normal file
@@ -0,0 +1,27 @@
|
||||
SRCMODULES = zip.c unzip.c ioapi.c
|
||||
ARMOBJMODULES = $(addprefix ./arm64/,$(SRCMODULES:.c=.o))
|
||||
X86OBJMODULES = $(addprefix ./x86_64/,$(SRCMODULES:.c=.o))
|
||||
HEADERS = $(wildcard ./include/*.h)
|
||||
|
||||
CC = clang
|
||||
CFLAGS = -g
|
||||
|
||||
./arm64/%.o: %.c $(HEADERS)
|
||||
@:$(if $(value MACOS_VERSION),,$(error MACOS_VERSION is not defined))
|
||||
$(CC) -target arm64-apple-macos -mmacosx-version-min=$(MACOS_VERSION) \
|
||||
$(CFLAGS) -fmodule-file=./module/module.modulemap -I./include \
|
||||
-c $< -o ./$@
|
||||
|
||||
./x86_64/%.o: %.c $(HEADERS)
|
||||
@:$(if $(value MACOS_VERSION),,$(error MACOS_VERSION is not defined))
|
||||
@$(CC) -target x86_64-apple-macos -mmacosx-version-min=$(MACOS_VERSION) \
|
||||
$(CFLAGS) -fmodule-file=./module/module.modulemap -I./include \
|
||||
-c $< -o ./$@
|
||||
|
||||
all: $(ARMOBJMODULES) $(X86OBJMODULES)
|
||||
|
||||
default: $(OBJMODULES)
|
||||
|
||||
clean:
|
||||
rm -rf arm64 x86_64
|
||||
mkdir arm64 x86_64
|
||||
16
src/libs/Zip/Zip/minizip/include/Minizip.h
Normal file
@@ -0,0 +1,16 @@
|
||||
//
|
||||
// Minizip.h
|
||||
// Zip
|
||||
//
|
||||
// Created by Florian Friedrich on 3/27/19.
|
||||
// Copyright © 2019 Roy Marmelstein. All rights reserved.
|
||||
//
|
||||
|
||||
#ifndef Minizip_h
|
||||
#define Minizip_h
|
||||
|
||||
#import "crypt.h"
|
||||
#import "unzip.h"
|
||||
#import "zip.h"
|
||||
|
||||
#endif /* Minizip_h */
|
||||
131
src/libs/Zip/Zip/minizip/include/crypt.h
Normal file
@@ -0,0 +1,131 @@
|
||||
/* crypt.h -- base code for traditional PKWARE encryption
|
||||
Version 1.01e, February 12th, 2005
|
||||
|
||||
Copyright (C) 1998-2005 Gilles Vollant
|
||||
Modifications for Info-ZIP crypting
|
||||
Copyright (C) 2003 Terry Thorsen
|
||||
|
||||
This code is a modified version of crypting code in Info-ZIP distribution
|
||||
|
||||
Copyright (C) 1990-2000 Info-ZIP. All rights reserved.
|
||||
|
||||
See the Info-ZIP LICENSE file version 2000-Apr-09 or later for terms of use
|
||||
which also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html
|
||||
|
||||
The encryption/decryption parts of this source code (as opposed to the
|
||||
non-echoing password parts) were originally written in Europe. The
|
||||
whole source package can be freely distributed, including from the USA.
|
||||
(Prior to January 2000, re-export from the US was a violation of US law.)
|
||||
|
||||
This encryption code is a direct transcription of the algorithm from
|
||||
Roger Schlafly, described by Phil Katz in the file appnote.txt. This
|
||||
file (appnote.txt) is distributed with the PKZIP program (even in the
|
||||
version without encryption capabilities).
|
||||
|
||||
If you don't need crypting in your application, just define symbols
|
||||
NOCRYPT and NOUNCRYPT.
|
||||
*/
|
||||
|
||||
#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8))
|
||||
|
||||
/***********************************************************************
|
||||
* Return the next byte in the pseudo-random sequence
|
||||
*/
|
||||
static int decrypt_byte(unsigned long* pkeys)
|
||||
{
|
||||
unsigned temp; /* POTENTIAL BUG: temp*(temp^1) may overflow in an
|
||||
* unpredictable manner on 16-bit systems; not a problem
|
||||
* with any known compiler so far, though */
|
||||
|
||||
temp = ((unsigned)(*(pkeys+2)) & 0xffff) | 2;
|
||||
return (int)(((temp * (temp ^ 1)) >> 8) & 0xff);
|
||||
}
|
||||
|
||||
/***********************************************************************
|
||||
* Update the encryption keys with the next byte of plain text
|
||||
*/
|
||||
static int update_keys(unsigned long* pkeys, const unsigned long* pcrc_32_tab, int c)
|
||||
{
|
||||
(*(pkeys+0)) = CRC32((*(pkeys+0)), c);
|
||||
(*(pkeys+1)) += (*(pkeys+0)) & 0xff;
|
||||
(*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1;
|
||||
{
|
||||
register int keyshift = (int)((*(pkeys+1)) >> 24);
|
||||
(*(pkeys+2)) = CRC32((*(pkeys+2)), keyshift);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
|
||||
/***********************************************************************
|
||||
* Initialize the encryption keys and the random header according to
|
||||
* the given password.
|
||||
*/
|
||||
static void init_keys(const char* passwd, unsigned long* pkeys, const unsigned long* pcrc_32_tab)
|
||||
{
|
||||
*(pkeys+0) = 305419896L;
|
||||
*(pkeys+1) = 591751049L;
|
||||
*(pkeys+2) = 878082192L;
|
||||
while (*passwd != 0)
|
||||
{
|
||||
update_keys(pkeys,pcrc_32_tab,(int)*passwd);
|
||||
passwd++;
|
||||
}
|
||||
}
|
||||
|
||||
#define zdecode(pkeys,pcrc_32_tab,c) \
|
||||
(update_keys(pkeys,pcrc_32_tab,c ^= decrypt_byte(pkeys)))
|
||||
|
||||
#define zencode(pkeys,pcrc_32_tab,c,t) \
|
||||
(t=decrypt_byte(pkeys), update_keys(pkeys,pcrc_32_tab,c), t^(c))
|
||||
|
||||
#ifdef INCLUDECRYPTINGCODE_IFCRYPTALLOWED
|
||||
|
||||
#define RAND_HEAD_LEN 12
|
||||
/* "last resort" source for second part of crypt seed pattern */
|
||||
# ifndef ZCR_SEED2
|
||||
# define ZCR_SEED2 3141592654UL /* use PI as default pattern */
|
||||
# endif
|
||||
|
||||
static int crypthead(const char* passwd, /* password string */
|
||||
unsigned char* buf, /* where to write header */
|
||||
int bufSize,
|
||||
unsigned long* pkeys,
|
||||
const unsigned long* pcrc_32_tab,
|
||||
unsigned long crcForCrypting)
|
||||
{
|
||||
int n; /* index in random header */
|
||||
int t; /* temporary */
|
||||
int c; /* random byte */
|
||||
unsigned char header[RAND_HEAD_LEN-2]; /* random header */
|
||||
static unsigned calls = 0; /* ensure different random header each time */
|
||||
|
||||
if (bufSize < RAND_HEAD_LEN)
|
||||
return 0;
|
||||
|
||||
/* First generate RAND_HEAD_LEN-2 random bytes. We encrypt the
|
||||
* output of rand() to get less predictability, since rand() is
|
||||
* often poorly implemented.
|
||||
*/
|
||||
if (++calls == 1)
|
||||
{
|
||||
srand((unsigned)(time(NULL) ^ ZCR_SEED2));
|
||||
}
|
||||
init_keys(passwd, pkeys, pcrc_32_tab);
|
||||
for (n = 0; n < RAND_HEAD_LEN-2; n++)
|
||||
{
|
||||
c = (rand() >> 7) & 0xff;
|
||||
header[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, c, t);
|
||||
}
|
||||
/* Encrypt random header (last two bytes is high word of crc) */
|
||||
init_keys(passwd, pkeys, pcrc_32_tab);
|
||||
for (n = 0; n < RAND_HEAD_LEN-2; n++)
|
||||
{
|
||||
buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t);
|
||||
}
|
||||
buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0xff, t);
|
||||
buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0xff, t);
|
||||
return n;
|
||||
}
|
||||
|
||||
#endif
|
||||
178
src/libs/Zip/Zip/minizip/include/ioapi.h
Normal file
@@ -0,0 +1,178 @@
|
||||
/* ioapi.h -- IO base function header for compress/uncompress .zip
|
||||
part of the MiniZip project
|
||||
|
||||
Copyright (C) 1998-2010 Gilles Vollant
|
||||
http://www.winimage.com/zLibDll/minizip.html
|
||||
Modifications for Zip64 support
|
||||
Copyright (C) 2009-2010 Mathias Svensson
|
||||
http://result42.com
|
||||
|
||||
This program is distributed under the terms of the same license as zlib.
|
||||
See the accompanying LICENSE file for the full text of the license.
|
||||
*/
|
||||
|
||||
#ifndef _ZLIBIOAPI64_H
|
||||
#define _ZLIBIOAPI64_H
|
||||
|
||||
#if (!defined(_WIN32)) && (!defined(WIN32)) && (!defined(__APPLE__))
|
||||
# ifndef __USE_FILE_OFFSET64
|
||||
# define __USE_FILE_OFFSET64
|
||||
# endif
|
||||
# ifndef __USE_LARGEFILE64
|
||||
# define __USE_LARGEFILE64
|
||||
# endif
|
||||
# ifndef _LARGEFILE64_SOURCE
|
||||
# define _LARGEFILE64_SOURCE
|
||||
# endif
|
||||
# ifndef _FILE_OFFSET_BIT
|
||||
# define _FILE_OFFSET_BIT 64
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#ifndef _ZLIB_H
|
||||
#include <zlib.h>
|
||||
#endif
|
||||
|
||||
#if defined(USE_FILE32API)
|
||||
# define fopen64 fopen
|
||||
# define ftello64 ftell
|
||||
# define fseeko64 fseek
|
||||
#else
|
||||
# if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__OpenBSD__)
|
||||
# define fopen64 fopen
|
||||
# define ftello64 ftello
|
||||
# define fseeko64 fseeko
|
||||
# endif
|
||||
# ifdef _MSC_VER
|
||||
# define fopen64 fopen
|
||||
# if (_MSC_VER >= 1400) && (!(defined(NO_MSCVER_FILE64_FUNC)))
|
||||
# define ftello64 _ftelli64
|
||||
# define fseeko64 _fseeki64
|
||||
# else /* old MSC */
|
||||
# define ftello64 ftell
|
||||
# define fseeko64 fseek
|
||||
# endif
|
||||
# endif
|
||||
#endif
|
||||
|
||||
/* a type choosen by DEFINE */
|
||||
#ifdef HAVE_64BIT_INT_CUSTOM
|
||||
typedef 64BIT_INT_CUSTOM_TYPE ZPOS64_T;
|
||||
#else
|
||||
# ifdef HAVE_STDINT_H
|
||||
# include "stdint.h"
|
||||
typedef uint64_t ZPOS64_T;
|
||||
# else
|
||||
# if defined(_MSC_VER) || defined(__BORLANDC__)
|
||||
typedef unsigned __int64 ZPOS64_T;
|
||||
# else
|
||||
typedef unsigned long long int ZPOS64_T;
|
||||
# endif
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define ZLIB_FILEFUNC_SEEK_CUR (1)
|
||||
#define ZLIB_FILEFUNC_SEEK_END (2)
|
||||
#define ZLIB_FILEFUNC_SEEK_SET (0)
|
||||
|
||||
#define ZLIB_FILEFUNC_MODE_READ (1)
|
||||
#define ZLIB_FILEFUNC_MODE_WRITE (2)
|
||||
#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3)
|
||||
#define ZLIB_FILEFUNC_MODE_EXISTING (4)
|
||||
#define ZLIB_FILEFUNC_MODE_CREATE (8)
|
||||
|
||||
#ifndef ZCALLBACK
|
||||
# if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || \
|
||||
defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK)
|
||||
# define ZCALLBACK CALLBACK
|
||||
# else
|
||||
# define ZCALLBACK
|
||||
# endif
|
||||
#endif
|
||||
|
||||
typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, const char* filename, int mode));
|
||||
typedef voidpf (ZCALLBACK *opendisk_file_func) OF((voidpf opaque, voidpf stream, int number_disk, int mode));
|
||||
typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size));
|
||||
typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
|
||||
typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream));
|
||||
typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream));
|
||||
|
||||
typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream));
|
||||
typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin));
|
||||
|
||||
/* here is the "old" 32 bits structure structure */
|
||||
typedef struct zlib_filefunc_def_s
|
||||
{
|
||||
open_file_func zopen_file;
|
||||
opendisk_file_func zopendisk_file;
|
||||
read_file_func zread_file;
|
||||
write_file_func zwrite_file;
|
||||
tell_file_func ztell_file;
|
||||
seek_file_func zseek_file;
|
||||
close_file_func zclose_file;
|
||||
testerror_file_func zerror_file;
|
||||
voidpf opaque;
|
||||
} zlib_filefunc_def;
|
||||
|
||||
typedef ZPOS64_T (ZCALLBACK *tell64_file_func) OF((voidpf opaque, voidpf stream));
|
||||
typedef long (ZCALLBACK *seek64_file_func) OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
|
||||
typedef voidpf (ZCALLBACK *open64_file_func) OF((voidpf opaque, const void* filename, int mode));
|
||||
typedef voidpf (ZCALLBACK *opendisk64_file_func)OF((voidpf opaque, voidpf stream, int number_disk, int mode));
|
||||
|
||||
typedef struct zlib_filefunc64_def_s
|
||||
{
|
||||
open64_file_func zopen64_file;
|
||||
opendisk64_file_func zopendisk64_file;
|
||||
read_file_func zread_file;
|
||||
write_file_func zwrite_file;
|
||||
tell64_file_func ztell64_file;
|
||||
seek64_file_func zseek64_file;
|
||||
close_file_func zclose_file;
|
||||
testerror_file_func zerror_file;
|
||||
voidpf opaque;
|
||||
} zlib_filefunc64_def;
|
||||
|
||||
void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
|
||||
void fill_fopen64_filefunc OF((zlib_filefunc64_def* pzlib_filefunc_def));
|
||||
|
||||
/* now internal definition, only for zip.c and unzip.h */
|
||||
typedef struct zlib_filefunc64_32_def_s
|
||||
{
|
||||
zlib_filefunc64_def zfile_func64;
|
||||
open_file_func zopen32_file;
|
||||
opendisk_file_func zopendisk32_file;
|
||||
tell_file_func ztell32_file;
|
||||
seek_file_func zseek32_file;
|
||||
} zlib_filefunc64_32_def;
|
||||
|
||||
#define ZREAD64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zread_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
|
||||
#define ZWRITE64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zwrite_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
|
||||
/*#define ZTELL64(filefunc,filestream) ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream))*/
|
||||
/*#define ZSEEK64(filefunc,filestream,pos,mode) ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode))*/
|
||||
#define ZCLOSE64(filefunc,filestream) ((*((filefunc).zfile_func64.zclose_file)) ((filefunc).zfile_func64.opaque,filestream))
|
||||
#define ZERROR64(filefunc,filestream) ((*((filefunc).zfile_func64.zerror_file)) ((filefunc).zfile_func64.opaque,filestream))
|
||||
|
||||
voidpf call_zopen64 OF((const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode));
|
||||
voidpf call_zopendisk64 OF((const zlib_filefunc64_32_def* pfilefunc, voidpf filestream, int number_disk, int mode));
|
||||
long call_zseek64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin));
|
||||
ZPOS64_T call_ztell64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream));
|
||||
|
||||
void fill_zlib_filefunc64_32_def_from_filefunc32 OF((zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32));
|
||||
|
||||
#define ZOPEN64(filefunc,filename,mode) (call_zopen64((&(filefunc)),(filename),(mode)))
|
||||
#define ZOPENDISK64(filefunc,filestream,diskn,mode) (call_zopendisk64((&(filefunc)),(filestream),(diskn),(mode)))
|
||||
#define ZTELL64(filefunc,filestream) (call_ztell64((&(filefunc)),(filestream)))
|
||||
#define ZSEEK64(filefunc,filestream,pos,mode) (call_zseek64((&(filefunc)),(filestream),(pos),(mode)))
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
319
src/libs/Zip/Zip/minizip/include/unzip.h
Normal file
@@ -0,0 +1,319 @@
|
||||
/* unzip.h -- IO for uncompress .zip files using zlib
|
||||
Version 1.1, February 14h, 2010
|
||||
part of the MiniZip project
|
||||
|
||||
Copyright (C) 1998-2010 Gilles Vollant
|
||||
http://www.winimage.com/zLibDll/minizip.html
|
||||
Modifications of Unzip for Zip64
|
||||
Copyright (C) 2007-2008 Even Rouault
|
||||
Modifications for Zip64 support on both zip and unzip
|
||||
Copyright (C) 2009-2010 Mathias Svensson
|
||||
http://result42.com
|
||||
|
||||
This program is distributed under the terms of the same license as zlib.
|
||||
See the accompanying LICENSE file for the full text of the license.
|
||||
*/
|
||||
|
||||
#ifndef _UNZ_H
|
||||
#define _UNZ_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#ifndef _ZLIB_H
|
||||
#include <zlib.h>
|
||||
#endif
|
||||
|
||||
#ifndef _ZLIBIOAPI_H
|
||||
#include "ioapi.h"
|
||||
#endif
|
||||
|
||||
#ifdef HAVE_BZIP2
|
||||
#include "bzlib.h"
|
||||
#endif
|
||||
|
||||
#define Z_BZIP2ED 12
|
||||
|
||||
#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP)
|
||||
/* like the STRICT of WIN32, we define a pointer that cannot be converted
|
||||
from (void*) without cast */
|
||||
typedef struct TagunzFile__ { int unused; } unzFile__;
|
||||
typedef unzFile__ *unzFile;
|
||||
#else
|
||||
typedef voidp unzFile;
|
||||
#endif
|
||||
|
||||
#define UNZ_OK (0)
|
||||
#define UNZ_END_OF_LIST_OF_FILE (-100)
|
||||
#define UNZ_ERRNO (Z_ERRNO)
|
||||
#define UNZ_EOF (0)
|
||||
#define UNZ_PARAMERROR (-102)
|
||||
#define UNZ_BADZIPFILE (-103)
|
||||
#define UNZ_INTERNALERROR (-104)
|
||||
#define UNZ_CRCERROR (-105)
|
||||
|
||||
/* tm_unz contain date/time info */
|
||||
typedef struct tm_unz_s
|
||||
{
|
||||
uInt tm_sec; /* seconds after the minute - [0,59] */
|
||||
uInt tm_min; /* minutes after the hour - [0,59] */
|
||||
uInt tm_hour; /* hours since midnight - [0,23] */
|
||||
uInt tm_mday; /* day of the month - [1,31] */
|
||||
uInt tm_mon; /* months since January - [0,11] */
|
||||
uInt tm_year; /* years - [1980..2044] */
|
||||
} tm_unz;
|
||||
|
||||
/* unz_global_info structure contain global data about the ZIPfile
|
||||
These data comes from the end of central dir */
|
||||
typedef struct unz_global_info64_s
|
||||
{
|
||||
ZPOS64_T number_entry; /* total number of entries in the central dir on this disk */
|
||||
uLong number_disk_with_CD; /* number the the disk with central dir, used for spanning ZIP*/
|
||||
uLong size_comment; /* size of the global comment of the zipfile */
|
||||
} unz_global_info64;
|
||||
|
||||
typedef struct unz_global_info_s
|
||||
{
|
||||
uLong number_entry; /* total number of entries in the central dir on this disk */
|
||||
uLong number_disk_with_CD; /* number the the disk with central dir, used for spanning ZIP*/
|
||||
uLong size_comment; /* size of the global comment of the zipfile */
|
||||
} unz_global_info;
|
||||
|
||||
/* unz_file_info contain information about a file in the zipfile */
|
||||
typedef struct unz_file_info64_s
|
||||
{
|
||||
uLong version; /* version made by 2 bytes */
|
||||
uLong version_needed; /* version needed to extract 2 bytes */
|
||||
uLong flag; /* general purpose bit flag 2 bytes */
|
||||
uLong compression_method; /* compression method 2 bytes */
|
||||
uLong dosDate; /* last mod file date in Dos fmt 4 bytes */
|
||||
uLong crc; /* crc-32 4 bytes */
|
||||
ZPOS64_T compressed_size; /* compressed size 8 bytes */
|
||||
ZPOS64_T uncompressed_size; /* uncompressed size 8 bytes */
|
||||
uLong size_filename; /* filename length 2 bytes */
|
||||
uLong size_file_extra; /* extra field length 2 bytes */
|
||||
uLong size_file_comment; /* file comment length 2 bytes */
|
||||
|
||||
uLong disk_num_start; /* disk number start 2 bytes */
|
||||
uLong internal_fa; /* internal file attributes 2 bytes */
|
||||
uLong external_fa; /* external file attributes 4 bytes */
|
||||
|
||||
tm_unz tmu_date;
|
||||
ZPOS64_T disk_offset;
|
||||
uLong size_file_extra_internal;
|
||||
} unz_file_info64;
|
||||
|
||||
typedef struct unz_file_info_s
|
||||
{
|
||||
uLong version; /* version made by 2 bytes */
|
||||
uLong version_needed; /* version needed to extract 2 bytes */
|
||||
uLong flag; /* general purpose bit flag 2 bytes */
|
||||
uLong compression_method; /* compression method 2 bytes */
|
||||
uLong dosDate; /* last mod file date in Dos fmt 4 bytes */
|
||||
uLong crc; /* crc-32 4 bytes */
|
||||
uLong compressed_size; /* compressed size 4 bytes */
|
||||
uLong uncompressed_size; /* uncompressed size 4 bytes */
|
||||
uLong size_filename; /* filename length 2 bytes */
|
||||
uLong size_file_extra; /* extra field length 2 bytes */
|
||||
uLong size_file_comment; /* file comment length 2 bytes */
|
||||
|
||||
uLong disk_num_start; /* disk number start 2 bytes */
|
||||
uLong internal_fa; /* internal file attributes 2 bytes */
|
||||
uLong external_fa; /* external file attributes 4 bytes */
|
||||
|
||||
tm_unz tmu_date;
|
||||
uLong disk_offset;
|
||||
} unz_file_info;
|
||||
|
||||
/***************************************************************************/
|
||||
/* Opening and close a zip file */
|
||||
|
||||
extern unzFile ZEXPORT unzOpen OF((const char *path));
|
||||
extern unzFile ZEXPORT unzOpen64 OF((const void *path));
|
||||
/* Open a Zip file.
|
||||
|
||||
path should contain the full pathname (by example, on a Windows XP computer
|
||||
"c:\\zlib\\zlib113.zip" or on an Unix computer "zlib/zlib113.zip".
|
||||
return NULL if zipfile cannot be opened or doesn't exist
|
||||
return unzFile handle if no error
|
||||
|
||||
NOTE: The "64" function take a const void* pointer, because the path is just the value passed to the
|
||||
open64_file_func callback. Under Windows, if UNICODE is defined, using fill_fopen64_filefunc, the path
|
||||
is a pointer to a wide unicode string (LPCTSTR is LPCWSTR), so const char* does not describe the reality */
|
||||
|
||||
extern unzFile ZEXPORT unzOpen2 OF((const char *path, zlib_filefunc_def* pzlib_filefunc_def));
|
||||
/* Open a Zip file, like unzOpen, but provide a set of file low level API for read/write operations */
|
||||
extern unzFile ZEXPORT unzOpen2_64 OF((const void *path, zlib_filefunc64_def* pzlib_filefunc_def));
|
||||
/* Open a Zip file, like unz64Open, but provide a set of file low level API for read/write 64-bit operations */
|
||||
|
||||
extern int ZEXPORT unzClose OF((unzFile file));
|
||||
/* Close a ZipFile opened with unzipOpen. If there is files inside the .Zip opened with unzOpenCurrentFile,
|
||||
these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
|
||||
|
||||
return UNZ_OK if there is no error */
|
||||
|
||||
extern int ZEXPORT unzGetGlobalInfo OF((unzFile file, unz_global_info *pglobal_info));
|
||||
extern int ZEXPORT unzGetGlobalInfo64 OF((unzFile file, unz_global_info64 *pglobal_info));
|
||||
/* Write info about the ZipFile in the *pglobal_info structure.
|
||||
|
||||
return UNZ_OK if no error */
|
||||
|
||||
extern int ZEXPORT unzGetGlobalComment OF((unzFile file, char *comment, uLong comment_size));
|
||||
/* Get the global comment string of the ZipFile, in the comment buffer.
|
||||
|
||||
uSizeBuf is the size of the szComment buffer.
|
||||
return the number of byte copied or an error code <0 */
|
||||
|
||||
/***************************************************************************/
|
||||
/* Reading the content of the current zipfile, you can open it, read data from it, and close it
|
||||
(you can close it before reading all the file) */
|
||||
|
||||
extern int ZEXPORT unzOpenCurrentFile OF((unzFile file));
|
||||
/* Open for reading data the current file in the zipfile.
|
||||
|
||||
return UNZ_OK if no error */
|
||||
|
||||
extern int ZEXPORT unzOpenCurrentFilePassword OF((unzFile file, const char* password));
|
||||
/* Open for reading data the current file in the zipfile.
|
||||
password is a crypting password
|
||||
|
||||
return UNZ_OK if no error */
|
||||
|
||||
extern int ZEXPORT unzOpenCurrentFile2 OF((unzFile file, int* method, int* level, int raw));
|
||||
/* Same as unzOpenCurrentFile, but open for read raw the file (not uncompress)
|
||||
if raw==1 *method will receive method of compression, *level will receive level of compression
|
||||
|
||||
NOTE: you can set level parameter as NULL (if you did not want known level,
|
||||
but you CANNOT set method parameter as NULL */
|
||||
|
||||
extern int ZEXPORT unzOpenCurrentFile3 OF((unzFile file, int* method, int* level, int raw, const char* password));
|
||||
/* Same as unzOpenCurrentFile, but takes extra parameter password for encrypted files */
|
||||
|
||||
extern int ZEXPORT unzReadCurrentFile OF((unzFile file, voidp buf, unsigned len));
|
||||
/* Read bytes from the current file (opened by unzOpenCurrentFile)
|
||||
buf contain buffer where data must be copied
|
||||
len the size of buf.
|
||||
|
||||
return the number of byte copied if somes bytes are copied
|
||||
return 0 if the end of file was reached
|
||||
return <0 with error code if there is an error (UNZ_ERRNO for IO error, or zLib error for uncompress error) */
|
||||
|
||||
extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file, unz_file_info *pfile_info, char *filename,
|
||||
uLong filename_size, void *extrafield, uLong extrafield_size, char *comment, uLong comment_size));
|
||||
extern int ZEXPORT unzGetCurrentFileInfo64 OF((unzFile file, unz_file_info64 *pfile_info, char *filename,
|
||||
uLong filename_size, void *extrafield, uLong extrafield_size, char *comment, uLong comment_size));
|
||||
/* Get Info about the current file
|
||||
|
||||
pfile_info if != NULL, the *pfile_info structure will contain somes info about the current file
|
||||
filename if != NULL, the file name string will be copied in filename
|
||||
filename_size is the size of the filename buffer
|
||||
extrafield if != NULL, the extra field information from the central header will be copied in to
|
||||
extrafield_size is the size of the extraField buffer
|
||||
comment if != NULL, the comment string of the file will be copied in to
|
||||
comment_size is the size of the comment buffer */
|
||||
|
||||
extern ZPOS64_T ZEXPORT unzGetCurrentFileZStreamPos64 OF((unzFile file));
|
||||
|
||||
extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file, voidp buf, unsigned len));
|
||||
/* Read extra field from the current file (opened by unzOpenCurrentFile)
|
||||
This is the local-header version of the extra field (sometimes, there is
|
||||
more info in the local-header version than in the central-header)
|
||||
|
||||
if buf == NULL, it return the size of the local extra field
|
||||
if buf != NULL, len is the size of the buffer, the extra header is copied in buf.
|
||||
|
||||
return number of bytes copied in buf, or (if <0) the error code */
|
||||
|
||||
extern int ZEXPORT unzCloseCurrentFile OF((unzFile file));
|
||||
/* Close the file in zip opened with unzOpenCurrentFile
|
||||
|
||||
return UNZ_CRCERROR if all the file was read but the CRC is not good */
|
||||
|
||||
/***************************************************************************/
|
||||
/* Browse the directory of the zipfile */
|
||||
|
||||
typedef int (*unzFileNameComparer)(unzFile file, const char *filename1, const char *filename2);
|
||||
typedef int (*unzIteratorFunction)(unzFile file);
|
||||
typedef int (*unzIteratorFunction2)(unzFile file, unz_file_info64 *pfile_info, char *filename,
|
||||
uLong filename_size, void *extrafield, uLong extrafield_size, char *comment, uLong comment_size);
|
||||
|
||||
extern int ZEXPORT unzGoToFirstFile OF((unzFile file));
|
||||
/* Set the current file of the zipfile to the first file.
|
||||
|
||||
return UNZ_OK if no error */
|
||||
|
||||
extern int ZEXPORT unzGoToFirstFile2 OF((unzFile file, unz_file_info64 *pfile_info, char *filename,
|
||||
uLong filename_size, void *extrafield, uLong extrafield_size, char *comment, uLong comment_size));
|
||||
/* Set the current file of the zipfile to the first file and retrieves the current info on success.
|
||||
Not as seek intensive as unzGoToFirstFile + unzGetCurrentFileInfo.
|
||||
|
||||
return UNZ_OK if no error */
|
||||
|
||||
extern int ZEXPORT unzGoToNextFile OF((unzFile file));
|
||||
/* Set the current file of the zipfile to the next file.
|
||||
|
||||
return UNZ_OK if no error
|
||||
return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest */
|
||||
|
||||
extern int ZEXPORT unzGoToNextFile2 OF((unzFile file, unz_file_info64 *pfile_info, char *filename,
|
||||
uLong filename_size, void *extrafield, uLong extrafield_size, char *comment, uLong comment_size));
|
||||
/* Set the current file of the zipfile to the next file and retrieves the current
|
||||
info on success. Does less seeking around than unzGotoNextFile + unzGetCurrentFileInfo.
|
||||
|
||||
return UNZ_OK if no error
|
||||
return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest */
|
||||
|
||||
extern int ZEXPORT unzLocateFile OF((unzFile file, const char *filename, unzFileNameComparer filename_compare_func));
|
||||
/* Try locate the file szFileName in the zipfile. For custom filename comparison pass in comparison function.
|
||||
|
||||
return UNZ_OK if the file is found (it becomes the current file)
|
||||
return UNZ_END_OF_LIST_OF_FILE if the file is not found */
|
||||
|
||||
/***************************************************************************/
|
||||
/* Raw access to zip file */
|
||||
|
||||
typedef struct unz_file_pos_s
|
||||
{
|
||||
uLong pos_in_zip_directory; /* offset in zip file directory */
|
||||
uLong num_of_file; /* # of file */
|
||||
} unz_file_pos;
|
||||
|
||||
extern int ZEXPORT unzGetFilePos OF((unzFile file, unz_file_pos* file_pos));
|
||||
extern int ZEXPORT unzGoToFilePos OF((unzFile file, unz_file_pos* file_pos));
|
||||
|
||||
typedef struct unz64_file_pos_s
|
||||
{
|
||||
ZPOS64_T pos_in_zip_directory; /* offset in zip file directory */
|
||||
ZPOS64_T num_of_file; /* # of file */
|
||||
} unz64_file_pos;
|
||||
|
||||
extern int ZEXPORT unzGetFilePos64 OF((unzFile file, unz64_file_pos* file_pos));
|
||||
extern int ZEXPORT unzGoToFilePos64 OF((unzFile file, const unz64_file_pos* file_pos));
|
||||
|
||||
extern uLong ZEXPORT unzGetOffset OF((unzFile file));
|
||||
extern ZPOS64_T ZEXPORT unzGetOffset64 OF((unzFile file));
|
||||
/* Get the current file offset */
|
||||
|
||||
extern int ZEXPORT unzSetOffset OF((unzFile file, uLong pos));
|
||||
extern int ZEXPORT unzSetOffset64 OF((unzFile file, ZPOS64_T pos));
|
||||
/* Set the current file offset */
|
||||
|
||||
extern z_off_t ZEXPORT unztell OF((unzFile file));
|
||||
extern ZPOS64_T ZEXPORT unztell64 OF((unzFile file));
|
||||
/* return current position in uncompressed data */
|
||||
|
||||
extern int ZEXPORT unzseek OF((unzFile file, z_off_t offset, int origin));
|
||||
extern int ZEXPORT unzseek64 OF((unzFile file, ZPOS64_T offset, int origin));
|
||||
/* Seek within the uncompressed data if compression method is storage */
|
||||
|
||||
extern int ZEXPORT unzeof OF((unzFile file));
|
||||
/* return 1 if the end of file was reached, 0 elsewhere */
|
||||
|
||||
/***************************************************************************/
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* _UNZ_H */
|
||||
198
src/libs/Zip/Zip/minizip/include/zip.h
Normal file
@@ -0,0 +1,198 @@
|
||||
/* zip.h -- IO on .zip files using zlib
|
||||
Version 1.1, February 14h, 2010
|
||||
part of the MiniZip project
|
||||
|
||||
Copyright (C) 1998-2010 Gilles Vollant
|
||||
http://www.winimage.com/zLibDll/minizip.html
|
||||
Modifications for Zip64 support
|
||||
Copyright (C) 2009-2010 Mathias Svensson
|
||||
http://result42.com
|
||||
|
||||
This program is distributed under the terms of the same license as zlib.
|
||||
See the accompanying LICENSE file for the full text of the license.
|
||||
*/
|
||||
|
||||
#ifndef _ZIP_H
|
||||
#define _ZIP_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#ifndef _ZLIB_H
|
||||
# include <zlib.h>
|
||||
#endif
|
||||
|
||||
#ifndef _ZLIBIOAPI_H
|
||||
# include "ioapi.h"
|
||||
#endif
|
||||
|
||||
#ifdef HAVE_BZIP2
|
||||
# include "bzlib.h"
|
||||
#endif
|
||||
|
||||
#define Z_BZIP2ED 12
|
||||
|
||||
#if defined(STRICTZIP) || defined(STRICTZIPUNZIP)
|
||||
/* like the STRICT of WIN32, we define a pointer that cannot be converted
|
||||
from (void*) without cast */
|
||||
typedef struct TagzipFile__ { int unused; } zipFile__;
|
||||
typedef zipFile__ *zipFile;
|
||||
#else
|
||||
typedef voidp zipFile;
|
||||
#endif
|
||||
|
||||
#define ZIP_OK (0)
|
||||
#define ZIP_EOF (0)
|
||||
#define ZIP_ERRNO (Z_ERRNO)
|
||||
#define ZIP_PARAMERROR (-102)
|
||||
#define ZIP_BADZIPFILE (-103)
|
||||
#define ZIP_INTERNALERROR (-104)
|
||||
|
||||
#ifndef DEF_MEM_LEVEL
|
||||
# if MAX_MEM_LEVEL >= 8
|
||||
# define DEF_MEM_LEVEL 8
|
||||
# else
|
||||
# define DEF_MEM_LEVEL MAX_MEM_LEVEL
|
||||
# endif
|
||||
#endif
|
||||
/* default memLevel */
|
||||
|
||||
/* tm_zip contain date/time info */
|
||||
typedef struct tm_zip_s
|
||||
{
|
||||
uInt tm_sec; /* seconds after the minute - [0,59] */
|
||||
uInt tm_min; /* minutes after the hour - [0,59] */
|
||||
uInt tm_hour; /* hours since midnight - [0,23] */
|
||||
uInt tm_mday; /* day of the month - [1,31] */
|
||||
uInt tm_mon; /* months since January - [0,11] */
|
||||
uInt tm_year; /* years - [1980..2044] */
|
||||
} tm_zip;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
tm_zip tmz_date; /* date in understandable format */
|
||||
uLong dosDate; /* if dos_date == 0, tmu_date is used */
|
||||
uLong internal_fa; /* internal file attributes 2 bytes */
|
||||
uLong external_fa; /* external file attributes 4 bytes */
|
||||
} zip_fileinfo;
|
||||
|
||||
#define APPEND_STATUS_CREATE (0)
|
||||
#define APPEND_STATUS_CREATEAFTER (1)
|
||||
#define APPEND_STATUS_ADDINZIP (2)
|
||||
|
||||
/***************************************************************************/
|
||||
/* Writing a zip file */
|
||||
|
||||
extern zipFile ZEXPORT zipOpen OF((const char *pathname, int append));
|
||||
extern zipFile ZEXPORT zipOpen64 OF((const void *pathname, int append));
|
||||
/* Create a zipfile.
|
||||
|
||||
pathname should contain the full pathname (by example, on a Windows XP computer
|
||||
"c:\\zlib\\zlib113.zip" or on an Unix computer "zlib/zlib113.zip".
|
||||
|
||||
return NULL if zipfile cannot be opened
|
||||
return zipFile handle if no error
|
||||
|
||||
If the file pathname exist and append == APPEND_STATUS_CREATEAFTER, the zip
|
||||
will be created at the end of the file. (useful if the file contain a self extractor code)
|
||||
If the file pathname exist and append == APPEND_STATUS_ADDINZIP, we will add files in existing
|
||||
zip (be sure you don't add file that doesn't exist)
|
||||
|
||||
NOTE: There is no delete function into a zipfile. If you want delete file into a zipfile,
|
||||
you must open a zipfile, and create another. Of course, you can use RAW reading and writing to copy
|
||||
the file you did not want delete. */
|
||||
|
||||
extern zipFile ZEXPORT zipOpen2 OF((const char *pathname, int append, const char ** globalcomment,
|
||||
zlib_filefunc_def* pzlib_filefunc_def));
|
||||
|
||||
extern zipFile ZEXPORT zipOpen2_64 OF((const void *pathname, int append, const char ** globalcomment,
|
||||
zlib_filefunc64_def* pzlib_filefunc_def));
|
||||
|
||||
extern zipFile ZEXPORT zipOpen3 OF((const char *pathname, int append, ZPOS64_T disk_size,
|
||||
const char ** globalcomment, zlib_filefunc_def* pzlib_filefunc_def));
|
||||
/* Same as zipOpen2 but allows specification of spanned zip size */
|
||||
|
||||
extern zipFile ZEXPORT zipOpen3_64 OF((const void *pathname, int append, ZPOS64_T disk_size,
|
||||
const char ** globalcomment, zlib_filefunc64_def* pzlib_filefunc_def));
|
||||
|
||||
extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file, const char* filename, const zip_fileinfo* zipfi,
|
||||
const void* extrafield_local, uInt size_extrafield_local, const void* extrafield_global,
|
||||
uInt size_extrafield_global, const char* comment, int method, int level));
|
||||
/* Open a file in the ZIP for writing.
|
||||
|
||||
filename : the filename in zip (if NULL, '-' without quote will be used
|
||||
*zipfi contain supplemental information
|
||||
extrafield_local buffer to store the local header extra field data, can be NULL
|
||||
size_extrafield_local size of extrafield_local buffer
|
||||
extrafield_global buffer to store the global header extra field data, can be NULL
|
||||
size_extrafield_global size of extrafield_local buffer
|
||||
comment buffer for comment string
|
||||
method contain the compression method (0 for store, Z_DEFLATED for deflate)
|
||||
level contain the level of compression (can be Z_DEFAULT_COMPRESSION)
|
||||
zip64 is set to 1 if a zip64 extended information block should be added to the local file header.
|
||||
this MUST be '1' if the uncompressed size is >= 0xffffffff. */
|
||||
|
||||
extern int ZEXPORT zipOpenNewFileInZip64 OF((zipFile file, const char* filename, const zip_fileinfo* zipfi,
|
||||
const void* extrafield_local, uInt size_extrafield_local, const void* extrafield_global,
|
||||
uInt size_extrafield_global, const char* comment, int method, int level, int zip64));
|
||||
/* Same as zipOpenNewFileInZip with zip64 support */
|
||||
|
||||
extern int ZEXPORT zipOpenNewFileInZip2 OF((zipFile file, const char* filename, const zip_fileinfo* zipfi,
|
||||
const void* extrafield_local, uInt size_extrafield_local, const void* extrafield_global,
|
||||
uInt size_extrafield_global, const char* comment, int method, int level, int raw));
|
||||
/* Same as zipOpenNewFileInZip, except if raw=1, we write raw file */
|
||||
|
||||
extern int ZEXPORT zipOpenNewFileInZip2_64 OF((zipFile file, const char* filename, const zip_fileinfo* zipfi,
|
||||
const void* extrafield_local, uInt size_extrafield_local, const void* extrafield_global,
|
||||
uInt size_extrafield_global, const char* comment, int method, int level, int raw, int zip64));
|
||||
/* Same as zipOpenNewFileInZip3 with zip64 support */
|
||||
|
||||
extern int ZEXPORT zipOpenNewFileInZip3 OF((zipFile file, const char* filename, const zip_fileinfo* zipfi,
|
||||
const void* extrafield_local, uInt size_extrafield_local, const void* extrafield_global,
|
||||
uInt size_extrafield_global, const char* comment, int method, int level, int raw, int windowBits, int memLevel,
|
||||
int strategy, const char* password, uLong crcForCrypting));
|
||||
/* Same as zipOpenNewFileInZip2, except
|
||||
windowBits, memLevel, strategy : see parameter strategy in deflateInit2
|
||||
password : crypting password (NULL for no crypting)
|
||||
crcForCrypting : crc of file to compress (needed for crypting) */
|
||||
|
||||
extern int ZEXPORT zipOpenNewFileInZip3_64 OF((zipFile file, const char* filename, const zip_fileinfo* zipfi,
|
||||
const void* extrafield_local, uInt size_extrafield_local, const void* extrafield_global,
|
||||
uInt size_extrafield_global, const char* comment, int method, int level, int raw, int windowBits, int memLevel,
|
||||
int strategy, const char* password, uLong crcForCrypting, int zip64));
|
||||
/* Same as zipOpenNewFileInZip3 with zip64 support */
|
||||
|
||||
extern int ZEXPORT zipOpenNewFileInZip4 OF((zipFile file, const char* filename, const zip_fileinfo* zipfi,
|
||||
const void* extrafield_local, uInt size_extrafield_local, const void* extrafield_global,
|
||||
uInt size_extrafield_global, const char* comment, int method, int level, int raw, int windowBits, int memLevel,
|
||||
int strategy, const char* password, uLong crcForCrypting, uLong versionMadeBy, uLong flagBase));
|
||||
/* Same as zipOpenNewFileInZip3 except versionMadeBy & flag fields */
|
||||
|
||||
extern int ZEXPORT zipOpenNewFileInZip4_64 OF((zipFile file, const char* filename, const zip_fileinfo* zipfi,
|
||||
const void* extrafield_local, uInt size_extrafield_local, const void* extrafield_global,
|
||||
uInt size_extrafield_global, const char* comment, int method, int level, int raw, int windowBits, int memLevel,
|
||||
int strategy, const char* password, uLong crcForCrypting, uLong versionMadeBy, uLong flagBase, int zip64));
|
||||
/* Same as zipOpenNewFileInZip4 with zip64 support */
|
||||
|
||||
extern int ZEXPORT zipWriteInFileInZip OF((zipFile file, const void* buf, unsigned len));
|
||||
/* Write data in the zipfile */
|
||||
|
||||
extern int ZEXPORT zipCloseFileInZip OF((zipFile file));
|
||||
/* Close the current file in the zipfile */
|
||||
|
||||
extern int ZEXPORT zipCloseFileInZipRaw OF((zipFile file, uLong uncompressed_size, uLong crc32));
|
||||
extern int ZEXPORT zipCloseFileInZipRaw64 OF((zipFile file, ZPOS64_T uncompressed_size, uLong crc32));
|
||||
/* Close the current file in the zipfile, for file opened with parameter raw=1 in zipOpenNewFileInZip2
|
||||
uncompressed_size and crc32 are value for the uncompressed size */
|
||||
|
||||
extern int ZEXPORT zipClose OF((zipFile file, const char* global_comment));
|
||||
/* Close the zipfile */
|
||||
|
||||
/***************************************************************************/
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* _ZIP_H */
|
||||
369
src/libs/Zip/Zip/minizip/ioapi.c
Normal file
@@ -0,0 +1,369 @@
|
||||
/* ioapi.h -- IO base function header for compress/uncompress .zip
|
||||
part of the MiniZip project
|
||||
|
||||
Copyright (C) 1998-2010 Gilles Vollant
|
||||
http://www.winimage.com/zLibDll/minizip.html
|
||||
Modifications for Zip64 support
|
||||
Copyright (C) 2009-2010 Mathias Svensson
|
||||
http://result42.com
|
||||
|
||||
This program is distributed under the terms of the same license as zlib.
|
||||
See the accompanying LICENSE file for the full text of the license.
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "ioapi.h"
|
||||
|
||||
#if defined(_WIN32)
|
||||
# define snprintf _snprintf
|
||||
#endif
|
||||
|
||||
#ifdef __APPLE__
|
||||
/* In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions */
|
||||
# define FOPEN_FUNC(filename, mode) fopen(filename, mode)
|
||||
# define FTELLO_FUNC(stream) ftello(stream)
|
||||
# define FSEEKO_FUNC(stream, offset, origin) fseeko(stream, offset, origin)
|
||||
#else
|
||||
# define FOPEN_FUNC(filename, mode) fopen64(filename, mode)
|
||||
# define FTELLO_FUNC(stream) ftello64(stream)
|
||||
# define FSEEKO_FUNC(stream, offset, origin) fseeko64(stream, offset, origin)
|
||||
#endif
|
||||
|
||||
/* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */
|
||||
#ifndef SEEK_CUR
|
||||
# define SEEK_CUR 1
|
||||
#endif
|
||||
#ifndef SEEK_END
|
||||
# define SEEK_END 2
|
||||
#endif
|
||||
#ifndef SEEK_SET
|
||||
# define SEEK_SET 0
|
||||
#endif
|
||||
|
||||
voidpf call_zopen64 (const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode)
|
||||
{
|
||||
if (pfilefunc->zfile_func64.zopen64_file != NULL)
|
||||
return (*(pfilefunc->zfile_func64.zopen64_file)) (pfilefunc->zfile_func64.opaque,filename,mode);
|
||||
return (*(pfilefunc->zopen32_file))(pfilefunc->zfile_func64.opaque,(const char*)filename,mode);
|
||||
}
|
||||
|
||||
voidpf call_zopendisk64 OF((const zlib_filefunc64_32_def* pfilefunc, voidpf filestream, int number_disk, int mode))
|
||||
{
|
||||
if (pfilefunc->zfile_func64.zopendisk64_file != NULL)
|
||||
return (*(pfilefunc->zfile_func64.zopendisk64_file)) (pfilefunc->zfile_func64.opaque,filestream,number_disk,mode);
|
||||
return (*(pfilefunc->zopendisk32_file))(pfilefunc->zfile_func64.opaque,filestream,number_disk,mode);
|
||||
}
|
||||
|
||||
long call_zseek64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin)
|
||||
{
|
||||
uLong offsetTruncated;
|
||||
if (pfilefunc->zfile_func64.zseek64_file != NULL)
|
||||
return (*(pfilefunc->zfile_func64.zseek64_file)) (pfilefunc->zfile_func64.opaque,filestream,offset,origin);
|
||||
offsetTruncated = (uLong)offset;
|
||||
if (offsetTruncated != offset)
|
||||
return -1;
|
||||
return (*(pfilefunc->zseek32_file))(pfilefunc->zfile_func64.opaque,filestream,offsetTruncated,origin);
|
||||
}
|
||||
|
||||
ZPOS64_T call_ztell64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream)
|
||||
{
|
||||
uLong tell_uLong;
|
||||
if (pfilefunc->zfile_func64.zseek64_file != NULL)
|
||||
return (*(pfilefunc->zfile_func64.ztell64_file)) (pfilefunc->zfile_func64.opaque,filestream);
|
||||
tell_uLong = (*(pfilefunc->ztell32_file))(pfilefunc->zfile_func64.opaque,filestream);
|
||||
if ((tell_uLong) == 0xffffffff)
|
||||
return (ZPOS64_T)-1;
|
||||
return tell_uLong;
|
||||
}
|
||||
|
||||
void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32)
|
||||
{
|
||||
p_filefunc64_32->zfile_func64.zopen64_file = NULL;
|
||||
p_filefunc64_32->zfile_func64.zopendisk64_file = NULL;
|
||||
p_filefunc64_32->zopen32_file = p_filefunc32->zopen_file;
|
||||
p_filefunc64_32->zopendisk32_file = p_filefunc32->zopendisk_file;
|
||||
p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file;
|
||||
p_filefunc64_32->zfile_func64.zread_file = p_filefunc32->zread_file;
|
||||
p_filefunc64_32->zfile_func64.zwrite_file = p_filefunc32->zwrite_file;
|
||||
p_filefunc64_32->zfile_func64.ztell64_file = NULL;
|
||||
p_filefunc64_32->zfile_func64.zseek64_file = NULL;
|
||||
p_filefunc64_32->zfile_func64.zclose_file = p_filefunc32->zclose_file;
|
||||
p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file;
|
||||
p_filefunc64_32->zfile_func64.opaque = p_filefunc32->opaque;
|
||||
p_filefunc64_32->zseek32_file = p_filefunc32->zseek_file;
|
||||
p_filefunc64_32->ztell32_file = p_filefunc32->ztell_file;
|
||||
}
|
||||
|
||||
static voidpf ZCALLBACK fopen_file_func OF((voidpf opaque, const char* filename, int mode));
|
||||
static uLong ZCALLBACK fread_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size));
|
||||
static uLong ZCALLBACK fwrite_file_func OF((voidpf opaque, voidpf stream, const void* buf,uLong size));
|
||||
static ZPOS64_T ZCALLBACK ftell64_file_func OF((voidpf opaque, voidpf stream));
|
||||
static long ZCALLBACK fseek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
|
||||
static int ZCALLBACK fclose_file_func OF((voidpf opaque, voidpf stream));
|
||||
static int ZCALLBACK ferror_file_func OF((voidpf opaque, voidpf stream));
|
||||
|
||||
typedef struct
|
||||
{
|
||||
FILE *file;
|
||||
int filenameLength;
|
||||
void *filename;
|
||||
} FILE_IOPOSIX;
|
||||
|
||||
static voidpf file_build_ioposix(FILE *file, const char *filename)
|
||||
{
|
||||
FILE_IOPOSIX *ioposix = NULL;
|
||||
if (file == NULL)
|
||||
return NULL;
|
||||
ioposix = (FILE_IOPOSIX*)malloc(sizeof(FILE_IOPOSIX));
|
||||
ioposix->file = file;
|
||||
ioposix->filenameLength = (int)strlen(filename) + 1;
|
||||
ioposix->filename = (char*)malloc(ioposix->filenameLength * sizeof(char));
|
||||
strncpy(ioposix->filename, filename, ioposix->filenameLength);
|
||||
return (voidpf)ioposix;
|
||||
}
|
||||
|
||||
static voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode)
|
||||
{
|
||||
FILE* file = NULL;
|
||||
const char* mode_fopen = NULL;
|
||||
if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) == ZLIB_FILEFUNC_MODE_READ)
|
||||
mode_fopen = "rb";
|
||||
else if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
|
||||
mode_fopen = "r+b";
|
||||
else if (mode & ZLIB_FILEFUNC_MODE_CREATE)
|
||||
mode_fopen = "wb";
|
||||
|
||||
if ((filename != NULL) && (mode_fopen != NULL))
|
||||
{
|
||||
file = fopen(filename, mode_fopen);
|
||||
return file_build_ioposix(file, filename);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
static voidpf ZCALLBACK fopen64_file_func (voidpf opaque, const void* filename, int mode)
|
||||
{
|
||||
FILE* file = NULL;
|
||||
const char* mode_fopen = NULL;
|
||||
if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) == ZLIB_FILEFUNC_MODE_READ)
|
||||
mode_fopen = "rb";
|
||||
else if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
|
||||
mode_fopen = "r+b";
|
||||
else if (mode & ZLIB_FILEFUNC_MODE_CREATE)
|
||||
mode_fopen = "wb";
|
||||
|
||||
if ((filename != NULL) && (mode_fopen != NULL))
|
||||
{
|
||||
file = FOPEN_FUNC((const char*)filename, mode_fopen);
|
||||
return file_build_ioposix(file, (const char*)filename);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
static voidpf ZCALLBACK fopendisk64_file_func (voidpf opaque, voidpf stream, int number_disk, int mode)
|
||||
{
|
||||
FILE_IOPOSIX *ioposix = NULL;
|
||||
char *diskFilename = NULL;
|
||||
voidpf ret = NULL;
|
||||
int i = 0;
|
||||
|
||||
if (stream == NULL)
|
||||
return NULL;
|
||||
ioposix = (FILE_IOPOSIX*)stream;
|
||||
diskFilename = (char*)malloc(ioposix->filenameLength * sizeof(char));
|
||||
strncpy(diskFilename, ioposix->filename, ioposix->filenameLength);
|
||||
for (i = ioposix->filenameLength - 1; i >= 0; i -= 1)
|
||||
{
|
||||
if (diskFilename[i] != '.')
|
||||
continue;
|
||||
snprintf(&diskFilename[i], ioposix->filenameLength - i, ".z%02d", number_disk + 1);
|
||||
break;
|
||||
}
|
||||
if (i >= 0)
|
||||
ret = fopen64_file_func(opaque, diskFilename, mode);
|
||||
free(diskFilename);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static voidpf ZCALLBACK fopendisk_file_func (voidpf opaque, voidpf stream, int number_disk, int mode)
|
||||
{
|
||||
FILE_IOPOSIX *ioposix = NULL;
|
||||
char *diskFilename = NULL;
|
||||
voidpf ret = NULL;
|
||||
int i = 0;
|
||||
|
||||
if (stream == NULL)
|
||||
return NULL;
|
||||
ioposix = (FILE_IOPOSIX*)stream;
|
||||
diskFilename = (char*)malloc(ioposix->filenameLength * sizeof(char));
|
||||
strncpy(diskFilename, ioposix->filename, ioposix->filenameLength);
|
||||
for (i = ioposix->filenameLength - 1; i >= 0; i -= 1)
|
||||
{
|
||||
if (diskFilename[i] != '.')
|
||||
continue;
|
||||
snprintf(&diskFilename[i], ioposix->filenameLength - i, ".z%02d", number_disk + 1);
|
||||
break;
|
||||
}
|
||||
if (i >= 0)
|
||||
ret = fopen_file_func(opaque, diskFilename, mode);
|
||||
free(diskFilename);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size)
|
||||
{
|
||||
FILE_IOPOSIX *ioposix = NULL;
|
||||
uLong ret;
|
||||
if (stream == NULL)
|
||||
return -1;
|
||||
ioposix = (FILE_IOPOSIX*)stream;
|
||||
ret = (uLong)fread(buf, 1, (size_t)size, ioposix->file);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static uLong ZCALLBACK fwrite_file_func (voidpf opaque, voidpf stream, const void* buf, uLong size)
|
||||
{
|
||||
FILE_IOPOSIX *ioposix = NULL;
|
||||
uLong ret;
|
||||
if (stream == NULL)
|
||||
return -1;
|
||||
ioposix = (FILE_IOPOSIX*)stream;
|
||||
ret = (uLong)fwrite(buf, 1, (size_t)size, ioposix->file);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static long ZCALLBACK ftell_file_func (voidpf opaque, voidpf stream)
|
||||
{
|
||||
FILE_IOPOSIX *ioposix = NULL;
|
||||
long ret = -1;
|
||||
if (stream == NULL)
|
||||
return ret;
|
||||
ioposix = (FILE_IOPOSIX*)stream;
|
||||
ret = ftell(ioposix->file);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static ZPOS64_T ZCALLBACK ftell64_file_func (voidpf opaque, voidpf stream)
|
||||
{
|
||||
FILE_IOPOSIX *ioposix = NULL;
|
||||
ZPOS64_T ret = -1;
|
||||
if (stream == NULL)
|
||||
return ret;
|
||||
ioposix = (FILE_IOPOSIX*)stream;
|
||||
ret = FTELLO_FUNC(ioposix->file);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static long ZCALLBACK fseek_file_func (voidpf opaque, voidpf stream, uLong offset, int origin)
|
||||
{
|
||||
FILE_IOPOSIX *ioposix = NULL;
|
||||
int fseek_origin = 0;
|
||||
long ret = 0;
|
||||
|
||||
if (stream == NULL)
|
||||
return -1;
|
||||
ioposix = (FILE_IOPOSIX*)stream;
|
||||
|
||||
switch (origin)
|
||||
{
|
||||
case ZLIB_FILEFUNC_SEEK_CUR:
|
||||
fseek_origin = SEEK_CUR;
|
||||
break;
|
||||
case ZLIB_FILEFUNC_SEEK_END:
|
||||
fseek_origin = SEEK_END;
|
||||
break;
|
||||
case ZLIB_FILEFUNC_SEEK_SET:
|
||||
fseek_origin = SEEK_SET;
|
||||
break;
|
||||
default:
|
||||
return -1;
|
||||
}
|
||||
if (fseek(ioposix->file, offset, fseek_origin) != 0)
|
||||
ret = -1;
|
||||
return ret;
|
||||
}
|
||||
|
||||
static long ZCALLBACK fseek64_file_func (voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)
|
||||
{
|
||||
FILE_IOPOSIX *ioposix = NULL;
|
||||
int fseek_origin = 0;
|
||||
long ret = 0;
|
||||
|
||||
if (stream == NULL)
|
||||
return -1;
|
||||
ioposix = (FILE_IOPOSIX*)stream;
|
||||
|
||||
switch (origin)
|
||||
{
|
||||
case ZLIB_FILEFUNC_SEEK_CUR:
|
||||
fseek_origin = SEEK_CUR;
|
||||
break;
|
||||
case ZLIB_FILEFUNC_SEEK_END:
|
||||
fseek_origin = SEEK_END;
|
||||
break;
|
||||
case ZLIB_FILEFUNC_SEEK_SET:
|
||||
fseek_origin = SEEK_SET;
|
||||
break;
|
||||
default:
|
||||
return -1;
|
||||
}
|
||||
|
||||
if(FSEEKO_FUNC(ioposix->file, offset, fseek_origin) != 0)
|
||||
ret = -1;
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
static int ZCALLBACK fclose_file_func (voidpf opaque, voidpf stream)
|
||||
{
|
||||
FILE_IOPOSIX *ioposix = NULL;
|
||||
int ret = -1;
|
||||
if (stream == NULL)
|
||||
return ret;
|
||||
ioposix = (FILE_IOPOSIX*)stream;
|
||||
if (ioposix->filename != NULL)
|
||||
free(ioposix->filename);
|
||||
ret = fclose(ioposix->file);
|
||||
free(ioposix);
|
||||
return ret;
|
||||
}
|
||||
|
||||
static int ZCALLBACK ferror_file_func (voidpf opaque, voidpf stream)
|
||||
{
|
||||
FILE_IOPOSIX *ioposix = NULL;
|
||||
int ret = -1;
|
||||
if (stream == NULL)
|
||||
return ret;
|
||||
ioposix = (FILE_IOPOSIX*)stream;
|
||||
ret = ferror(ioposix->file);
|
||||
return ret;
|
||||
}
|
||||
|
||||
void fill_fopen_filefunc (zlib_filefunc_def* pzlib_filefunc_def)
|
||||
{
|
||||
pzlib_filefunc_def->zopen_file = fopen_file_func;
|
||||
pzlib_filefunc_def->zopendisk_file = fopendisk_file_func;
|
||||
pzlib_filefunc_def->zread_file = fread_file_func;
|
||||
pzlib_filefunc_def->zwrite_file = fwrite_file_func;
|
||||
pzlib_filefunc_def->ztell_file = ftell_file_func;
|
||||
pzlib_filefunc_def->zseek_file = fseek_file_func;
|
||||
pzlib_filefunc_def->zclose_file = fclose_file_func;
|
||||
pzlib_filefunc_def->zerror_file = ferror_file_func;
|
||||
pzlib_filefunc_def->opaque = NULL;
|
||||
}
|
||||
|
||||
void fill_fopen64_filefunc (zlib_filefunc64_def* pzlib_filefunc_def)
|
||||
{
|
||||
pzlib_filefunc_def->zopen64_file = fopen64_file_func;
|
||||
pzlib_filefunc_def->zopendisk64_file = fopendisk64_file_func;
|
||||
pzlib_filefunc_def->zread_file = fread_file_func;
|
||||
pzlib_filefunc_def->zwrite_file = fwrite_file_func;
|
||||
pzlib_filefunc_def->ztell64_file = ftell64_file_func;
|
||||
pzlib_filefunc_def->zseek64_file = fseek64_file_func;
|
||||
pzlib_filefunc_def->zclose_file = fclose_file_func;
|
||||
pzlib_filefunc_def->zerror_file = ferror_file_func;
|
||||
pzlib_filefunc_def->opaque = NULL;
|
||||
}
|
||||
5
src/libs/Zip/Zip/minizip/module/module.modulemap
Normal file
@@ -0,0 +1,5 @@
|
||||
module Minizip [system][extern_c] {
|
||||
header "../include/Minizip.h"
|
||||
link "z"
|
||||
export *
|
||||
}
|
||||
1947
src/libs/Zip/Zip/minizip/unzip.c
Normal file
2020
src/libs/Zip/Zip/minizip/zip.c
Executable file
0
src/libs/Zip/Zip/zlib/module.modulemap
Normal file
7
src/main.swift
Normal file
@@ -0,0 +1,7 @@
|
||||
import AppKit
|
||||
|
||||
let app = NSApplication.shared
|
||||
let delegate = AppDelegate()
|
||||
app.delegate = delegate
|
||||
|
||||
_ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
|
||||
BIN
src/resources/AppIcon.icns
Normal file
BIN
src/resources/icon.iconset/icon_128x128.png
Normal file
|
After Width: | Height: | Size: 11 KiB |
BIN
src/resources/icon.iconset/icon_128x128@2x.png
Normal file
|
After Width: | Height: | Size: 31 KiB |
BIN
src/resources/icon.iconset/icon_16x16.png
Normal file
|
After Width: | Height: | Size: 746 B |
BIN
src/resources/icon.iconset/icon_16x16@2x.png
Normal file
|
After Width: | Height: | Size: 1.7 KiB |
BIN
src/resources/icon.iconset/icon_256x256.png
Normal file
|
After Width: | Height: | Size: 31 KiB |
BIN
src/resources/icon.iconset/icon_256x256@2x.png
Normal file
|
After Width: | Height: | Size: 94 KiB |
BIN
src/resources/icon.iconset/icon_32x32.png
Normal file
|
After Width: | Height: | Size: 1.7 KiB |
BIN
src/resources/icon.iconset/icon_32x32@2x.png
Normal file
|
After Width: | Height: | Size: 4.0 KiB |
BIN
src/resources/icon.iconset/icon_512x512.png
Normal file
|
After Width: | Height: | Size: 94 KiB |
BIN
src/resources/icon.iconset/icon_512x512@2x.png
Normal file
|
After Width: | Height: | Size: 285 KiB |
29
src/updater/Makefile
Normal file
@@ -0,0 +1,29 @@
|
||||
CC = swiftc
|
||||
FLAGS = -g
|
||||
#-O
|
||||
#TARGET =
|
||||
MACOS_VERSION = 13.0
|
||||
|
||||
FILES = main.swift
|
||||
|
||||
EXEC = cmdbar_updater
|
||||
|
||||
FRAMEWORKS = -framework AppKit
|
||||
|
||||
./arm64/$(EXEC): $(FILES)
|
||||
$(CC) -target arm64-apple-macos$(MACOS_VERSION) $(FLAGS) $^ \
|
||||
$(FRAMEWORKS) -o $@
|
||||
|
||||
./x86_64/$(EXEC): $(FILES)
|
||||
$(CC) -target x86_64-apple-macos$(MACOS_VERSION) $(FLAGS) $^ \
|
||||
$(FRAMEWORKS) -o $@
|
||||
|
||||
$(EXEC): ./arm64/$(EXEC) ./x86_64/$(EXEC)
|
||||
lipo -create -output $(EXEC) $^ && \
|
||||
codesign -s ${DEVELOPER_ID} -f --timestamp -o runtime $(EXEC)
|
||||
|
||||
all: $(EXEC)
|
||||
|
||||
clean:
|
||||
rm -rf arm64 x86_64 $(EXEC)
|
||||
mkdir arm64 x86_64
|
||||
33
src/updater/main.swift
Normal file
@@ -0,0 +1,33 @@
|
||||
//
|
||||
// main.swift
|
||||
// cmdbar_updater
|
||||
//
|
||||
// Created by Igor Kolokolnikov on 5/23/24.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
|
||||
fileprivate func existsAtPath(_ path: String, isDirectory: Bool = false) -> Bool {
|
||||
var isDirectory: ObjCBool = ObjCBool(isDirectory)
|
||||
let exists = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
|
||||
return exists
|
||||
}
|
||||
|
||||
let tmp = FileManager.default.temporaryDirectory.appending(path: "CmdBar.app")
|
||||
let app = Bundle.main.bundleURL
|
||||
|
||||
if !existsAtPath(tmp.path(), isDirectory: true) { exit(1) }
|
||||
|
||||
do {
|
||||
let _ = try FileManager.default.replaceItemAt(app, withItemAt: tmp)
|
||||
} catch {
|
||||
if existsAtPath(tmp.path(), isDirectory: true) {
|
||||
do { try FileManager.default.removeItem(at: tmp) } catch {}
|
||||
}
|
||||
exit(1)
|
||||
}
|
||||
|
||||
let configuration = NSWorkspace.OpenConfiguration()
|
||||
NSWorkspace.shared.openApplication(at: app, configuration: configuration, completionHandler: nil)
|
||||
|
||||
usleep(100000*2) // Allow 2 seconds to let `NSWorkspace.shared.openApplication` finish launching our app.
|
||||