start removing subtrees

This commit is contained in:
2023-04-28 09:03:53 -06:00
parent ce1ef04568
commit b000d0a750
184 changed files with 0 additions and 13188 deletions

View File

@@ -1,2 +0,0 @@
bin/
externLog.txt

View File

@@ -1,504 +0,0 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
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 this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser 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 Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey 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 library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random
Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View File

@@ -1,9 +0,0 @@
** LICENSING: Modified MIT license to restrict commercial use & require attribution **
Copyright (c) 2018 Phr00t's Software
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software with only commercial use restrictions & a requirement to attribute Phr00t's Software. You are free to to use, copy, modify, merge, publish, distribute this Software for private, personal & non-commercial uses as long as Phr00t's Software is attributed.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -1,8 +0,0 @@
-lib kiss
-lib uuid
-lib tink_macro
-lib tink_json
-lib requests-externs
-cp src
--main nat.CLI
--interp

View File

@@ -1,3 +0,0 @@
-lib hxcpp
--cpp bin/cpp
--cmd bash test-cpp.sh

View File

@@ -1 +0,0 @@
-lib remarkable-typescript

View File

@@ -1,23 +0,0 @@
{
"name": "nat-archive-tool-js-externs",
"version": "0.0.0",
"description": "",
"main": "index.js",
"scripts": {
"postinstall": "dts2hx --all"
},
"repository": {
"type": "git",
"url": "git+https://github.com/NQNStudios/kisslang.git"
},
"author": "NQNStudios",
"license": "LGPL2",
"bugs": {
"url": "https://github.com/NQNStudios/kisslang/issues"
},
"homepage": "https://github.com/NQNStudios/kisslang#readme",
"devDependencies": {
"dts2hx": "^0.16.1",
"remarkable-typescript": "^1.1.3"
}
}

View File

@@ -1 +0,0 @@
-lib requests-externs

View File

@@ -1 +0,0 @@
import requests_externs.Requests;

View File

@@ -1 +0,0 @@
requests==2.26.0

View File

@@ -1,17 +0,0 @@
{
"name": "nat-archive-tool",
"url": "https://github.com/NQNStudios/kisslang",
"license": "LGPL",
"tags": ["cross"],
"description": "",
"version": "0.0.0",
"releasenote": "It isn't safe to use this library yet.",
"contributors": ["NQNStudios"],
"classPath": "src/",
"main": "nat.CLI",
"dependencies": {
"kiss": "",
"kiss-tools": "",
"tink_json": ""
}
}

View File

@@ -1,3 +0,0 @@
-lib hxnodejs
--js bin/js/main.js
--cmd node bin/js/main.js

View File

@@ -1,2 +0,0 @@
--python bin/python/main.py
--cmd python bin/python/main.py

View File

@@ -1,13 +0,0 @@
package nat;
import sys.FileSystem;
import kiss.Prelude;
import sys.io.File;
import uuid.Uuid;
import haxe.DynamicAccess;
import haxe.ds.Option;
using haxe.io.Path;
@:build(kiss.Kiss.build())
class Archive {}

View File

