This commit is contained in:
Jeff Carr 2019-06-13 17:53:47 -07:00
commit b1717b9be2
57 changed files with 3941 additions and 0 deletions

231
LICENSE Normal file
View File

@ -0,0 +1,231 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://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 <http://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 <http://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 <http://www.gnu.org/philosophy/why-not-lgpl.html>.

93
Makefile Normal file
View File

@ -0,0 +1,93 @@
GITCOMMIT = $(shell git rev-list -1 HEAD)
GOVERSION = $(shell go version | cut -d' ' -f 3)
BUILDTIME = $(shell date -u --iso-8601=seconds)
VERSION = $(shell cat resources/VERSION)
GO111MODULE=on
# try go get github.com/ahmetb/govvv
# this will add branch info & build RFC3339 date also
run:
@echo your version of go must be greater than 2.10. Your version is ${GOVERSION}
go build
./cloud-control-panel
build:
go build
default-config: config-delete
echo loading the test config
./cloud-control-panel --defaultconfig
debug:
@echo your version of go must be greater than 2.10. Your version is ${GOVERSION}
go build -ldflags "-X main.GITCOMMIT=${GITCOMMIT} -X main.GOVERSION='${GOVERSION}' -X main.BUILDTIME='${BUILDTIME}' -X main.VERSION=${VERSION}"
./cloud-control-panel --debug
nogui:
go build
./cloud-control-panel -nogui
gaper:
# 'gaper' is a simple and smart golang tool that just rebuilds every time you change a file
# go get -u github.com/maxcnunes/gaper
gaper
#### NEVER DO THIS. THIS APPEARS TO INDUCE INSTABILITY IN GTK
bad-run:
#### NEVER DO THIS. THIS APPEARS TO INDUCE INSTABILITY IN GTK
# go run *.go
# simple sortcut to push all git changes
push:
# git checkout devel
git pull
git add --all
-git commit -a -s
git push --all
tag-version:
# git push --delete origin v0.6.15 # to delete a tag upstream
git diff --quiet
go build # just an extra check to make sure the damn thing builds
git tag v${VERSION}
git push --tags
cp .git/refs/tags/v${VERSION} resources/tags/
scp resources/VERSION root@mirrors.wit.com:/data/mirrors/cloud/control-panel/
scp resources/VERSION root@mirrors.wit.com:/data/mirrors/cloud/control-panel/linux/
# should update every go dependancy (?)
update:
git pull
go get -v -t -u .
# make the json config file human readable
config-make-readable:
cat ~/.config/cloud-control-panel.json |jq -r --tab
config-delete:
echo deleting your current config
-mv ~/.config/cloud-control-panel.json /tmp
diff:
git diff
# https://www.digitalocean.com/community/tutorials/how-to-build-go-executables-for-multiple-platforms-on-ubuntu-16-04
build-darwin:
env GOOS=darwin GOARCH=amd64 go build
build-windows:
env GOOS=windows GOARCH=amd64 go build
# git branch devel
# git push --set-upstream origin devel
devel:
git checkout devel
merge-devel:
git checkout master
git pull origin master
git merge devel
git push origin master
git checkout devel

38
README.md Normal file
View File

@ -0,0 +1,38 @@
# cloud-control-panel
This is how the cloud should work. It's time to change the rules.
This app requires IPv6 to work.
Obviously I'm developing this app on Linux so if things are
broken in the MacOS or Windows, check the Linux version if
possible to see if it is also broken there.
# IMPORTANT NOTES
To use the cross platform UI, all GUI interactions must be
done from within the same goroutine for it to work properly
on Windows. This is an annoying limitation of how Windows works
(or so it appears. maybe someone will figure out how to fix that)
This means the Windows version of this GUI will probably always
be sub-par verses the Linux and Macintosh versions
# build
```
go get -v -t -u git.wit.com/wit/cloud-control-panel
cd ~/go/src/git.wit.com/wit/cloud-control-panel
go build
./cloud-control-panel
```
# License
This is a GPL 3.0 Project.
# Credits
* All the GO developers & Google
* The andlabs people that made the golang cross platform UI
* All the kernel, KVM and QEMU developers

2
autobuild/Makefile Normal file
View File

@ -0,0 +1,2 @@
all:
go install

154
autobuild/autobuild.go Normal file
View File

@ -0,0 +1,154 @@
package main
// This should build and upload the binary to mirrors
// upload binary to mirrors.wit.com/cloud/control-panel
import "log"
import "fmt"
import "time"
import "strings"
import "os/user"
import "os"
import "runtime"
import "github.com/davecgh/go-spew/spew"
import "git.wit.com/wit/shell"
// import "os/user"
// import "io/ioutil"
// github.com/bramvdbogaerde/go-scp
var BuildMap map[string]*bool
var filename string
var builddir string
func main() {
BuildMap = make(map[string]*bool)
setbuilddir()
// shell.Quiet(true)
shell.Quiet(false)
// shell.Run("git tag --list")
// os.Exit(-1)
for {
shell.Run("git checkout master")
shell.Run("git pull --tags")
shell.Run("go get -v ...")
shell.Run("go get -v -u ...")
shell.Run("go get -v -u -t")
findtags()
time.Sleep(time.Second * 60)
}
}
func findtags() {
tags := shell.Run("git tag --list")
// log.Println(tags)
for _, tag := range strings.Split(tags, "\n") {
tag = strings.Replace(tag, "v", "", -1) // remove all 'v' chars
if (BuildMap[tag] == nil) {
log.Println("TAG =", tag, "is nil")
log.Println("\tCHECK IF BUILD WAS ATTEMPTED =", tag)
BuildMap[tag] = build(tag)
} else {
if (*BuildMap[tag] == true) {
log.Println("TAG =", tag, "is true")
} else {
log.Println("TAG =", tag, "is false")
}
}
}
// os.Exit(0)
}
func build(tag string) *bool {
var b bool
url := "https://mirrors.wit.com/cloud/control-panel/linux/" + filename + "-v" + tag + ".md5sum"
log.Println("\tTRYING URL", url)
md5sum := shell.Chomp(shell.Wget(url))
if (md5sum != "") {
log.Println("\tBUILD ALREADY DONE TAG =", tag, "md5sum =", md5sum)
b = true
// for {}
return &b
}
// for {}
shell.Quiet(false)
shell.Run("git checkout v" + tag)
gitref := shell.Run("git rev-list -1 HEAD")
tagref := shell.Run("cat .git/refs/tags/v" + tag) // what is the right way?
if (gitref != tagref) {
log.Println("\tJESUS HOW TO DO THIS CORRECTLY?", gitref, "ne", tagref)
// os.Exit(-1)
// return nil
}
// setup the files that will end up in the binary
epoch := fmt.Sprintf("%d", time.Now().Unix())
shell.Write("./resources/BUILDDATE", epoch)
shell.Write("./resources/BUILDREF", gitref)
// rebuild the binary (always remove the old one
shell.Run("rm " + filename)
shell.Run("go build")
md5sum = shell.Run("md5sum " + filename)
log.Println("\tmd5sum =", md5sum)
if (md5sum == "") {
log.Println("\tBUILD FAILED")
b = false
return &b
}
shell.Write("/tmp/autobuild.md5sum", md5sum)
upload(tag)
// This version has been built yet
log.Println("\tTHIS VERSION HAS BEEN UPLOADED =", tag)
b = true
return &b
}
func setbuilddir() {
user, err := user.Current()
spew.Dump(user)
if err != nil {
os.Exit(-1)
}
if runtime.GOOS == "linux" {
log.Println("loadConfigFile() OS: Linux")
filename = "cloud-control-panel"
builddir = user.HomeDir + "/go/src/git.wit.com/wit/cloud-control-panel"
} else if runtime.GOOS == "windows" {
log.Println("loadConfigFile() OS: Windows")
builddir = user.HomeDir + "\\go\\src\\git.wit.com\\wit\\cloud-control-panel"
filename = "cloud-control-panel.exe"
} else {
log.Println("loadConfigFile() OS: " + runtime.GOOS)
filename = "cloud-control-panel"
builddir = user.HomeDir + "/go/src/git.wit.com/wit/cloud-control-panel"
}
}
// upload the files to mirrors
func upload(tag string) {
mirrors := "root@mirrors.wit.com:/data/mirrors/cloud/control-panel/linux/"
// don't update the master VERSION here
// shell.Run("scp resources/VERSION " + mirrors)
shell.Run("scp cloud-control-panel " + mirrors)
shell.Run("scp resources/BUILDDATE " + mirrors + filename + "-v" + tag + ".BUILDDATE")
shell.Run("scp cloud-control-panel " + mirrors + filename + "-v" + tag)
shell.Run("scp /tmp/autobuild.md5sum " + mirrors + filename + "-v" + tag + ".md5sum")
}

3
bench1/Makefile Normal file
View File

@ -0,0 +1,3 @@
all:
go test --race
# go test bench=.

193
bench1/benchmark_test.go Normal file
View File

@ -0,0 +1,193 @@
package benchmark
import (
"bytes"
"strings"
"testing"
)
var result interface{}
//BenchmarkBytesToStrings convert a []bytes in a string
//https://golang.org/pkg/bytes/#Compare
func BenchmarkBytesToStrings(b *testing.B) {
s1 := []byte("string to convert")
b.ResetTimer()
b.ReportAllocs()
var r string
for n := 0; n < b.N; n++ {
r = string(s1)
}
result = r
}
//BenchmarkBytesCompare compare 2 []bytes.
//https://golang.org/pkg/bytes/#Compare
func BenchmarkBytesCompare(b *testing.B) {
s1 := []byte("string to compare")
s2 := []byte("string to compare")
b.ResetTimer()
b.ReportAllocs()
var r int
for n := 0; n < b.N; n++ {
r = bytes.Compare(s1, s2)
}
result = r
}
//BenchmarkStringsCompare compare 2 strings.
//https://golang.org/pkg/strings/#Compare
func BenchmarkStringsCompare(b *testing.B) {
s1 := "string to compare"
s2 := "string to compare"
b.ResetTimer()
b.ReportAllocs()
var r int
for n := 0; n < b.N; n++ {
r = strings.Compare(s1, s2)
}
result = r
}
//BenchmarkBytesContains check contains method
//https://golang.org/pkg/bytes/#Contains
func BenchmarkBytesContains(b *testing.B) {
s1 := []byte("string to compare")
s2 := []byte("comparc")
b.ResetTimer()
b.ReportAllocs()
var r bool
for n := 0; n < b.N; n++ {
r = bytes.Contains(s1, s2)
}
result = r
}
//BenchmarkStringsContains check contains method
//https://golang.org/pkg/strings/#Contains
func BenchmarkStringsContains(b *testing.B) {
s1 := "string to compare"
s2 := "comparc"
b.ResetTimer()
b.ReportAllocs()
var r bool
for n := 0; n < b.N; n++ {
r = strings.Contains(s1, s2)
}
result = r
}
//BenchmarkBytesIndex check contains index
//https://golang.org/pkg/bytes/#Index
func BenchmarkBytesIndex(b *testing.B) {
s1 := []byte("string to compare")
s2 := []byte("e")
b.ResetTimer()
b.ReportAllocs()
var r int
for n := 0; n < b.N; n++ {
r = bytes.Index(s1, s2)
}
result = r
}
//BenchmarkStringIndex check contains index
//https://golang.org/pkg/strings/#Index
func BenchmarkStringIndex(b *testing.B) {
s1 := "string to compare"
s2 := "e"
b.ResetTimer()
b.ReportAllocs()
var r int
for n := 0; n < b.N; n++ {
r = strings.Index(s1, s2)
}
result = r
}
//BenchmarkBytesReplace check replace method
//https://golang.org/pkg/bytes/#Replace
func BenchmarkBytesReplace(b *testing.B) {
s1 := []byte("string to comparc")
s2 := []byte("comparc")
s3 := []byte("compare")
b.ResetTimer()
b.ReportAllocs()
var r []byte
for n := 0; n < b.N; n++ {
r = bytes.Replace(s1, s2, s3, -1)
}
result = r
}
//BenchmarkStringsReplace check replace method
//https://golang.org/pkg/strings/#Replace
func BenchmarkStringsReplace(b *testing.B) {
s1 := "string to comparc"
s2 := "comparc"
s3 := "compare"
b.ResetTimer()
b.ReportAllocs()
var r string
for n := 0; n < b.N; n++ {
r = strings.Replace(s1, s2, s3, -1)
}
result = r
}
//BenchmarkBytesConcat concats 2 bytes
func BenchmarkBytesConcat2(b *testing.B) {
s1 := []byte("string to compare")
s2 := []byte("string to add")
b.ResetTimer()
b.ReportAllocs()
for n := 0; n < b.N; n++ {
r := make([]byte, 0, len(s1)+len(s2))
r = append(r, s1...)
r = append(r, s2...)
}
}
//BenchmarkStringsConcat concats 2 strings
func BenchmarkStringsConcat2(b *testing.B) {
s1 := "string to compare"
s2 := "string to add"
b.ResetTimer()
b.ReportAllocs()
var r string
for n := 0; n < b.N; n++ {
r = s1 + s2
}
result = r
}
//BenchmarkStringsJoin joins 2 strings
//https://golang.org/pkg/strings/#Join
func BenchmarkStringsJoin2(b *testing.B) {
s1 := "string to compare"
s2 := "string to add"
b.ResetTimer()
b.ReportAllocs()
var r string
for n := 0; n < b.N; n++ {
j := []string{s1, s2}
r = strings.Join(j, "")
}
result = r
}
//BenchmarkMapHints bench mymap[string(abytes)]
func BenchmarkMapHints(b *testing.B) {
mymap := make(map[string]string)
mymap["key"] = "value"
abytes := []byte("key")
b.ResetTimer()
b.ReportAllocs()
var v string
for n := 0; n < b.N; n++ {
v, _ = mymap[string(abytes)]
}
result = v
}
//BenchmarkMapsHints_Dont bench key := string(abytes)
//v, _ = mymap[key]
func BenchmarkMapsHints_Dont(b *testing.B) {
mymap := make(map[string]string)
mymap["key"] = "value"
abytes := []byte("key")
b.ResetTimer()
b.ReportAllocs()
var v string
for n := 0; n < b.N; n++ {
key := string(abytes)
v, _ = mymap[key]
}
result = v
}