@@ -1,111 +0,0 @@
(defNew [&prop :String archiveDir]
[:Array<System> systems
[]
:Option<String> gitDir
(let [gitDir (joinPath archiveDir ".git")]
(if (FileSystem.exists gitDir)
(Some gitDir)
None))
// Parse all entries into a dictionary of id => entry
:Map<String,Entry> entries
(let [entryDir (joinPath archiveDir "entries")
filesDir (joinPath archiveDir "files")]
(assert (FileSystem.exists archiveDir) "Archive directory $archiveDir does not exist")
(assert (FileSystem.isDirectory archiveDir) "$archiveDir is not a directory")
(FileSystem.createDirectory entryDir)
(FileSystem.createDirectory filesDir)
// Sync with git if the archive is a repository:
(whenLet [(Some gitDir) gitDir]
(assertProcess "git" ["pull"] [] true archiveDir))
(let [entryFiles (FileSystem.readDirectory entryDir)]
(for file entryFiles
=>(file.withoutExtension)
(the Entry (tink.Json.parse (File.getContent (joinPath archiveDir "entries" file)))))))
:DynamicAccess<Dynamic> playgrounds
(let [playgroundsFile (joinPath archiveDir "playgrounds.json")]
(unless (FileSystem.exists playgroundsFile)
(File.saveContent playgroundsFile
#"{
"default": "Playground-MAIN",
"Playground-MAIN": {
"catsMatch": "true"
}
}
"#))
(haxe.Json.parse (File.getContent playgroundsFile)))])
(method changePlaygrounds [:Dynamic->Void change]
(change playgrounds)
(File.saveContent (joinPath archiveDir "playgrounds.json") (haxe.Json.stringify playgrounds "\t"))
(gitSync))
(method :String currentPlayground []
(dictGet playgrounds "default"))
(method addSystem [:System system]
(systems.push system)
system)
(method addAndProcessSystem [:System system &opt :ArchiveUI ui]
(addSystem system)
(refreshSystem system)
(system.process this ui)
system)
(method refreshSystem [:System system]
(doFor =>id e entries
(system.checkEntryInOrOut this e)))
(method forceProcessAll [&opt :ArchiveUI ui]
(doFor system systems (refreshSystem system))
(processSystems))
(method processSystems [&opt :ArchiveUI ui]
(doFor system systems
(system.process this ui)))
(prop &mut :Entry->Dynamic defaultInitializer null)
(method :Entry createEntry [:Entry->Dynamic initializer] // initializer returns Dynamic so ->:Void isn't required
(let [e (new Entry)]
(when defaultInitializer
(defaultInitializer e))
(initializer e)
(dictSet entries e.id e)
(refreshEntry e)
e))
// After modifying an entry, this must be called. If you are writing in a createEntry
// initializer or a system's processEntry function, this will happen automatically.
// Also most functions that only affect the Entry, not its components' contents,
// will call this automatically though (withWritableEntry).
// When changing components, use the (withWritableComponents) macro in Lib.kiss
(method refreshEntry [:Entry e]
(_saveEntry e)
(doFor system systems
(system.checkEntryInOrOut this e)))
(method gitSync []
// Sync with git if the archive is a repository:
(whenLet [(Some gitDir) gitDir
gitDo ->gitArgs (assertProcess "git" gitArgs [] true archiveDir)]
(gitDo ["add" "playgrounds.json"])
(gitDo ["add" "entries"])
(gitDo ["add" "files"])
(gitDo ["commit" "--no-verify" "--allow-empty" "-m" "$(Date.now)"])
(gitDo ["push"])))
(method _saveEntry [:Entry e]
(File.saveContent
(joinPath archiveDir "entries" (e.id.withExtension "json"))
(tink.Json.stringify e))
(gitSync))
(method fullString [:Entry e]
(haxe.Json.stringify e null "\t"))
(method :String filePath [file]
(joinPath archiveDir "files" file))

View File

@@ -1,56 +0,0 @@
package nat;
import kiss.Prelude;
import kiss.List;
import kiss.Stream;
import nat.components.Position;
import haxe.Constraints;
import haxe.DynamicAccess;
import uuid.Uuid;
import nat.systems.*;
import nat.components.*;
enum CommandArgType {
// When called interactively, automatically pass the currently selected Entry(s) to the function
// TODO eventually these will also be passed automatically when called programatically
SelectedEntry;
SelectedEntries(min:Null<Int>, max:Null<Int>);
// String input
Text(maxLength:Null<Float>); // max length is a float so Math.POSITIVE_INFINITY can be used
// Any number of string inputs:
VarText(maxLength:Null<Float>);
// Numerical input, can be forced to align with a fixed step from the minimum
Number(min:Null<Float>, max:Null<Float>, inStepsOf:Null<Float>);
// Any number of numerical inputs, can be forced to align with a fixed step from the minimum
Numbers(min:Null<Float>, max:Null<Float>, inStepsOf:Null<Float>);
// Make the user select Entry(s) when called interactively
OneEntry; // This constructor must be disambiguated from the typedef "Entry"
Entries(min:Null<Int>, max:Null<Int>);
TagsFromAll;
TagsFromSelected;
// TODO File
// TODO Files
Position;
// Then again the more of these I add the more convoluted CollectAndValidateArgs gets,
// and the more stream reader methods I need to write
}
typedef CommandArg = {
name:String,
type:CommandArgType
};
typedef Command = {
args:Array<CommandArg>,
handler:Function
// Command handlers need to return a ChangeSet
};
typedef ChangeSet = Array<Entry>;
@:build(kiss.Kiss.build())
class ArchiveController {}

View File

@@ -1,533 +0,0 @@
(load "Lib.kiss")
(method :Void _collectAndValidateArg [:CommandArg arg :Stream stream :Dynamic->Void continuation]
(case arg.type
(SelectedEntry
(if (= 1 _selectedEntries.length)
(continuation (first (getSelectedEntries)))
(ui.reportError "The requested command expects 1 entry to be selected. You have selected: $_selectedEntries.length")))
((SelectedEntries min max)
(unless min (set min 0))
// TODO might want to optimize this O(n) count operation by pre-calculating it
(unless max (set max (count archive.entries)))
(if !(<= min _selectedEntries.length max)
(ui.reportError "The requested command expects between $min and $max entries to be selected. You have selected: $_selectedEntries.length")
(continuation (getSelectedEntries))))
((Text maxLength)
(unless maxLength (set maxLength Math.POSITIVE_INFINITY))
(stream.dropWhitespace)
(localFunction :Void trySubmit [text]
(stream.dropWhitespace)
(if !(<= text.length maxLength)
(ui.reportError "The requested command expected a string up to $maxLength characters long. You entered: $text.length characters")
(continuation text)))
(if (or (stream.isEmpty) (stream.dropStringIf "_"))
// If no text argument was pre-supplied, use the ui for it
(ui.enterText
"${arg.name} (up to ${maxLength} characters):"
trySubmit
maxLength)
(trySubmit (readString stream))))
((VarText maxLength)
(unless maxLength (set maxLength Math.POSITIVE_INFINITY))
(stream.dropWhitespace)
(let [collectedText []]
(localFunction :Void enterTextAgain []
(localFunction :Void trySubmit [text]
(stream.dropWhitespace)
(if !text
(continuation collectedText)
(if !(<= text.length maxLength)
(ui.reportError "The requested command expected a list of strings up to $maxLength characters long. You entered: $text.length characters")
{(collectedText.push text)
(enterTextAgain)})))
(if (or (stream.isEmpty) (stream.dropStringIf "_"))
// If no vartext argument was pre-supplied, use the ui for it
(ui.enterText
"${arg.name} (up to ${maxLength} characters):"
trySubmit
maxLength)
(trySubmit (readString stream))))
(enterTextAgain)))
((or TagsFromAll TagsFromSelected)
(chooseFromTags arg.type continuation))
((Number min max inStepsOf)
(unless min (set min Math.NEGATIVE_INFINITY))
(unless max (set max Math.POSITIVE_INFINITY))
(stream.dropWhitespace)
(let [&mut prompt "${arg.name} (${min}-${max}"]
(when inStepsOf
(+= prompt " in steps of ${inStepsOf}"))
(+= prompt "):")
(localFunction :Void trySubmit [number]
(stream.dropWhitespace)
(let [minMaxError
"The requested command expected a number between $min and $max"
stepError
"$minMaxError in steps of $inStepsOf"
youEntered
". You entered: $number"]
(if (or
!(<= min number max)
(and inStepsOf !(= 0 (% (- number min) inStepsOf))))
(if inStepsOf
(ui.reportError "${stepError}$youEntered")
(ui.reportError "${minMaxError}$youEntered"))
(continuation number))))
// If no text argument was pre-supplied, use the ui for it
(if (or (stream.isEmpty) (stream.dropStringIf "_"))
(ui.enterNumber
prompt
trySubmit
min
max
inStepsOf)
(trySubmit (readNumber stream)))))
((Numbers min max inStepsOf)
(unless min (set min Math.NEGATIVE_INFINITY))
(unless max (set max Math.POSITIVE_INFINITY))
(stream.dropWhitespace)
(let [&mut prompt "${arg.name} (${min}-${max}"
collectedNumbers []]
(when inStepsOf
(+= prompt " in steps of ${inStepsOf}"))
(+= prompt "):")
(localFunction :Void enterNumAgain []
(localFunction :Void trySubmit [number]
(stream.dropWhitespace)
(let [minMaxError
"The requested command expected numbers between $min and $max"
stepError
"$minMaxError in steps of $inStepsOf"
youEntered
". You entered: $number"]
(if (Math.isNaN number)
(continuation collectedNumbers)
(if (or
!(<= min number max)
(and inStepsOf !(= 0 (% (- number min) inStepsOf))))
(if inStepsOf
(ui.reportError "${stepError}$youEntered")
(ui.reportError "${minMaxError}$youEntered"))
{(collectedNumbers.push number)
(enterNumAgain)}))))
(if (or (stream.isEmpty) (stream.dropStringIf "_"))
// If no vartext argument was pre-supplied, use the ui for it
(ui.enterNumber
prompt
trySubmit
min
max
inStepsOf
true)
(trySubmit (readNumber stream))))
(enterNumAgain)))
(OneEntry
(ui.chooseEntry
"${arg.name}:"
archive
continuation))
((Entries min max)
(unless min (set min 1))
// TODO might want to optimize this O(n) count operation by pre-calculating it
(unless max (set max (count archive.entries)))
(ui.chooseEntries
"${arg.name}:"
archive
(lambda :Void [:Array<Entry> entries]
(if (or
(> min entries.length)
(< max entries.length))
(ui.reportError "The requested command expects between $min and $max entries. You chose: $entries.length")
(continuation entries)))
min
max))
(Position
(ui.choosePosition "${arg.name}:" continuation))
(never null)))
(method :Array<String> allTags [&opt :Array<Entry> entries]
(let [:Array<Entry> entries (or entries (collect (archive.entries.iterator)))
:Tags tags (new Map)]
(doFor e entries
(when (hasComponent e Tags)
(doFor =>tag _ (readComponent e Tags)
(dictSet tags tag 1))))
(sort (collect (tags.keys)))))
(method :Array<String> allSelectedTags []
(allTags _selectedEntries))
(method chooseFromTags [:CommandArgType type :Dynamic->Void cc &opt tagsToChooseFrom &opt tagsChosen]
(let [tagsToChooseFrom
(or tagsToChooseFrom
(concat ["CONFIRM"]
(case type
(TagsFromAll (concat ["DEFINE NEW TAG"] (allTags)))
(TagsFromSelected (allSelectedTags))
(never otherwise))))
tagsChosen (or tagsChosen [])]
(ui.chooseBetweenStrings
"Tags:"
tagsToChooseFrom
->:Void choice (case choice
("CONFIRM" (cc tagsChosen))
("DEFINE NEW TAG"
(ui.enterText "New tag (must be legal as a haxe var name):"
// TODO check lowercase valid symbol etc.
->:Void newTag {(tagsChosen.push newTag) (chooseFromTags type cc tagsToChooseFrom tagsChosen)}
Math.POSITIVE_INFINITY))
(other
(tagsToChooseFrom.remove other)
(tagsChosen.push other)
(chooseFromTags type cc tagsToChooseFrom tagsChosen))
(never null)))))
// TODO try catch and ui.reportError
// TODO maaaybe support escape sequences?
(function readString [:Stream stream]
(let [terminator
(case (stream.takeChars 1)
((Some "\"") "\"")
((Some "'") "'")
(otherwise (throw "string arg must start with \" or '")))]
(case (stream.takeUntilAndDrop terminator)
((Some s) s)
(otherwise (throw "string arg must end with $terminator")))))
// TODO try catch and ui.reportError
(function readNumber [:Stream stream]
(Std.parseFloat (case (stream.takeUntilOneOf [" "] true) ((Some f) f) (otherwise ""))))
(method :Void->Void _composeArgCollector [:Array<Dynamic> collectedArgs :CommandArg arg :Stream stream :Void->Void lastCollector]
(lambda :Void []
(_collectAndValidateArg arg stream ->:Void [:Dynamic argValue] {(collectedArgs.push argValue) (lastCollector)})))
(method :Void tryRunCommand [:String command &opt :Void->Void doAfter]
(let [parts (command.split " ")
commandName (parts.shift)
stream (Stream.fromString (parts.join " "))
lowerCommandName (commandName.toLowerCase)]
(if (commands.exists lowerCommandName)
(_runCommand (dictGet commands lowerCommandName) stream doAfter)
(ui.reportError "$commandName is not a valid command"))))
(method :Void tryRunCommands [:Array<String> commands]
(when commands
(tryRunCommand (commands.shift) ->:Void (tryRunCommands commands))))
(method :Void _runCommand [:Command command :Stream stream &opt :Void->Void doAfter]
(let [collectedArgs
[]
&mut lastCollector
(lambda []
(let [result (Reflect.callMethod null command.handler collectedArgs)]
(assert !(Prelude.isNull result) "Command implementation forgot to return a ChangeSet")
(set lastChangeSet (the ChangeSet result))
(when lastChangeSet
(doFor e lastChangeSet
(assert (and e (isEntry e)) "Lib function forgot to return the Entry that was modified"))
(doFor e lastChangeSet
(archive.refreshEntry e))
(ui.handleChanges archive lastChangeSet)
(archive.processSystems)
(when doAfter (doAfter)))))]
// To facilitate asynchronous arg input via UI, we need to construct an insanely complicated nested callback to give the UI
(doFor arg (reverse command.args)
(set lastCollector (_composeArgCollector collectedArgs arg stream lastCollector)))
(lastCollector)))
// TODO SelectedEntry and SelectedEntries functions should be stateful and use the actual
// selected entries automatically
(defMacro defCommand [name args &body body]
(let [argPairs
(groups (expList args) 2)
methodArgs
(for [name type] argPairs
(exprCase type
((exprOr SelectedEntry OneEntry) `:nat.Entry ,name)
((exprOr (SelectedEntries _ _) (Entries _ _)) `:Array<nat.Entry> ,name)
((Text _) `:String ,name)
((VarText _) `:Array<String> ,name)
(TagsFromAll `:Array<String> ,name)
(TagsFromSelected `:Array<String> ,name)
((Number _ _ _) `:Float ,name)
((Numbers _ _ _) `:Array<Float> ,name)
(Position `:Position ,name)))
commandArgs
(for [name type] argPairs
`(object name ,(symbolName name) type ,type))]
`{
(method ,name [,@methodArgs] ,@body)
// Preserve the capitalization of the command name for pretty help message
(commandNames.push ,(symbolName name))
// Store the command name without capitalization for forgiving call conventions
(dictSet commands ,(ReaderExp.StrExp (.toLowerCase (symbolNameValue name))) (object args [,@commandArgs] handler (the Function ,name)))
}))
(var :Array<String> commandNames [])
(method isSelected [:Entry e]
!(= -1 (_selectedEntries.indexOf e)))
(method getSelectedEntries []
(_selectedEntries.copy))
(prop &mut :PlaygroundSystem<Dynamic> playgroundSystem null)
(method :Void typeCommand []
(when ui.shortcutHandler (ui.shortcutHandler.cancel))
(ui.enterText
"Command:"
->command
(tryRunCommand command)
Math.POSITIVE_INFINITY))
// TODO typeShortcut
(defNew [&prop :Archive archive
&prop :ArchiveUI ui]
[&mut :Array<Entry> _selectedEntries []
&mut :ChangeSet lastChangeSet []
:Map<String,Command> commands (new Map)
:NameSystem nameSystem (new NameSystem)]
(set ui.controller this)
// Add systems!
(archive.addAndProcessSystem nameSystem ui)
(archive.addSystem (new RemarkableAPISystem))
(archive.addSystem (new WikipediaImageSystem))
(archive.addSystem (new ImageAttachmentSystem))
(archive.addAndProcessSystem (new KeyShortcutSystem this) ui)
(archive.addSystem (new DLSystem))
(archive.addSystem (new AutoStepperSystem))
(localFunction colorEqual [:nat.components.ColorI c1 :nat.components.ColorI c2]
(and (= c1.r c2.r) (= c1.g c2.g) (= c1.b c2.b) (= c1.a c2.a)))
(localFunction colorsContain [:Array<nat.components.ColorI> cs :nat.components.ColorI c1]
(doFor c2 cs
(when (colorEqual c2 c1)
(return true)))
(return false))
(localFunction addColorTagSystems [:Map<String,nat.components.ColorI> info]
(let [colors (collect (info.iterator))]
(doFor =>tagExp color info
(archive.addSystem (new TagSystem "ColorTagSystem{${tagExp}}" tagExp ->[archive e &opt ui]
(when (or !(hasComponent e ColorI) (colorsContain colors (readComponent e ColorI)))
(AddColorIRGBA [e] color.r color.g color.b color.a)))))))
(addColorTagSystems [
// Active: green
=>"(or active enabled)" (object r 0 g 255 b 0 a 255)
// Inactive: gray
=>"(or inactive disabled)" (object r 128 g 128 b 128 a 255)
// todo: orange
=>"todo" (object r 255 g 128 b 0 a 255)])
(whenLet [ps (ui.playgroundSystem)]
(set playgroundSystem ps)
(set ps.setupProcess true)
(archive.addAndProcessSystem ps)
(ps.switchPlaygroundKey (dictGet archive.playgrounds "default")))
(defCommand Help []
(ui.displayMessage
(+ "Available commands:\n"
(commandNames.join "\n"))) [])
(load "SelectionCommands.kiss")
(defCommand Rename [e SelectedEntry newName (Text null)]
(withWritableComponents archive e [name Name]
(set name newName))
[e])
(defCommand PrintSelectedEntries [entries (SelectedEntries 1 null)]
(doFor e entries (ui.displayMessage (archive.fullString e))) [])
(defCommand PrintComponent [entries (SelectedEntries 1 null)
componentType (Text null)]
(doFor e entries
(if (e.components.exists componentType)
(ui.displayMessage (dictGet e.components componentType))
(ui.displayMessage "Entry ${e.id} has no $componentType component"))) [])
(defCommand RemoveComponent [entries (SelectedEntries 1 null)
componentType (Text null)]
(for e entries
(withWritableEntry archive e
(e.components.remove componentType)
e)))
(defCommand CreateEntry [name (Text null)]
[(archive.createEntry ->e (addComponent archive e Name name))])
(defCommand CreateEntries [names (VarText null)]
// createEntry returns a list, so these lists must be flattened
(flatten (for name names
(CreateEntry name))))
(defCommand CreateTaggedEntry [tags TagsFromAll name (Text null)]
[(archive.createEntry ->e
{(addComponent archive e Name name)
(addTags archive e tags)})])
(defCommand CreateTaggedEntries [tags TagsFromAll names (VarText null)]
// createEntry returns a list, so these lists must be flattened
(flatten (for name names
(CreateTaggedEntry tags name))))
(defCommand CreateCircleEntry [tags (VarText null) radius (Number 0 null null)]
[(archive.createEntry ->e
{(addTags archive e tags)
(addComponent archive e Circle (objectWith radius))})])
(defCommand AddTags [entries (SelectedEntries 1 null)
tagsToAdd TagsFromAll]
(doFor e entries
(addTags archive e tagsToAdd))
entries) // TODO this includes entries that already had the tag in the changeset
(defCommand RemoveTags [entries (SelectedEntries 1 null) tagsToRemove TagsFromSelected]
(doFor e entries
(removeTags archive e tagsToRemove))
entries) // TODO this includes entries that didn't have the tag in the changeset
(defCommand AddRectangle [entries (SelectedEntries 1 null)
width (Number 0 null null)
height (Number 0 null null)]
(doFor e entries
(addComponent archive e Rectangle (objectWith width height)))
entries)
(defCommand CreateRectangleEntry [p1 Position p2 Position]
[(archive.createEntry ->e
(let [x (min p1.x p2.x)
y (min p1.y p2.y)
w (- (max p1.x p2.x) x)
h (- (max p1.y p2.y) y)]
(addComponent archive e Positions [=>(archive.currentPlayground) (objectWith [z 0.0] x y)])
(addComponent archive e Rectangle (object width w height h))))])
(defCommand AddDLURL [e SelectedEntry url (Text null)]
[(addComponent archive e DLURL url)])
(defCommand AddYoutubeMusic [name (Text null) url (Text null)]
[(archive.createEntry ->e
{(addComponent archive e Name name)
(addTags archive e ["music"])
(AddDLURL e url)})])
(defCommand AddKeyShortcut [e SelectedEntry description (Text null)]
(addComponent archive e KeyShortcut description))
(defCommand AddNATCommand [e (SelectedEntries null null) command (Text null)]
(doFor e e (addComponent archive e NATCommand command)))
(defCommand AddNATCommands [e (SelectedEntries null null) commands (VarText null)]
(doFor e e (addComponent archive e NATCommands commands)))
(defCommand CreateShortcutEntry [description (Text null) command (Text null)]
[(archive.createEntry ->e {
(addComponent archive e Name description)
(AddKeyShortcut e description)
(AddNATCommand [e] command)})])
(defCommand CreateMultiCommandShortcut [description (Text null) commands (VarText null)]
[(archive.createEntry ->e {
(addComponent archive e Name description)
(AddKeyShortcut e description)
(AddNATCommands [e] commands)})])
(defCommand AddFiles [entries (SelectedEntries 1 null)
// TODO add File and Files as an argument type for commands, ArchiveUI
// TODO make tkinter file browser externs and use tkinter as the file picking mechanism for CLI
files (VarText null)]
(doFor e entries
(addFiles archive e files))
entries)
(method adjustImagePins [:Array<Entry> entries increment]
(doFor e entries
(if (hasComponent e Images2)
(withWritableComponents archive e [images Images2]
(set images.pinnedImageIndex (max 0 (min (- images.imageFiles.length 1) (+ increment images.pinnedImageIndex)))))
(ui.reportError "Entry $e has no Images2 component")))
entries)
(defCommand PinNextImage [entries (SelectedEntries 1 null)]
(adjustImagePins entries 1))
(defCommand PinPreviousImage [entries (SelectedEntries 1 null)]
(adjustImagePins entries -1))
(defCommand SetScale [entries (SelectedEntries 1 null) scale (Number 0 null null)]
(doFor e entries
(cond
((hasComponent e Images2)
(withWritableComponents archive e [i2 Images2]
(setNth i2.imageScales i2.pinnedImageIndex scale)))
((hasComponent e Scale)
(withWritableComponents archive e [scaleComponent Scale]
(set scaleComponent scale)))
(true (addComponent archive e Scale scale))))
entries)
(defCommand CreatePlayground [name (Text null) catsMatchExp (Text null) defaultTags TagsFromAll]
(archive.changePlaygrounds ->:Void [:DynamicAccess<Dynamic> p]
(dictSet p name (object catsMatch catsMatchExp)))
(let [[e] (CreateTaggedEntry ["playground"] name)]
(addComponent archive e CatsMatchExp catsMatchExp)
(addComponent archive e TagList defaultTags)
[e]))
(defCommand SwitchPlayground [name (Text null)]
(archive.changePlaygrounds ->:Void [:DynamicAccess<Dynamic> p] (dictSet p "default" name))
(SelectEntries [])
(when playgroundSystem (playgroundSystem.switchPlaygroundKey name))
[])
(defCommand ChoosePlayground []
(ui.chooseBetweenStrings
"Choose a playground:"
(sort (for =>key _ archive.playgrounds (if (= key "default") (continue) key)))
->pg (SwitchPlayground pg))
[])
(defCommand AddConnections [entries (SelectedEntries 1 null) entriesToConnect (Entries 1 null)]
(for e entries
(addConnections archive e entriesToConnect)))
(defCommand RemoveConnections [entries (SelectedEntries 1 null) entriesToRemove (Entries 1 null)]
(for e entries
(addConnections archive e entriesToRemove)))
(defCommand AddColorFRGBA [entries (SelectedEntries 1 null) r (Number 0 1 null) g (Number 0 1 null) b (Number 0 1 null) a (Number 0 1 null)]
(for e entries
(addColorFRGBA archive e r g b a)))
(defCommand AddColorIRGBA [entries (SelectedEntries 1 null) r (Number 0 255 1) g (Number 0 255 1) b (Number 0 255 1) a (Number 0 255 1)]
(for e entries
(addColorIRGBA archive e (Std.int r) (Std.int g) (Std.int b) (Std.int a))))
(defCommand VibeCheck [accounts (Numbers null null null) monthlyExpenses (Numbers null null null) energy (Number 1 10 1) hope (Number 1 10 1) note (Text null)]
[(archive.createEntry ->e {
(let [nw (apply + accounts)
me (apply + monthlyExpenses)
runway (/ nw me)]
(ui.displayMessage "Your net worth is \$$nw")
(if (< nw 0)
(ui.displayMessage "You are in debt and spending \$$me per month.")
(ui.displayMessage "It will last for roughly $runway months!")))
(addComponent archive e VibeCheck (objectWith [energy (Std.int energy) hope (Std.int hope)] accounts monthlyExpenses note))
(addComponent archive e Dates [=>"Created" (Date.now)])
})])
)

View File

@@ -1,83 +0,0 @@
package nat;
import nat.Entry;
import nat.ArchiveController;
import kiss_tools.KeyShortcutHandler;
import nat.systems.PlaygroundSystem;
import haxe.ds.Option;
import nat.components.Position;
interface ArchiveUI {
/**
* Reference to the ArchiveController
*/
var controller(default, default):ArchiveController;
/**
* A KeyShortcutHandler that will integrate with the KeyShortcutSystem if provided
*/
var shortcutHandler(default, null):Null<KeyShortcutHandler<Entry>>;
function showPrefixMap(map:Map<String,String>):Void;
function hidePrefixMap():Void;
/**
* A PlaygroundSystem that will display interactible entry representations
*/
function playgroundSystem():Null<PlaygroundSystem<Dynamic>>;
/**
* Prompt the user to enter text
*/
function enterText(prompt:String, resolve:(String) -> Void, maxLength:Float):Void;
/**
* Prompt the user to enter a number
*/
function enterNumber(prompt:String, resolve:(Float) -> Void, min:Float, max:Float, ?inStepsOf:Float, ?allowNaN:Bool):Void;
/**
* Prompt the user to choose a single Entry
*/
function chooseEntry(prompt:String, archive:Archive, resolve:(Entry) -> Void):Void;
/**
* Prompt the user to choose multiple Entries
*/
function chooseEntries(prompt:String, archive:Archive, resolve:(Array<Entry>) -> Void, min:Int, max:Float):Void;
/**
* Update the interface to reflect changes made to Entries through commands
*/
function handleChanges(archive:Archive, changeSet:ChangeSet):Void;
/**
* Tell the user something useful
*/
function displayMessage(message:String):Void;
/**
* Tell the user that something is wrong
*/
function reportError(error:String):Void;
/**
* Update UI to show that the set of selected entries has changed
*/
function onSelectionChanged(selectedEntries:Array<Entry>, lastSelectedEntries:Array<Entry>):Void;
/**
* Prompt the user to choose a position
*/
function choosePosition(prompt:String, resolve:Position->Void):Void;
/**
* A way to tell NAT where the cursor is
*/
function cursorPosition():Option<Position>;
/**
* Prompt the user between some string options
*/
function chooseBetweenStrings(prompt:String, choices:Array<String>, resolve:String->Void):Void;
}

View File

@@ -1,19 +0,0 @@
package nat;
import kiss.KissInterp;
import kiss.Prelude;
@:build(kiss.Kiss.build())
class BoolExpInterp extends KissInterp {
public function new() {
super();
}
override function resolve(id:String):Dynamic {
return try {
super.resolve(id);
} catch (e:Dynamic) {
false;
}
}
}

View File

@@ -1,5 +0,0 @@
(function eval [:String expStr :Array<String> activeConditions]
(let [interp (new BoolExpInterp)]
(doFor condition activeConditions
(interp.variables.set condition true))
?(interp.evalKiss expStr)))

View File

@@ -1,7 +0,0 @@
package nat;
class CLI {
static function main() {
CLI_.main();
}
}

View File

@@ -1,128 +0,0 @@
(import sys.FileSystem)
(import nat.ArchiveController)
(import nat.systems.PlaygroundSystem)
(importAll nat.components)
(import haxe.ds.Option)
(implements nat.ArchiveUI)
// External programs can load Lib.kiss with (loadFrom "nat-archive-tool" "src/nat/Lib.kiss")
(load "Lib.kiss")
(let [[archiveDir] (Sys.args)]
(unless (= "_TEST_" archiveDir)
(let [controller
(new ArchiveController
(new Archive archiveDir)
(new CLI_))]
(loop
(Sys.print ">> ")
(let [command
(.trim (.toString (.readLine (Sys.stdin))))]
(controller.tryRunCommand command))))))
(prop &mut :ArchiveController controller)
(prop :kiss_tools.KeyShortcutHandler<Entry> shortcutHandler null)
(defNew [])
(method :Void enterText [prompt :String->Void resolve maxLength]
(Sys.print "$prompt ")
(loop
(let [entered (.toString (.readLine (Sys.stdin)))]
(if !(<= entered.length maxLength)
(Sys.print "Try again? ")
{(resolve entered)
(break)}))))
(method :Void enterNumber [prompt :Float->Void resolve :Float min :Float max &opt :Float inStepsOf :Bool allowNaN]
(Sys.print "$prompt ")
(loop
(let [entered (Std.parseFloat (.toString (.readLine (Sys.stdin))))]
(if
(and (or !allowNaN !(Math.isNaN entered))
(or
!(<= min entered max)
(and inStepsOf !(= 0 (% (- entered min) inStepsOf)))))
(Sys.print "Try again? ")
{(resolve entered)
(break)}))))
(method :Void chooseEntry [prompt :Archive archive :Entry->Void resolve]
(_chooseEntry prompt archive resolve ->(chooseEntry "empty name doesn't match any entries. Try again?" archive resolve)))
(method :Void _chooseEntry [prompt :Archive archive :Entry->Void resolve :Void->Void onEmptyString]
// TODO allow narrowing down with a tag string
(enterText "entry name for $prompt"
->:Void name {
(if !name
(onEmptyString)
(let [matchingEntries (controller.nameSystem.getEntries name)]
(case (the Array<Entry> matchingEntries)
([e] (resolve e))
([] (chooseEntry "name $name doesn't match any entries. Try again?" archive resolve))
// TODO disambiguate entries with the same names by listing stringified versions of them and using enterNumber
(multipleEntries (throw "ambiguous between multiple entries"))
(otherwise))))}
Math.POSITIVE_INFINITY))
(method :Void chooseEntries [prompt archive :Array<nat.Entry>->Void resolve min max]
(_chooseEntries prompt archive resolve min max []))
(method :Void _chooseEntries [prompt archive :Array<nat.Entry>->Void resolve min max :Array<Entry> collectedEntries]
(let [onEmptyString
->:Void (if (<= min collectedEntries.length)
(resolve collectedEntries)
(throw "not enough entries chosen"))
&mut :Void->Void chooseNextEntry
null
_chooseNextEntry
->:Void {(_chooseEntry
prompt
archive
->:Void e {(collectedEntries.push e)
// If the maximum is reached, return it
(if (= max collectedEntries.length)
(resolve collectedEntries)
// Otherwise, recurse
(chooseNextEntry))}
onEmptyString)}]
(set chooseNextEntry _chooseNextEntry)
(_chooseNextEntry)))
(method handleChanges [:Archive archive :ChangeSet changeSet]
(archive.processSystems this)
(doFor e changeSet
(print (archive.fullString e))))
(method :Void displayMessage [message]
(print message))
(method :Void reportError [error]
(print error))
(method :Void onSelectionChanged [:Array<Entry> selectedEntries :Array<Entry> _]
(print "Selected:")
(controller.PrintSelectedEntries selectedEntries))
(method :Void chooseBetweenStrings [prompt :Array<String> choices :String->Void resolve]
(print prompt)
(doFor [idx choice] (enumerate choices)
(print "$(+ idx 1). $choice"))
(enterNumber "Choice" ->num (resolve (nth choices (- (Std.int num) 1))) 1 choices.length 1))
(defAlias &ident neg Math.NEGATIVE_INFINITY)
(defAlias &ident pos Math.POSITIVE_INFINITY)
(method :Void choosePosition [prompt :Position->Void resolve]
(enterNumber "x" ->x (enterNumber "y" ->y (enterNumber "z" ->z (resolve (objectWith x y z)) neg pos) neg pos) neg pos))
(method :Option<Position> cursorPosition [] None)
(method :Void showPrefixMap [:Map<String,String> map]
(doFor =>key thing map
(print "$key - $thing")))
(method :Void hidePrefixMap [])
(method :PlaygroundSystem<String> playgroundSystem [] null)

View File

@@ -1,18 +0,0 @@
package nat;
import uuid.Uuid;
@:jsonParse(function (json) return new nat.Entry(json.id, json.components, json.files))
class Entry {
public var id:String;
public var components:Map<String, String> = [];
public var files:Array<FileRef> = [];
function toString() {
return if (components.exists("Name")) components["Name"] else 'entry $id';
}
public function new(?id:String, ?components:Map<String,String>, ?files:Array<String>) {
this.id = if (id != null) id else Uuid.v4();
if (components != null) this.components = components;
if (files != null) this.files = files;
}
}

View File

@@ -1,3 +0,0 @@
package nat;
typedef EntryRef = String;

View File

@@ -1,3 +0,0 @@
package nat;
typedef FileRef = String;

View File

@@ -1,11 +0,0 @@
package nat;
import kiss.Prelude;
import sys.io.File;
import tink.Json;
import uuid.Uuid;
using haxe.io.Path;
@:build(kiss.Kiss.build())
class Lib {}

View File

@@ -1,171 +0,0 @@
// Lib is its own class because, while it would make sense to group its functions and macros in Archive.kiss,
// other files would not be able to (load "Archive.kiss") for the macro definitions without taking on Archive's constructor.
// External programs can load Lib.kiss with (loadFrom "nat-archive-tool" "src/nat/Lib.kiss")
(function _log [msg]
(#when (or test debug) (print msg)))
(defMacro log [ui msg]
(withEvalOnce [ui msg]
(when ui
(ui.displayMessage msg))
(_log msg)))
(defMacro hasComponent [e componentType]
`(.exists .components ,e ,(symbolName componentType)))
// Changes to the object returned by (readComponent) will not be saved! Use (withWritableComponents) for making changes
(defMacro readComponent [e componentType]
`(let [componentData (dictGet (the Map<String,String> .components ,e) ,(symbolName componentType))]
// (log null (+ "reading " componentData " as " ,(symbolName componentType) " for " .id ,e))
(the nat.components ,componentType
// TODO add to the documentation a hint that macros should use fully qualified type paths so macro caller classes don't need to import everything
(tink.Json.parse componentData))))
// Return either the desired component, or def if no such component exists
(defMacro readComponentOr [e componentType def]
(withEvalOnce [e]
(if (hasComponent e ,componentType)
(readComponent e ,componentType)
,def)))
// TODO check not overwriting a component
(defMacro addComponent [archive e componentType c]
(withEvalOnce [archive e c]
(withWritableEntry archive e
(log null (+ "adding " (the nat.components ,componentType c) " as " ,(symbolName componentType) " for " e.id))
(dictSet e.components ,(symbolName componentType) (tink.Json.stringify (the nat.components ,componentType c)))
e)))
(defMacro removeComponent [archive e componentType]
(withEvalOnce [archive e]
(withWritableEntry archive e
(log null (+ "removing " ,(symbolName componentType) " component from " e.id))
(e.components.remove ,(symbolName componentType))
e)))
// Retrieve multiple components from an Entity with mutable access.
// All components will be serialized after the block is done.
(defMacro withWritableComponents [archive e bindings &body body]
(let [bindingPairs
(groups (expList bindings) 2 Throw)
bindingList
[]
saveList
[]
retValSymbol
(symbol)]
(doFor [name type] bindingPairs
(bindingList.push `&mut ,name)
(bindingList.push `(readComponent ,e ,type))
(saveList.push `(dictSet .components ,e ,(symbolName type) (tink.Json.stringify (the nat.components ,type ,name)))))
`(let [,@bindingList
,retValSymbol {,@body}]
,@saveList
(.refreshEntry ,archive ,e) // Check the entry in and out of systems when its components change
,retValSymbol)))
(defMacro withWritableEntry [archive e &body body]
(let [retValSymbol
(symbol)]
`(let [,retValSymbol {,@body}]
(.refreshEntry ,archive ,e)
,retValSymbol)))
// Create a system that selects Entries according to a single string component (i.e. Name or Author) matching the given value
(defMacro stringComponentSystem [componentType value process]
`(new System
(lambda [archive :nat.Entry e]
?(and (hasComponent e ,componentType)
(= ,value (readComponent e ,componentType))))
,process))
(function :Array<String> tagList [:nat.Entry e]
(if (hasComponent e Tags)
(let [t (readComponent e Tags)]
(collect (t.keys)))
[]))
(function :Array<String> componentList [:nat.Entry e]
(for =>cType cId e.components cType))
(function tagsMatch [e tagsBoolExp]
(nat.BoolExpInterp.eval tagsBoolExp (tagList e)))
(function componentsMatch [:nat.Entry e componentsBoolExp]
(nat.BoolExpInterp.eval componentsBoolExp (componentList e)))
(function componentsAndTagsMatch [:nat.Entry e componentsAndTagsBoolExp]
(nat.BoolExpInterp.eval componentsAndTagsBoolExp (cast (concat (tagList e) (componentList e)))))
(defAlias &call catsMatch componentsAndTagsMatch)
(function addFiles [:nat.Archive archive :nat.Entry e :Array<String> files &opt leaveOriginalCopy]
(withWritableEntry archive e
(doFor file files
(let [pathWithoutDir (haxe.io.Path.withoutDirectory file)]
(unless (contains e.files pathWithoutDir)
(let [pathInArchive (joinPath archive.archiveDir "files" pathWithoutDir)]
(unless (sys.FileSystem.exists pathInArchive)
((if leaveOriginalCopy sys.io.File.copy sys.FileSystem.rename)
file pathInArchive)))
(e.files.push pathWithoutDir))))))
(function removeFiles [:nat.Archive archive :nat.Entry e :Array<String> files]
(withWritableEntry archive e
(doFor file files
(e.files.remove file))))
(function addTags [:nat.Archive archive :nat.Entry e :Array<String> tagsToAdd]
(if (hasComponent e Tags)
(withWritableComponents archive e [tags Tags]
(doFor tag tagsToAdd (dictSet tags tag 1)))
(addComponent archive e Tags (for tag tagsToAdd =>tag 1))))
(function removeTags [:nat.Archive archive :nat.Entry e :Array<String> tagsToRemove]
(when (hasComponent e Tags)
(withWritableComponents archive e [tags Tags]
(doFor tag tagsToRemove (tags.remove tag)))))
(function :Float getScale [:nat.Entry e]
(if (hasComponent e Images2)
(let [i2 (readComponent e Images2)]
(nth i2.imageScales i2.pinnedImageIndex))
(if (hasComponent e Scale)
(readComponent e Scale)
1.0)))
(function addConnections [:nat.Archive archive :nat.Entry e :Array<nat.Entry> entriesToConnect]
(if (hasComponent e Connections)
(withWritableComponents archive e [conn Connections]
(doFor e2 entriesToConnect (dictSet conn e2.id 1)))
(addComponent archive e Connections (for e2 entriesToConnect =>e2.id 1)))
e)
(function removeConnections [:nat.Archive archive :nat.Entry e :Array<nat.Entry> entriesToRemove]
(when (hasComponent e Connections)
(withWritableComponents archive e [conn Connections]
(doFor e2 entriesToRemove (conn.remove e2.id))))
e)
(function colorIFromF [:nat.components.ColorF cf]
(object r (Std.int (* 255 cf.r)) g (Std.int (* 255 cf.g)) b (Std.int (* 255 cf.b)) a (Std.int (* 255 cf.a))))
(function colorFFromI [:nat.components.ColorI ci]
(object r (/ ci.r 255.0) g (/ ci.g 255.0) b (/ ci.b 255.0) a (/ ci.a 255)))
(function addColorFRGBA [:nat.Archive archive :nat.Entry e :Float r :Float g :Float b :Float a]
(let [cf (objectWith r g b a)]
(addComponent archive e ColorF cf)
(addComponent archive e ColorI (colorIFromF cf))))
(function addColorIRGBA [:nat.Archive archive :nat.Entry e :Int r :Int g :Int b :Int a]
(let [ci (objectWith r g b a)]
(addComponent archive e ColorI ci)
(addComponent archive e ColorF (colorFFromI ci))))
(function isEntry [o]
(let [fields (Reflect.fields o)]
(and (= fields.length 3)
(apply and (for f ["id" "components" "files"] (contains fields f))))))

View File

@@ -1,84 +0,0 @@
// Every command that can select entries has variants that can toggleSelect,
// addSelect or deSelect instead of setting the selection directly
// TODO The three varations of selection are all O(n) when they would't need to be if _selectedEntries was a Map
// TODO these commands could avoid calling onSelectionChanged if they don't actually modify the selection
(method selectionCommand [:Array<Entry> entries]
(let [lastSelectedEntries _selectedEntries]
(set _selectedEntries entries)
(ui.onSelectionChanged entries lastSelectedEntries)) [])
(method addSelectionCommand [:Array<Entry> entries]
(let [lastSelectedEntries (_selectedEntries.copy)]
(doFor e entries
(unless (_selectedEntries.contains e)
(_selectedEntries.push e)))
(ui.onSelectionChanged _selectedEntries lastSelectedEntries)) [])
(method deSelectionCommand [:Array<Entry> entries]
(let [lastSelectedEntries (_selectedEntries.copy)]
(doFor e entries
(_selectedEntries.remove e))
(ui.onSelectionChanged _selectedEntries lastSelectedEntries)) [])
(method toggleSelectionCommand [:Array<Entry> entries]
(let [lastSelectedEntries (_selectedEntries.copy)]
(doFor e entries
(unless (_selectedEntries.remove e)
(_selectedEntries.push e)))
(ui.onSelectionChanged _selectedEntries lastSelectedEntries)) [])
// Define all 4 variants of the command that selects according to the behavior in body
(defMacro defSelectCommand [name args &body body]
(let [nameStr (symbolNameValue name)
addName (symbol "Add$nameStr")
deSelectName (symbol "De$nameStr")
toggleName (symbol "Toggle$nameStr")]
`{
(defCommand ,name ,args
(selectionCommand {,@body}))
(defCommand ,addName ,args
(addSelectionCommand {,@body}))
(defCommand ,deSelectName ,args
(deSelectionCommand {,@body}))
(defCommand ,toggleName ,args
(toggleSelectionCommand {,@body}))
}))
(defSelectCommand SelectEntry [e OneEntry]
[e])
(defSelectCommand SelectEntries [entries (Entries null null)]
entries)
(defSelectCommand SelectAllEntries []
(for =>id e archive.entries e))
(defSelectCommand SelectById [id (Text null)]
(filter [(dictGet archive.entries id)]))
(defSelectCommand SelectLastChangeSet []
lastChangeSet)
(defSelectCommand SelectByTags [tagsBoolExp (Text null)]
(filter archive.entries ->e (tagsMatch e tagsBoolExp)))
// variations of SelectByTags that take input from TagsFromAll, not a tagsBoolExp:
// TODO if we're being really picky these would want a variation of TagsFromAll where DEFINE NEW TAG is not an option :)
// TODO SelectByTagsAnd
// TODO SelectByTagsOr
(defSelectCommand SelectByComponents [componentsBoolExp (Text null)]
(filter archive.entries ->e (componentsMatch e componentsBoolExp)))
// TODO selectByCats
// there is currently no easy way to defAlias for every variation of a selection command,
// so Cats may be the canonical name
(defSelectCommand SelectByName [name (Text null)]
(nameSystem.getEntries name))