33
bench1/fast-timer.go Normal file
View File

@ -0,0 +1,33 @@
package main
import (
"fmt"
"time"
)
var start time.Time
func init() {
start = time.Now()
}
func main() {
fmt.Println("main() started", time.Since(start))
chan1 := make(chan string, 2)
chan2 := make(chan string, 2)
chan1 <- "Value 1"
chan1 <- "Value 2"
chan2 <- "Value 1"
chan2 <- "Value 2"
select {
case res := <-chan1:
fmt.Println("Response from chan1", res, time.Since(start))
case res := <-chan2:
fmt.Println("Response from chan2", res, time.Since(start))
}
fmt.Println("main() stopped", time.Since(start))
for {}
}

115
bench1/readWriteOps.go Normal file
View File

@ -0,0 +1,115 @@
// In the previous example we used explicit locking with
// [mutexes](mutexes) to synchronize access to shared state
// across multiple goroutines. Another option is to use the
// built-in synchronization features of goroutines and
// channels to achieve the same result. This channel-based
// approach aligns with Go's ideas of sharing memory by
// communicating and having each piece of data owned
// by exactly 1 goroutine.
package main
import (
"fmt"
"math/rand"
"sync/atomic"
"time"
)
// In this example our state will be owned by a single
// goroutine. This will guarantee that the data is never
// corrupted with concurrent access. In order to read or
// write that state, other goroutines will send messages
// to the owning goroutine and receive corresponding
// replies. These `readOp` and `writeOp` `struct`s
// encapsulate those requests and a way for the owning
// goroutine to respond.
type readOp struct {
key int
resp chan int
}
type writeOp struct {
key int
val int
resp chan bool
}
func main() {
// As before we'll count how many operations we perform.
var readOps uint64
var writeOps uint64
// The `reads` and `writes` channels will be used by
// other goroutines to issue read and write requests,
// respectively.
reads := make(chan readOp)
writes := make(chan writeOp)
// Here is the goroutine that owns the `state`, which
// is a map as in the previous example but now private
// to the stateful goroutine. This goroutine repeatedly
// selects on the `reads` and `writes` channels,
// responding to requests as they arrive. A response
// is executed by first performing the requested
// operation and then sending a value on the response
// channel `resp` to indicate success (and the desired
// value in the case of `reads`).
go func() {
var state = make(map[int]int)
for {
select {
case read := <-reads:
read.resp <- state[read.key]
case write := <-writes:
state[write.key] = write.val
write.resp <- true
}
}
}()
// This starts 100 goroutines to issue reads to the
// state-owning goroutine via the `reads` channel.
// Each read requires constructing a `readOp`, sending
// it over the `reads` channel, and the receiving the
// result over the provided `resp` channel.
for r := 0; r < 100; r++ {
go func() {
for {
read := readOp{
key: rand.Intn(5),
resp: make(chan int)}
reads <- read
<-read.resp
atomic.AddUint64(&readOps, 1)
time.Sleep(time.Millisecond)
}
}()
}
// We start 10 writes as well, using a similar
// approach.
for w := 0; w < 10; w++ {
go func() {
for {
write := writeOp{
key: rand.Intn(5),
val: rand.Intn(100),
resp: make(chan bool)}
writes <- write
<-write.resp
atomic.AddUint64(&writeOps, 1)
time.Sleep(time.Millisecond)
}
}()
}
// Let the goroutines work for a second.
time.Sleep(time.Second)
// Finally, capture and report the op counts.
readOpsFinal := atomic.LoadUint64(&readOps)
fmt.Println("readOps:", readOpsFinal)
writeOpsFinal := atomic.LoadUint64(&writeOps)
fmt.Println("writeOps:", writeOpsFinal)
}

7
crash1-fqdn Normal file
View File

@ -0,0 +1,7 @@
This thing segfault'd with fqdn lookup on weird network errors when I was at the office on wifi
2019/06/01 21:11:47 connecting to ws://v000185.testing.com.customers.wprod.wit.com:9000/event
2019/06/01 21:11:47 fqdn.Get() = librem15.lab.wit.com
INFO[0000] *** error: read udp [2604:bbc0:1:22::f5d3:7f44]:50435->[2001:500:12::d0d]:53: i/o timeout
make: *** [Makefile:52: config-default-config] Error 1

7
example-aminal/Makefile Normal file
View File

@ -0,0 +1,7 @@
build:
go build
./example-aminal
build-windows:
env GOOS=windows GOARCH=amd64 go build

122
example-aminal/config.go Normal file
View File

@ -0,0 +1,122 @@
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"github.com/liamg/aminal/config"
"github.com/liamg/aminal/version"
)
func getActuallyProvidedFlags() map[string]bool {
result := make(map[string]bool)
flag.Visit(func(f *flag.Flag) {
result[f.Name] = true
})
return result
}
func getConfig() *config.Config {
showVersion := false
ignoreConfig := false
shell := ""
debugMode := false
slomo := false
if flag.Parsed() == false {
flag.BoolVar(&showVersion, "version", showVersion, "Output version information")
flag.BoolVar(&ignoreConfig, "ignore-config", ignoreConfig, "Ignore user config files and use defaults")
flag.StringVar(&shell, "shell", shell, "Specify the shell to use")
flag.BoolVar(&debugMode, "debug", debugMode, "Enable debug logging")
flag.BoolVar(&slomo, "slomo", slomo, "Render in slow motion (useful for debugging)")
flag.Parse() // actual parsing and fetching flags from the command line
}
actuallyProvidedFlags := getActuallyProvidedFlags()
if showVersion {
v := version.Version
if v == "" {
v = "development"
}
fmt.Println(v)
os.Exit(0)
}
var conf *config.Config
if ignoreConfig {
conf = &config.DefaultConfig
} else {
conf = loadConfigFile()
}
// Override values in the configuration file with the values specified in the command line, if any.
if actuallyProvidedFlags["shell"] {
conf.Shell = shell
}
if actuallyProvidedFlags["debug"] {
conf.DebugMode = debugMode
}
if actuallyProvidedFlags["slomo"] {
conf.Slomo = slomo
}
return conf
}
func loadConfigFile() *config.Config {
usr, err := user.Current()
if err != nil {
fmt.Printf("Failed to get current user information: %s\n", err)
return &config.DefaultConfig
}
home := usr.HomeDir
if home == "" {
return &config.DefaultConfig
}
places := []string{}
xdgHome := os.Getenv("XDG_CONFIG_HOME")
if xdgHome != "" {
places = append(places, filepath.Join(xdgHome, "aminal/config.toml"))
}
places = append(places, filepath.Join(home, ".config/aminal/config.toml"))
places = append(places, filepath.Join(home, ".aminal.toml"))
for _, place := range places {
if b, err := ioutil.ReadFile(place); err == nil {
if c, err := config.Parse(b); err == nil {
return c
}
fmt.Printf("Invalid config at %s: %s\n", place, err)
}
}
if b, err := config.DefaultConfig.Encode(); err != nil {
fmt.Printf("Failed to encode config file: %s\n", err)
} else {
err = os.MkdirAll(filepath.Dir(places[0]), 0744)
if err != nil {
fmt.Printf("Failed to create config file directory: %s\n", err)
} else {
if err = ioutil.WriteFile(places[0], b, 0644); err != nil {
fmt.Printf("Failed to encode config file: %s\n", err)
}
}
}
return &config.DefaultConfig
}

25
example-aminal/logger.go Normal file
View File

@ -0,0 +1,25 @@
package main
import (
"fmt"
"github.com/liamg/aminal/config"
"go.uber.org/zap"
)
func getLogger(conf *config.Config) (*zap.SugaredLogger, error) {
var logger *zap.Logger
var err error
if conf.DebugMode {
logger, err = zap.NewDevelopment()
} else {
loggerConfig := zap.NewProductionConfig()
loggerConfig.Encoding = "console"
logger, err = loggerConfig.Build()
}
if err != nil {
return nil, fmt.Errorf("Failed to create logger: %s", err)
}
return logger.Sugar(), nil
}

80
example-aminal/main.go Normal file
View File

@ -0,0 +1,80 @@
package main
import (
"fmt"
"github.com/liamg/aminal/gui"
"github.com/liamg/aminal/platform"
"github.com/liamg/aminal/terminal"
"github.com/riywo/loginshell"
"os"
"runtime"
)
type callback func(terminal *terminal.Terminal, g *gui.GUI)
func init() {
runtime.LockOSThread()
}
func main() {
initialize(nil)
}
func initialize(unitTestfunc callback) {
conf := getConfig()
logger, err := getLogger(conf)
if err != nil {
fmt.Printf("Failed to create logger: %s\n", err)
os.Exit(1)
}
defer logger.Sync()
logger.Infof("Allocating pty...")
pty, err := platform.NewPty(80, 25)
if err != nil {
logger.Fatalf("Failed to allocate pty: %s", err)
}
shellStr := conf.Shell
if shellStr == "" {
loginShell, err := loginshell.Shell()
if err != nil {
logger.Fatalf("Failed to ascertain your shell: %s", err)
}
shellStr = loginShell
}
os.Setenv("TERM", "xterm-256color") // controversial! easier than installing terminfo everywhere, but obviously going to be slightly different to xterm functionality, so we'll see...
os.Setenv("COLORTERM", "truecolor")
guestProcess, err := pty.CreateGuestProcess(shellStr)
if err != nil {
pty.Close()
logger.Fatalf("Failed to start your shell: %s", err)
}
defer guestProcess.Close()
logger.Infof("Creating terminal...")
terminal := terminal.New(pty, logger, conf)
g, err := gui.New(conf, terminal, logger)
if err != nil {
logger.Fatalf("Cannot start: %s", err)
}
if unitTestfunc != nil {
go unitTestfunc(terminal, g)
} else {
go func() {
if err := guestProcess.Wait(); err != nil {
logger.Fatalf("Failed to wait for guest process: %s", err)
}
g.Close()
}()
}
if err := g.Render(); err != nil {
logger.Fatalf("Render error: %s", err)
}
}

2
example-gui/Makefile Normal file
View File

@ -0,0 +1,2 @@
run:
go run *.go

92
example-gui/main.go Normal file
View File