View File

@@ -1,9 +0,0 @@
package nat;
import kiss.Prelude;
typedef EntryChecker = (Archive, Entry) -> Bool;
typedef EntryProcessor = (Archive, Entry, ?ArchiveUI) -> Dynamic; // Whatever value is returned will be dropped, but this is easier than requiring ->:Void
@:build(kiss.Kiss.build())
class System {}

View File

@@ -1,20 +0,0 @@
(prop :Map<String,Entry> entries (new Map))
(method :Void process [:Archive archive &opt :ArchiveUI ui]
(doFor e (entries.iterator)
(print "${name} processing ${e.id}")
(processEntry archive e ui)))
(defNew [&prop :String name
&prop :EntryChecker canProcessEntry
&prop :EntryProcessor processEntry]
[])
(prop &mut :Null<EntryProcessor> onRemoveEntry)
(method :Void checkEntryInOrOut [:Archive archive :Entry e]
(if (canProcessEntry archive e)
(dictSet entries e.id e)
(when (entries.exists e.id)
(entries.remove e.id)
(when onRemoveEntry (onRemoveEntry archive e)))))

View File

@@ -1,3 +0,0 @@
package nat.components;
typedef Author = String;

View File

@@ -1,3 +0,0 @@
package nat.components;
typedef CatsMatchExp = String;

View File

@@ -1,5 +0,0 @@
package nat.components;
typedef Circle = {
radius:Float
};

View File

@@ -1,8 +0,0 @@
package nat.components;
typedef ColorF = {
r:Float,
g:Float,
b:Float,
a:Float
};

View File

@@ -1,8 +0,0 @@
package nat.components;
typedef ColorI = {
r:Int,
g:Int,
b:Int,
a:Int
};

View File

@@ -1,3 +0,0 @@
package nat.components;
typedef Connections = Map<EntryRef,Int>;

View File

@@ -1,3 +0,0 @@
package nat.components;
typedef DLURL = String;

View File

@@ -1,3 +0,0 @@
package nat.components;
typedef Dates = Map<String, Date>;

View File

@@ -1,6 +0,0 @@
package nat.components;
typedef Images = {
imageFiles:Array<FileRef>,
pinnedImageIndex:Int
};

View File

@@ -1,7 +0,0 @@
package nat.components;
typedef Images2 = {
imageFiles:Array<FileRef>,
imageScales:Array<Float>,
pinnedImageIndex:Int
};

View File

@@ -1,3 +0,0 @@
package nat.components;
typedef KeyShortcut = String;

View File

@@ -1,3 +0,0 @@
package nat.components;
typedef NATCommand = String;