@ -0,0 +1,92 @@
package main
import "github.com/andlabs/ui"
import _ "github.com/andlabs/ui/winmanifest"
var mainwin *ui.Window
func makeNumbersPage() ui.Control {
hbox := ui.NewHorizontalBox()
hbox.SetPadded(true)
group := ui.NewGroup("Numbers")
group.SetMargined(true)
hbox.Append(group, true)
vbox := ui.NewVerticalBox()
vbox.SetPadded(true)
group.SetChild(vbox)
spinbox := ui.NewSpinbox(47, 100)
slider := ui.NewSlider(21, 100)
pbar := ui.NewProgressBar()
spinbox.OnChanged(func(*ui.Spinbox) {
slider.SetValue(spinbox.Value())
pbar.SetValue(spinbox.Value())
})
slider.OnChanged(func(*ui.Slider) {
spinbox.SetValue(slider.Value())
pbar.SetValue(slider.Value())
})
vbox.Append(spinbox, false)
vbox.Append(slider, false)
vbox.Append(pbar, false)
ip := ui.NewProgressBar()
ip.SetValue(-1)
vbox.Append(ip, false)
group = ui.NewGroup("Lists")
group.SetMargined(true)
hbox.Append(group, true)
vbox = ui.NewVerticalBox()
vbox.SetPadded(true)
group.SetChild(vbox)
cbox := ui.NewCombobox()
cbox.Append("Combobox Item 1")
cbox.Append("Combobox Item 2")
cbox.Append("Combobox Item 3")
vbox.Append(cbox, false)
ecbox := ui.NewEditableCombobox()
ecbox.Append("Editable Item 1")
ecbox.Append("Editable Item 2")
ecbox.Append("Editable Item 3")
vbox.Append(ecbox, false)
rb := ui.NewRadioButtons()
rb.Append("Radio Button 1")
rb.Append("Radio Button 2")
rb.Append("Radio Button 3")
vbox.Append(rb, false)
return hbox
}
func setupUI() {
mainwin = ui.NewWindow("gui-example1", 300, 200, false)
mainwin.OnClosing(func(*ui.Window) bool {
ui.Quit()
return true
})
ui.OnShouldQuit(func() bool {
mainwin.Destroy()
return true
})
tab := ui.NewTab()
mainwin.SetChild(tab)
mainwin.SetMargined(true)
tab.Append("example1", makeNumbersPage())
tab.SetMargined(0, true)
mainwin.Show()
}
func main() {
ui.Main(setupUI)
}

View File

@ -0,0 +1,3 @@
run:
go build
./example-lookupAAAA

View File

@ -0,0 +1,28 @@
package main
import "log"
import "github.com/miekg/dns"
import "git.wit.com/jcarr/dnssecsocket"
import "github.com/davecgh/go-spew/spew"
// import "github.com/Showmax/go-fqdn"
func lookupAAAA(hostname string) string {
// lookup the IP address from DNS
dnsRR := dnssecsocket.Dnstrace(hostname, "AAAA")
spew.Dump(dnsRR)
if (dnsRR == nil) {
return "BROKEN"
}
ipaddr := dns.Field(dnsRR, 1)
log.Println("ipaddr", ipaddr)
return ipaddr
}
func main() {
hostname := "v000185.testing.com.customers.wprod.wit.com"
// 2604:bbc0:2:248:5054:f0ff:fe00:156
lookupAAAA(hostname)
}

View File

@ -0,0 +1,3 @@
run:
go build
./example-multiple-windows

View File

@ -0,0 +1,123 @@
package main
// import "os"
import "log"
import "fmt"
import "time"
import "github.com/davecgh/go-spew/spew"
import "git.wit.com/wit/gui"
import pb "git.wit.com/wit/witProtobuf"
import "github.com/andlabs/ui"
import _ "github.com/andlabs/ui/winmanifest"
var first *gui.GuiWindow
var config *pb.Config
// This sometimes crashes on the most recent window
// under linux. but it doesn't always crash
func main() {
config = pb.MakeDefaultConfig()
// gui.Data.Config = c
i := 1
config.Width = int32(400 + 50 * i)
config.Height = int32(400 + 50 * i)
config.Hostname = fmt.Sprintf("splash %d", i)
first = StartNewWindow(config, true, "SPLASH")
i += 1
config.Width = int32(400 + 50 * i)
config.Hostname = fmt.Sprintf("splash %d", i)
StartNewWindow(config, true, "BLAH")
i += 1
config.Width = int32(400 + 50 * i)
config.Hostname = fmt.Sprintf("splash %d", i)
StartNewWindow(config, false, "BLAH")
for {
i += 1
config.Width = int32(400 + 50 * i)
config.Hostname = fmt.Sprintf("splash %d", i)
StartNewWindow(config, false, "SPLASH")
i += 1
config.Width = int32(400 + 50 * i)
config.Hostname = fmt.Sprintf("splash %d", i)
StartNewWindow(config, false, "BLAH")
}
}
func StartNewWindow(c *pb.Config, bg bool, action string) *gui.GuiWindow {
log.Println("InitNewWindow() Create a new window")
var newGuiWindow *gui.GuiWindow
newGuiWindow = new(gui.GuiWindow)
// newGuiWindow.Config = c
/*
ui.OnShouldQuit(func() bool {
// mouseClick(&newBM)
ui.Quit()
return true
})
*/
time.Sleep(1000 * time.Millisecond)
if (bg) {
log.Println("ShowWindow() IN NEW GOROUTINE")
go ui.Main(func() {
InitWindow(newGuiWindow)
})
time.Sleep(2000 * time.Millisecond)
} else {
log.Println("ShowWindow() WAITING for ui.Main()")
ui.Main(func() {
InitWindow(newGuiWindow)
})
}
return newGuiWindow
}
func InitWindow(gw *gui.GuiWindow) {
log.Println("InitWindow() NEW WINDOW gw =", gw)
c := config
gw.UiWindow = ui.NewWindow("", int(c.Width), int(c.Height), true)
// gw.UiWindow.SetBorderless(false)
blah := gw
gw.UiWindow.OnClosing(func(*ui.Window) bool {
log.Println("InitWindow() OnClosing() blah")
log.Println("InitWindow() OnClosing() blah")
log.Println("InitWindow() OnClosing() blah")
log.Println("InitWindow() OnClosing() blah")
spew.Dump(blah)
spew.Dump(gw)
log.Println("InitWindow() OnClosing() THIS WINDOW IS CLOSING gw=", gw)
spew.Dump(gw)
spew.Dump(gw.UiWindow)
// mouseClick(&newBM)
if (gw.UiWindow != nil) {
gw.UiWindow.Hide()
}
time.Sleep(1000 * time.Millisecond)
spew.Dump(gw)
// gw.UiWindow.Destroy()
ui.Quit()
time.Sleep(1000 * time.Millisecond)
return true
})
// gw.UiWindow.SetChild(gw.T)
// gw.UiWindow.SetMargined(true)
log.Println("InitWindow() Show() gw.Name =", gw.Name)
gw.UiWindow.Show()
}

20
example-nohup/main.go Normal file
View File

@ -0,0 +1,20 @@
package main
// import "os/exec"
import "log"
import "github.com/go-cmd/cmd"
func main() {
p := cmd.NewCmdOptions(
cmd.Options{
Buffered: false,
Streaming: false,
},
"/bin/bash",
"ping",
"localhost",
)
log.Println("cmd p = ", p)
p.Start()
// for {}
}

78
example-pprof/main.go Normal file
View File

@ -0,0 +1,78 @@
package main
// run this and then hit:
// http://localhost:6060/debug/pprof/
//
// Also run from the command line:
// go tool pprof 'localhost:6060/debug/pprof/wit_pprof_experiment_thing?debug=1'
//
// https://medium.com/@cep21/creating-custom-go-profiles-with-pprof-b737dfc58e11
import "fmt"
import "log"
import "net/http"
import _ "net/http/pprof" // the _ means only the init() is needed
import "os"
import "runtime/pprof"
import "sync/atomic"
import "time"
var libProfile *pprof.Profile
func init() {
profName := "wit_pprof_experiment_thing" // this ends up in the URL
libProfile = pprof.Lookup(profName)
if libProfile == nil {
libProfile = pprof.NewProfile(profName)
}
}
type someResource struct {
*os.File
}
var fileIndex = int64(0)
func MustResource() *someResource {
f, err := os.Create(fmt.Sprintf("/tmp/%d.txt", atomic.AddInt64(&fileIndex, 1)))
if err != nil {
panic(err)
}
r := &someResource{f}
libProfile.Add(r, 1)
return r
}
func (r *someResource) Close() error {
libProfile.Remove(r)
return r.File.Close()
}
func trackAFunction() {
tracked := new(byte)
libProfile.Add(tracked, 1)
defer libProfile.Remove(tracked)
time.Sleep(time.Second)
}
func usesAResource() {
res := MustResource()
defer res.Close()
for i := 0; i < 10; i++ {
time.Sleep(time.Second)
}
}
func main() {
http.HandleFunc("/nonblock", func(rw http.ResponseWriter, req *http.Request) {
go usesAResource()
})
http.HandleFunc("/functiontrack", func(rw http.ResponseWriter, req *http.Request) {
trackAFunction()
})
http.HandleFunc("/block", func(rw http.ResponseWriter, req *http.Request) {
usesAResource()
})
log.Println("Running!")
log.Println(http.ListenAndServe("localhost:6060", nil))
}

Binary file not shown.

2
example-splash/Makefile Normal file
View File

@ -0,0 +1,2 @@
run:
go run *.go

View File

@ -0,0 +1,140 @@
package main
import "log"
import "github.com/andlabs/ui"
import _ "github.com/andlabs/ui/winmanifest"
// import "github.com/davecgh/go-spew/spew"
func addAccountWindow() {
accounthWin := ui.NewWindow("Add Account", 400, 300, false)
accounthWin.OnClosing(func(*ui.Window) bool {
ui.Quit()
return true
})
ui.OnShouldQuit(func() bool {
accounthWin.Destroy()
return true
})
vbox := ui.NewVerticalBox()
vbox.SetPadded(true)
accounthWin.SetChild(vbox)
accounthWin.SetMargined(true)
// This displays the window
accounthWin.Show()
// START create new account button
newAccountButton := ui.NewButton("Create New Account")
newAccountButton.OnClicked(func(*ui.Button) {
log.Println("OK. Closing window.")
accounthWin.Destroy()
ui.Quit()
})
vbox.Append(newAccountButton, false)
// END create new account button
vbox.Append(ui.NewHorizontalSeparator(), false)
vbox.Append(ui.NewLabel("or"), false)
vbox.Append(ui.NewHorizontalSeparator(), false)
// START add account hbox
hboxAccount := ui.NewHorizontalBox()
hboxAccount.SetPadded(true)
vbox.Append(hboxAccount, false)
// Start 'Provider' vertical box
vboxC := ui.NewVerticalBox()
vboxC.SetPadded(true)
vboxC.Append(ui.NewLabel("Cloud Provider:"), false)
cbox := ui.NewCombobox()
cbox.Append("WIT")
cbox.Append("Evocative")
vboxC.Append(cbox, false)
cbox.SetSelected(0)
cbox.OnSelected(func(*ui.Combobox) {
log.Println("OK. Selected Cloud Provider =", cbox.Selected())
})
hboxAccount.Append(vboxC, false)
// End 'Cloud Provider' vertical box
// Start 'Region' vertical box
vboxR := ui.NewVerticalBox()
vboxR.SetPadded(true)
vboxR.Append(ui.NewLabel("Region:"), false)
regbox := ui.NewCombobox()
regbox.Append("Any")
regbox.Append("SF")
vboxR.Append(regbox, false)
regbox.SetSelected(0)
regbox.OnSelected(func(*ui.Combobox) {
log.Println("OK. Selected something =", regbox.Selected())
})
hboxAccount.Append(vboxR, false)
// End 'Region' vertical box
// Start 'Nickname' vertical box
vboxN := ui.NewVerticalBox()
vboxN.SetPadded(true)
vboxN.Append(ui.NewLabel("Account Nickname:"), false)
entryNick := ui.NewEntry()
entryNick.SetReadOnly(false)
vboxN.Append(entryNick, false)
entryNick.OnChanged(func(*ui.Entry) {
log.Println("OK. nickname =", entryNick.Text())
})
hboxAccount.Append(vboxN, false)
// End 'Nickname' vertical box
// Start 'Username' vertical box
vboxU := ui.NewVerticalBox()
vboxU.SetPadded(true)
vboxU.Append(ui.NewLabel("Account Username:"), false)
entryUser := ui.NewEntry()
entryUser.SetReadOnly(false)
vboxU.Append(entryUser, false)
entryUser.OnChanged(func(*ui.Entry) {
log.Println("OK. username =", entryUser.Text())
})
hboxAccount.Append(vboxU, false)
// End 'Username' vertical box
// Start 'Password' vertical box
vboxP := ui.NewVerticalBox()
vboxP.SetPadded(true)
vboxP.Append(ui.NewLabel("Account Password:"), false)
entryPass := ui.NewEntry()
entryPass.SetReadOnly(false)
vboxP.Append(entryPass, false)
entryPass.OnChanged(func(*ui.Entry) {
log.Println("OK. password =", entryPass.Text())
})
hboxAccount.Append(vboxP, false)
// End 'Password' vertical box
vbox.Append(ui.NewHorizontalSeparator(), false)
okButton := ui.NewButton("Add Account")
okButton.OnClicked(func(*ui.Button) {
log.Println("OK. Closing window.")
accounthWin.Destroy()
ui.Quit()
})
vbox.Append(okButton, false)
// END add account hbox
}

117
example-splash/area.go Normal file
View File