View File

@@ -1,3 +0,0 @@
package nat.components;
typedef NATCommands = Array<NATCommand>;

View File

@@ -1,3 +0,0 @@
package nat.components;
typedef Name = String;

View File

@@ -1,3 +0,0 @@
package nat.components;
typedef Position = {x:Float, y:Float, z:Float};

View File

@@ -1,7 +0,0 @@
package nat.components;
/**
* Entries can have multiple positions in different UIs/folders/whatever.
*/
typedef Positions = Map<String, Position>;

View File

@@ -1,6 +0,0 @@
package nat.components;
typedef Rectangle = {
width:Float,
height:Float
}

View File

@@ -1,3 +0,0 @@
package nat.components;
typedef Scale = Float;

View File

@@ -1,3 +0,0 @@
package nat.components;
typedef TagList = Array<String>;

View File

@@ -1,3 +0,0 @@
package nat.components;
typedef Tags = Map<String, Int>;

View File

@@ -1,9 +0,0 @@
package nat.components;
typedef VibeCheck = {
accounts: Array<Float>,
monthlyExpenses: Array<Float>,
energy: Int,
hope: Int,
note: String
};

View File

@@ -1,17 +0,0 @@
package nat.systems;
import kiss.Prelude;
import kiss.List;
import nat.System;
import haxe.Json;
using haxe.io.Path;
typedef AttachmentProcessor = (Archive, Entry, Array<FileRef>, ?ArchiveUI) -> Dynamic;
/**
* Base System that processes Entries based on whether they have file attachments
* which match a given set of extensions
*/
@:build(kiss.Kiss.build())
class AttachmentSystem extends System {}