@ -0,0 +1,117 @@
package main
// import "time"
import "log"
// import "fmt"
// import "runtime"
import "github.com/andlabs/ui"
import _ "github.com/andlabs/ui/winmanifest"
import "github.com/davecgh/go-spew/spew"
var fontButton *ui.FontButton
var attrstr *ui.AttributedString
var splashArea *ui.Area
func makeSplashArea() *ui.Area {
fontButton = ui.NewFontButton()
fontButton.OnChanged(func(*ui.FontButton) {
spew.Dump(fontButton.Font())
// SplashArea.QueueRedrawAll()
})
spew.Dump(fontButton.Font())
makeAttributedString()
splashArea = ui.NewArea(areaHandler{})
spew.Dump(splashArea)
return splashArea
}
func appendWithAttributes(what string, attrs ...ui.Attribute) {
start := len(attrstr.String())
end := start + len(what)
attrstr.AppendUnattributed(what)
for _, a := range attrs {
attrstr.SetAttribute(a, start, end)
}
}
func makeAttributedString() {
attrstr = ui.NewAttributedString("")
appendWithAttributes("Welcome to the Cloud Control Panel\n", ui.TextSize(16), ui.TextColor{0.0, 0.0, 0.8, .8}) // "RGBT"
appendWithAttributes("(alpha)\n\n", ui.TextSize(10))
appendWithAttributes("This control panel was designed to be an interface to your 'private' cloud. ", ui.TextWeightBold)
appendWithAttributes("The concept of a private cloud means that you can use a providers system, or, seemlessly, use your own hardware in your own datacenter. ", ui.TextWeightBold)
attrstr.AppendUnattributed("\n")
attrstr.AppendUnattributed("\n")
appendWithAttributes("This control panel requires:\n")
attrstr.AppendUnattributed("\n")
appendWithAttributes("IPv6\n")
appendWithAttributes("Your hostname in DNS\n")
attrstr.AppendUnattributed("\n\n\n\n\n")
appendWithAttributes("<click or press any key>\n", ui.TextSize(10))
}
type areaHandler struct{}
func (areaHandler) Draw(a *ui.Area, p *ui.AreaDrawParams) {
tl := ui.DrawNewTextLayout(&ui.DrawTextLayoutParams{
String: attrstr,
DefaultFont: fontButton.Font(),
Width: p.AreaWidth,
Align: ui.DrawTextAlign(1),
})
defer tl.Free()
p.Context.Text(tl, 0, 0)
}
func (areaHandler) MouseEvent(a *ui.Area, me *ui.AreaMouseEvent) {
log.Println("GOT MouseEvent()")
spew.Dump(me)
if (me.Down == 1) {
log.Println("GOT MOUSE DOWN")
log.Println("GOT MOUSE DOWN")
log.Println("GOT MOUSE DOWN")
}
if (me.Up == 1) {
log.Println("GOT MOUSE UP")
log.Println("GOT MOUSE UP")
log.Println("GOT MOUSE UP")
splashWin.Destroy()
ui.Quit()
}
}
func (areaHandler) MouseCrossed(a *ui.Area, left bool) {
log.Println("GOT MouseCrossed()")
}
func (areaHandler) DragBroken(a *ui.Area) {
log.Println("GOT DragBroken()")
}
func (areaHandler) KeyEvent(a *ui.Area, ke *ui.AreaKeyEvent) (handled bool) {
log.Println("GOT KeyEvent()")
if (ke.Key == 10) {
log.Println("GOT ENTER")
log.Println("GOT ENTER")
log.Println("GOT ENTER")
}
if (ke.Key == 32) {
log.Println("GOT ENTER")
log.Println("GOT ENTER")
log.Println("GOT ENTER")
}
spew.Dump(ke)
splashWin.Destroy()
ui.Quit()
return false
}

101
example-splash/main.go Normal file
View File

@ -0,0 +1,101 @@
package main
import "time"
import "log"
import "fmt"
import "os"
import "github.com/andlabs/ui"
import _ "github.com/andlabs/ui/winmanifest"
var mainwin *ui.Window
var hbox *ui.Box
func makeSplashPage() ui.Control {
hbox = ui.NewHorizontalBox()
hbox.SetPadded(true)
group := ui.NewGroup("Numbers")
group.SetMargined(true)
hbox.Append(group, true)
vbox := ui.NewVerticalBox()
vbox.SetPadded(true)
group.SetChild(vbox)
spinbox := ui.NewSpinbox(47, 100)
slider := ui.NewSlider(21, 100)
pbar := ui.NewProgressBar()
spinbox.OnChanged(func(*ui.Spinbox) {
slider.SetValue(spinbox.Value())
pbar.SetValue(spinbox.Value())
})
slider.OnChanged(func(*ui.Slider) {
spinbox.SetValue(slider.Value())
pbar.SetValue(slider.Value())
})
vbox.Append(spinbox, false)
vbox.Append(slider, false)
vbox.Append(pbar, false)
return hbox
}
func setupUI() {
mainwin := ui.NewWindow("gui-example1", 300, 200, true)
mainwin.OnClosing(func(*ui.Window) bool {
ui.Quit()
os.Exit(0)
return true
})
ui.OnShouldQuit(func() bool {
mainwin.Destroy()
return true
})
tab := ui.NewTab()
mainwin.SetChild(tab)
mainwin.SetMargined(true)
tab.Append("WIT Splash", makeSplashPage())
tab.SetMargined(0, true)
mainwin.Show()
}
func main() {
ui.Main(addAccountWindow)
ui.Main(showSplash)
go ui.Main(setupUI)
// locks up GTK after a while (50 times)
time.Sleep(1000 * time.Millisecond)
count := 0
var newgroup *ui.Group
name := "Test " + fmt.Sprintf("%d", count)
log.Println("name=",name)
newgroup = ui.NewGroup(name)
newgroup.SetMargined(true)
hbox.Append(newgroup, false)
// display the splash screen info
log.Println("sleep for 3")
time.Sleep(3000 * time.Millisecond)
hbox.Delete(1)
// newgroup.Delete()
// can't destroy when there is a parent
newgroup.Destroy()
newgroup = nil
// wait forever here
for {
log.Println("sleep for 3 forever here")
time.Sleep(3000 * time.Millisecond)
}
}

57
example-splash/splash.go Normal file
View File

@ -0,0 +1,57 @@
package main
// import "github.com/davecgh/go-spew/spew"
// import "time"
// import "fmt"
import "log"
import "runtime"
import "github.com/andlabs/ui"
import _ "github.com/andlabs/ui/winmanifest"
var splashWin *ui.Window
func showSplash() {
splashWin = ui.NewWindow("", 640, 480, true)
splashWin.SetBorderless(true)
splashWin.OnClosing(func(*ui.Window) bool {
ui.Quit()
return true
})
ui.OnShouldQuit(func() bool {
splashWin.Destroy()
return true
})
vbox := ui.NewVerticalBox()
vbox.SetPadded(true)
splashWin.SetChild(vbox)
splashWin.SetMargined(true)
// This displays the window
splashWin.Show()
makeAttributedString()
myArea := makeSplashArea()
vbox.Append(myArea, true)
if runtime.GOOS == "linux" {
vbox.Append(ui.NewLabel("OS: Linux"), false)
} else if runtime.GOOS == "windows" {
vbox.Append(ui.NewLabel("OS: Windows"), false)
} else {
vbox.Append(ui.NewLabel("OS: " + runtime.GOOS), false)
}
vbox.Append(ui.NewLabel("Version: v0.3"), false)
okButton := ui.NewButton("OK")
okButton.OnClicked(func(*ui.Button) {
log.Println("OK. Closing window.")
splashWin.Destroy()
ui.Quit()
})
vbox.Append(okButton, false)
}

2
example-ssh/Makefile Normal file
View File

@ -0,0 +1,2 @@
all:
go run ssh-ed25519.go

26
example-ssh/ed25519.go Normal file
View File

@ -0,0 +1,26 @@
package main
import (
"crypto/rand"
"encoding/pem"
"io/ioutil"
"github.com/mikesmitty/edkey"
"golang.org/x/crypto/ed25519"
"golang.org/x/crypto/ssh"
)
func main() {
// Generate a new private/public keypair for OpenSSH
pubKey, privKey, _ := ed25519.GenerateKey(rand.Reader)
publicKey, _ := ssh.NewPublicKey(pubKey)
pemKey := &pem.Block{
Type: "OPENSSH PRIVATE KEY",
Bytes: edkey.MarshalED25519PrivateKey(privKey),
}
privateKey := pem.EncodeToMemory(pemKey)
authorizedKey := ssh.MarshalAuthorizedKey(publicKey)
_ = ioutil.WriteFile("id_ed25519", privateKey, 0600)
_ = ioutil.WriteFile("id_ed25519.pub", authorizedKey, 0644)
}

143
example-ssh/ssh-client.go Normal file
View File

@ -0,0 +1,143 @@
package main
import (
"bufio"
"io/ioutil"
"os/signal"
//"syscall"
"fmt"
"log"
"os"
"strings"
//"code.google.com/p/go.crypto/ssh"
//"code.google.com/p/go.crypto/ssh/terminal"
"golang.org/x/crypto/ssh"
//"github.com/fatih/color"
"github.com/shiena/ansicolor"
)
type password string
func (p password) Password(user string) (password string, err error) {
return string(p), nil
}
func init() {
// Verbose logging with file name and line number
log.SetFlags(log.Lshortfile)
}
func main() {
fmt.Print("Remote host: ")
// server := scanConfig()
server := "mirror.wit.com"
fmt.Print("Port: ")
// port := scanConfig()
// server = server + ":" + port
//fmt.Print("UserName?: ")
//user := scanConfig()
user := "jcarr"
//fmt.Print("Password?: ")
//p := scanConfig()
// publicKey, err := PublicKeyFile(`privatekey.pem`)
publicKey, err := PublicKeyFile(`id_ed25519.pub`)
if err != nil {
log.Println(err)
return
}
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
//ssh.Password(p),
publicKey,
},
}
conn, err := ssh.Dial("tcp", server, config)
if err != nil {
panic("Failed to dial: " + err.Error())
}
defer conn.Close()
// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
session, err := conn.NewSession()
if err != nil {
panic("Failed to create session: " + err.Error())
}
defer session.Close()
// Set IO
session.Stdout = ansicolor.NewAnsiColorWriter(os.Stdout)
session.Stderr = ansicolor.NewAnsiColorWriter(os.Stderr)
in, _ := session.StdinPipe()
// Set up terminal modes
// https://net-ssh.github.io/net-ssh/classes/Net/SSH/Connection/Term.html
// https://www.ietf.org/rfc/rfc4254.txt
// https://godoc.org/golang.org/x/crypto/ssh
// THIS IS THE TITLE
// https://pythonhosted.org/ANSIColors-balises/ANSIColors.html
modes := ssh.TerminalModes{
ssh.ECHO: 0, // Disable echoing
ssh.IGNCR: 1, // Ignore CR on input.
}
// Request pseudo terminal
//if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
//if err := session.RequestPty("xterm-256color", 80, 40, modes); err != nil {
if err := session.RequestPty("vt100", 80, 40, modes); err != nil {
//if err := session.RequestPty("vt220", 80, 40, modes); err != nil {
log.Fatalf("request for pseudo terminal failed: %s", err)
}
// Start remote shell
if err := session.Shell(); err != nil {
log.Fatalf("failed to start shell: %s", err)
}
// Handle control + C
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for {
<-c
fmt.Println("^C")
fmt.Fprint(in, "\n")
//fmt.Fprint(in, '\t')
}
}()
// var b []byte = make([]byte, 1)
// Accepting commands
for {
reader := bufio.NewReader(os.Stdin)
str, _ := reader.ReadString('\n')
fmt.Fprint(in, str)
}
}
func scanConfig() string {
config, _ := bufio.NewReader(os.Stdin).ReadString('\n')
config = strings.Trim(config, "\n")
return config
}
func PublicKeyFile(file string) (ssh.AuthMethod, error) {
buffer, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
key, err := ssh.ParsePrivateKey(buffer)
if err != nil {
return nil, err
}
return ssh.PublicKeys(key), nil
}

135
example-ssh/ssh-ed25519.go Normal file
View File