View File

@@ -1,18 +0,0 @@
(load "../Lib.kiss")
(defNew [:String name
:Array<String> _extensions
:AttachmentProcessor processor]
[:Array<String> extensions (for extension _extensions (extension.toLowerCase))]
(super
name
->[archive e]
{
(doFor file e.files
(when !(= -1 (extensions.indexOf (.toLowerCase (file.extension))))
(return true)))
false
}
->[archive e &opt ui]
(processor archive e (filter e.files ->file !(= -1 (extensions.indexOf (file.extension)))) ui)))

View File

@@ -1,18 +0,0 @@
package nat.systems;
import kiss.Prelude;
import kiss.List;
import nat.System;
import haxe.Json;
#if target.threaded
import sys.thread.Thread;
#end
using haxe.io.Path;
/**
* Base System that processes Entries based on whether they have file attachments
* which match a given set of extensions
*/
@:build(kiss.Kiss.build())
class AutoStepperSystem extends AttachmentSystem {}

View File

@@ -1,28 +0,0 @@
(load "../Lib.kiss")
(defNew []
[:String jarPath (joinPath (libPath "nat-archive-tool") "apps/autostepper/AutoStepper.jar")]
(super
"AutoStepperSystem"
["mp3"]
->[archive e mp3Files &opt ui]
(unless (tagsMatch e "stepperProcessed")
(doFor file mp3Files
(localFunction :Void runAutoStepper []
(try
{
(ui.displayMessage "autoStepping $file")
```
java -jar "${jarPath}" input="$(archive.filePath file)" duration=130 hard=true
```
(ui.displayMessage "done autostepping $file")
(addTags archive e ["stepperProcessed"])
}
(catch [e] (ui.displayMessage "failed autostepping $file"))))
(#if target.threaded
(Thread.create runAutoStepper)
{
(ui.displayMessage "threading unavailable -- the program will freeze while autostepping")
(runAutoStepper)
})))))

View File

@@ -1,12 +0,0 @@
package nat.systems;
import kiss.Prelude;
import kiss.List;
import nat.System;
using StringTools;
#if target.threaded
import sys.thread.Thread;
#end
@:build(kiss.Kiss.build())
class DLSystem extends System {}

View File