@ -0,0 +1,135 @@
package main
import "bufio"
import "log"
import "os"
import "os/user"
import "io/ioutil"
import "path/filepath"
import "strings"
import "time"
import "golang.org/x/crypto/ssh"
func main() {
host := "mirrors.wit.com"
port := "22"
username := "jcarr"
pass := "tryme"
cmd := "ps"
// get host public key
// hostKey := getHostKey(host)
// log.Println("hostkey =", hostKey)
user, _ := user.Current()
publicKey, err := PublicKeyFile(user.HomeDir + "/.ssh/id_ed25519")
if (err != nil) {
log.Println("PublicKeyFile() error =", err)
}
// ssh client config
config := ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.Password(pass),
publicKey,
},
// allow any host key to be used (non-prod)
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
// verify host public key
// HostKeyCallback: ssh.FixedHostKey(hostKey),
// optional host key algo list
HostKeyAlgorithms: []string{
ssh.KeyAlgoRSA,
ssh.KeyAlgoDSA,
ssh.KeyAlgoECDSA256,
ssh.KeyAlgoECDSA384,
ssh.KeyAlgoECDSA521,
ssh.KeyAlgoED25519,
},
// optional tcp connect timeout
Timeout: 5 * time.Second,
}
// connect
client, err := ssh.Dial("tcp", host+":"+port, &config)
if err != nil {
log.Fatal(err)
}
defer client.Close()
// start session
sess, err := client.NewSession()
if err != nil {
log.Fatal(err)
}
defer sess.Close()
// setup standard out and error
// uses writer interface
sess.Stdout = os.Stdout
sess.Stderr = os.Stderr
// run single command
err = sess.Run(cmd)
if err != nil {
log.Fatal(err)
}
}
func getHostKey(host string) ssh.PublicKey {
// parse OpenSSH known_hosts file
// ssh or use ssh-keyscan to get initial key
file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts"))
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
var hostKey ssh.PublicKey
for scanner.Scan() {
fields := strings.Split(scanner.Text(), " ")
if len(fields) != 3 {
continue
}
if strings.Contains(fields[0], host) {
var err error
hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes())
if err != nil {
log.Fatalf("error parsing %q: %v", fields[2], err)
}
break
}
}
// 9enFJdMhb8eHN/6qfHSU/jww2Mo=|pcsWQCvAyve9QXBhjL+w/LhkcHU= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBMQx8BJXxD+vk3wyjy7Irzw4FA6xxJvqUP7Hb+Z+ygpOuidYj9G8x6gHEXFUnABn5YirePrWh5tNsk4Rqs48VwU=
hostKey, _, _, _, err = ssh.ParseAuthorizedKey([]byte("9enFJdMhb8eHN/6qfHSU/jww2Mo=|pcsWQCvAyve9QXBhjL+w/LhkcHU= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBMQx8BJXxD+vk3wyjy7Irzw4FA6xxJvqUP7Hb+Z+ygpOuidYj9G8x6gHEXFUnABn5YirePrWh5tNsk4Rqs48VwU="))
log.Println("hostkey err =", err)
log.Println("hostkey =", hostKey)
if hostKey == nil {
log.Println("no hostkey found err =", err)
log.Fatalf("no hostkey found for %s", host)
}
return hostKey
}
func PublicKeyFile(file string) (ssh.AuthMethod, error) {
buffer, err := ioutil.ReadFile(file)
log.Println("buffer =", string(buffer))
if err != nil {
return nil, err
}
key, err := ssh.ParsePrivateKey(buffer)
if err != nil {
return nil, err
}
return ssh.PublicKeys(key), nil
}

View File

@ -0,0 +1,51 @@
package main
import (
"fmt"
"log"
"os"
"golang.org/x/crypto/ssh"
)
func main() {
if len(os.Args) != 4 {
log.Fatalf("Usage: %s <user> <host:port> <command>", os.Args[0])
}
client, session, err := connectToHost(os.Args[1], os.Args[2])
if err != nil {
panic(err)
}
out, err := session.CombinedOutput(os.Args[3])
if err != nil {
panic(err)
}
fmt.Println(string(out))
client.Close()
}
func connectToHost(user, host string) (*ssh.Client, *ssh.Session, error) {
var pass string
fmt.Print("Password: ")
fmt.Scanf("%s\n", &pass)
sshConfig := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{ssh.Password(pass)},
}
sshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()
client, err := ssh.Dial("tcp", host, sshConfig)
if err != nil {
return nil, nil, err
}
session, err := client.NewSession()
if err != nil {
client.Close()
return nil, nil, err
}
return client, session, nil
}

102
example-sshd/main.go Normal file
View File

@ -0,0 +1,102 @@
package main
import (
"fmt"
"io"
"io/ioutil"
"log"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
// "code.google.com/p/go.crypto/ssh"
// "code.google.com/p/go.crypto/ssh/terminal"
)
func main() {
// An SSH server is represented by a ServerConfig, which holds
// certificate details and handles authentication of ServerConns.
config := &ssh.ServerConfig{
PasswordCallback: func(conn *ssh.ServerConn, user, pass string) bool {
return user == "testuser" && pass == "tiger"
},
}
pemBytes, err := ioutil.ReadFile("id_rsa")
if err != nil {
log.Fatal("Failed to load private key:", err)
}
if err = config.SetRSAPrivateKey(pemBytes); err != nil {
log.Fatal("Failed to parse private key:", err)
}
// Once a ServerConfig has been configured, connections can be
// accepted.
conn, err := ssh.Listen("tcp", "0.0.0.0:2022", config)
if err != nil {
log.Fatal("failed to listen for connection")
}
for {
// A ServerConn multiplexes several channels, which must
// themselves be Accepted.
log.Println("accept")
sConn, err := conn.Accept()
if err != nil {
log.Println("failed to accept incoming connection")
continue
}
if err := sConn.Handshake(); err != nil {
log.Println("failed to handshake")
continue
}
go handleServerConn(sConn)
}
}
func handleServerConn(sConn *ssh.ServerConn) {
defer sConn.Close()
for {
// Accept reads from the connection, demultiplexes packets
// to their corresponding channels and returns when a new
// channel request is seen. Some goroutine must always be
// calling Accept; otherwise no messages will be forwarded
// to the channels.
ch, err := sConn.Accept()
if err == io.EOF {
return
}
if err != nil {
log.Println("handleServerConn Accept:", err)
break
}
// Channels have a type, depending on the application level
// protocol intended. In the case of a shell, the type is
// "session" and ServerShell may be used to present a simple
// terminal interface.
if ch.ChannelType() != "session" {
ch.Reject(ssh.UnknownChannelType, "unknown channel type")
break
}
go handleChannel(ch)
}
}
func handleChannel(ch ssh.Channel) {
term := terminal.NewTerminal(ch, "> ")
serverTerm := &ssh.ServerTerminal{
Term: term,
Channel: ch,
}
ch.Accept()
defer ch.Close()
for {
line, err := serverTerm.ReadLine()
if err == io.EOF {
return
}
if err != nil {
log.Println("handleChannel readLine err:", err)
continue
}
fmt.Println(line)
}
}

202
example-sshd/sshd.go Normal file
View File

@ -0,0 +1,202 @@
// A small SSH daemon providing bash sessions
//
// Server:
// cd my/new/dir/
// #generate server keypair
// ssh-keygen -t rsa
// go get -v .
// go run sshd.go
//
// Client:
// ssh foo@localhost -p 2200 #pass=bar
package main
import (
"encoding/binary"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os/exec"
"sync"
"syscall"
"unsafe"
"github.com/kr/pty"
"golang.org/x/crypto/ssh"
)
func main() {
// In the latest version of crypto/ssh (after Go 1.3), the SSH server type has been removed
// in favour of an SSH connection type. A ssh.ServerConn is created by passing an existing
// net.Conn and a ssh.ServerConfig to ssh.NewServerConn, in effect, upgrading the net.Conn
// into an ssh.ServerConn
config := &ssh.ServerConfig{
//Define a function to run when a client attempts a password login
PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
// Should use constant-time compare (or better, salt+hash) in a production setting.
if c.User() == "foo" && string(pass) == "bar" {
return nil, nil
}
return nil, fmt.Errorf("password rejected for %q", c.User())
},
// You may also explicitly allow anonymous client authentication, though anon bash
// sessions may not be a wise idea
// NoClientAuth: true,
}
// You can generate a keypair with 'ssh-keygen -t rsa'
privateBytes, err := ioutil.ReadFile("id_rsa")
if err != nil {
log.Fatal("Failed to load private key (./id_rsa)")
}
private, err := ssh.ParsePrivateKey(privateBytes)
if err != nil {
log.Fatal("Failed to parse private key")
}
config.AddHostKey(private)
// Once a ServerConfig has been configured, connections can be accepted.
listener, err := net.Listen("tcp", "0.0.0.0:2200")
if err != nil {
log.Fatalf("Failed to listen on 2200 (%s)", err)
}
// Accept all connections
log.Print("Listening on 2200...")
for {
tcpConn, err := listener.Accept()
if err != nil {
log.Printf("Failed to accept incoming connection (%s)", err)
continue
}
// Before use, a handshake must be performed on the incoming net.Conn.
sshConn, chans, reqs, err := ssh.NewServerConn(tcpConn, config)
if err != nil {
log.Printf("Failed to handshake (%s)", err)
continue
}
log.Printf("New SSH connection from %s (%s)", sshConn.RemoteAddr(), sshConn.ClientVersion())
// Discard all global out-of-band Requests
go ssh.DiscardRequests(reqs)
// Accept all channels
go handleChannels(chans)
}
}
func handleChannels(chans <-chan ssh.NewChannel) {
// Service the incoming Channel channel in go routine
for newChannel := range chans {
go handleChannel(newChannel)
}
}
func handleChannel(newChannel ssh.NewChannel) {
// Since we're handling a shell, we expect a
// channel type of "session". The also describes
// "x11", "direct-tcpip" and "forwarded-tcpip"
// channel types.
if t := newChannel.ChannelType(); t != "session" {
newChannel.Reject(ssh.UnknownChannelType, fmt.Sprintf("unknown channel type: %s", t))
return
}
// At this point, we have the opportunity to reject the client's
// request for another logical connection
connection, requests, err := newChannel.Accept()
if err != nil {
log.Printf("Could not accept channel (%s)", err)
return
}
// Fire up bash for this session
bash := exec.Command("bash")
// Prepare teardown function
close := func() {
connection.Close()
_, err := bash.Process.Wait()
if err != nil {
log.Printf("Failed to exit bash (%s)", err)
}
log.Printf("Session closed")
}
// Allocate a terminal for this channel
log.Print("Creating pty...")
bashf, err := pty.Start(bash)
if err != nil {
log.Printf("Could not start pty (%s)", err)
close()
return
}
//pipe session to bash and visa-versa
var once sync.Once
go func() {
io.Copy(connection, bashf)
once.Do(close)
}()
go func() {
io.Copy(bashf, connection)
once.Do(close)
}()
// Sessions have out-of-band requests such as "shell", "pty-req" and "env"
go func() {
for req := range requests {
switch req.Type {
case "shell":
// We only accept the default shell
// (i.e. no command in the Payload)
if len(req.Payload) == 0 {
req.Reply(true, nil)
}
case "pty-req":
termLen := req.Payload[3]
w, h := parseDims(req.Payload[termLen+4:])
SetWinsize(bashf.Fd(), w, h)
// Responding true (OK) here will let the client
// know we have a pty ready for input
req.Reply(true, nil)
case "window-change":
w, h := parseDims(req.Payload)
SetWinsize(bashf.Fd(), w, h)
}
}
}()
}
// =======================
// parseDims extracts terminal dimensions (width x height) from the provided buffer.
func parseDims(b []byte) (uint32, uint32) {
w := binary.BigEndian.Uint32(b)
h := binary.BigEndian.Uint32(b[4:])
return w, h
}
// ======================
// Winsize stores the Height and Width of a terminal.
type Winsize struct {
Height uint16
Width uint16
x uint16 // unused
y uint16 // unused
}
// SetWinsize sets the size of the given pty.
func SetWinsize(fd uintptr, w, h uint32) {
ws := &Winsize{Width: uint16(w), Height: uint16(h)}
syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCSWINSZ), uintptr(unsafe.Pointer(ws)))
}
// Borrowed from https://github.com/creack/termios/blob/master/win/win.go

202
example-systray/LICENSE Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2014 Brave New Software Project, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

6
example-systray/Makefile Normal file
View File

@ -0,0 +1,6 @@
build:
go build
./example-systray
run:
go run *.go

88
example-systray/main.go Normal file
View File

@ -0,0 +1,88 @@
package main
import "fmt"
import "github.com/getlantern/systray"
import "github.com/getlantern/systray/example/icon"
import "github.com/skratchdot/open-golang/open"
func main() {
onExit := func() {
fmt.Println("Starting onExit")
/*
now := time.Now()
ioutil.WriteFile(fmt.Sprintf(`on_exit_%d.txt`, now.UnixNano()), []byte(now.String()), 0644)
now = time.Now()
ioutil.WriteFile(fmt.Sprintf(`on_exit_%d.2.txt`, now.UnixNano()), []byte(now.String()), 0644)
*/
fmt.Println("Finished onExit")
}
// Should be called at the very beginning of main().
systray.Run(onReady, onExit)
}
func onReady() {
systray.SetIcon(icon.Data)
systray.SetTitle("Awesome App")
systray.SetTooltip("Lantern")
mQuitOrig := systray.AddMenuItem("Quit", "Quit the whole app")
go func() {
<-mQuitOrig.ClickedCh
fmt.Println("Requesting quit")
systray.Quit()
fmt.Println("Finished quitting")
}()
// We can manipulate the systray in other goroutines
go func() {
systray.SetIcon(icon.Data)
systray.SetTitle("Awesome App")
systray.SetTooltip("Pretty awesome棒棒嗒")
mChange := systray.AddMenuItem("Change Me", "Change Me")
mChecked := systray.AddMenuItem("Unchecked", "Check Me")
mEnabled := systray.AddMenuItem("Enabled", "Enabled")
systray.AddMenuItem("Ignored", "Ignored")
mUrl := systray.AddMenuItem("Open Lantern.org", "my home")
mQuit := systray.AddMenuItem("退出", "Quit the whole app")
// Sets the icon of a menu item. Only available on Mac.
mQuit.SetIcon(icon.Data)
systray.AddSeparator()
mToggle := systray.AddMenuItem("Toggle", "Toggle the Quit button")
shown := true
for {
select {
case <-mChange.ClickedCh:
mChange.SetTitle("I've Changed")
case <-mChecked.ClickedCh:
if mChecked.Checked() {
mChecked.Uncheck()
mChecked.SetTitle("Unchecked")
} else {
mChecked.Check()
mChecked.SetTitle("Checked")
}
case <-mEnabled.ClickedCh:
mEnabled.SetTitle("Disabled")
mEnabled.Disable()
case <-mUrl.ClickedCh:
open.Run("https://www.getlantern.org")
case <-mToggle.ClickedCh:
if shown {
mQuitOrig.Hide()
mEnabled.Hide()
shown = false
} else {
mQuitOrig.Show()
mEnabled.Show()
shown = true
}
case <-mQuit.ClickedCh:
systray.Quit()
fmt.Println("Quit2 now...")
return
}
}
}()
}

8
example-table/Makefile Normal file
View File

@ -0,0 +1,8 @@
run:
go run *.go
build:
go build
build-windows:
env GOOS=windows GOARCH=amd64 go build

1
example-table/README.md Normal file
View File

@ -0,0 +1 @@
This is the example directly from andlabs/ui

454
example-table/table.go Normal file
View File

@ -0,0 +1,454 @@
// taken directly from the andlabs/ui/examples
// 26 august 2018
// TODO possible bugs in libui:
// - the checkboxes on macOS retain their values when they shouldn't
package main
import (
"fmt"
"image"
_ "image/png"
"image/draw"
"bytes"
"github.com/andlabs/ui"
_ "github.com/andlabs/ui/winmanifest"
)
type modelHandler struct {
row9Text string
yellowRow int
checkStates [15]int
}
func newModelHandler() *modelHandler {
m := new(modelHandler)
m.row9Text = "You can edit this one"
m.yellowRow = -1
return m
}
func (mh *modelHandler) ColumnTypes(m *ui.TableModel) []ui.TableValue {
return []ui.TableValue{
ui.TableString(""), // column 0 text
ui.TableString(""), // column 1 text
ui.TableString(""), // column 2 text
ui.TableColor{}, // row background color
ui.TableColor{}, // column 1 text color
ui.TableImage{}, // column 1 image
ui.TableString(""), // column 4 button text
ui.TableInt(0), // column 3 checkbox state
ui.TableInt(0), // column 5 progress
}
}
func (mh *modelHandler) NumRows(m *ui.TableModel) int {
return 15
}
var img [2]*ui.Image
func (mh *modelHandler) CellValue(m *ui.TableModel, row, column int) ui.TableValue {
if column == 3 {
if row == mh.yellowRow {
return ui.TableColor{1, 1, 0, 1}
}
if row == 3 {
return ui.TableColor{1, 0, 0, 1}
}
if row == 11 {
return ui.TableColor{0, 0.5, 1, 0.5}
}
return nil
}
if column == 4 {
if (row % 2) == 1 {
return ui.TableColor{0.5, 0, 0.75, 1}
}
return nil
}
if column == 5 {
if row < 8 {
return ui.TableImage{img[0]}
}
return ui.TableImage{img[1]}
}
if column == 7 {
return ui.TableInt(mh.checkStates[row])
}
if column == 8 {
if row == 0 {
return ui.TableInt(0)
}
if row == 13 {
return ui.TableInt(100)
}
if row == 14 {
return ui.TableInt(-1)
}
return ui.TableInt(50)
}
switch column {
case 0:
return ui.TableString(fmt.Sprintf("Row %d", row))
case 2:
if row == 9 {
return ui.TableString(mh.row9Text)
}
return ui.TableString("Editing this won't change anything")
case 1:
return ui.TableString("Colors!")
case 6:
return ui.TableString("Make Yellow")
}
panic("unreachable")
}
func (mh *modelHandler) SetCellValue(m *ui.TableModel, row, column int, value ui.TableValue) {
if row == 9 && column == 2 {
mh.row9Text = string(value.(ui.TableString))
}
if column == 6 { // row background color
prevYellowRow := mh.yellowRow
mh.yellowRow = row
if prevYellowRow != -1 {
m.RowChanged(prevYellowRow)
}
m.RowChanged(mh.yellowRow)
}
if column == 7 { // checkboxes
mh.checkStates[row] = int(value.(ui.TableInt))
}
}
func appendImageNamed(i *ui.Image, which string) {
b := rawImages[which]
img, _, err := image.Decode(bytes.NewReader(b))
if err != nil {
panic(err)
}
nr, ok := img.(*image.RGBA)
if !ok {
i2 := image.NewRGBA(img.Bounds())
draw.Draw(i2, i2.Bounds(), img, img.Bounds().Min, draw.Src)
nr = i2
}
i.Append(nr)
}
func setupUI() {
mainwin := ui.NewWindow("libui Control Gallery", 640, 480, true)
mainwin.OnClosing(func(*ui.Window) bool {
ui.Quit()
return true
})
ui.OnShouldQuit(func() bool {
mainwin.Destroy()
return true
})
img[0] = ui.NewImage(16, 16)
appendImageNamed(img[0], "andlabs_16x16test_24june2016.png")
appendImageNamed(img[0], "andlabs_32x32test_24june2016.png")
img[1] = ui.NewImage(16, 16)
appendImageNamed(img[1], "tango-icon-theme-0.8.90_16x16_x-office-spreadsheet.png")
appendImageNamed(img[1], "tango-icon-theme-0.8.90_32x32_x-office-spreadsheet.png")
mh := newModelHandler()
model := ui.NewTableModel(mh)
table := ui.NewTable(&ui.TableParams{
Model: model,
RowBackgroundColorModelColumn: 3,
})
vbox := ui.NewVerticalBox()
vbox.SetPadded(true)
vbox.Append(table, true)
mainwin.SetChild(vbox)
mainwin.SetMargined(true)
table.AppendTextColumn("Column 1",
0, ui.TableModelColumnNeverEditable, nil)
table.AppendImageTextColumn("Column 2",
5,
1, ui.TableModelColumnNeverEditable, &ui.TableTextColumnOptionalParams{
ColorModelColumn: 4,
});
table.AppendTextColumn("Editable",
2, ui.TableModelColumnAlwaysEditable, nil)
table.AppendCheckboxColumn("Checkboxes",
7, ui.TableModelColumnAlwaysEditable)
table.AppendButtonColumn("Buttons",
6, ui.TableModelColumnAlwaysEditable)
table.AppendProgressBarColumn("Progress Bar",
8)
mainwin.Show()
}
func main() {
ui.Main(setupUI)
}
var rawImages = map[string][]byte{
"andlabs_16x16test_24june2016.png": []byte{
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10,
0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0xf3, 0xff, 0x61, 0x00, 0x00, 0x00,
0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00,
0x00, 0xca, 0x49, 0x44, 0x41, 0x54, 0x38, 0x11, 0xa5, 0x93, 0xb1, 0x0d,
0xc2, 0x40, 0x0c, 0x45, 0x1d, 0xc4, 0x14, 0x0c, 0x12, 0x41, 0x0f, 0x62,
0x12, 0x46, 0x80, 0x8a, 0x2e, 0x15, 0x30, 0x02, 0x93, 0x20, 0x68, 0x11,
0x51, 0x06, 0x61, 0x0d, 0x88, 0x2d, 0x7f, 0xdb, 0x07, 0x87, 0x08, 0xdc,
0x49, 0x91, 0x7d, 0xf6, 0xf7, 0xf3, 0x4f, 0xa4, 0x54, 0xbb, 0xeb, 0xf6,
0x41, 0x05, 0x67, 0xcc, 0xb3, 0x9b, 0xfa, 0xf6, 0x17, 0x62, 0xdf, 0xcd,
0x48, 0x00, 0x32, 0xbd, 0xa8, 0x1d, 0x72, 0xee, 0x3c, 0x47, 0x16, 0xfb,
0x5c, 0x53, 0x8d, 0x03, 0x30, 0x14, 0x84, 0xf7, 0xd5, 0x89, 0x26, 0xc7,
0x25, 0x10, 0x36, 0xe4, 0x05, 0xa2, 0x51, 0xbc, 0xc4, 0x1c, 0xc3, 0x1c,
0xed, 0x30, 0x1c, 0x8f, 0x16, 0x3f, 0x02, 0x78, 0x33, 0x20, 0x06, 0x60,
0x97, 0x70, 0xaa, 0x45, 0x7f, 0x85, 0x60, 0x5d, 0xb6, 0xf4, 0xc2, 0xc4,
0x3e, 0x0f, 0x44, 0xcd, 0x1b, 0x20, 0x90, 0x0f, 0xed, 0x85, 0xa8, 0x55,
0x05, 0x42, 0x43, 0xb4, 0x9e, 0xce, 0x71, 0xb3, 0xe8, 0x0e, 0xb4, 0xc4,
0xc3, 0x39, 0x21, 0xb7, 0x73, 0xbd, 0xe4, 0x1b, 0xe4, 0x04, 0xb6, 0xaa,
0x4f, 0x18, 0x2c, 0xee, 0x42, 0x31, 0x01, 0x84, 0xfa, 0xe0, 0xd4, 0x00,
0xdf, 0xb6, 0x83, 0xf8, 0xea, 0xc2, 0x00, 0x10, 0xfc, 0x1a, 0x05, 0x30,
0x74, 0x3b, 0xe0, 0xd1, 0x45, 0xb1, 0x83, 0xaa, 0xf4, 0x77, 0x7e, 0x02,
0x87, 0x1f, 0x42, 0x7f, 0x9e, 0x2b, 0xe8, 0xdf, 0x00, 0x00, 0x00, 0x00,
0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
},
"andlabs_32x32test_24june2016.png": []byte{
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20,
0x08, 0x06, 0x00, 0x00, 0x00, 0x73, 0x7a, 0x7a, 0xf4, 0x00, 0x00, 0x00,
0x01, 0x73, 0x52, 0x47, 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00,
0x01, 0x6a, 0x49, 0x44, 0x41, 0x54, 0x58, 0x09, 0xc5, 0x97, 0xc1, 0x0d,
0xc2, 0x30, 0x0c, 0x45, 0x03, 0x62, 0x0a, 0x06, 0x41, 0x70, 0x07, 0x31,
0x09, 0x23, 0xc0, 0x89, 0x05, 0x80, 0x11, 0x98, 0x04, 0xc1, 0x15, 0x81,
0x18, 0x84, 0x35, 0x00, 0x57, 0xfd, 0x8d, 0x13, 0x92, 0x3a, 0x4e, 0x03,
0x8d, 0x54, 0x39, 0x35, 0xb1, 0xff, 0x8b, 0xed, 0x1e, 0x18, 0xec, 0xae,
0xdb, 0x97, 0xe9, 0x71, 0x8d, 0x48, 0x7b, 0x33, 0xb9, 0xf5, 0x82, 0xb0,
0x7f, 0xcc, 0x4c, 0x05, 0x50, 0xa9, 0x2f, 0x26, 0x32, 0xc4, 0xf9, 0x21,
0x9f, 0xa1, 0x13, 0x8a, 0x5c, 0x16, 0x40, 0x4a, 0x9e, 0x92, 0x14, 0x78,
0x8a, 0x5c, 0x43, 0xc4, 0xf4, 0x65, 0x3b, 0x01, 0x3c, 0x57, 0x27, 0x43,
0x4f, 0x97, 0x95, 0x0d, 0x40, 0xc2, 0xe3, 0xe3, 0xb2, 0x7a, 0xba, 0x40,
0xd8, 0x19, 0x50, 0x5c, 0x03, 0xe2, 0x08, 0x21, 0x10, 0xdf, 0xd7, 0x3a,
0x88, 0x6c, 0x46, 0xd4, 0x00, 0x5f, 0x42, 0x35, 0x85, 0x03, 0x41, 0x03,
0xcb, 0x44, 0x00, 0x1a, 0xb2, 0x2e, 0x80, 0x66, 0xd2, 0x43, 0xd9, 0x32,
0x7c, 0x2e, 0x40, 0x1b, 0x75, 0x0d, 0xe7, 0xdc, 0x94, 0x09, 0xc6, 0x2a,
0xc3, 0x8e, 0x04, 0xb7, 0x59, 0x43, 0x08, 0x08, 0x64, 0xcc, 0x15, 0xa7,
0x78, 0x5b, 0x01, 0x45, 0xdf, 0x28, 0x90, 0x43, 0xd0, 0x3e, 0x77, 0x59,
0x80, 0x8c, 0x0c, 0x5d, 0x84, 0x21, 0xe7, 0x02, 0x94, 0x1c, 0x42, 0x29,
0x57, 0x3d, 0x6f, 0x16, 0xa0, 0x6d, 0x00, 0x81, 0xcb, 0xec, 0xe1, 0x7e,
0x61, 0x6f, 0xc6, 0xac, 0xa7, 0x73, 0xfb, 0xae, 0xc8, 0x65, 0x01, 0x6c,
0xb8, 0xb8, 0x23, 0x71, 0x47, 0xf0, 0x13, 0x11, 0xf2, 0x89, 0x89, 0x3e,
0x07, 0xd4, 0x5f, 0x41, 0x4c, 0x88, 0x80, 0xfc, 0xaa, 0x14, 0x07, 0x88,
0x89, 0x43, 0x28, 0x07, 0x42, 0x5d, 0x01, 0x88, 0x95, 0xb2, 0xc9, 0x00,
0xd2, 0xed, 0x01, 0xa4, 0xad, 0x82, 0x38, 0x84, 0xe8, 0xab, 0x3f, 0x74,
0x10, 0x0c, 0x59, 0x0e, 0x21, 0xc5, 0xb5, 0x02, 0xa4, 0xde, 0x3a, 0x06,
0x41, 0x7e, 0x29, 0x47, 0x72, 0x0b, 0x42, 0x22, 0x25, 0x7c, 0x51, 0x00,
0x89, 0x3c, 0x55, 0x9c, 0xb7, 0x23, 0x14, 0xf3, 0xd5, 0x82, 0x9c, 0x9e,
0x87, 0x12, 0x73, 0x1f, 0x87, 0xf0, 0x67, 0xc2, 0x01, 0x28, 0x75, 0x6b,
0x2e, 0x8e, 0x3d, 0x84, 0x7d, 0x8d, 0x68, 0x0b, 0x10, 0xf8, 0x6b, 0xdb,
0x00, 0xf8, 0x64, 0xbf, 0x12, 0xe6, 0xed, 0x20, 0x8d, 0x0a, 0xe0, 0x5f,
0xe2, 0xb8, 0x14, 0x87, 0x68, 0x2a, 0x80, 0x1f, 0xff, 0x6d, 0x07, 0x7d,
0xff, 0x3d, 0x7f, 0x03, 0x93, 0xca, 0x91, 0xa9, 0x89, 0x2a, 0x2e, 0xd2,
0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
},
"tango-icon-theme-0.8.90_16x16_x-office-spreadsheet.png": []byte{
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10,
0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0xf3, 0xff, 0x61, 0x00, 0x00, 0x00,
0x06, 0x62, 0x4b, 0x47, 0x44, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0xa0,
0xbd, 0xa7, 0x93, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00,
0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18,
0x00, 0x00, 0x00, 0x07, 0x74, 0x49, 0x4d, 0x45, 0x07, 0xd5, 0x04, 0x16,
0x14, 0x0d, 0x09, 0xd9, 0x88, 0x44, 0xfa, 0x00, 0x00, 0x02, 0x4d, 0x49,
0x44, 0x41, 0x54, 0x38, 0xcb, 0x95, 0x92, 0xdf, 0x4b, 0x53, 0x61, 0x18,
0xc7, 0x3f, 0x67, 0x9b, 0x6e, 0x7a, 0xd6, 0xfc, 0x55, 0xe0, 0x59, 0x8a,
0x95, 0x71, 0x08, 0x52, 0x21, 0x91, 0x2c, 0x8a, 0x0a, 0x94, 0x11, 0x14,
0x78, 0x21, 0x99, 0x14, 0x81, 0xdd, 0x48, 0x7f, 0x45, 0x63, 0x5d, 0x75,
0x1b, 0x34, 0xd0, 0x9b, 0x52, 0x83, 0x0a, 0xad, 0x0b, 0x43, 0x72, 0xd0,
0x85, 0x14, 0x14, 0x68, 0x77, 0x39, 0xcd, 0x6c, 0x94, 0x0c, 0xf4, 0x48,
0x4d, 0x5b, 0x5b, 0x4b, 0xcf, 0x39, 0x3b, 0xef, 0xe9, 0x62, 0x3f, 0xec,
0xd7, 0x2e, 0x7c, 0xae, 0xbe, 0x2f, 0xef, 0xf3, 0xfd, 0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0x40, 0x20, 0x37, 0x8d, 0xc1,
0x41, 0xde, 0xdd, 0x1f, 0xe3, 0xe0, 0xf5, 0x5e, 0xea, 0x0e, 0x1c, 0xc1,
0x76, 0xb9, 0xa8, 0x3e, 0x5d, 0x87, 0xa8, 0x70, 0x10, 0xec, 0x90, 0x78,
0xfc, 0x39, 0x4d, 0x63, 0x7c, 0x91, 0xf6, 0xc9, 0x09, 0x2a, 0x55, 0x75,
0x5c, 0x0a, 0x87, 0xc3, 0x53, 0x89, 0x44, 0xe2, 0xc2, 0xef, 0xb3, 0xad,
0x9d, 0x99, 0x41, 0x7e, 0xf3, 0x1a, 0xf3, 0xdc, 0x09, 0xca, 0x1a, 0xaa,
0xf1, 0x9c, 0xb5, 0xd1, 0x0d, 0x41, 0x66, 0xc3, 0x64, 0x7a, 0x4a, 0xd0,
0x33, 0xfb, 0x8a, 0x0a, 0x55, 0x7d, 0x71, 0x6d, 0x61, 0x21, 0x50, 0xea,
0x7f, 0x30, 0xd2, 0xdd, 0x7d, 0x49, 0x5f, 0x5a, 0xba, 0xe9, 0x4e, 0x26,
0x55, 0xe7, 0xcf, 0x4c, 0xb9, 0x6d, 0x83, 0x90, 0x65, 0xc3, 0xa5, 0x28,
0xcb, 0x07, 0xbb, 0xba, 0x6e, 0x9d, 0x1a, 0x1a, 0x9a, 0x00, 0xf8, 0x05,
0xf4, 0xf5, 0x23, 0xe9, 0x30, 0xeb, 0x2d, 0xf9, 0x00, 0x00, 0x00, 0x00,
0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
},
"tango-icon-theme-0.8.90_32x32_x-office-spreadsheet.png": []byte{
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20,
0x08, 0x06, 0x00, 0x00, 0x00, 0x73, 0x7a, 0x7a, 0xf4, 0x00, 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45,
0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
},
}