@@ -1,48 +0,0 @@
(load "../Lib.kiss")
(defNew []
// Check if youtube-dl is installed before doing anything
(let [&mut hasYTDL false]
(tryProcess "youtube-dl" [] ->error (when (contains error "You must provide at least one URL") (set hasYTDL true)))
(super
"DLSystem"
->[archive e]
(and hasYTDL (catsMatch e "(unless dlProcessed DLURL)"))
->[archive e &opt ui]
(let [basename "$(readComponentOr e Name (uuid))-DL"
o "\"${basename}.%(ext)s\""
o (if (= (Sys.systemName) "Windows")
(o.replace "%" "%%")
o)
url (readComponent e DLURL)]
(cond
((tagsMatch e "music")
// TODO put active dl processes in a map and
// don't start new ones when re-processing
(localFunction :Void downloadMp3 []
(try
{
(ui.displayMessage "downloading $url as $basename")
```
youtube-dl -x --audio-format mp3 -o $o $url
```
(ui.displayMessage "done downloading $basename")
(addFiles archive e ["${basename}.mp3"])
(addTags archive e ["dlProcessed"]
}
(catch [e] (ui.displayMessage "failed downloading $basename"))))
(#if target.threaded
(Thread.create downloadMp3)
{
(ui.displayMessage "threading unavailable -- the program will freeze while downloading with youtube-dl")
(downloadMp3)
null
}))
(true
(log ui "DLSystem doesn't know what to do with $(readComponent e Tags)")
(return null)))
))))

View File

@@ -1,8 +0,0 @@
package nat.systems;
import kiss.Prelude;
import kiss.List;
using StringTools;
@:build(kiss.Kiss.build())
class ImageAttachmentSystem extends AttachmentSystem {}

View File

@@ -1,44 +0,0 @@
(load "../Lib.kiss")
(defNew []
(super
"ImageAttachmentSystem"
["jpg" "jpeg" "png" "svg"]
->[archive e imageFiles &opt ui]
(unless (upgradeToVersion2 archive e)
// TODO an edge case exists when more image files are added to an Entry
// after it is assigned an Images component. The new files won't be added
(unless (hasComponent e Images2)
(addComponent archive e Images2
(object
imageFiles imageFiles
imageScales (for _ (range imageFiles.length) 1.0)
pinnedImageIndex 0))))))
// Retrofit Images components into Images2 components,
// which can track a separate scale value for each image.
// Also, remove text image files -- now that text sprites
// are generated on the fly.
(function :Bool upgradeToVersion2 [:nat.Archive archive :nat.Entry e]
(if (hasComponent e Images)
(let [images1 (readComponent e Images)
scale (readComponentOr e Scale 1.0)
pIdx images1.pinnedImageIndex
textImageFiles (filter images1.imageFiles ->[:String f] (f.startsWith "textImage"))]
(removeComponent archive e Images)
(removeFiles archive e textImageFiles)
(doFor f textImageFiles (images1.imageFiles.remove f))
// If all images were removed (the entry only had a text image), don't add Images2
(unless images1.imageFiles (return true))
(addComponent archive e Images2
(object
imageFiles images1.imageFiles
imageScales (cast (concat
(for _ (range pIdx) 1.0)
[scale]
(for _ (range (- images1.imageFiles.length 1 pIdx)) 1.0)))
pinnedImageIndex pIdx))
(removeComponent archive e Scale)
true)
false))

View File

@@ -1,7 +0,0 @@
package nat.systems;
import kiss.Prelude;
import kiss.List;
@:build(kiss.Kiss.build())
class KeyShortcutSystem extends System {}

View File

@@ -1,37 +0,0 @@
(load "../Lib.kiss")
(prop :Map<String,Bool> descriptions (new Map))
(defNew [&prop :ArchiveController controller]
[&mut :Bool setup false]
(super
"KeyShortcutSystem"
->[archive e]
(hasComponent e KeyShortcut)
->[archive e &opt ui]
{
(when (and ui ui.shortcutHandler)
(unless setup
(set ui.shortcutHandler.onSelectPrefixMap ->:Void [_ map] (ui.showPrefixMap map))
(set ui.shortcutHandler.onSelectItem
->e {
(ui.hidePrefixMap)
(invokeEntry archive ui e)
})
(set ui.shortcutHandler.onBadKey ->[key map] (ui.displayMessage "$key is not mapped to a shortcut in this context: $map"))
(set setup true))
(unless (descriptions.exists (readComponent e KeyShortcut))
(ui.shortcutHandler.registerItem (readComponent e KeyShortcut) e)
(dictSet descriptions (readComponent e KeyShortcut) true)))
0
}))
(method invokeEntry [archive ui :Entry e]
// TODO make this doCond
(cond
((hasComponent e NATCommand)
(controller.tryRunCommand (readComponent e NATCommand)) 0)
((hasComponent e NATCommands)
(controller.tryRunCommands (readComponent e NATCommands)) 0)
(true (ui.displayMessage "tried to invoke ${e.id} but it has no available actions"))) 0)

View File

@@ -1,13 +0,0 @@
package nat.systems;
import kiss.Prelude;
import kiss.List;
import nat.System;
import haxe.Json;
import haxe.ds.Option;
/**
* Base System that processes Entries using the HTTP API for any wiki built with MediaWiki
*/
@:build(kiss.Kiss.build())
class MediaWikiSystem extends System {}

View File

@@ -1,67 +0,0 @@
(load "../Lib.kiss")
(defNew [:String name
&prop :String mediaWikiUrl
// TODO make a &super annotation that passes an argument to the super constructor
:EntryChecker canProcess
:EntryProcessor processor
&prop :Null<Float> maxLag]
(super
name
canProcess
processor))
// TODO make this an externMethod --
// but mediaWikiUrl, headers, and maxLag will still have to be specified, not as args
// unless all vars and props are passed to externmethods by default
(method :Option<Dynamic> query [:Map<String,Array<String>> params]
(let [data
(Json.parse
(#extern String python
(object
hxmlFile "extern-files/python/args.hxml"
langProjectFile "extern-files/python/requirements.txt")
[:Map<String,Array<String>> params _ :String mediaWikiUrl _ :String maxLag (if maxLag (Std.string maxLag) "1") :Map<String,String> headers _]
(import requests_externs.Requests)
(print "extern query call $params")
(let [response
(Requests.get mediaWikiUrl
(let [innerParams
[
=>"action" "query"
=>"maxlag" maxLag
=>"format" "json"
]]
(doFor =>param paramValues params (dictSet innerParams param (paramValues.join "|")))
innerParams)
(object
headers headers
timeout 2))]
(assert response.ok "MediaWiki query failed")
(print "call finished: ${response.text}")
response.text)))]
(if data.query
(Some data.query)
None)))
(method :Array<String> queryImageTitles [:Array<String> pageTitles]
(ifLet [(Some queryResult) (query [=>"titles" pageTitles =>"prop" ["images"]])]
(flatten
(for =>_id page (the haxe.DynamicAccess<Dynamic> queryResult.pages)
(if page.images
(page.images.map ->image image.title)
[])))
[]))
(method :Array<String> queryImageUrls [:Array<String> imageTitles]
(ifLet [(Some queryResult) (query [=>"titles" imageTitles =>"prop" ["imageinfo"] =>"iiprop" ["url"]])]
(flatten
(for =>_id image
(the haxe.DynamicAccess<Dynamic> queryResult.pages)
(if image.imageinfo
(image.imageinfo.map ->image image.url)
[])))
[]))
(var headers [=>"User-Agent" "NatArchiveTool/0.0.0 (https://github.com/NQNStudios/kisslang/tree/main/projects/nat-archive-tool; natquaylenelson@gmail.com) Requests/2.26.0"])

View File

@@ -1,8 +0,0 @@
package nat.systems;
import kiss.Prelude;
import kiss.List;
import nat.System;
@:build(kiss.Kiss.build())
class NameSystem extends System {}

View File

@@ -1,21 +0,0 @@
(load "../Lib.kiss")
(prop :Map<String,Array<Entry>> entriesByName (new Map))
// Stores a case-insensitive map of named entries, for instant lookup by name
(defNew []
(super
"NameSystem"
->[archive e] (hasComponent e Name)
->[archive e &opt ui] (let [name (readComponent e Name)]
(if (entriesByName.exists (name.toLowerCase))
(.push (dictGet entriesByName (name.toLowerCase)) e)
(dictSet entriesByName (name.toLowerCase) [e]))
// Because the if statement doesn't unify by type :(
null)))
(method :Array<Entry> getEntries [name]
(let [entries (dictGet entriesByName (name.toLowerCase))]
(if entries
entries
[])))

View File

@@ -1,18 +0,0 @@
package nat.systems;
import kiss.Prelude;
import kiss.List;
import nat.System;
import nat.components.*;
import haxe.DynamicAccess;
import haxe.ds.Option;
typedef PlaygroundEntryProcessor = (Archive, Entry, Position, ?ArchiveUI) -> Dynamic; // Whatever value is returned will be dropped, but this is easier than requiring ->:Void
typedef PlaygroundConnectionProcessor = (Archive, Entry, Position, Entry, Position, ?ArchiveUI) -> Dynamic; // Whatever value is returned will be dropped, but this is easier than requiring ->:Void
/**
* Base class for Systems that process Entries in a playground view and displays them in an interactive form
* (EntrySpriteSystem, for example)
*/
@:build(kiss.Kiss.build())
class PlaygroundSystem<EntryRep> extends System {}

View File

@@ -1,106 +0,0 @@
(load "../Lib.kiss")
(prop &mut :String _playgroundKey "")
(method :TagList currentDefaultTags []
(or
(dictGet playgroundDefaultTags _playgroundKey)
(new Array<String>)))
(method :String getPlaygroundKey [] _playgroundKey)
(prop :Map<String,TagList> playgroundDefaultTags (new Map))
(prop :Map<String,ColorF> playgroundBGColors (new Map))
(prop :Map<String,EntryRep> entryReps (new Map))
(defNew [:String name
&prop :ArchiveUI ui
:EntryChecker canProcess
&prop :PlaygroundEntryProcessor createEntryRep
&prop :PlaygroundConnectionProcessor connectionProcessor
:EntryProcessor onRemoveEntry]
[:PlaygroundEntryProcessor processor
->[archive e pos &opt ui]
(unless (entryReps.exists e.id)
(let [eRep (createEntryRep archive e pos ui)]
(dictSet entryReps e.id eRep)))]
(super
name
->[archive e]
(or (tagsMatch e "playground")
(and (tagsMatch e "!(or done hidden)") (canProcess archive e)))
->[archive e &opt ui]
(if setupProcess
// Read playground information from playground Entries
(when (catsMatch e "(and playground Name)")
(let [name (readComponent e Name)]
(if (hasComponent e CatsMatchExp)
(archive.changePlaygrounds ->:Void [:DynamicAccess<Dynamic> p] (set .catsMatch (dictGet p name) (readComponent e CatsMatchExp)))
(addComponent archive e CatsMatchExp .catsMatch (dictGet archive.playgrounds name)))
(dictSet playgroundBGColors name (readComponentOr e ColorF (object r 0.0 g 0.0 b 0.0 a 1.0)))
(dictSet playgroundDefaultTags name (readComponentOr e TagList []))))
// Process Entries belonging to the current playground
(when (catsMatch e .catsMatch (dictGet archive.playgrounds _playgroundKey))
(when !(hasComponent e Positions)
(addComponent archive e Positions (new Map)))
(let [positions (readComponent e Positions)]
(when !(positions.exists _playgroundKey)
(withWritableComponents archive e [positions Positions]
(dictSet positions _playgroundKey (defaultPosition e)))))
(let [pos (dictGet (readComponent e Positions) _playgroundKey)]
(processor archive e pos ui)))))
(set this.onRemoveEntry
->[archive e &opt ui] {
(onRemoveEntry archive e ui)
(entryReps.remove e.id)
}))
(method switchPlaygroundKey [key]
(set _playgroundKey key)
(clear (or (dictGet playgroundBGColors _playgroundKey) (object r 0.0 g 0.0 b 0.0 a 1.0)))
(set ui.controller.archive.defaultInitializer ->e
{
(when (currentDefaultTags)
(addTags ui.controller.archive e (currentDefaultTags)))
(whenLet [(Some position) (ui.cursorPosition)]
(addComponent ui.controller.archive e Positions [=>_playgroundKey position]))
})
(process ui.controller.archive ui))
(method :Void clear [:ColorF color]
(throw "(PlaygroundSystem.clear <color>) not implemented"))
(prop &mut :Bool setupProcess false)
(method &override :Void process [:Archive archive &opt :ArchiveUI ui]
(when setupProcess
(super.process archive ui)
(set setupProcess false)
(return))
(when _playgroundKey
(super.process archive ui)
(doFor e (entries.iterator)
(when (hasComponent e Positions)
(let [pos (dictGet (readComponent e Positions) _playgroundKey)]
(doFor =>e2id _ (readComponentOr e Connections (new Map<String,Int>))
(whenLet [e2 (dictGet archive.entries e2id)
pos2 (dictGet (readComponent e2 Positions) _playgroundKey)]
(connectionProcessor archive e pos e2 pos2 ui))))))))
(method savePosition [:Entry e :Float x :Float y &opt :Float z]
(withWritableComponents ui.controller.archive e [positions Positions]
(let [oldPos (dictGet positions _playgroundKey)]
(dictSet positions _playgroundKey
(objectWith [z (or z oldPos.z)] x y)))))
(method defaultPosition [:Entry e]
(object x 0.0 y 0.0 z 0.0))
(method getSelectedReps []
(filter (for e (ui.controller.getSelectedEntries) (dictGet entryReps e.id))))
// TODO overridable circleContainsEntry function (default is to check only the position, Flixel version will use scaled sprite bounding box)
// TODO when a circle contains an entry in the current playground, add it as a child

View File

@@ -1,8 +0,0 @@
package nat.systems;
import kiss.Prelude;
import kiss.List;
import nat.System;
@:build(kiss.Kiss.build())
class RemarkableAPISystem extends System {}

View File

@@ -1,16 +0,0 @@
(load "../Lib.kiss")
(defNew []
(super
"RemarkableAPISystem"
->[archive e] false
->[archive e &opt ui] null)
**(#extern String js
(object
hxmlFile "extern-files/js/args.hxml"
skipHaxelibInstall true
langProjectFile "extern-files/js/package.json")
[]
(print "extern hello world!")))

View File

@@ -1,7 +0,0 @@
package nat.systems;
import kiss.Prelude;
import nat.System;
@:build(kiss.Kiss.build())
class TagSystem extends System {}

View File

@@ -1,11 +0,0 @@
(load "../Lib.kiss")
(defNew [:String name
&prop :String tagFilterString // This doesn't need to be a &prop because it will be captured by the lambda, but maybe it will be useful to query from the system later
// TODO make a &super annotation that passes an argument to the super constructor
:EntryProcessor processor]
[]
(super
name
(lambda [:Archive archive :Entry e] (tagsMatch e tagFilterString))
processor))

View File

@@ -1,13 +0,0 @@
package nat.systems;
import nat.systems.MediaWikiSystem;
import kiss.Prelude;
using haxe.io.Path;
using StringTools;
/**
* System which downloads and attaches images from Wikipedia pages that match Entries' names.
*/
@:build(kiss.Kiss.build())
class WikipediaImageSystem extends MediaWikiSystem {}

View File

@@ -1,31 +0,0 @@
(load "../Lib.kiss")
(defNew []
(super
"WikipediaImageSystem"
"https://en.wikipedia.org/w/api.php"
->[archive e] (tagsMatch e "(and media !wikipediaProcessed)")
scrapeForImages
1))
// named method in case a user will want to run it on selectedEntries instead of on media entries
(method scrapeForImages [archive e &opt ui]
(let [:String title
(readComponent e Name)
:Array<String> wikipediaImageUrls
(queryImageUrls (queryImageTitles [title]))]
(addFiles archive e
(for url wikipediaImageUrls
(let [filePath
(joinPath archive.archiveDir
~(.replace
(.urlDecode (url.withoutDirectory))
// Some symbols shouldn't be decoded because they're invalid in file systems!
"\"" "%22"))]
(log ui "Downloading $title image: $url")
(assertProcess "curl" ["--output" filePath url])
filePath)))
// Trigger the creation of a new Images component including the wikipedia images
(removeComponent archive e Images)
(removeComponent archive e Images2)
(addTags archive e ["wikipediaProcessed"])))

View File

@@ -1,59 +0,0 @@
package test;
import nat.*;
import nat.systems.PlaygroundSystem;
import nat.components.Position;
import nat.ArchiveController.ChangeSet;
import haxe.ds.Option;
import kiss_tools.KeyShortcutHandler;
class DummyUI implements ArchiveUI {
public var controller:ArchiveController = null;
public function new() {}
public function enterText(prompt:String, resolve:(String) -> Void, maxLength:Float) {
// TODO for proper testing, this will need to resolve with specific pre-coded strings
resolve("");
}
public function enterNumber(prompt:String, resolve:(Float) -> Void, min:Float, max:Float, ?inStepsOf:Float, ?allowNaN:Bool) {
// TODO for proper testing, this will need to resolve with specific pre-coded numbers
resolve(min);
}
public function chooseEntry(prompt:String, archive:Archive, resolve:(Entry) -> Void) {
// TODO for proper testing, this will need to resolve with specific pre-coded entries
resolve(null);
}
public function chooseEntries(prompt:String, archive:Archive, resolve:(Array<Entry>) -> Void, min:Int, max:Float) {
// TODO for proper testing, this will need to resolve with specific pre-coded entry lists
resolve([]);
}
public function chooseBetweenStrings(prompt:String, choices:Array<String>, resolve:String->Void) {
resolve(choices[0]);
}
public function handleChanges(archive:Archive, changeSet:ChangeSet) {}
public function displayMessage(message:String) {}
public function reportError(error:String) {}
public function onSelectionChanged(selectedEntries:Array<Entry>, lastSelectedEntries:Array<Entry>) {}
public function showPrefixMap(map:Map<String,String>) {}
public function hidePrefixMap() {}
public function cursorPosition():Option<Position> {
return None;
};
public function choosePosition(prompt:String, resolve:Position->Void) {
resolve({x: 0, y: 0, z: 0});
}
public function playgroundSystem():Null<PlaygroundSystem<Dynamic>> {
return null;
}
public var shortcutHandler:Null<KeyShortcutHandler<Entry>> = null;
}

View File

@@ -1,7 +0,0 @@
package test;
class TestMain {
static function main() {
TestMain_.main();
}
}

View File

@@ -1,46 +0,0 @@
(import nat.BoolExpInterp)
(import nat.Archive)
(import nat.ArchiveController)
(import nat.Lib)
(importAll nat.components)
(importAll nat.systems)
(import uuid.Uuid)
// External programs can load Lib.kiss with (loadFrom "nat-archive-tool" "src/nat/Lib.kiss")
(load "../nat/Lib.kiss")
(assert (BoolExpInterp.eval "true" []))
(assert !(BoolExpInterp.eval "false" []))
(assert !(BoolExpInterp.eval "flag" []))
(assert (BoolExpInterp.eval "flag" ["flag"]))
(assert !(BoolExpInterp.eval "(and flag false)" ["flag"]))
(assert (BoolExpInterp.eval "(or flag otherFlag)" ["otherFlag"]))
(let [archive
(new Archive "src/test/example-archive")
song1
(dictGet archive.entries "song1")
song2
(dictGet archive.entries "song2")]
(assert (hasComponent song1 Tags))
(assert (hasComponent song2 Tags))
(assert (componentsMatch song1 "(and Name Author)"))
(assert (componentsMatch song2 "(and Name Author)"))
(assert (tagsMatch song1 "(and song western)"))
(assert !(tagsMatch song1 "(and song religious)"))
(assert (tagsMatch song2 "(and song religious)"))
(assert !(tagsMatch song2 "(and song western)"))
(withWritableComponents archive song1
[author Author
name Name]
(assert (= author "Rafael Krux"))
(assert (= name "Adventure")))
(let [wikipedia (new MediaWikiSystem "Test Wikipedia system" "https://en.wikipedia.org/w/api.php" null null 1)]
~(wikipedia.queryImageUrls (wikipedia.queryImageTitles ["Phoenix Wright"])))
(let [controller (new ArchiveController archive (new DummyUI))]
// TODO test controller
0))

View File

@@ -1 +0,0 @@
{"components":[["Tags","[[\"song\", 1],[\"stepperProcessed\", 1],[\"western\", 1]]"],["Name","\"Adventure\""],["Author","\"Rafael Krux\""]],"files":["Adventure.mp3"],"id":"song1"}

View File

@@ -1 +0,0 @@
{"components":[["Tags","[[\"song\", 1],[\"stepperProcessed\", 1],[\"religious\", 1]]"],["Name","\"Ancient Rite\""],["Author","\"Kevin MacLeod\""]],"files":["Ancient Rite.mp3"],"id":"song2"}

View File

@@ -1,6 +0,0 @@
{
"default": "Playground-MAIN",
"Playground-MAIN": {
"catsMatch": "true"
}
}

View File

@@ -1,2 +0,0 @@
#! /bin/bash
./bin/cpp/TestMain

View File

@@ -1,6 +0,0 @@
-D test
-lib kiss
-lib nat-archive-tool
-lib requests-externs
-cp test
--main test.TestMain

View File

@@ -1,9 +0,0 @@
#! /bin/bash
# Run these tests on every target that could be used for a NAT front-end
# (also to test (#extern) on multiple targets)
haxe test.hxml py.hxml &&
haxe test.hxml js.hxml &&
haxe test.hxml cpp.hxml &&
haxe test.hxml --interp &&
haxelib run nat-archive-tool _TEST_