2
example-test/Makefile Normal file
View File

@ -0,0 +1,2 @@
all:
go test --race

21
example-test/ex_test.go Normal file
View File

@ -0,0 +1,21 @@
package ex
import "sync"
import "testing"
type Item struct{}
func TestAppend(t *testing.T) {
var list []Item
n := 2
wg := sync.WaitGroup{}
wg.Add(n)
for i := 0; i < n; i++ {
go func() {
defer wg.Done()
list = append(list, Item{})
}()
}
wg.Wait()
}

3
test1/Makefile Normal file
View File

@ -0,0 +1,3 @@
run:
go build
./test1

1
test1/README.md Normal file
View File

@ -0,0 +1 @@
this eventually crashes (GTK / Linux)

35
test1/crash1 Normal file
View File

@ -0,0 +1,35 @@
2019/05/17 10:59:15 name= Test 128
2019/05/17 10:59:15 sleep
2019/05/17 10:59:15 sleep
2019/05/17 10:59:15 name= Test 129
2019/05/17 10:59:16 sleep
fatal error: unexpected signal during runtime execution
[signal SIGSEGV: segmentation violation code=0x1 addr=0x7f8c000000b8 pc=0x7f8cbfb2f8e5]
runtime stack:
runtime.throw(0x50c4b8, 0x2a)
/usr/lib/go-1.11/src/runtime/panic.go:608 +0x72
runtime.sigpanic()
/usr/lib/go-1.11/src/runtime/signal_unix.go:374 +0x2f2
goroutine 19 [syscall]:
runtime.cgocall(0x4b5490, 0xc00004df78, 0xc0000ac048)
/usr/lib/go-1.11/src/runtime/cgocall.go:128 +0x5e fp=0xc00004df48 sp=0xc00004df10 pc=0x41688e
github.com/andlabs/ui._Cfunc_uiMain()
_cgo_gotypes.go:2518 +0x41 fp=0xc00004df78 sp=0xc00004df48 pc=0x4a9711
github.com/andlabs/ui.Main(0x50d890, 0xc00003a701, 0xc0000842c0)
/home/jcarr/go/src/github.com/andlabs/ui/main.go:41 +0xfd fp=0xc00004dfc8 sp=0xc00004df78 pc=0x4ad6cd
runtime.goexit()
/usr/lib/go-1.11/src/runtime/asm_amd64.s:1333 +0x1 fp=0xc00004dfd0 sp=0xc00004dfc8 pc=0x466461
created by main.main
/home/jcarr/go/src/git.wit.com/wit/cloud-control-panel/example-splash/main.go:68 +0x53
goroutine 1 [sleep, locked to thread]:
time.Sleep(0x11e1a300)
/usr/lib/go-1.11/src/runtime/time.go:105 +0x14f
main.main()
/home/jcarr/go/src/git.wit.com/wit/cloud-control-panel/example-splash/main.go:74 +0x74
exit status 2
make: *** [Makefile:2: run] Error 1
jcarr@librem15:~/go/src/git.wit.com/wit/cloud-control-panel/example-splash$ git diff

BIN
test1/main Executable file

Binary file not shown.

93
test1/main.go Normal file
View File

@ -0,0 +1,93 @@
package main
import "time"
import "log"
import "fmt"
import "github.com/andlabs/ui"
import _ "github.com/andlabs/ui/winmanifest"
var mainwin *ui.Window
var hbox *ui.Box
var vbox *ui.Box
var newgroup *ui.Group
func makeSplashPage() ui.Control {
hbox = ui.NewHorizontalBox()
hbox.SetPadded(true)
group := ui.NewGroup("Numbers")
group.SetMargined(true)
hbox.Append(group, true)
vbox = ui.NewVerticalBox()
vbox.SetPadded(true)
group.SetChild(vbox)
spinbox := ui.NewSpinbox(47, 100)
slider := ui.NewSlider(21, 100)
pbar := ui.NewProgressBar()
spinbox.OnChanged(func(*ui.Spinbox) {
slider.SetValue(spinbox.Value())
pbar.SetValue(spinbox.Value())
})
slider.OnChanged(func(*ui.Slider) {
spinbox.SetValue(slider.Value())
pbar.SetValue(slider.Value())
})
vbox.Append(spinbox, false)
vbox.Append(slider, false)
vbox.Append(pbar, false)
return hbox
}
func setupUI() {
mainwin = ui.NewWindow("gui-example1", 300, 200, false)
mainwin.OnClosing(func(*ui.Window) bool {
ui.Quit()
return true
})
ui.OnShouldQuit(func() bool {
mainwin.Destroy()
return true
})
tab := ui.NewTab()
mainwin.SetChild(tab)
mainwin.SetMargined(true)
tab.Append("WIT Splash", makeSplashPage())
tab.SetMargined(0, true)
mainwin.Show()
}
func main() {
go ui.Main(setupUI)
// locks up GTK after a while (50 times)
time.Sleep(1000 * time.Millisecond)
count := 0
for {
time.Sleep(300 * time.Millisecond)
log.Println("sleep")
if (newgroup == nil) {
name := "Test " + fmt.Sprintf("%d", count)
log.Println("name=",name)
newgroup = ui.NewGroup(name)
newgroup.SetMargined(true)
hbox.Append(newgroup, false)
// newgroup = append(newgroup, group)
count += 1
} else {
hbox.Delete(1)
// newgroup.Delete()
// can't destroy when there is a parent
newgroup.Destroy()
newgroup = nil
}
}
}

3
test2/Makefile Normal file
View File

@ -0,0 +1,3 @@
run:
go build
./test2

44
test2/config.go Normal file
View File

@ -0,0 +1,44 @@
package main
/*
This simply parses the command line arguments using the default golang
package called 'flag'. This can be used as a simple template to parse
command line arguments in other programs.
It puts everything in the 'config' package which I think is a good
wrapper around the 'flags' package and doesn't need a whole mess of
global variables
*/
import "log"
import "strings"
import "io/ioutil"
import "github.com/golang/protobuf/jsonpb"
import pb "git.wit.com/wit/witProtobuf"
import "github.com/davecgh/go-spew/spew"
// TEST UNMARSHAL JSON TO PROTOBUF
// This is known to crash unless done exactly like this
// with strings.NewReader & 'sets'
func loadDefaultConfig(a string) pb.Config {
sets := pb.Config{}
b, err := ioutil.ReadFile("../resources/cloud-control-panel.json")
if err != nil {
log.Println("ioutil.ReadFile() ERROR =", err)
}
// log.Println("ioutil.ReadFile() b =", b)
err = jsonpb.Unmarshal(strings.NewReader(string(b)), &sets)
if err != nil {
log.Println("jsonpb.Unmarshal() ERROR =", err)
}
spew.Dump(sets)
return sets
}
func main() {
loadDefaultConfig("")
}

3
test3/Makefile Normal file
View File

@ -0,0 +1,3 @@
run:
go build
./test3

32
test3/main.go Normal file
View File

@ -0,0 +1,32 @@
package main
import "log"
import "os"
import "github.com/andlabs/ui"
import _ "github.com/andlabs/ui/winmanifest"
import "git.wit.com/wit/gui"
func TestAttributedString() *ui.AttributedString {
newText := ui.NewAttributedString("")
gui.AreaAppendText(newText, "Welcome to the Cloud Control Panel\n", ui.TextSize(16), ui.TextColor{0.0, 0.0, 0.8, .8}) // "RGBT"
return newText
}
func main() {
// THIS CRASHES IF YOU RUN IT HERE
// text := TestAttributedString()
// log.Println("text =", text)
ui.Main(setupUI)
}
func setupUI() {
// this doesn't crash here
text := TestAttributedString()
log.Println("text =", text)
os.Exit(0)
}

3
test4/Makefile Normal file
View File

@ -0,0 +1,3 @@
run:
go build
./test4

220
test4/config.go Normal file
View File

@ -0,0 +1,220 @@
package main
/*
This simply parses the command line arguments using the default golang
package called 'flag'. This can be used as a simple template to parse
command line arguments in other programs.
It puts everything in a 'config' Protobuf which I think is a good
wrapper around the 'flags' package and doesn't need a whole mess of
global variables
*/
import "log"
import "os"
import "os/user"
import "flag"
import "fmt"
import "runtime"
import "io/ioutil"
import "strings"
import "github.com/golang/protobuf/jsonpb"
import pb "git.wit.com/wit/witProtobuf"
import "github.com/davecgh/go-spew/spew"
var config *pb.Config
// This loads the config file and marshals it into the
// config protocol buffer definition.
// Then it is very easy to pass all the config options
// around and the re-write that JSON file when the GUI
// exits
func loadConfigFile() {
// look up the user information
user, err := user.Current()
if err != nil {
onExit(err)
}
spew.Dump(user)
filename := ""
// TODO: confirm this is correct for MacOS and Windows
if runtime.GOOS == "linux" {
log.Println("loadConfigFile() OS: Linux")
filename = user.HomeDir + "/.config/cloud-control-panel.json"
} else if runtime.GOOS == "windows" {
log.Println("loadConfigFile() OS: Windows")
filename = user.HomeDir + "\\cloud-control-panel.json"
} else {
log.Println("loadConfigFile() OS: " + runtime.GOOS)
filename = user.HomeDir + "/.cloud-control-panel.json"
}
tmp := loadConfigFromFilename(filename)
config = &tmp
config.Filename = filename
}
var customUsage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
fmt.Println("")
fmt.Println("EXAMPLES:")
fmt.Println("")
fmt.Println(os.Args[0] + " --hostname test.hostname.wit.com")
fmt.Println("")
}
var defaultconfig *bool
func parseFlags() {
var hostname string
// always override the debugging flag from the command line
var debug *bool
var debugtable *bool
flag.StringVar (&hostname, "hostname", "localhost", "Your full hostname")
height := flag.Int ("height", 0, "Height of the Window")
width := flag.Int ("width", 0, "Width of the Window")
debug = flag.Bool("debug", false, "Enable debugging")
defaultconfig = flag.Bool("defaultconfig", false, "Use the default config file")
debugtable = flag.Bool("debugtable", false, "Enable GUI table debugging")
// Set the output if something fails to stdout rather than stderr
flag.CommandLine.SetOutput(os.Stdout)
flag.Usage = customUsage
flag.Parse()
if flag.Parsed() {
log.Println("flag.Parse() worked")
} else {
log.Println("flag.Parse() failed")
onExit(nil)
}
if (*width > 100) {
log.Println("ENABLE width =", int32(*width))
config.Width = int32(*width)
}
if (*height > 100) {
log.Println("ENABLE height =", int32(*height))
config.Height = int32(*height)
}
if (hostname == "") {
config.Hostname = hostname
}
// never allow these to be set in the config file
config.Debug = *debug
config.Debugtable = *debugtable
}
// Convert a Protobuf to JSON
func PBtoJSON() string {
// this makes a sample protobuf
c := pb.MakeDefaultConfig()
marshaler := &jsonpb.Marshaler{}
stuff, _ := marshaler.MarshalToString(c)
log.Println(stuff)
return stuff
}
func writeToFile(filename string, a string) {
f, _ := os.Create(filename)
f.WriteString(a)
f.Close()
}
func saveConfig() {
filename := config.Filename
if (filename == "") {
log.Println("NOT SAVING CONFIG FILE")
} else {
marshaler := &jsonpb.Marshaler{}
stuff, _ := marshaler.MarshalToString(config)
log.Println(stuff)
writeToFile(filename, stuff)
}
}
// will load the default config from within the go binary
func loadConfigFromFilename(filename string) pb.Config {
sets := pb.Config{}
b, err := ioutil.ReadFile(filename)
if err != nil {
log.Println("ioutil.ReadFile() ERROR =", err)
// This probably means this is the first time the user is opening this
sets.Errors += 1
sets.Crash = "err"
sets.Counter = 1
sets.Width = 500
sets.Height = 500
return sets
}
log.Println("ioutil.ReadFile() b =", b)
err = jsonpb.Unmarshal(strings.NewReader(string(b)), &sets)
if err != nil {
log.Println("jsonpb.Unmarshal() ERROR =", err)
}
spew.Dump(sets)
return sets
}
// will load the default config from within the go binary
func loadDefaultConfig() *pb.Config {
log.Println("TRY TO LOAD DEFAULT CONFIG")
// defaultConfig, _ := packrBox.FindString("protobuf-config.json")
b, err := packrBox.FindString("cloud-control-panel.json")
log.Println("b =", b)
log.Println("err =", err)
// var newpb *pb.Config
sets := pb.Config{}
err = jsonpb.Unmarshal(strings.NewReader(string(b)), &sets)
if err != nil {
log.Println("jsonpb.Unmarshal() ERROR =", err)
}
spew.Dump(sets)
return &sets
}
//
// This is what you call from main()
//
func parseConfig() {
// first load the config file
loadConfigFile()
// override the config file from the command line
parseFlags()
log.Println("config.width", config.Width)
log.Println("config.height", config.Height)
log.Println("config.debug", config.Debug)
// check that the config parsing worked
for key, foo := range config.Accounts {
log.Println("account = ", key, foo)
log.Println("Accounts[key] = ", config.Accounts[key])
}
if (config.Accounts == nil) {
log.Println("loadConfigFile() config.Accounts == nil")
log.Println("If debugging is on, should load default config here")
if (*defaultconfig == true) {
log.Println("Debugging is on, loading debug config accounts")
tmp := loadDefaultConfig()
config.Accounts = tmp.Accounts
log.Println("loadConfigFile() config.Accounts =", config.Accounts)
}
}
}

103
test4/main.go Normal file
View File

@ -0,0 +1,103 @@
package main
import "log"
import "os"
import "time"
// import "reflect"
// this is the king of dns libraries
// import "github.com/miekg/dns"
import "git.wit.com/wit/gui"
import pb "git.wit.com/wit/witProtobuf"
// import "git.wit.com/jcarr/dnssecsocket"
import "github.com/gobuffalo/packr"
// import "github.com/davecgh/go-spew/spew"
var GITCOMMIT string // this is passed in as an ldflag
var GOVERSION string // this is passed in as an ldflag
var BUILDTIME string // this is passed in as an ldflag
var VERSION string // this is passed in as an ldflag
var State string // used as a State machine
type myButtonInfo struct {
Account *pb.Account // associated with what account?
Accounts []*pb.Account // associated with what account?
VM *pb.Event_VM // associated with which VM?
Custom func (*gui.GuiButton)
ADD func (*gui.GuiButton)
Name string
Action string
}
var packrBox packr.Box
func onExit(err error) {
os.Exit(0)
}
func main() {
packrBox = packr.NewBox("./resources")
parseConfig()
go gui.WatchGUI()
config.Hostname = "localhost"
config.IPv6 = "notvalid"
gui.Data.MouseClick = func (*gui.GuiButton) {
log.Println("mainMouseClick() BACK IN CONTROL PANEL CODE")
}
gui.Config.Width = int(config.Width)
gui.Config.Height = int(config.Height)
gui.Config.Debug = config.Debug
gui.Config.DebugTable = config.Debugtable
log.Println("gui.Config.Debug = ", gui.Config.Debug)
log.Println("gui.Config.DebugTable = ", gui.Config.DebugTable)
go gui.StartNewWindow(false, "test4", showBox)
time.Sleep(time.Second * 2)
gui.StartNewWindow(false, "test5", showBox)
}
func showBox(gw *gui.GuiWindow) *gui.GuiBox {
log.Println("ShowSplashBox() START")
box := gui.HardBox(gw, gui.Yaxis, "Cloud Accounts")
log.Println("showBox() START GW IS NOW: gw =", gw)
log.Println("showBox() box =", box)
gui.NewLabel(box, "Hostname:")
makeButton(box, nil, nil, "EMPTY", "SUBDOMAIN", nil)
makeButton(box, nil, nil, "List all windows & tabs", "SUBDOMAIN", func (*gui.GuiButton) {
log.Println("showBox() gui.DumpBoxes()")
gui.DumpBoxes()
})
return box
}
// stores the fields we want to map into our private structure 'values'
func makeGuiButtonValues(box *gui.GuiBox, a *pb.Account, vm *pb.Event_VM,
name string, action string, custom func(*gui.GuiButton)) *myButtonInfo {
val := &myButtonInfo{}
val.Account = a
val.Accounts = config.Accounts
val.VM = vm
val.Custom = custom
val.Name = "jcarr"
val.Action = action
return val
}
func makeButton(box *gui.GuiBox, a *pb.Account, vm *pb.Event_VM,
name string, action string, custom func(*gui.GuiButton)) *gui.GuiButton {
val := makeGuiButtonValues(box, a, vm, name, action, custom)
return gui.CreateButton(box, custom, name, val)
}

3
test5/Makefile Normal file
View File

@ -0,0 +1,3 @@
run:
go build
./test5

86
test5/main.go Normal file
View File

@ -0,0 +1,86 @@
package main
import "fmt"
import "io"
import "log"
import "reflect"
import "strings"
import "encoding/json"
type S struct{
blah int
foo string
}
func (s *S) addr() { fmt.Printf("%p\n", s) }
type Codec interface {
Encode(w io.Writer, v interface{}) error
Decode(r io.Reader, v interface{}) error
}
func (jsonCodec) Encode(w io.Writer, v interface{}) error {
return json.NewEncoder(w).Encode(v)
}
func (jsonCodec) Decode(r io.Reader, v interface{}) error {
return json.NewDecoder(r).Decode(v)
}
var JSON Codec = jsonCodec{}
type jsonCodec struct{}
type buttons interface {
Encode(w io.Writer, v interface{}) error
Decode(r io.Reader, v interface{}) error
}
type foo struct{}
type goo struct{
test int
}
func bar(baz interface{}) {
log.Println("baz =", baz)
log.Println("reflect.TypeOf(baz) =", reflect.TypeOf(baz))
switch f := baz.(type) {
case int:
log.Println("baz.(type) is an int =", f * 3)
case *foo: // f is of type *foo
log.Println("baz.(type) is known as *foo")
default: // f is some other type
log.Println("baz.(type) =", f)
}
}
func main() {
var a, b S
a.addr() // 0x1beeb0
b.addr() // 0x1beeb0
f := &foo{}
bar(f) // every type implements interface{}. Nothing special required
g := &goo{}
g.test = 4
bar(g) // every type implements interface{}. Nothing special required
bar("hello") // every type implements interface{}. Nothing special required
// what is this?
// s := &Service{
// Codec: JSON,
// }
r := strings.NewReader("Hello, Reader!")
err := JSON.Decode(r, "afjd")
log.Println("JSON.Decoder err =", err)
// err := JSON.Encode(w, obj)
// log.Println("err =", err)
}