init
This commit is contained in:
commit
fe7c9508e7
CHANGELOG.mdLICENSESetupSetup.hiSetup.hsSetup.oTaggerSchemaDefinition.sqlTaggerSchemaTeardown.sqlYui_signature_SS.bmpYui_signature_SS.pngtagger.cabal
app
tagger
taggercli
dist-newstyle/cache
iosevka_bold.ttfiosevka_regular.ttfiosevka_thin.ttflib
Data
Database
Tagger
Text
tagger-exe-internal/Tagger
test
355
CHANGELOG.md
Normal file
355
CHANGELOG.md
Normal file
@ -0,0 +1,355 @@
|
||||
# Revision history for Tagger
|
||||
|
||||
------
|
||||
|
||||
# Unreleased
|
||||
|
||||
------
|
||||
|
||||
# Planned
|
||||
|
||||
* A Query builder element in the query widget section.
|
||||
* Filter tags showing up in the results pane by pattern and meta-descriptor.
|
||||
|
||||
### 1.0.2.1 -- 2021-10-04
|
||||
|
||||
* Limited CLI functionality.
|
||||
Exposed through the `taggercli` program.
|
||||
* Querying
|
||||
* Report stats or audit results
|
||||
|
||||
------
|
||||
|
||||
### 1.0.2.0 -- 2022-09-19
|
||||
|
||||
* Enhanced the UI so that image is central and always fit to the full size of the page.
|
||||
* Other widgets are semi-transparent and float on top to the left or right side
|
||||
as resizeable panels.
|
||||
* Added new hotkeys for selectively hiding and showing each respective panel.
|
||||
* Furthermore, the layout of the widgets was changed and some extraneous widgets were
|
||||
removed altogether.
|
||||
* Also changed the default SetOp in a query to be Intersect from Union.
|
||||
* This change could potentially break more complex queries, but it designed to make
|
||||
the query language more logically consistent. And it should have been the default from
|
||||
the beginning. See TN: 2edceb0e05
|
||||
|
||||
------
|
||||
|
||||
#### 1.0.1.1 -- 2022-08-21
|
||||
|
||||
* Fixed a bug: a50b7d8d4c81c844f22c502654b790e3895e7bb4
|
||||
* Relating to subquery accuracy. Specifically, queries of the format
|
||||
`r.a{b c} or any general type of criteria c for c.a{b c}` would return a superset of
|
||||
the intended results.
|
||||
* Giving a whole version to this fix because the presence
|
||||
of bugs in the query engine is quite vexing to me no matter how minor.
|
||||
|
||||
------
|
||||
|
||||
#### 1.0.1.1 -- 2022-07-23
|
||||
* Reworked the complex term query engine to be more accurate.
|
||||
Refer to Tech-note f02a13240b for some more information.
|
||||
|
||||
------
|
||||
|
||||
### 1.0.1.0 -- 2022-07-14
|
||||
* Removed the "Last Saved" field in the info widget, because there is currenlty no
|
||||
save functionality.
|
||||
* Making the descriptor management pane more obvious and less intrusive by
|
||||
moving it to the bottom of the Unrelated descriptor tree widget and not hiding it
|
||||
behind a button.
|
||||
* Improved spacing slightly in the tag list widget.
|
||||
* Reduced visual weirdness of the buttons resizing when the file list is in view.
|
||||
* Moved the addFileWidget and the edit button to the bottom of the file list in the scrollable
|
||||
zone.
|
||||
|
||||
------
|
||||
|
||||
# 1.0.0.0 -- 2022-07-11
|
||||
|
||||
* I rewrote everything from scratch. Most functionality is the same.
|
||||
Go to the wiki in the fossil repo to get up to speed on v1.0.0.0.
|
||||
|
||||
------
|
||||
|
||||
#### 0.3.4.1 -- 2022-06-13
|
||||
|
||||
* Changed VCS from git to fossil.
|
||||
|
||||
------
|
||||
|
||||
### 0.3.4.0 -- 2022-06-11
|
||||
|
||||
* Added some new command line options.
|
||||
* -h, --help, displays usage info.
|
||||
* -f, --database-file [path], sets a file to perform operations on. Possible operations are:
|
||||
* -r, --remove, removes the file from the database.
|
||||
* -m, --move [path], specify a path to move the given file to.
|
||||
* --delete deletes, a file from both the database and the system.
|
||||
It is recommended to remove a file then delete it, but deleting a file with this option
|
||||
should be completely safe.
|
||||
* -a, --add [path], a files at the given path to the database.
|
||||
* -p, --database-path [path], specifies the database for tagger to open.
|
||||
Specifying this option will temporarily override the database path given in tagger's config
|
||||
and any CLI options or operations done with tagger's GUI will use the database specified with this option.
|
||||
* Changed the ShellCMD functionality to output ExitSuccess or other messages from completed commands to stderr instead of stdout.
|
||||
|
||||
------
|
||||
|
||||
### 0.3.3.0 -- 2022-05-24
|
||||
|
||||
* Introducing some command line arguments.
|
||||
* -v, --version, remains
|
||||
* -q, --query [query], will take a query string written in TaggerQL and return a list of file paths.
|
||||
|
||||
------
|
||||
|
||||
#### 0.3.2.3 -- 2022-05-17
|
||||
|
||||
* Changed the hotkeys used in the operation widget to apply globally,
|
||||
not just when a widget in the operation widget is in focus. The hotkeys are described below.
|
||||
* Added some sorting options to the tags "In Selection" in the image detail pane.
|
||||
* Can sort by tag alphabetically, or number of tags in the selection.
|
||||
* Ascending and Descending ordering.
|
||||
* Adjusted ordering of DescriptorTrees so that Meta trees now sort by alphabetical value
|
||||
of their descriptors instead of the length of their children lists.
|
||||
* Fixed a bug where querying by untagged files would return 0 files if an empty query string was used.
|
||||
|
||||
| Hotkey | Event |
|
||||
|--------------|--------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| Ctrl-y | Clears the file selection, with the selection buffer. |
|
||||
| Ctrl-u | Runs the given shell cmd as specified in the `Cmd` textfield. |
|
||||
| Ctrl-i | Previews the next image in the file selection. Consumes selection and adds to the buffer. |
|
||||
| Ctrl-k | Previews the previous image in the file selection. Consumes the buffer and pushes it back to the selection. |
|
||||
| Ctrl-j | Changes the query's set arithmetic to the next value e.g. Union -> Intersect -> Diff |
|
||||
| Ctrl-Shift-j | Changes the query's arithmetic to the previous value e.g. Union -> Diff -> Intersect |
|
||||
| Ctrl-l | Changes the query's query criteria to the next value e.g. Tag -> Pattern -> Relation -> Untagged |
|
||||
| Ctrl-Shift-l | Changes the query's query criteria to the previous value e.g. Tag -> Untagged -> Relation -> Pattern |
|
||||
| Ctrl-o | Toggles between Tag and Untag mode |
|
||||
| Ctrl-Shift-o | Toggles between Tag and Untag mode but in the opposite direction :^) |
|
||||
| Ctrl-r | Refreshes the application, searching for tag updates in the database, refreshing descriptor trees, and re-putting the image preview. |
|
||||
| Ctrl-t | Toggles `Solo Tagging Mode` |
|
||||
|
||||
------
|
||||
|
||||
#### 0.3.2.2 -- 2022-05-16
|
||||
|
||||
* Added a connection string to the window that shows what database tagger is connected to
|
||||
and if it has connected yet.
|
||||
* Migrated Monomer to the official release of 1.4.1.0
|
||||
|
||||
------
|
||||
|
||||
#### 0.3.2.1 -- 2022-05-15
|
||||
|
||||
* Fixed a bug that would cause the lastBackup time string to get reset in the database whenever it's connected to.
|
||||
|
||||
------
|
||||
|
||||
### 0.3.2.0 -- 2022-05-14
|
||||
|
||||
##### Breaking Changes
|
||||
|
||||
* Changed some column names in Tag.
|
||||
* Added a new TaggerDBInfo table for database-level version tracking.
|
||||
|
||||
To upgrade, run the script `Migrate0_3_1_0To0_3_2_0.sql` on a database that is up-to-date with tagger v0.3.1.0
|
||||
|
||||
#### Non-breaking changes:
|
||||
|
||||
* Implemented a new SDL query language to use in the Query textfield!
|
||||
* Normal queries as they have been previously written still work.
|
||||
* With the new language, you can fit many unions, intersections, and differences in to one query
|
||||
* You can also query by Descriptor, Relation, and Pattern in one query.
|
||||
|
||||
### Tagger Query Language:
|
||||
|
||||
Previously, file patterns, descriptor patterns, and descriptor relation trees could be queried all by text input
|
||||
in the Query textfield. But if you wanted to search for a tag relationship then difference that by a file pattern query, you had to run two separate queries and interact with the GUI dropdowns to change set arithmetic. With the Tagger Query Language, you can now combine many queries into one.
|
||||
|
||||
The rules are simple: Tag search, Relation search, or Pattern search can now specified per-token by prepending a specific operator to the front of the token. For instance, if you wanted to search for files that contain the string "roughdraft" in them, you would normally select the Pattern option from the dropdown then query with the token "%roughdraft%". But with the Tagger Query Language, this can be written as "p.%roughdraft%" and tagger will search by file pattern, regardless of what the current dropdown selection is.
|
||||
|
||||
The tokens for these searches are:
|
||||
```
|
||||
Tag -> t.
|
||||
Relation -> r.
|
||||
Pattern -> p.
|
||||
```
|
||||
|
||||
Unions, intersections, and differences work similary. These tokens are placed inbetween query sections to describe how they are combined together.
|
||||
|
||||
The tokens for these operations are:
|
||||
```
|
||||
union -> u|
|
||||
intersect -> i|
|
||||
difference -> d|
|
||||
```
|
||||
|
||||
Here are some examples.
|
||||
|
||||
I want to find all files that are tagged with 'Rough_Draft' and are in a folder called 'documents'
|
||||
```
|
||||
t.Rough_Draft i| p.%documents%
|
||||
```
|
||||
|
||||
I want to find all files that are related to the tag 'Work' but not the files tagged with 'Side_Project'
|
||||
```
|
||||
r.Work d| t.Side_Project
|
||||
```
|
||||
|
||||
I want to find find all images of Yui Otsuki that are subtagged with 'dress' or 'cute' that are not seasonal and do not have white backgrounds
|
||||
```
|
||||
t.otsuki_yui {dress r.cute} d| r.seasonal d| image_background{white}
|
||||
```
|
||||
|
||||
From these examples, you can see that the search tokens are optional, if they are not specified, then Tagger uses whatever is selected in the relevant dropdown.
|
||||
|
||||
Some restrictions:
|
||||
* You can not precede a subtag search with a pattern query.
|
||||
* `p.%filepattern% {something}` will fail to parse and output a parse error.
|
||||
* You can not use pattern queries inside subtag searches.
|
||||
* `something {p.%filepattern%}`
|
||||
* You can not do set arithmetic inside a subtag search, though this is planned as a future feature. By default, all results from individual subtags are unioned together.
|
||||
* `something {this d| that}` fails to parse and prints a parse error.
|
||||
|
||||
------
|
||||
|
||||
### 0.3.1.0 -- 2022-05-12
|
||||
|
||||
* Migrated to Monomer 1.4.0.0-dc848e8ddb76ba6d8339b47f8bc3a0ff3982950c.
|
||||
* Introduced a new config option, `style.window.window_scaling_factor`.
|
||||
* A double value that controls the relative size of text and widgets in the window.
|
||||
* Values will most likely be in-between 1.0 and 2.0.
|
||||
* Introduced an optional config option `style.window.window_icon`.
|
||||
* Takes a path to .bmp images and uses it as the window icon.
|
||||
##### Minor Changes
|
||||
* Added a dispose event to close the database connection.
|
||||
|
||||
------
|
||||
|
||||
## 0.3.0.0 -- 2022-05-10
|
||||
|
||||
* Introduced Subtagging!
|
||||
* Using the image featured in 0.2.0.0, I will demonstrate how subtags may be used.
|
||||
* Subtags are added to an image using curly brackets in the Tag textfield. For instance,
|
||||
I want to tag the character Momo Chiyoda in the above image but I want to also tag the image with
|
||||
descriptors that may only apply to her specifically. For that I will use subtags.
|
||||
```
|
||||
Chiyoda_Momo{tanned}
|
||||
```
|
||||
With this, we can see that the tanned keyword is only applied to the Chiyoda_Momo tag.
|
||||
* Queries using Subtags.
|
||||
* Querying with subtags can be done normally, as in any file with a queried tag will be part of the new selection.
|
||||
* Querying using subtag notation will fetch a selection that contains only files that have that specific sub-tagging combination.
|
||||
* If I search `tanned` I will get all images with tanned characters. However, if I search `Chiyoda_Momo{tanned}`
|
||||
I will get only the images with that specific combination.
|
||||
* Draggable tag association.
|
||||
* In the Image details pane, for tags on a single image only, each tag is draggable.
|
||||
* A new zone has been designated `untag` for these tags. When a tag is drag-and-dropped into that zone,
|
||||
that specific tag will be deleted.
|
||||
* Untagging can still be done via the Tag text field but is less precise and may end up deleting more than you wanted to.
|
||||
* New subtags can be made from existing tags by dragging one tag on top of another, this will place the dragged tag as a
|
||||
sub tag of the target.
|
||||
* Breaking changes:
|
||||
* Any databases created on versions 2.x or lower need to run the Migrate0_2_XTo0_3_X.sql
|
||||
script. Any desired subtags will have to be created manually.
|
||||
|
||||
------
|
||||
|
||||
#### 0.2.0.1 -- 2022-05-02
|
||||
|
||||
* Fixed a bug with unioning results into a BufferList. Should hopefully no longer union duplicate files into the selection BufferList.
|
||||
|
||||
------
|
||||
|
||||
## 0.2.0.0 -- 2022-05-01
|
||||
|
||||

|
||||
* Added a new Representative File feature:
|
||||
* Added a new table `Representative`
|
||||
* This table creates links between a descriptor and an image. The purpose of creating
|
||||
Representative links is to provide a quintessential example of what a descriptor is meant
|
||||
to convey when it tags a file. It is meant to be used as an aid for tagging, rather than querying.
|
||||
Shell commands cannot be performed on a Representative file that is being previewed, nor can it be tagged.
|
||||
* Representative files are viewed in the `Descriptor` config page.
|
||||
* From the Descriptor tree structure of the database, drag a descriptor into the Representative box.
|
||||
If there is a representative file for a given Descriptor it will be displayed, otherwise nothing will happen.
|
||||
* To create a Representative file, in the main page of the application, drag an image or filename from either the active image preview or the image selection buffer.
|
||||
Then drop it onto the descriptor, in the Main descriptor widget on the bottom left, that you want to create a representative link for.
|
||||
A box will appear around a given descriptor as you drag a file over it to show you which descriptor a link will be created for.
|
||||
* Minor fixes involving the lazy selection buffer. When unioning, intersecting, or diffing a new query.
|
||||
The buffer will not flush but rather be unioned, intersected, or diffed appropriately with the contents of the new query selection.
|
||||
* Added new fields to the config file: `style`, `style.font`, and `style.window`.
|
||||
* `style.font` takes three keys, `regular`, `thin`, and `bold`. These are paths to a font for tagger to use.
|
||||
* `style.window` takes three keys. `maximize`, `window_size_x`, and `window_size_y`.
|
||||
* `maximize` is a boolean, if true the window is maximized on start-up.
|
||||
The other two keys are the x and y sizes to use for the window if false.
|
||||
* Moved the `Shell Command` used on startup to the config file under the key `shell_command`.
|
||||
* Exporting the config will now export the current shell command as well.
|
||||
|
||||
------
|
||||
|
||||
#### 0.1.4.1 -- 2022-04-30
|
||||
|
||||
* Fixed a bug with the lazy selection that would flush the buffer when an image was tagged.
|
||||
* Fixed a bug where shuffling an empty selection would result in an infinite hang.
|
||||
|
||||
------
|
||||
|
||||
### 0.1.4.0 -- 2022-04-30
|
||||
|
||||
* Added the FileSelection widget back in.
|
||||
* It uses a lazy buffer that can be loaded or flushed for a more responsive GUI.
|
||||
* Uses a new config field ```selection.buffer_size = int``` to determine how many elements to load.
|
||||
* Added buttons to load, load all, flush, and shuffle the file selection.
|
||||
* Improved styling of the ImagePreview widget.
|
||||
* Added a filename to the top left.
|
||||
* Made it a drop target for FileWithTags.
|
||||
* Dropping a file from the fileSelection Widget into the image preview widget will open a preview of that file.
|
||||
* Does not change the order in which images are cycled via Ctrl-i or -k.
|
||||
* Made it a draggable FileWithTags.
|
||||
* There aren't currently any other widgets that are drop targets for this message type.
|
||||
|
||||
------
|
||||
|
||||
### 0.1.3.0 -- 2022-04-27
|
||||
|
||||
* Added a field to rename descriptors.
|
||||
* In the Descriptor configuration page.
|
||||
|
||||
------
|
||||
|
||||
#### 0.1.2.1 -- 2022-04-27
|
||||
|
||||
* Added a command line option `-v, --version` to see the program version.
|
||||
|
||||
------
|
||||
|
||||
### 0.1.2.0 -- 2022-04-26
|
||||
|
||||
* Adjusted the Cmd so that, if Solo Tagging Mode is enabled, the shell cmd
|
||||
will take the file currently previewed as the command's only argument.
|
||||
If Solo Tagging Mode is not enabled or there is no file previewed then all files in the
|
||||
selection are arguments to the shell cmd.
|
||||
* The argument substitution keyword is still '`%file`'
|
||||
|
||||
------
|
||||
|
||||
### 0.1.1.0 -- 2022-04-25
|
||||
|
||||
* Added a new configuration table and field:
|
||||
* [descriptor_tree]
|
||||
* main_request
|
||||
* A text field with the name of a descriptor for the main descriptor tree widget
|
||||
to request when the refresh button is pushed.
|
||||
* Also added a 'Descriptor' configuration page.
|
||||
* Can change the value of descriptor_tree.main_request there.
|
||||
* Can also view a similar version of the main descriptor tree widget there.
|
||||
* Stopped the descriptors in the #UNRELATED# tree widget from sending request events
|
||||
to the main tree widget when clicked.
|
||||
|
||||
------
|
||||
|
||||
## 0.1.0.0 -- 2022-04-23
|
||||
|
||||
* First version. Released on an unsuspecting world.
|
674
LICENSE
Normal file
674
LICENSE
Normal file
@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
BIN
Setup
Executable file
BIN
Setup
Executable file
Binary file not shown.
BIN
Setup.hi
Normal file
BIN
Setup.hi
Normal file
Binary file not shown.
2
Setup.hs
Normal file
2
Setup.hs
Normal file
@ -0,0 +1,2 @@
|
||||
import Distribution.Simple
|
||||
main = defaultMain
|
BIN
Setup.o
Normal file
BIN
Setup.o
Normal file
Binary file not shown.
47
TaggerSchemaDefinition.sql
Normal file
47
TaggerSchemaDefinition.sql
Normal file
@ -0,0 +1,47 @@
|
||||
PRAGMA foreign_keys = on;
|
||||
CREATE TABLE IF NOT EXISTS "Descriptor" (
|
||||
"id" INTEGER PRIMARY KEY NOT NULL,
|
||||
"descriptor" VARCHAR NOT NULL,
|
||||
CONSTRAINT "DescriptorName" UNIQUE("descriptor") ON CONFLICT IGNORE
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS "File" (
|
||||
"id" INTEGER PRIMARY KEY NOT NULL,
|
||||
"filePath" VARCHAR NOT NULL,
|
||||
CONSTRAINT "FilePath" UNIQUE("filePath") ON CONFLICT IGNORE
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS "MetaDescriptor" (
|
||||
"metaDescriptorId" INTEGER NOT NULL,
|
||||
"infraDescriptorId" INTEGER NOT NULL,
|
||||
CONSTRAINT "InfraRelationUnique" UNIQUE ("infraDescriptorId") ON CONFLICT REPLACE,
|
||||
FOREIGN KEY("metaDescriptorId") REFERENCES "Descriptor"("id") ON DELETE CASCADE,
|
||||
FOREIGN KEY("infraDescriptorId") REFERENCES "Descriptor"("id") ON DELETE CASCADE
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS "Tag" (
|
||||
"id" INTEGER PRIMARY KEY NOT NULL,
|
||||
"fileId" INTEGER NOT NULL,
|
||||
"descriptorId" INTEGER NOT NULL,
|
||||
"subTagOfId" INTEGER,
|
||||
CONSTRAINT "TagUnique" UNIQUE (fileId, descriptorId, subTagOfId) ON CONFLICT IGNORE,
|
||||
FOREIGN KEY("fileId") REFERENCES "File"("id") ON DELETE CASCADE,
|
||||
FOREIGN KEY("descriptorId") REFERENCES "Descriptor"("id") ON DELETE CASCADE,
|
||||
FOREIGN KEY ("subTagOfId") REFERENCES "Tag"("id") ON DELETE CASCADE
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS "TaggerDBInfo" (
|
||||
_tagger INTEGER NOT NULL,
|
||||
version TEXT NOT NULL,
|
||||
lastAccessed TEXT,
|
||||
lastBackup TEXT,
|
||||
lastAudit TEXT,
|
||||
lastClean TEXT,
|
||||
CONSTRAINT uniqueInfo UNIQUE(_tagger) ON CONFLICT REPLACE
|
||||
);
|
||||
INSERT INTO Descriptor (descriptor) VALUES ('#ALL#'), ('#META#'), ('#UNRELATED#');
|
||||
-- relate #META# and #UNRELATED# to #ALL#
|
||||
INSERT INTO MetaDescriptor (metaDescriptorId, infraDescriptorId)
|
||||
SELECT
|
||||
(SELECT id FROM Descriptor WHERE descriptor = '#ALL#'),
|
||||
id
|
||||
FROM Descriptor
|
||||
WHERE descriptor IN ('#META#','#UNRELATED#');
|
||||
INSERT INTO TaggerDBInfo (_tagger, version, lastAccessed)
|
||||
VALUES (0, '0.3.2.0', datetime());
|
6
TaggerSchemaTeardown.sql
Normal file
6
TaggerSchemaTeardown.sql
Normal file
@ -0,0 +1,6 @@
|
||||
PRAGMA foreign_keys = on;
|
||||
DROP TABLE IF EXISTS Tag;
|
||||
DROP TABLE IF EXISTS MetaDescriptor;
|
||||
DROP TABLE IF EXISTS TaggerDBInfo;
|
||||
DROP TABLE IF EXISTS File;
|
||||
DROP TABLE IF EXISTS Descriptor;
|
BIN
Yui_signature_SS.bmp
Normal file
BIN
Yui_signature_SS.bmp
Normal file
Binary file not shown.
After ![]() (image error) Size: 27 KiB |
BIN
Yui_signature_SS.png
Normal file
BIN
Yui_signature_SS.png
Normal file
Binary file not shown.
After ![]() (image error) Size: 100 KiB |
49
app/tagger/Config.hs
Normal file
49
app/tagger/Config.hs
Normal file
@ -0,0 +1,49 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
{-# HLINT ignore "Use newtype instead of data" #-}
|
||||
|
||||
module Config (
|
||||
TaggerConfig (..),
|
||||
getOptConf,
|
||||
) where
|
||||
|
||||
import Control.Monad (guard, (<=<))
|
||||
import Control.Monad.Trans.Class (MonadTrans (lift))
|
||||
import Control.Monad.Trans.Maybe (MaybeT (MaybeT))
|
||||
import qualified Data.Text as T
|
||||
import Paths_tagger
|
||||
import System.Directory (doesFileExist)
|
||||
import System.FilePath
|
||||
import System.IO (hPutStrLn, stderr)
|
||||
import Toml (
|
||||
TomlCodec,
|
||||
decodeFileEither,
|
||||
dioptional,
|
||||
double,
|
||||
prettyTomlDecodeErrors,
|
||||
(.=),
|
||||
)
|
||||
|
||||
data TaggerConfig = TaggerConfig
|
||||
{ taggerConfigScaleFactor :: !(Maybe Double)
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
taggerConfigCodec :: TomlCodec TaggerConfig
|
||||
taggerConfigCodec =
|
||||
TaggerConfig <$> dioptional (double "scale_factor") .= taggerConfigScaleFactor
|
||||
|
||||
getOptConf :: MaybeT IO TaggerConfig
|
||||
getOptConf = do
|
||||
bd <- lift getBinDir
|
||||
let f = bd </> "tagger.toml"
|
||||
optConfigExists <- lift $ doesFileExist f
|
||||
guard optConfigExists
|
||||
c <- lift $ decodeFileEither taggerConfigCodec f
|
||||
either
|
||||
( const (MaybeT . return $ Nothing)
|
||||
<=< lift . hPutStrLn stderr . T.unpack . prettyTomlDecodeErrors
|
||||
)
|
||||
return
|
||||
c
|
141
app/tagger/Data/Event.hs
Normal file
141
app/tagger/Data/Event.hs
Normal file
@ -0,0 +1,141 @@
|
||||
{-# LANGUAGE RankNTypes #-}
|
||||
{-# HLINT ignore "Use newtype instead of data" #-}
|
||||
{-# LANGUAGE StrictData #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
module Data.Event (
|
||||
TaggerEvent (..),
|
||||
TaggerAnonymousEvent (..),
|
||||
anonymousEvent,
|
||||
FileSelectionEvent (..),
|
||||
FileSelectionWidgetEvent (..),
|
||||
DescriptorTreeEvent (..),
|
||||
FocusedFileEvent (..),
|
||||
TaggerInfoEvent (..),
|
||||
) where
|
||||
|
||||
import Data.HashSet
|
||||
import Data.IntMap.Strict (IntMap)
|
||||
import Data.Model
|
||||
import Data.OccurrenceHashMap (OccurrenceHashMap)
|
||||
import Data.Sequence (Seq)
|
||||
import Data.Text (Text)
|
||||
import Database.Tagger.Type
|
||||
import Monomer (AppEventResponse)
|
||||
|
||||
data TaggerEvent
|
||||
= DoFocusedFileEvent FocusedFileEvent
|
||||
| DoFileSelectionEvent FileSelectionEvent
|
||||
| DoDescriptorTreeEvent DescriptorTreeEvent
|
||||
| DoTaggerInfoEvent TaggerInfoEvent
|
||||
| TaggerInit
|
||||
| RefreshUI
|
||||
| ToggleMainVisibility Text
|
||||
| ToggleTagMode
|
||||
| CloseConnection
|
||||
| IOEvent ()
|
||||
| -- | A constructor for producing nested lists of tasks in other tasks.
|
||||
-- a slightly more flexible way of calling 'Event` that should be easier to use
|
||||
-- in either a 'Task` or normal 'Event` context
|
||||
AnonymousEvent [TaggerAnonymousEvent]
|
||||
| ClearTextField (TaggerLens TaggerModel Text)
|
||||
deriving (Show, Eq)
|
||||
|
||||
anonymousEvent :: [AppEventResponse TaggerModel TaggerEvent] -> TaggerEvent
|
||||
anonymousEvent = AnonymousEvent . fmap TaggerAnonymousEvent
|
||||
|
||||
newtype TaggerAnonymousEvent
|
||||
= TaggerAnonymousEvent (AppEventResponse TaggerModel TaggerEvent)
|
||||
|
||||
instance Eq TaggerAnonymousEvent where
|
||||
_ == _ = False
|
||||
|
||||
instance Show TaggerAnonymousEvent where
|
||||
show _ = "TaggerAnonymousEvent"
|
||||
|
||||
data FileSelectionEvent
|
||||
= AddFiles
|
||||
| AppendQueryText Text
|
||||
| ClearSelection
|
||||
| CycleNextFile
|
||||
| CycleNextSetOp
|
||||
| CyclePrevFile
|
||||
| CyclePrevSetOp
|
||||
| CycleTagOrderCriteria
|
||||
| CycleTagOrderDirection
|
||||
| DeleteFileFromFileSystem (RecordKey File)
|
||||
| DoFileSelectionWidgetEvent FileSelectionWidgetEvent
|
||||
| MakeFileSelectionInfoMap (Seq File)
|
||||
| NextAddFileHist
|
||||
| NextQueryHist
|
||||
| PrevAddFileHist
|
||||
| PrevQueryHist
|
||||
| PutChunkSequence
|
||||
| PutFiles (HashSet File)
|
||||
| PutFilesNoCombine (Seq File)
|
||||
| PutTagOccurrenceHashMap_ (OccurrenceHashMap Descriptor)
|
||||
| Query
|
||||
| RefreshFileSelection
|
||||
| RefreshSpecificFile (RecordKey File)
|
||||
| RefreshSpecificFile_ File
|
||||
| RefreshTagOccurrences
|
||||
| -- | Given a Traversable of File keys, fetch an OccurrenceHashMap. Saves having to
|
||||
-- call toList on the selection Seq in RefreshTagOccurrences.
|
||||
RefreshTagOccurrencesWith (Seq (RecordKey File))
|
||||
| RemoveFileFromDatabase (RecordKey File)
|
||||
| RemoveFileFromSelection (RecordKey File)
|
||||
| RenameFile (RecordKey File)
|
||||
| ResetAddFileHistIndex
|
||||
| ResetQueryHistIndex
|
||||
| RunSelectionShellCommand
|
||||
| ShuffleSelection
|
||||
| ToggleSelectionView
|
||||
| TogglePaneVisibility Text
|
||||
deriving (Show, Eq)
|
||||
|
||||
data FileSelectionWidgetEvent
|
||||
= CycleNextChunk
|
||||
| CyclePrevChunk
|
||||
| ResetFileSelectionWidgetChunk
|
||||
| ResetFileSelectionWidgetScroll
|
||||
deriving (Show, Eq)
|
||||
|
||||
data FocusedFileEvent
|
||||
= AppendTagText Text
|
||||
| CommitTagText
|
||||
| DeleteTag (RecordKey Tag)
|
||||
| MoveTag ConcreteTag (Maybe (RecordKey Tag))
|
||||
| NextTagHist
|
||||
| PrevTagHist
|
||||
| PutConcreteFile_ ConcreteTaggedFile
|
||||
| PutFile File
|
||||
| RefreshFocusedFileAndSelection
|
||||
| ResetTagHistIndex
|
||||
| RunFocusedFileShellCommand
|
||||
| TagFile (RecordKey Descriptor) (Maybe (RecordKey Tag))
|
||||
| ToggleFocusedFilePaneVisibility Text
|
||||
| UnSubTag (RecordKey Tag)
|
||||
deriving (Show, Eq)
|
||||
|
||||
data DescriptorTreeEvent
|
||||
= CreateRelation Descriptor Descriptor
|
||||
| DeleteDescriptor Descriptor
|
||||
| DescriptorTreeInit
|
||||
| InsertDescriptor
|
||||
| PutFocusedTree_ Descriptor [Descriptor] (IntMap DescriptorInfo)
|
||||
| PutUnrelated_ [Descriptor] (IntMap DescriptorInfo)
|
||||
| PutUnrelatedNode_ Descriptor
|
||||
| RefreshBothDescriptorTrees
|
||||
| RefreshFocusedTree
|
||||
| RefreshUnrelated
|
||||
| RequestFocusedNode Text
|
||||
| RequestFocusedNodeParent
|
||||
| ToggleDescriptorTreeVisibility Text
|
||||
| UpdateDescriptor (RecordKey Descriptor)
|
||||
deriving (Show, Eq)
|
||||
|
||||
data TaggerInfoEvent
|
||||
= PutLastAccessed Text
|
||||
| PutLastSaved Text
|
||||
| PutWorkingDirectory Text
|
||||
deriving (Show, Eq)
|
7
app/tagger/Data/Model.hs
Normal file
7
app/tagger/Data/Model.hs
Normal file
@ -0,0 +1,7 @@
|
||||
module Data.Model (
|
||||
module Data.Model.Core,
|
||||
module Data.Model.Lens,
|
||||
) where
|
||||
|
||||
import Data.Model.Core
|
||||
import Data.Model.Lens
|
283
app/tagger/Data/Model/Core.hs
Normal file
283
app/tagger/Data/Model/Core.hs
Normal file
@ -0,0 +1,283 @@
|
||||
{-# LANGUAGE MultiWayIf #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE StrictData #-}
|
||||
{-# OPTIONS_GHC -Wno-type-defaults #-}
|
||||
{-# HLINT ignore "Use newtype instead of data" #-}
|
||||
{-# HLINT ignore "Eta reduce" #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
module Data.Model.Core (
|
||||
TaggerModel (..),
|
||||
createTaggerModel,
|
||||
FileSelectionModel (..),
|
||||
createFileSelectionModel,
|
||||
getSelectionChunk,
|
||||
selectionChunkLength,
|
||||
FileInfo (..),
|
||||
createFileInfo,
|
||||
constructFileInfo,
|
||||
FocusedFileModel (..),
|
||||
focusedFileDefaultDataFile,
|
||||
focusedFileDefaultRecordKey,
|
||||
DescriptorTreeModel (..),
|
||||
DescriptorInfo (..),
|
||||
createDescriptorInfo,
|
||||
createDescriptorTreeModel,
|
||||
Renderability (..),
|
||||
TaggerInfoModel (..),
|
||||
createTaggerInfoModel,
|
||||
PositioningModel (..),
|
||||
createPositioningModel,
|
||||
defaultSelectionAndQueryPositioningModel,
|
||||
defaultFileDetailAndDescriptorTreePositioningModel,
|
||||
) where
|
||||
|
||||
import Data.HierarchyMap (empty)
|
||||
import Data.IntMap.Strict (IntMap)
|
||||
import qualified Data.IntMap.Strict as IntMap
|
||||
import Data.Maybe
|
||||
import Data.Model.Shared
|
||||
import Data.OccurrenceHashMap (OccurrenceHashMap)
|
||||
import qualified Data.OccurrenceHashMap as OHM
|
||||
import Data.Sequence (Seq)
|
||||
import qualified Data.Sequence as S
|
||||
import qualified Data.Sequence as Seq
|
||||
import Data.Tagger
|
||||
import Data.Text (Text)
|
||||
import Database.Tagger.Type
|
||||
|
||||
data TaggerModel = TaggerModel
|
||||
{ _taggermodelDescriptorTreeModel :: DescriptorTreeModel
|
||||
, _taggermodelFocusedFileModel :: FocusedFileModel
|
||||
, _taggermodelFileSelectionModel :: FileSelectionModel
|
||||
, _taggermodelTaggerInfoModel :: TaggerInfoModel
|
||||
, _taggermodelPositioningModel :: PositioningModel
|
||||
, _taggermodelVisibilityModel :: Visibility
|
||||
, _taggermodelConnection :: TaggedConnection
|
||||
, _taggermodelIsTagMode :: Bool
|
||||
, _taggerMassTagText :: Text
|
||||
, _taggerIsMassOpMode :: Bool
|
||||
, _taggerShellText :: Text
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
createTaggerModel ::
|
||||
TaggedConnection ->
|
||||
Descriptor ->
|
||||
Descriptor ->
|
||||
Text ->
|
||||
TaggerModel
|
||||
createTaggerModel tc d unRelatedD defaultFilePath =
|
||||
TaggerModel
|
||||
{ _taggermodelDescriptorTreeModel = createDescriptorTreeModel d unRelatedD
|
||||
, _taggermodelFocusedFileModel = createFocusedFileModel defaultFilePath
|
||||
, _taggermodelFileSelectionModel = createFileSelectionModel
|
||||
, _taggermodelTaggerInfoModel = createTaggerInfoModel
|
||||
, _taggermodelPositioningModel = createPositioningModel
|
||||
, _taggermodelVisibilityModel = VisibilityMain
|
||||
, _taggermodelConnection = tc
|
||||
, _taggermodelIsTagMode = True
|
||||
, _taggerMassTagText = ""
|
||||
, _taggerIsMassOpMode = False
|
||||
, _taggerShellText = ""
|
||||
}
|
||||
|
||||
data FileSelectionModel = FileSelectionModel
|
||||
{ _fileselectionSelection :: Seq File
|
||||
, _fileselectionCurrentChunk :: Int
|
||||
, _fileselectionChunkSize :: Int
|
||||
, _fileselectionChunkSequence :: Seq Int
|
||||
, _fileselectionTagOccurrences :: OccurrenceHashMap Descriptor
|
||||
, _fileselectionTagOrdering :: OrderBy
|
||||
, _fileselectionFileSelectionInfoMap :: IntMap FileInfo
|
||||
, _fileselectionSetOp :: SetOp
|
||||
, _fileselectionQueryText :: Text
|
||||
, _fileselectionQueryHistory :: TextHistory
|
||||
, _fileselectionFileSelectionVis :: Visibility
|
||||
, _fileselectionAddFileText :: Text
|
||||
, _fileselectionAddFileHistory :: TextHistory
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
createFileSelectionModel :: FileSelectionModel
|
||||
createFileSelectionModel =
|
||||
FileSelectionModel
|
||||
{ _fileselectionSelection = S.empty
|
||||
, _fileselectionCurrentChunk = 0
|
||||
, _fileselectionChunkSize = 50
|
||||
, _fileselectionChunkSequence = S.singleton 0
|
||||
, _fileselectionTagOccurrences = OHM.empty
|
||||
, _fileselectionTagOrdering = OrderBy Numeric Desc
|
||||
, _fileselectionFileSelectionInfoMap = IntMap.empty
|
||||
, _fileselectionSetOp = Union
|
||||
, _fileselectionQueryText = mempty
|
||||
, _fileselectionQueryHistory = createHistory 10
|
||||
, _fileselectionFileSelectionVis = VisibilityMain
|
||||
, _fileselectionAddFileText = mempty
|
||||
, _fileselectionAddFileHistory = createHistory 30
|
||||
}
|
||||
|
||||
data FileInfo = FileInfo
|
||||
{ _fileinfoFileInfoRenameText :: Text
|
||||
, _fileinfoDeleteFileIsVis :: Bool
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
createFileInfo :: FileInfo
|
||||
createFileInfo = FileInfo "" False
|
||||
|
||||
constructFileInfo :: Text -> FileInfo
|
||||
constructFileInfo t = FileInfo t False
|
||||
|
||||
selectionChunkLength :: TaggerModel -> Int
|
||||
selectionChunkLength m = 1 + ((Seq.length . _fileselectionSelection . _taggermodelFileSelectionModel $ m) `div` (_fileselectionChunkSize . _taggermodelFileSelectionModel $ m))
|
||||
|
||||
getSelectionChunk :: TaggerModel -> Seq File
|
||||
getSelectionChunk m =
|
||||
getSelectionChunk'
|
||||
(_fileselectionCurrentChunk . _taggermodelFileSelectionModel $ m)
|
||||
(_fileselectionChunkSize . _taggermodelFileSelectionModel $ m)
|
||||
(_fileselectionSelection . _taggermodelFileSelectionModel $ m)
|
||||
|
||||
{- |
|
||||
Get the indexed chunk of 50 or fewer items from the given seq.
|
||||
-}
|
||||
getSelectionChunk' :: Int -> Int -> Seq a -> Seq a
|
||||
getSelectionChunk' n cs s
|
||||
| Seq.null s = s
|
||||
| otherwise =
|
||||
let chunks = Seq.chunksOf cs s
|
||||
size = Seq.length chunks
|
||||
in ( if
|
||||
| n >= size -> fromJust . Seq.lookup (size - 1)
|
||||
| n < 0 -> fromJust . Seq.lookup 0
|
||||
| otherwise -> fromJust . Seq.lookup n
|
||||
)
|
||||
chunks
|
||||
|
||||
data FocusedFileModel = FocusedFileModel
|
||||
{ _focusedfilemodelFocusedFile :: ConcreteTaggedFile
|
||||
, _focusedfilemodelRenderability :: Renderability
|
||||
, _focusedfilemodelFocusedFileVis :: Visibility
|
||||
, _focusedfilemodelTagText :: Text
|
||||
, _focusedfilemodelTagHistory :: TextHistory
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
createFocusedFileModel :: Text -> FocusedFileModel
|
||||
createFocusedFileModel fp =
|
||||
FocusedFileModel
|
||||
{ _focusedfilemodelFocusedFile =
|
||||
ConcreteTaggedFile (File focusedFileDefaultRecordKey fp) empty
|
||||
, _focusedfilemodelRenderability = RenderingNotSupported
|
||||
, _focusedfilemodelFocusedFileVis = VisibilityMain
|
||||
, _focusedfilemodelTagText = mempty
|
||||
, _focusedfilemodelTagHistory = createHistory 10
|
||||
}
|
||||
|
||||
focusedFileDefaultDataFile :: FilePath
|
||||
focusedFileDefaultDataFile = "Yui_signature_SS.png"
|
||||
|
||||
{- |
|
||||
placeholder file id for a default file.
|
||||
events for this id should be filtered. (if negative file ids are common in the tagger db
|
||||
for some reason though they shouldn't be.)
|
||||
|
||||
\-1
|
||||
-}
|
||||
focusedFileDefaultRecordKey :: RecordKey File
|
||||
focusedFileDefaultRecordKey = -1
|
||||
|
||||
data DescriptorTreeModel = DescriptorTreeModel
|
||||
{ _descriptortreeUnrelatedNode :: Descriptor
|
||||
, _descriptortreeUnrelated :: [Descriptor]
|
||||
, _descriptortreeFocusedNode :: Descriptor
|
||||
, _descriptortreeFocusedTree :: [Descriptor]
|
||||
, _descriptortreeDescriptorInfoMap :: IntMap DescriptorInfo
|
||||
, _descriptortreeNewDescriptorText :: Text
|
||||
, _descriptortreeDescriptorTreeVis :: Visibility
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
data DescriptorWithInfo = DescriptorWithInfo
|
||||
{ _descriptorwithInfoDescriptor :: Descriptor
|
||||
, _descriptorwithinfoDescriptorIsMeta :: Bool
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
data DescriptorInfo = DescriptorInfo
|
||||
{ _descriptorinfoDescriptorIsMeta :: Bool
|
||||
, _descriptorinfoRenameText :: Text
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
createDescriptorInfo :: DescriptorInfo
|
||||
createDescriptorInfo = DescriptorInfo False ""
|
||||
|
||||
data Renderability
|
||||
= RenderAsImage
|
||||
| RenderAsText
|
||||
| RenderingNotSupported
|
||||
deriving (Show, Eq, Enum)
|
||||
|
||||
{- |
|
||||
Create a new 'DescriptorTreeModel` with the given 'Descriptor` as the parent
|
||||
node.
|
||||
-}
|
||||
createDescriptorTreeModel :: Descriptor -> Descriptor -> DescriptorTreeModel
|
||||
createDescriptorTreeModel n unrelatedD =
|
||||
DescriptorTreeModel
|
||||
{ _descriptortreeUnrelatedNode = unrelatedD
|
||||
, _descriptortreeUnrelated = mempty
|
||||
, _descriptortreeFocusedNode = n
|
||||
, _descriptortreeFocusedTree = mempty
|
||||
, _descriptortreeDescriptorInfoMap = IntMap.empty
|
||||
, _descriptortreeNewDescriptorText = "Create New Descriptors"
|
||||
, _descriptortreeDescriptorTreeVis = VisibilityMain
|
||||
}
|
||||
|
||||
data TaggerInfoModel = TaggerInfoModel
|
||||
{ _taggerinfoVersion :: Text
|
||||
, _taggerinfoVersionMessage :: Text
|
||||
, _taggerinfoMessage :: Text
|
||||
, _taggerinfoLastAccessed :: Text
|
||||
, _taggerinfoLastSaved :: Text
|
||||
, _taggerinfoWorkingDirectory :: Text
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
createTaggerInfoModel :: TaggerInfoModel
|
||||
createTaggerInfoModel =
|
||||
TaggerInfoModel
|
||||
mempty
|
||||
mempty
|
||||
mempty
|
||||
mempty
|
||||
mempty
|
||||
mempty
|
||||
|
||||
data PositioningModel = PositioningModel
|
||||
{ _positioningSelectionAndQueryPosV :: Double
|
||||
, _positionSelectionAndQueryPosH :: Double
|
||||
, _positionFileDetailAndDescriptorTreePosV :: Double
|
||||
, _positionFileDetailAndDescriptorTreePosH :: Double
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
createPositioningModel :: PositioningModel
|
||||
createPositioningModel =
|
||||
PositioningModel
|
||||
0.5
|
||||
0.2
|
||||
0.5
|
||||
0.8
|
||||
|
||||
defaultSelectionAndQueryPositioningModel :: PositioningModel -> PositioningModel
|
||||
defaultSelectionAndQueryPositioningModel (PositioningModel _ _ ov oh) =
|
||||
let (PositioningModel v h _ _) = createPositioningModel
|
||||
in PositioningModel v h ov oh
|
||||
|
||||
defaultFileDetailAndDescriptorTreePositioningModel :: PositioningModel -> PositioningModel
|
||||
defaultFileDetailAndDescriptorTreePositioningModel (PositioningModel ov oh _ _) =
|
||||
let (PositioningModel _ _ v h) = createPositioningModel
|
||||
in PositioningModel ov oh v h
|
52
app/tagger/Data/Model/Lens.hs
Normal file
52
app/tagger/Data/Model/Lens.hs
Normal file
@ -0,0 +1,52 @@
|
||||
{-# LANGUAGE FlexibleInstances #-}
|
||||
{-# LANGUAGE FunctionalDependencies #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE RankNTypes #-}
|
||||
{-# LANGUAGE TemplateHaskell #-}
|
||||
{-# OPTIONS_GHC -Wno-typed-holes #-}
|
||||
|
||||
module Data.Model.Lens (
|
||||
module Data.Model.Lens,
|
||||
) where
|
||||
|
||||
import Control.Lens
|
||||
import Data.IntMap.Strict (IntMap)
|
||||
import qualified Data.IntMap.Strict as IntMap
|
||||
import Data.Maybe
|
||||
import Data.Model.Core
|
||||
|
||||
newtype TaggerLens a b = TaggerLens {taggerLens :: Lens' a b}
|
||||
|
||||
instance Show (TaggerLens a b) where
|
||||
show _ = "Tagger Lens'"
|
||||
|
||||
instance Eq (TaggerLens a b) where
|
||||
_ == _ = True
|
||||
|
||||
makeLensesWith abbreviatedFields ''TaggerModel
|
||||
|
||||
makeLensesWith abbreviatedFields ''DescriptorTreeModel
|
||||
|
||||
makeLensesWith abbreviatedFields ''FocusedFileModel
|
||||
|
||||
makeLensesWith abbreviatedFields ''DescriptorInfo
|
||||
|
||||
makeLensesWith abbreviatedFields ''FileSelectionModel
|
||||
|
||||
makeLensesWith abbreviatedFields ''FileInfo
|
||||
|
||||
makeLensesWith abbreviatedFields ''TaggerInfoModel
|
||||
|
||||
makeLensesWith abbreviatedFields ''PositioningModel
|
||||
|
||||
fileInfoAt :: Int -> Lens' (IntMap FileInfo) FileInfo
|
||||
fileInfoAt n =
|
||||
lens
|
||||
(fromMaybe createFileInfo . IntMap.lookup n)
|
||||
(flip (IntMap.insert n))
|
||||
|
||||
descriptorInfoAt :: Int -> Lens' (IntMap DescriptorInfo) DescriptorInfo
|
||||
descriptorInfoAt n =
|
||||
lens
|
||||
(fromMaybe createDescriptorInfo . IntMap.lookup n)
|
||||
(flip (IntMap.insert n))
|
10
app/tagger/Data/Model/Shared.hs
Normal file
10
app/tagger/Data/Model/Shared.hs
Normal file
@ -0,0 +1,10 @@
|
||||
{-# OPTIONS_GHC -Wno-dodgy-exports #-}
|
||||
{-# OPTIONS_GHC -Wno-unused-imports #-}
|
||||
|
||||
module Data.Model.Shared (
|
||||
module Data.Model.Shared.Core,
|
||||
module Data.Model.Shared.Lens,
|
||||
) where
|
||||
|
||||
import Data.Model.Shared.Core
|
||||
import Data.Model.Shared.Lens
|
135
app/tagger/Data/Model/Shared/Core.hs
Normal file
135
app/tagger/Data/Model/Shared/Core.hs
Normal file
@ -0,0 +1,135 @@
|
||||
{-# HLINT ignore "Use newtype instead of data" #-}
|
||||
{-# LANGUAGE DeriveAnyClass #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
module Data.Model.Shared.Core (
|
||||
Visibility (..),
|
||||
toggleAltVis,
|
||||
setPaneVis,
|
||||
unsetPaneVis,
|
||||
hasVis,
|
||||
togglePaneVis,
|
||||
OrderDirection (..),
|
||||
OrderCriteria (..),
|
||||
OrderBy (..),
|
||||
cycleOrderCriteria,
|
||||
cycleOrderDir,
|
||||
TextHistory (..),
|
||||
createHistory,
|
||||
nextHist,
|
||||
prevHist,
|
||||
putHist,
|
||||
getHist,
|
||||
) where
|
||||
|
||||
import Data.Sequence (Seq ((:<|)), (<|))
|
||||
import qualified Data.Sequence as Seq
|
||||
import Data.Set (Set)
|
||||
import qualified Data.Set as S
|
||||
import Data.Tagger (CyclicEnum (next))
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
|
||||
{- |
|
||||
Generic data type for changing visibility of a widget.
|
||||
|
||||
Provides labels for visibility for a main page and alternate page and
|
||||
two additional constructors for either numbered pages or labeled pages.
|
||||
-}
|
||||
data Visibility
|
||||
= VisibilityMain
|
||||
| VisibilityAlt
|
||||
| VisibilityNum Int
|
||||
| VisibilityLabel Text
|
||||
| VisibilityPanes Visibility (Set Visibility)
|
||||
deriving (Show, Eq, Ord)
|
||||
|
||||
setPaneVis :: Visibility -> Visibility -> Visibility
|
||||
setPaneVis x y =
|
||||
case x of
|
||||
VisibilityPanes x' s -> VisibilityPanes x' (S.insert y s)
|
||||
_ -> VisibilityPanes x (S.singleton y)
|
||||
|
||||
unsetPaneVis :: Visibility -> Visibility -> Visibility
|
||||
unsetPaneVis x y =
|
||||
case x of
|
||||
VisibilityPanes x' s ->
|
||||
let newVisSet = S.delete y s
|
||||
in if S.null newVisSet then x' else VisibilityPanes x' newVisSet
|
||||
_ -> x
|
||||
|
||||
hasVis :: Visibility -> Visibility -> Bool
|
||||
hasVis x y =
|
||||
case x of
|
||||
VisibilityPanes x' s -> x' == y || S.member y s
|
||||
_ -> x == y
|
||||
|
||||
{- |
|
||||
Switches between Main and Alt visibility.
|
||||
|
||||
Does nothing if the visibility is not either of these two constructors.
|
||||
-}
|
||||
toggleAltVis :: Visibility -> Visibility
|
||||
toggleAltVis VisibilityAlt = VisibilityMain
|
||||
toggleAltVis VisibilityMain = VisibilityAlt
|
||||
toggleAltVis (VisibilityPanes x ps) = VisibilityPanes (toggleAltVis x) ps
|
||||
toggleAltVis x = x
|
||||
|
||||
togglePaneVis :: Visibility -> Visibility -> Visibility
|
||||
togglePaneVis x y =
|
||||
if x `hasVis` y
|
||||
then unsetPaneVis x y
|
||||
else setPaneVis x y
|
||||
|
||||
data OrderDirection = Asc | Desc
|
||||
deriving
|
||||
(Show, Eq, Ord, Enum, Bounded, CyclicEnum)
|
||||
|
||||
data OrderCriteria = Alphabetic | Numeric
|
||||
deriving
|
||||
(Show, Eq, Ord, Enum, Bounded, CyclicEnum)
|
||||
|
||||
data OrderBy = OrderBy OrderCriteria OrderDirection deriving (Show, Eq)
|
||||
|
||||
cycleOrderCriteria :: OrderBy -> OrderBy
|
||||
cycleOrderCriteria (OrderBy c d) = OrderBy (next c) d
|
||||
|
||||
cycleOrderDir :: OrderBy -> OrderBy
|
||||
cycleOrderDir (OrderBy c d) = OrderBy c (next d)
|
||||
|
||||
data TextHistory = TextHistory
|
||||
{ _textHistorySize :: Int
|
||||
, _textHistoryIndex :: Int
|
||||
, _textHistoryContents :: Seq Text
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
createHistory :: Int -> TextHistory
|
||||
createHistory n = TextHistory n 0 Seq.empty
|
||||
|
||||
getHist :: TextHistory -> Maybe Text
|
||||
getHist (TextHistory _ ix h) = Seq.lookup ix h
|
||||
|
||||
nextHist :: TextHistory -> TextHistory
|
||||
nextHist (TextHistory n ix h) =
|
||||
TextHistory
|
||||
n
|
||||
( if ix >= n
|
||||
then n
|
||||
else
|
||||
let histSize = Seq.length h - 1
|
||||
in if ix >= histSize then histSize else ix + 1
|
||||
)
|
||||
h
|
||||
|
||||
prevHist :: TextHistory -> TextHistory
|
||||
prevHist (TextHistory n ix h) =
|
||||
TextHistory n (if ix <= 0 then 0 else ix - 1) h
|
||||
|
||||
putHist :: Text -> TextHistory -> TextHistory
|
||||
putHist t th@(TextHistory n ix h)
|
||||
| T.null t = th
|
||||
| Seq.length h >= (n - 1) = case h of
|
||||
Seq.Empty -> TextHistory n ix h
|
||||
(_ :<| h') -> TextHistory n ix (t <| h')
|
||||
| otherwise = TextHistory n ix (t <| h)
|
13
app/tagger/Data/Model/Shared/Lens.hs
Normal file
13
app/tagger/Data/Model/Shared/Lens.hs
Normal file
@ -0,0 +1,13 @@
|
||||
{-# LANGUAGE FlexibleInstances #-}
|
||||
{-# LANGUAGE FunctionalDependencies #-}
|
||||
{-# LANGUAGE RankNTypes #-}
|
||||
{-# LANGUAGE TemplateHaskell #-}
|
||||
|
||||
module Data.Model.Shared.Lens (
|
||||
module Data.Model.Shared.Lens,
|
||||
) where
|
||||
|
||||
import Control.Lens
|
||||
import Data.Model.Shared.Core
|
||||
|
||||
makeLensesWith abbreviatedFields ''TextHistory
|
19
app/tagger/Interface.hs
Normal file
19
app/tagger/Interface.hs
Normal file
@ -0,0 +1,19 @@
|
||||
module Interface (
|
||||
runTagger,
|
||||
) where
|
||||
|
||||
import Data.Event (TaggerEvent (TaggerInit))
|
||||
import Data.Model.Core (TaggerModel)
|
||||
import Interface.Handler (taggerEventHandler)
|
||||
import Interface.Theme (themeConfig)
|
||||
import Interface.Widget (taggerApplicationUI)
|
||||
import Monomer (appInitEvent, startApp)
|
||||
|
||||
runTagger :: TaggerModel -> IO ()
|
||||
runTagger m = do
|
||||
themeConf <- themeConfig
|
||||
startApp
|
||||
m
|
||||
taggerEventHandler
|
||||
taggerApplicationUI
|
||||
(themeConf ++ [appInitEvent TaggerInit])
|
838
app/tagger/Interface/Handler.hs
Normal file
838
app/tagger/Interface/Handler.hs
Normal file
@ -0,0 +1,838 @@
|
||||
{-# HLINT ignore "Use list comprehension" #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# HLINT ignore "Use const" #-}
|
||||
{-# LANGUAGE TupleSections #-}
|
||||
{-# LANGUAGE ViewPatterns #-}
|
||||
{-# OPTIONS_GHC -Wno-typed-holes #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
module Interface.Handler (
|
||||
taggerEventHandler,
|
||||
) where
|
||||
|
||||
import Control.Lens
|
||||
import Control.Monad
|
||||
import Control.Monad.Trans.Class
|
||||
import Control.Monad.Trans.Except
|
||||
import Control.Monad.Trans.Maybe
|
||||
import Data.Event
|
||||
import qualified Data.Foldable as F
|
||||
import qualified Data.HashSet as HS
|
||||
import Data.HierarchyMap (empty)
|
||||
import qualified Data.HierarchyMap as HAM
|
||||
import qualified Data.IntMap.Strict as IntMap
|
||||
import Data.Maybe
|
||||
import Data.Model
|
||||
import Data.Model.Shared
|
||||
import qualified Data.OccurrenceHashMap as OHM
|
||||
import Data.Sequence (Seq ((:<|), (:|>)))
|
||||
import qualified Data.Sequence as Seq
|
||||
import Data.Tagger
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Data.Version (showVersion)
|
||||
import Database.Tagger
|
||||
import Interface.Handler.Internal
|
||||
import Interface.Widget.Internal.Query (queryTextFieldKey)
|
||||
import Interface.Widget.Internal.Selection (fileSelectionScrollWidgetNodeKey)
|
||||
import Monomer
|
||||
import Paths_tagger
|
||||
import System.Directory (getCurrentDirectory)
|
||||
import System.FilePath
|
||||
import System.IO
|
||||
import Tagger.Info (taggerVersion)
|
||||
import Text.TaggerQL
|
||||
import Util
|
||||
|
||||
taggerEventHandler ::
|
||||
WidgetEnv TaggerModel TaggerEvent ->
|
||||
WidgetNode TaggerModel TaggerEvent ->
|
||||
TaggerModel ->
|
||||
TaggerEvent ->
|
||||
[AppEventResponse TaggerModel TaggerEvent]
|
||||
taggerEventHandler
|
||||
wenv
|
||||
node
|
||||
model@(_taggermodelConnection -> conn)
|
||||
event =
|
||||
case event of
|
||||
DoFocusedFileEvent e -> focusedFileEventHandler wenv node model e
|
||||
DoFileSelectionEvent e -> fileSelectionEventHandler wenv node model e
|
||||
DoDescriptorTreeEvent e -> descriptorTreeEventHandler wenv node model e
|
||||
DoTaggerInfoEvent e -> taggerInfoEventHandler wenv node model e
|
||||
TaggerInit ->
|
||||
[ Event (DoDescriptorTreeEvent DescriptorTreeInit)
|
||||
, Task
|
||||
( DoTaggerInfoEvent . PutWorkingDirectory
|
||||
<$> (T.pack <$> getCurrentDirectory)
|
||||
)
|
||||
, Task
|
||||
( DoTaggerInfoEvent . PutLastAccessed <$> do
|
||||
la <- runMaybeT $ getLastAccessed conn
|
||||
maybe (return "never") return la
|
||||
)
|
||||
, Task
|
||||
( DoTaggerInfoEvent . PutLastSaved <$> do
|
||||
la <- runMaybeT $ getLastSaved conn
|
||||
maybe (return "never") return la
|
||||
)
|
||||
, Model $
|
||||
model & taggerInfoModel . Data.Model.version
|
||||
.~ ( T.pack . showVersion $
|
||||
taggerVersion
|
||||
)
|
||||
& taggerInfoModel . message
|
||||
.~ "Thank you for using tagger!"
|
||||
& taggerInfoModel . versionMessage
|
||||
.~ mempty
|
||||
, SetFocusOnKey . WidgetKey $ queryTextFieldKey
|
||||
]
|
||||
RefreshUI ->
|
||||
[ Event (DoDescriptorTreeEvent RefreshBothDescriptorTrees)
|
||||
, Event . DoFocusedFileEvent $ RefreshFocusedFileAndSelection
|
||||
]
|
||||
ToggleMainVisibility t ->
|
||||
[Model $ model & visibilityModel %~ (flip togglePaneVis . VisibilityLabel $ t)]
|
||||
ToggleTagMode -> [Model $ model & isTagMode %~ not]
|
||||
CloseConnection -> [Task (IOEvent <$> close conn)]
|
||||
IOEvent _ -> []
|
||||
AnonymousEvent (fmap (\(TaggerAnonymousEvent e) -> e) -> es) -> es
|
||||
ClearTextField (TaggerLens l) -> [Model $ model & l .~ ""]
|
||||
|
||||
fileSelectionEventHandler ::
|
||||
WidgetEnv TaggerModel TaggerEvent ->
|
||||
WidgetNode TaggerModel TaggerEvent ->
|
||||
TaggerModel ->
|
||||
FileSelectionEvent ->
|
||||
[AppEventResponse TaggerModel TaggerEvent]
|
||||
fileSelectionEventHandler
|
||||
wenv
|
||||
node
|
||||
model@(_taggermodelConnection -> conn)
|
||||
event =
|
||||
case event of
|
||||
AddFiles ->
|
||||
[ Task (IOEvent <$> addFiles conn (model ^. fileSelectionModel . addFileText))
|
||||
, Model $
|
||||
model & fileSelectionModel . addFileHistory
|
||||
%~ putHist (T.strip $ model ^. fileSelectionModel . addFileText)
|
||||
, Event (ClearTextField (TaggerLens (fileSelectionModel . addFileText)))
|
||||
]
|
||||
AppendQueryText t ->
|
||||
[ Model $
|
||||
model
|
||||
& fileSelectionModel
|
||||
. queryText
|
||||
%~ flip
|
||||
T.append
|
||||
( ( if T.null (model ^. fileSelectionModel . queryText)
|
||||
then ""
|
||||
else " "
|
||||
)
|
||||
<> t
|
||||
)
|
||||
]
|
||||
ClearSelection ->
|
||||
[ Model $
|
||||
model & fileSelectionModel . selection .~ Seq.empty
|
||||
& fileSelectionModel . tagOccurrences .~ OHM.empty
|
||||
& fileSelectionModel . fileSelectionInfoMap .~ IntMap.empty
|
||||
& fileSelectionModel . fileSelectionVis .~ VisibilityMain
|
||||
]
|
||||
CycleNextFile ->
|
||||
case model ^. fileSelectionModel . selection of
|
||||
Seq.Empty -> []
|
||||
_ :<| Seq.Empty -> []
|
||||
(f' :<| (f :<| fs)) ->
|
||||
[ Event . DoFocusedFileEvent . PutFile $ f
|
||||
, Model $ model & fileSelectionModel . selection .~ (f <| (fs |> f'))
|
||||
]
|
||||
CycleNextSetOp -> [Model $ model & fileSelectionModel . setOp %~ next]
|
||||
CyclePrevFile ->
|
||||
case model ^. fileSelectionModel . selection of
|
||||
Seq.Empty -> []
|
||||
(Seq.Empty :|> _) -> []
|
||||
((f' :<| fs) :|> f) ->
|
||||
[ Event . DoFocusedFileEvent . PutFile $ f
|
||||
, Model $ model & fileSelectionModel . selection .~ (f <| (f' <| fs))
|
||||
]
|
||||
CyclePrevSetOp -> [Model $ model & fileSelectionModel . setOp %~ prev]
|
||||
CycleTagOrderCriteria ->
|
||||
[ Model $
|
||||
model & fileSelectionModel . tagOrdering
|
||||
%~ cycleOrderCriteria
|
||||
]
|
||||
CycleTagOrderDirection ->
|
||||
[ Model $
|
||||
model & fileSelectionModel . tagOrdering
|
||||
%~ cycleOrderDir
|
||||
]
|
||||
DeleteFileFromFileSystem fk ->
|
||||
[ Task (IOEvent <$> rmFile conn fk)
|
||||
, Event . DoFileSelectionEvent . RemoveFileFromSelection $ fk
|
||||
]
|
||||
DoFileSelectionWidgetEvent e -> fileSelectionWidgetEventHandler wenv node model e
|
||||
MakeFileSelectionInfoMap fseq ->
|
||||
[ let fiTuple (File fk fp) = (fromIntegral fk, constructFileInfo fp)
|
||||
m = F.toList $ fiTuple <$> fseq
|
||||
in Model $
|
||||
model
|
||||
& fileSelectionModel
|
||||
. fileSelectionInfoMap
|
||||
.~ IntMap.fromList m
|
||||
]
|
||||
NextAddFileHist ->
|
||||
[ Model $
|
||||
model
|
||||
& fileSelectionModel . addFileText
|
||||
.~ ( fromMaybe "" . getHist $
|
||||
(model ^. fileSelectionModel . addFileHistory)
|
||||
)
|
||||
& fileSelectionModel . addFileHistory %~ nextHist
|
||||
]
|
||||
NextQueryHist ->
|
||||
[ Model $
|
||||
model
|
||||
& fileSelectionModel . queryText
|
||||
.~ (fromMaybe "" . getHist $ (model ^. fileSelectionModel . queryHistory))
|
||||
& fileSelectionModel . queryHistory %~ nextHist
|
||||
]
|
||||
PrevAddFileHist ->
|
||||
[ Model $
|
||||
model
|
||||
& fileSelectionModel . addFileText
|
||||
.~ ( fromMaybe "" . getHist $
|
||||
(model ^. fileSelectionModel . addFileHistory)
|
||||
)
|
||||
& fileSelectionModel . addFileHistory %~ prevHist
|
||||
]
|
||||
PrevQueryHist ->
|
||||
[ Model $
|
||||
model
|
||||
& fileSelectionModel . queryText
|
||||
.~ (fromMaybe "" . getHist $ (model ^. fileSelectionModel . queryHistory))
|
||||
& fileSelectionModel . queryHistory %~ prevHist
|
||||
]
|
||||
PutChunkSequence ->
|
||||
[ Model $
|
||||
model & fileSelectionModel . chunkSequence
|
||||
.~ Seq.fromList
|
||||
[ 0
|
||||
.. selectionChunkLength model
|
||||
]
|
||||
]
|
||||
PutFiles fs ->
|
||||
let currentSet =
|
||||
HS.fromList
|
||||
. F.toList
|
||||
$ model ^. fileSelectionModel . selection
|
||||
combFun =
|
||||
case model ^. fileSelectionModel . setOp of
|
||||
Union -> HS.union
|
||||
Intersect -> HS.intersection
|
||||
Difference -> HS.difference
|
||||
newSeq =
|
||||
Seq.fromList
|
||||
. HS.toList
|
||||
. combFun currentSet
|
||||
$ fs
|
||||
in [Event . DoFileSelectionEvent . PutFilesNoCombine $ newSeq]
|
||||
PutFilesNoCombine
|
||||
( uncurry (Seq.><)
|
||||
. (\(x, y) -> (y, x))
|
||||
. Seq.breakl
|
||||
( ( concreteTaggedFile $
|
||||
model ^. focusedFileModel . focusedFile
|
||||
)
|
||||
==
|
||||
) ->
|
||||
fseq
|
||||
) ->
|
||||
[ Model $ model & fileSelectionModel . selection .~ fseq
|
||||
, Event
|
||||
( DoFileSelectionEvent
|
||||
(RefreshTagOccurrencesWith (fmap fileId fseq))
|
||||
)
|
||||
, Event (DoFileSelectionEvent . MakeFileSelectionInfoMap $ fseq)
|
||||
, Event
|
||||
. DoFileSelectionEvent
|
||||
. DoFileSelectionWidgetEvent
|
||||
$ ResetFileSelectionWidgetScroll
|
||||
, Event . DoFileSelectionEvent $ PutChunkSequence
|
||||
]
|
||||
++ ( case fseq of
|
||||
Seq.Empty -> []
|
||||
(f :<| _) -> [Event . DoFocusedFileEvent . PutFile $ f]
|
||||
)
|
||||
PutTagOccurrenceHashMap_ m ->
|
||||
[ Model $
|
||||
model
|
||||
& fileSelectionModel . tagOccurrences .~ m
|
||||
]
|
||||
Query ->
|
||||
[ Task
|
||||
( DoFileSelectionEvent
|
||||
. PutFiles
|
||||
<$> taggerQL
|
||||
(TaggerQLQuery . T.strip $ model ^. fileSelectionModel . queryText)
|
||||
conn
|
||||
)
|
||||
, Model $
|
||||
model & fileSelectionModel . queryHistory
|
||||
%~ putHist (T.strip $ model ^. fileSelectionModel . queryText)
|
||||
, Event (ClearTextField (TaggerLens (fileSelectionModel . queryText)))
|
||||
, Event (DoFileSelectionEvent ResetQueryHistIndex)
|
||||
]
|
||||
RefreshSpecificFile fk ->
|
||||
[ Task
|
||||
( do
|
||||
f <- runMaybeT $ queryForSingleFileByFileId fk conn
|
||||
maybe
|
||||
(return . IOEvent $ ())
|
||||
(return . DoFileSelectionEvent . RefreshSpecificFile_)
|
||||
f
|
||||
)
|
||||
]
|
||||
RefreshSpecificFile_ f@(File fk fp) ->
|
||||
let curSeq = model ^. fileSelectionModel . selection
|
||||
maybeIx = Seq.findIndexR ((==) fk . fileId) curSeq
|
||||
in [ Model $
|
||||
model & fileSelectionModel . selection
|
||||
%~ maybe
|
||||
(f <|)
|
||||
(Seq.adjust (const f))
|
||||
maybeIx
|
||||
& fileSelectionModel . fileSelectionInfoMap
|
||||
. fileInfoAt (fromIntegral fk)
|
||||
.~ constructFileInfo fp
|
||||
, Event $ DoFileSelectionEvent RefreshTagOccurrences
|
||||
]
|
||||
RefreshFileSelection ->
|
||||
[ Event (DoFileSelectionEvent RefreshTagOccurrences)
|
||||
, Event
|
||||
( DoFileSelectionEvent
|
||||
( MakeFileSelectionInfoMap $
|
||||
model ^. fileSelectionModel . selection
|
||||
)
|
||||
)
|
||||
, Event . DoFileSelectionEvent $ PutChunkSequence
|
||||
]
|
||||
RefreshTagOccurrences ->
|
||||
[ Task
|
||||
( DoFileSelectionEvent . PutTagOccurrenceHashMap_
|
||||
<$> getTagOccurrencesByFileKey
|
||||
(map fileId . F.toList $ model ^. fileSelectionModel . selection)
|
||||
conn
|
||||
)
|
||||
]
|
||||
RemoveFileFromDatabase fk ->
|
||||
[ Task (IOEvent <$> deleteFiles [fk] conn)
|
||||
, Event . DoFileSelectionEvent . RemoveFileFromSelection $ fk
|
||||
]
|
||||
RemoveFileFromSelection fk ->
|
||||
let curSeq = model ^. fileSelectionModel . selection
|
||||
maybeIx = Seq.findIndexR ((==) fk . fileId) curSeq
|
||||
in maybe
|
||||
[]
|
||||
( \sindex ->
|
||||
[ Event . DoFileSelectionEvent . PutFilesNoCombine
|
||||
. flip Seq.deleteAt curSeq
|
||||
$ sindex
|
||||
]
|
||||
)
|
||||
maybeIx
|
||||
RenameFile fk ->
|
||||
[ let newRenameText =
|
||||
model
|
||||
^. fileSelectionModel
|
||||
. fileSelectionInfoMap
|
||||
. fileInfoAt (fromIntegral fk)
|
||||
. fileInfoRenameText
|
||||
in Task
|
||||
( do
|
||||
-- refetch the fk from the db,
|
||||
-- to put the calculation in the MaybeT monad
|
||||
result <- runMaybeT $ do
|
||||
lift $ mvFile conn fk newRenameText
|
||||
queryForSingleFileByFileId fk conn
|
||||
maybe
|
||||
(return $ IOEvent ())
|
||||
(return . DoFileSelectionEvent . RefreshSpecificFile_)
|
||||
result
|
||||
)
|
||||
, Event . DoFocusedFileEvent $ RefreshFocusedFileAndSelection
|
||||
]
|
||||
ResetAddFileHistIndex ->
|
||||
[ Model $
|
||||
model
|
||||
& fileSelectionModel . addFileHistory . historyIndex .~ 0
|
||||
]
|
||||
ResetQueryHistIndex ->
|
||||
[ Model $
|
||||
model
|
||||
& fileSelectionModel . queryHistory . historyIndex .~ 0
|
||||
]
|
||||
RunSelectionShellCommand ->
|
||||
[ Task
|
||||
( IOEvent
|
||||
<$> runShellCmd
|
||||
(T.strip $ model ^. shellText)
|
||||
( F.toList
|
||||
( T.unpack . filePath <$> model
|
||||
^. fileSelectionModel
|
||||
. selection
|
||||
)
|
||||
)
|
||||
)
|
||||
]
|
||||
RefreshTagOccurrencesWith fks ->
|
||||
[ Task
|
||||
( DoFileSelectionEvent . PutTagOccurrenceHashMap_
|
||||
<$> getTagOccurrencesByFileKey fks conn
|
||||
)
|
||||
]
|
||||
ShuffleSelection ->
|
||||
[ Task
|
||||
( DoFileSelectionEvent . PutFilesNoCombine
|
||||
<$> shuffleSequence (model ^. fileSelectionModel . selection)
|
||||
)
|
||||
]
|
||||
TogglePaneVisibility t ->
|
||||
[ Model $
|
||||
model & fileSelectionModel . fileSelectionVis
|
||||
%~ flip togglePaneVis (VisibilityLabel t)
|
||||
]
|
||||
ToggleSelectionView ->
|
||||
[ Model $
|
||||
model
|
||||
& fileSelectionModel
|
||||
. fileSelectionVis
|
||||
%~ toggleAltVis
|
||||
]
|
||||
|
||||
fileSelectionWidgetEventHandler ::
|
||||
WidgetEnv TaggerModel TaggerEvent ->
|
||||
WidgetNode TaggerModel TaggerEvent ->
|
||||
TaggerModel ->
|
||||
FileSelectionWidgetEvent ->
|
||||
[AppEventResponse TaggerModel TaggerEvent]
|
||||
fileSelectionWidgetEventHandler
|
||||
_
|
||||
_
|
||||
model
|
||||
event = case event of
|
||||
CycleNextChunk ->
|
||||
let cSeq = model ^. fileSelectionModel . chunkSequence
|
||||
in case cSeq of
|
||||
(f' :<| (f :<| fs)) ->
|
||||
[ Model $
|
||||
model & fileSelectionModel . currentChunk .~ f
|
||||
& fileSelectionModel . chunkSequence .~ (f <| (fs |> f'))
|
||||
]
|
||||
_ -> []
|
||||
CyclePrevChunk ->
|
||||
let cSeq = model ^. fileSelectionModel . chunkSequence
|
||||
in case cSeq of
|
||||
(f' :<| (fs :|> f)) ->
|
||||
[ Model $
|
||||
model & fileSelectionModel . currentChunk .~ f
|
||||
& fileSelectionModel . chunkSequence .~ (f <| (f' <| fs))
|
||||
]
|
||||
_ -> []
|
||||
ResetFileSelectionWidgetChunk ->
|
||||
[ Model $
|
||||
model
|
||||
& fileSelectionModel . currentChunk .~ 0
|
||||
, Event . DoFileSelectionEvent . DoFileSelectionWidgetEvent $
|
||||
ResetFileSelectionWidgetScroll
|
||||
]
|
||||
ResetFileSelectionWidgetScroll ->
|
||||
[ Message
|
||||
(WidgetKey fileSelectionScrollWidgetNodeKey)
|
||||
ScrollReset
|
||||
]
|
||||
|
||||
focusedFileEventHandler ::
|
||||
WidgetEnv TaggerModel TaggerEvent ->
|
||||
WidgetNode TaggerModel TaggerEvent ->
|
||||
TaggerModel ->
|
||||
FocusedFileEvent ->
|
||||
[AppEventResponse TaggerModel TaggerEvent]
|
||||
focusedFileEventHandler
|
||||
_
|
||||
_
|
||||
model@(_taggermodelConnection -> conn)
|
||||
event =
|
||||
case event of
|
||||
AppendTagText t ->
|
||||
[ Model $
|
||||
model
|
||||
& focusedFileModel
|
||||
. tagText
|
||||
%~ flip
|
||||
T.append
|
||||
( ( if T.null (model ^. focusedFileModel . tagText)
|
||||
then ""
|
||||
else " "
|
||||
)
|
||||
<> t
|
||||
)
|
||||
]
|
||||
CommitTagText ->
|
||||
anonymousTask $ do
|
||||
taggerQLTag
|
||||
( fileId . concreteTaggedFile $
|
||||
model ^. focusedFileModel . focusedFile
|
||||
)
|
||||
( TaggerQLTagStmnt . T.strip $
|
||||
model ^. focusedFileModel . tagText
|
||||
)
|
||||
conn
|
||||
callback
|
||||
[ Model $
|
||||
model
|
||||
& focusedFileModel . tagHistory
|
||||
%~ putHist
|
||||
(T.strip $ model ^. focusedFileModel . tagText)
|
||||
, Event
|
||||
. ClearTextField
|
||||
$ TaggerLens (focusedFileModel . tagText)
|
||||
, Event . DoFocusedFileEvent $ RefreshFocusedFileAndSelection
|
||||
]
|
||||
DeleteTag t ->
|
||||
[ Task (IOEvent <$> deleteTags [t] conn)
|
||||
, Event . DoFocusedFileEvent $ RefreshFocusedFileAndSelection
|
||||
]
|
||||
MoveTag
|
||||
(ConcreteTag oldTagKey (Descriptor dk dp) oldSubTagKey)
|
||||
newMaybeSubTagKey ->
|
||||
let (fileId -> fk) =
|
||||
concreteTaggedFile $
|
||||
model
|
||||
^. focusedFileModel . focusedFile
|
||||
in anonymousTask $ do
|
||||
moveTagTask fk
|
||||
callback [Event . DoFocusedFileEvent $ RefreshFocusedFileAndSelection]
|
||||
where
|
||||
moveTagTask :: RecordKey File -> IO ()
|
||||
moveTagTask fk = do
|
||||
result <-
|
||||
runExceptT $ do
|
||||
withExceptT
|
||||
(const "Cannot move tags of the default file.")
|
||||
( guard (fk /= focusedFileDefaultRecordKey) ::
|
||||
ExceptT String IO ()
|
||||
)
|
||||
withExceptT
|
||||
( const
|
||||
( "Cannot move tag, "
|
||||
++ T.unpack dp
|
||||
++ ", to be a subtag of itself."
|
||||
)
|
||||
)
|
||||
( guard
|
||||
( maybe
|
||||
True
|
||||
( \newSubTagKey ->
|
||||
not
|
||||
. HAM.isInfraTo newSubTagKey oldTagKey
|
||||
. HAM.mapHierarchyMap concreteTagId
|
||||
. concreteTaggedFileDescriptors
|
||||
$ model ^. focusedFileModel . focusedFile
|
||||
)
|
||||
newMaybeSubTagKey
|
||||
) ::
|
||||
ExceptT String IO ()
|
||||
)
|
||||
withExceptT
|
||||
( const
|
||||
( "Tag, "
|
||||
++ T.unpack dp
|
||||
++ ", is already subtagged to the destination."
|
||||
)
|
||||
)
|
||||
( guard
|
||||
( oldSubTagKey
|
||||
/= newMaybeSubTagKey
|
||||
) ::
|
||||
ExceptT String IO ()
|
||||
)
|
||||
newTags <-
|
||||
lift $
|
||||
insertTags [(fk, dk, newMaybeSubTagKey)] conn
|
||||
-- moving all old subtags to the new tag
|
||||
-- or else they will be cascade deleted when the old tag is.
|
||||
lift $ moveSubTags ((oldTagKey,) <$> newTags) conn
|
||||
lift $ deleteTags [oldTagKey] conn
|
||||
either (hPutStrLn stderr) return result
|
||||
NextTagHist ->
|
||||
[ Model $
|
||||
model
|
||||
& focusedFileModel . tagText
|
||||
.~ (fromMaybe "" . getHist $ (model ^. focusedFileModel . tagHistory))
|
||||
& focusedFileModel . tagHistory %~ nextHist
|
||||
]
|
||||
PrevTagHist ->
|
||||
[ Model $
|
||||
model
|
||||
& focusedFileModel . tagText
|
||||
.~ (fromMaybe "" . getHist $ (model ^. focusedFileModel . tagHistory))
|
||||
& focusedFileModel . tagHistory %~ prevHist
|
||||
]
|
||||
PutConcreteFile_ cf@(ConcreteTaggedFile (File _ fp) _) ->
|
||||
[ Model $
|
||||
model
|
||||
& focusedFileModel . focusedFile .~ cf
|
||||
& focusedFileModel . renderability .~ getRenderability fp
|
||||
]
|
||||
PutFile (File fk _) ->
|
||||
[ Task
|
||||
( do
|
||||
cft <- runMaybeT $ queryForConcreteTaggedFileWithFileId fk conn
|
||||
maybe
|
||||
( DoFocusedFileEvent . PutConcreteFile_ <$> do
|
||||
defaultFile <- T.pack <$> getDataFileName focusedFileDefaultDataFile
|
||||
return $
|
||||
ConcreteTaggedFile
|
||||
( File
|
||||
focusedFileDefaultRecordKey
|
||||
defaultFile
|
||||
)
|
||||
empty
|
||||
)
|
||||
(return . DoFocusedFileEvent . PutConcreteFile_)
|
||||
cft
|
||||
)
|
||||
]
|
||||
RefreshFocusedFileAndSelection ->
|
||||
[ Event
|
||||
. DoFocusedFileEvent
|
||||
. PutFile
|
||||
. concreteTaggedFile
|
||||
$ model ^. focusedFileModel . focusedFile
|
||||
, Event . DoFileSelectionEvent $ RefreshFileSelection
|
||||
]
|
||||
ResetTagHistIndex ->
|
||||
[ Model $
|
||||
model
|
||||
& focusedFileModel . tagHistory . historyIndex .~ 0
|
||||
]
|
||||
RunFocusedFileShellCommand ->
|
||||
[ Task
|
||||
( IOEvent
|
||||
<$> runShellCmd
|
||||
(T.strip $ model ^. shellText)
|
||||
[ T.unpack . filePath . concreteTaggedFile $
|
||||
model
|
||||
^. focusedFileModel
|
||||
. focusedFile
|
||||
]
|
||||
)
|
||||
]
|
||||
-- Should:
|
||||
-- submit a tag in the db
|
||||
-- refresh the focused file detail widget
|
||||
-- refresh the selection if tag counts are displayed (?)
|
||||
TagFile dk mtk ->
|
||||
let (File fk _) =
|
||||
concreteTaggedFile $
|
||||
model
|
||||
^. focusedFileModel . focusedFile
|
||||
in [ Task
|
||||
( IOEvent
|
||||
<$> if or [fk == focusedFileDefaultRecordKey]
|
||||
then hPutStrLn stderr "Cannot tag the default file."
|
||||
else void $ insertTags [(fk, dk, mtk)] conn
|
||||
)
|
||||
, Event . DoFocusedFileEvent $ RefreshFocusedFileAndSelection
|
||||
]
|
||||
ToggleFocusedFilePaneVisibility t ->
|
||||
[ Model $
|
||||
model & focusedFileModel . focusedFileVis
|
||||
%~ flip togglePaneVis (VisibilityLabel t)
|
||||
]
|
||||
UnSubTag tk ->
|
||||
[ Task (IOEvent <$> unSubTags [tk] conn)
|
||||
, Event . DoFocusedFileEvent $ RefreshFocusedFileAndSelection
|
||||
]
|
||||
|
||||
{- |
|
||||
Performs some IO then executes the returned 'AppEventResponse`s
|
||||
|
||||
The list of 'AppEventResponse`s is like a callback to be executed after the
|
||||
IO body is executed.
|
||||
-}
|
||||
anonymousTask ::
|
||||
IO [AppEventResponse TaggerModel TaggerEvent] ->
|
||||
[EventResponse s TaggerEvent sp ep]
|
||||
anonymousTask = (: []) . Task . fmap anonymousEvent
|
||||
|
||||
{- |
|
||||
'return` alias
|
||||
-}
|
||||
callback :: Monad m => a -> m a
|
||||
callback = return
|
||||
|
||||
-- this is kind of stupid but whatever.
|
||||
getRenderability :: Text -> Renderability
|
||||
getRenderability (takeExtension . T.unpack . T.toLower -> ext)
|
||||
| ext `elem` [".jpg", ".png", ".jfif", ".bmp", ".gif", ".jpeg"] = RenderAsImage
|
||||
| ext `elem` [".mp3", ".mp4", ".webm", ".mkv", ".m4v", ".wav", ".flac", ".ogg"] =
|
||||
RenderingNotSupported
|
||||
| otherwise = RenderAsText
|
||||
|
||||
descriptorTreeEventHandler ::
|
||||
WidgetEnv TaggerModel TaggerEvent ->
|
||||
WidgetNode TaggerModel TaggerEvent ->
|
||||
TaggerModel ->
|
||||
DescriptorTreeEvent ->
|
||||
[AppEventResponse TaggerModel TaggerEvent]
|
||||
descriptorTreeEventHandler
|
||||
_
|
||||
_
|
||||
model@(_taggermodelConnection -> conn)
|
||||
event =
|
||||
case event of
|
||||
CreateRelation (Descriptor mk _) (Descriptor ik _) ->
|
||||
[ Task
|
||||
( IOEvent <$> do
|
||||
insertDescriptorRelation mk ik conn
|
||||
)
|
||||
, Event (DoDescriptorTreeEvent RefreshBothDescriptorTrees)
|
||||
]
|
||||
DeleteDescriptor (Descriptor dk _) ->
|
||||
[ Task (IOEvent <$> deleteDescriptors [dk] conn)
|
||||
, Event (DoDescriptorTreeEvent RefreshBothDescriptorTrees)
|
||||
]
|
||||
DescriptorTreeInit ->
|
||||
[ Event (DoDescriptorTreeEvent RefreshUnrelated)
|
||||
, Event
|
||||
( DoDescriptorTreeEvent
|
||||
( RequestFocusedNode "#META#"
|
||||
)
|
||||
)
|
||||
, Task
|
||||
( DoDescriptorTreeEvent . PutUnrelatedNode_
|
||||
<$> (head <$> queryForDescriptorByPattern "#UNRELATED#" conn)
|
||||
)
|
||||
]
|
||||
InsertDescriptor ->
|
||||
[ Task
|
||||
( IOEvent <$> do
|
||||
let newDesText =
|
||||
T.words
|
||||
. T.strip
|
||||
$ model ^. descriptorTreeModel . newDescriptorText
|
||||
unless (null newDesText) (insertDescriptors newDesText conn)
|
||||
)
|
||||
, Event (DoDescriptorTreeEvent RefreshBothDescriptorTrees)
|
||||
, Event . ClearTextField $ TaggerLens (descriptorTreeModel . newDescriptorText)
|
||||
]
|
||||
PutFocusedTree_ nodeName ds desInfoMap ->
|
||||
[ Model $
|
||||
model
|
||||
& descriptorTreeModel . focusedTree .~ ds
|
||||
& descriptorTreeModel . focusedNode .~ nodeName
|
||||
& descriptorTreeModel . descriptorInfoMap %~ IntMap.union desInfoMap
|
||||
]
|
||||
PutUnrelated_ ds desInfoMap ->
|
||||
[ Model $
|
||||
model & descriptorTreeModel . unrelated .~ ds
|
||||
& descriptorTreeModel . descriptorInfoMap %~ IntMap.union desInfoMap
|
||||
]
|
||||
PutUnrelatedNode_ d -> [Model $ model & descriptorTreeModel . unrelatedNode .~ d]
|
||||
RefreshBothDescriptorTrees ->
|
||||
[ Model $ model & descriptorTreeModel . descriptorInfoMap .~ IntMap.empty
|
||||
, Event (DoDescriptorTreeEvent RefreshUnrelated)
|
||||
, Event (DoDescriptorTreeEvent RefreshFocusedTree)
|
||||
]
|
||||
RefreshFocusedTree ->
|
||||
[ Event
|
||||
( DoDescriptorTreeEvent
|
||||
( RequestFocusedNode . descriptor $
|
||||
model ^. descriptorTreeModel . focusedNode
|
||||
)
|
||||
)
|
||||
]
|
||||
RefreshUnrelated ->
|
||||
[ Task
|
||||
( DoDescriptorTreeEvent . uncurry PutUnrelated_ <$> do
|
||||
unrelatedDs <- queryForDescriptorByPattern "#UNRELATED#" conn
|
||||
ds <-
|
||||
concat
|
||||
<$> mapM
|
||||
(flip getInfraChildren conn . descriptorId)
|
||||
unrelatedDs
|
||||
dsInfos <- IntMap.unions <$> mapM (toDescriptorInfo conn) ds
|
||||
return (ds, dsInfos)
|
||||
)
|
||||
]
|
||||
RequestFocusedNode p ->
|
||||
[ Task
|
||||
( DoDescriptorTreeEvent . (\(x, y, z) -> PutFocusedTree_ x y z) <$> do
|
||||
ds <- queryForDescriptorByPattern p conn
|
||||
d <-
|
||||
maybe
|
||||
(head <$> queryForDescriptorByPattern "#ALL#" conn)
|
||||
return
|
||||
. head'
|
||||
$ ds
|
||||
ids <- getInfraChildren (descriptorId d) conn
|
||||
idsInfoMap <- IntMap.unions <$> mapM (toDescriptorInfo conn) ids
|
||||
return (d, ids, idsInfoMap)
|
||||
)
|
||||
]
|
||||
RequestFocusedNodeParent ->
|
||||
[ Task
|
||||
( do
|
||||
pd <-
|
||||
runMaybeT $
|
||||
getMetaParent
|
||||
(descriptorId $ model ^. descriptorTreeModel . focusedNode)
|
||||
conn
|
||||
maybe
|
||||
(pure (IOEvent ()))
|
||||
(pure . DoDescriptorTreeEvent . RequestFocusedNode . descriptor)
|
||||
pd
|
||||
)
|
||||
]
|
||||
ToggleDescriptorTreeVisibility l ->
|
||||
[ Model $
|
||||
model & descriptorTreeModel . descriptorTreeVis
|
||||
%~ flip togglePaneVis (VisibilityLabel l)
|
||||
]
|
||||
UpdateDescriptor rkd@(RecordKey (fromIntegral -> dk)) ->
|
||||
let updateText =
|
||||
T.strip $
|
||||
model
|
||||
^. descriptorTreeModel
|
||||
. descriptorInfoMap
|
||||
. descriptorInfoAt dk
|
||||
. renameText
|
||||
in if T.null updateText
|
||||
then []
|
||||
else
|
||||
[ Task
|
||||
( IOEvent
|
||||
<$> updateDescriptors [(updateText, rkd)] conn
|
||||
)
|
||||
, Event (DoDescriptorTreeEvent RefreshBothDescriptorTrees)
|
||||
]
|
||||
|
||||
taggerInfoEventHandler ::
|
||||
WidgetEnv TaggerModel TaggerEvent ->
|
||||
WidgetNode TaggerModel TaggerEvent ->
|
||||
TaggerModel ->
|
||||
TaggerInfoEvent ->
|
||||
[AppEventResponse TaggerModel TaggerEvent]
|
||||
taggerInfoEventHandler _ _ model e =
|
||||
case e of
|
||||
PutLastAccessed t -> [Model $ model & taggerInfoModel . lastAccessed .~ t]
|
||||
PutLastSaved t -> [Model $ model & taggerInfoModel . lastSaved .~ t]
|
||||
PutWorkingDirectory t -> [Model $ model & taggerInfoModel . workingDirectory .~ t]
|
||||
|
||||
toDescriptorInfo :: TaggedConnection -> Descriptor -> IO (IntMap.IntMap DescriptorInfo)
|
||||
toDescriptorInfo tc (Descriptor dk p) = do
|
||||
let consDes b = DescriptorInfo b p
|
||||
di <- consDes <$> hasInfraRelations dk tc
|
||||
return $ IntMap.singleton (fromIntegral dk) di
|
61
app/tagger/Interface/Handler/Internal.hs
Normal file
61
app/tagger/Interface/Handler/Internal.hs
Normal file
@ -0,0 +1,61 @@
|
||||
{-# LANGUAGE BangPatterns #-}
|
||||
{-# OPTIONS_GHC -Wno-typed-holes #-}
|
||||
|
||||
module Interface.Handler.Internal (
|
||||
addFiles,
|
||||
shuffleSequence,
|
||||
runShellCmd,
|
||||
) where
|
||||
|
||||
import Control.Monad ((<=<), (>=>))
|
||||
import Data.Hashable (Hashable, hashWithSalt)
|
||||
import Data.Sequence (Seq)
|
||||
import qualified Data.Sequence as Seq
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import System.IO (
|
||||
hGetContents,
|
||||
hPrint,
|
||||
hPutStrLn,
|
||||
stderr,
|
||||
stdout,
|
||||
)
|
||||
import System.Process (
|
||||
CreateProcess (delegate_ctlc, new_session),
|
||||
createProcess,
|
||||
proc,
|
||||
waitForProcess,
|
||||
)
|
||||
import System.Random (Random (random), StdGen, initStdGen)
|
||||
import Tagger.Shared (addFiles)
|
||||
|
||||
runShellCmd :: Text -> [FilePath] -> IO ()
|
||||
runShellCmd cmdString files =
|
||||
case T.unpack <$> T.words cmdString of
|
||||
(c : args) -> do
|
||||
let cmd =
|
||||
(proc c (args ++ files))
|
||||
{ delegate_ctlc = True
|
||||
, new_session = True
|
||||
}
|
||||
p <- createProcess cmd
|
||||
let pout = (\(_, h, _, _) -> h) p
|
||||
perr = (\(_, _, h, _) -> h) p
|
||||
pProc = (\(_, _, _, p') -> p') p
|
||||
hReadMaybe stdout pout
|
||||
hReadMaybe stderr perr
|
||||
hPrint stderr <=< waitForProcess $ pProc
|
||||
[] -> return ()
|
||||
where
|
||||
hReadMaybe oh mh =
|
||||
maybe (pure ()) (hGetContents >=> hPutStrLn oh) mh
|
||||
|
||||
{- |
|
||||
Sorts a given sequence with a random seed.
|
||||
-}
|
||||
shuffleSequence :: Hashable a => Seq a -> IO (Seq a)
|
||||
shuffleSequence s = do
|
||||
!shuffleSeed <- initStdGen :: IO StdGen
|
||||
let genFileHash = hashWithSalt (fst . random $ shuffleSeed)
|
||||
!sortedSeq = Seq.unstableSortOn genFileHash s
|
||||
return sortedSeq
|
126
app/tagger/Interface/Theme.hs
Normal file
126
app/tagger/Interface/Theme.hs
Normal file
@ -0,0 +1,126 @@
|
||||
{-# LANGUAGE AllowAmbiguousTypes #-}
|
||||
{-# LANGUAGE FlexibleContexts #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
|
||||
module Interface.Theme (
|
||||
module Interface.Theme,
|
||||
) where
|
||||
|
||||
import Config
|
||||
import Control.Monad
|
||||
import Control.Monad.Trans.Maybe
|
||||
import Data.Event (TaggerEvent (CloseConnection))
|
||||
import Data.Maybe
|
||||
import qualified Data.Text as T
|
||||
import Monomer (
|
||||
AppConfig,
|
||||
Color,
|
||||
MainWindowState (MainWindowMaximized),
|
||||
Theme,
|
||||
appDisposeEvent,
|
||||
appFontDef,
|
||||
appScaleFactor,
|
||||
appTheme,
|
||||
appWindowIcon,
|
||||
appWindowState,
|
||||
appWindowTitle,
|
||||
lightThemeColors,
|
||||
rgbHex,
|
||||
)
|
||||
import Monomer.Core.Themes.BaseTheme (
|
||||
BaseThemeColors (
|
||||
btnBgActive,
|
||||
btnBgBasic,
|
||||
btnBgFocus,
|
||||
btnBgHover,
|
||||
btnFocusBorder,
|
||||
clearColor,
|
||||
dialogBg,
|
||||
inputBgBasic,
|
||||
inputBgFocus,
|
||||
inputFocusBorder,
|
||||
inputSelBasic,
|
||||
inputSelFocus,
|
||||
sectionColor,
|
||||
slMainBg,
|
||||
slNormalBgHover,
|
||||
slNormalFocusBorder,
|
||||
slSelectedBgBasic,
|
||||
slSelectedBgHover,
|
||||
slSelectedFocusBorder
|
||||
),
|
||||
baseTheme,
|
||||
)
|
||||
import qualified Paths_tagger as PT
|
||||
import System.Directory (makeAbsolute)
|
||||
|
||||
themeConfig :: IO [AppConfig TaggerEvent]
|
||||
themeConfig = do
|
||||
defaultThinFont <- T.pack <$> (makeAbsolute =<< PT.getDataFileName "iosevka_thin.ttf")
|
||||
defaultRegularFont <-
|
||||
T.pack
|
||||
<$> (makeAbsolute =<< PT.getDataFileName "iosevka_regular.ttf")
|
||||
defaultBoldFont <- T.pack <$> (makeAbsolute =<< PT.getDataFileName "iosevka_bold.ttf")
|
||||
dataIcon <- T.pack <$> (makeAbsolute =<< PT.getDataFileName "Yui_signature_SS.bmp")
|
||||
maybeDefaultScaleFactor <- join <$> runMaybeT (taggerConfigScaleFactor <$> getOptConf)
|
||||
return
|
||||
[ appWindowTitle "Tagger"
|
||||
, appWindowState MainWindowMaximized
|
||||
, appScaleFactor $ fromMaybe 1.0 maybeDefaultScaleFactor
|
||||
, appTheme yuiTheme
|
||||
, appFontDef "Regular" defaultRegularFont
|
||||
, appFontDef "Thin" defaultThinFont
|
||||
, appFontDef "Bold" defaultBoldFont
|
||||
, appWindowIcon dataIcon
|
||||
, appDisposeEvent CloseConnection
|
||||
]
|
||||
|
||||
yuiTheme :: Theme
|
||||
yuiTheme =
|
||||
baseTheme
|
||||
lightThemeColors
|
||||
{ clearColor = yuiLightPeach
|
||||
, sectionColor = yuiRed
|
||||
, -- btn
|
||||
btnBgBasic = yuiLightPeach
|
||||
, btnBgFocus = yuiYellow
|
||||
, btnFocusBorder = yuiOrange
|
||||
, btnBgHover = yuiPeach
|
||||
, btnBgActive = yuiOrange
|
||||
, -- input
|
||||
inputBgBasic = yuiLightPeach
|
||||
, inputBgFocus = yuiYellow
|
||||
, inputFocusBorder = yuiOrange
|
||||
, -- input selected
|
||||
inputSelFocus = yuiOrange
|
||||
, inputSelBasic = yuiYellow
|
||||
, -- dialog
|
||||
dialogBg = yuiLightPeach
|
||||
, -- sl and dropdowns
|
||||
slMainBg = yuiLightPeach
|
||||
, -- sl normal
|
||||
slNormalBgHover = yuiYellow
|
||||
, slNormalFocusBorder = yuiOrange
|
||||
, -- sl selected
|
||||
slSelectedBgBasic = yuiPeach
|
||||
, slSelectedBgHover = yuiOrange
|
||||
, slSelectedFocusBorder = yuiRed
|
||||
}
|
||||
|
||||
yuiPeach :: Color
|
||||
yuiPeach = rgbHex "#FFECDE"
|
||||
|
||||
yuiLightPeach :: Color
|
||||
yuiLightPeach = rgbHex "#FFF9F6"
|
||||
|
||||
yuiYellow :: Color
|
||||
yuiYellow = rgbHex "#FFE29E"
|
||||
|
||||
yuiRed :: Color
|
||||
yuiRed = rgbHex "#E5444A"
|
||||
|
||||
yuiOrange :: Color
|
||||
yuiOrange = rgbHex "#FF8A44"
|
||||
|
||||
yuiBlue :: Color
|
||||
yuiBlue = rgbHex "#3554A0"
|
215
app/tagger/Interface/Widget.hs
Normal file
215
app/tagger/Interface/Widget.hs
Normal file
@ -0,0 +1,215 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# OPTIONS_GHC -Wno-typed-holes #-}
|
||||
|
||||
module Interface.Widget (
|
||||
taggerApplicationUI,
|
||||
) where
|
||||
|
||||
import Control.Lens ((%~), (&), (.~), (^.))
|
||||
import Data.Event (
|
||||
FileSelectionEvent (
|
||||
ClearSelection,
|
||||
CycleNextFile,
|
||||
CycleNextSetOp,
|
||||
CyclePrevFile,
|
||||
CyclePrevSetOp
|
||||
),
|
||||
TaggerEvent (DoFileSelectionEvent, RefreshUI, ToggleMainVisibility),
|
||||
anonymousEvent,
|
||||
)
|
||||
import Data.Model (
|
||||
HasFileDetailAndDescriptorTreePosH (fileDetailAndDescriptorTreePosH),
|
||||
HasFileDetailAndDescriptorTreePosV (fileDetailAndDescriptorTreePosV),
|
||||
HasPositioningModel (positioningModel),
|
||||
HasSelectionAndQueryPosH (selectionAndQueryPosH),
|
||||
HasSelectionAndQueryPosV (selectionAndQueryPosV),
|
||||
HasVisibilityModel (visibilityModel),
|
||||
TaggerModel,
|
||||
createPositioningModel,
|
||||
defaultFileDetailAndDescriptorTreePositioningModel,
|
||||
defaultSelectionAndQueryPositioningModel,
|
||||
)
|
||||
import Data.Model.Shared.Core (
|
||||
Visibility (VisibilityLabel),
|
||||
hasVis,
|
||||
)
|
||||
import Data.Text (Text)
|
||||
import Interface.Theme
|
||||
import Interface.Widget.Internal.Core (
|
||||
defaultElementOpacity,
|
||||
withNodeHidden,
|
||||
withStyleBasic,
|
||||
)
|
||||
import qualified Interface.Widget.Internal.DescriptorTree as DescriptorTree
|
||||
import qualified Interface.Widget.Internal.FileDetail as FileDetail
|
||||
import qualified Interface.Widget.Internal.FilePreview as FilePreview
|
||||
import qualified Interface.Widget.Internal.Query as Query
|
||||
import qualified Interface.Widget.Internal.Selection as Selection
|
||||
import Interface.Widget.Internal.Type (TaggerWidget)
|
||||
import Monomer (
|
||||
CmbBgColor (bgColor),
|
||||
CmbBorderB (borderB),
|
||||
CmbBorderL (borderL),
|
||||
CmbBorderR (borderR),
|
||||
CmbBorderT (borderT),
|
||||
CmbIgnoreEmptyArea (ignoreEmptyArea),
|
||||
CmbMaxWidth (maxWidth),
|
||||
CmbPaddingB (paddingB),
|
||||
CmbPaddingT (paddingT),
|
||||
CmbResizeFactor (resizeFactor),
|
||||
EventResponse (Event, Model, SetFocusOnKey),
|
||||
WidgetEnv,
|
||||
WidgetKey (WidgetKey),
|
||||
black,
|
||||
box_,
|
||||
hsplit_,
|
||||
keystroke_,
|
||||
onlyTopActive_,
|
||||
spacer_,
|
||||
splitHandlePos,
|
||||
splitIgnoreChildResize,
|
||||
vsplit_,
|
||||
zstack_,
|
||||
)
|
||||
import Monomer.Graphics.Lens (HasA (a))
|
||||
|
||||
taggerApplicationUI ::
|
||||
WidgetEnv TaggerModel TaggerEvent ->
|
||||
TaggerModel ->
|
||||
TaggerWidget
|
||||
taggerApplicationUI _ m =
|
||||
globalKeystrokes m
|
||||
. baseZStack m
|
||||
$ [ selectionQueryLayer m
|
||||
, fileDetailAndDescriptorTreeLayer m
|
||||
]
|
||||
|
||||
globalWidgetHideLabel :: Text
|
||||
globalWidgetHideLabel = "global-widget-hide"
|
||||
|
||||
baseZStack :: TaggerModel -> [TaggerWidget] -> TaggerWidget
|
||||
baseZStack m ws = zstack_ [onlyTopActive_ False] (FilePreview.widget m : ws)
|
||||
|
||||
fileDetailDescriptorTreeHide :: Text
|
||||
fileDetailDescriptorTreeHide = "file-detail-and-descriptor-tree-vis"
|
||||
|
||||
fileDetailAndDescriptorTreeLayer :: TaggerModel -> TaggerWidget
|
||||
fileDetailAndDescriptorTreeLayer m =
|
||||
withNodeHidden
|
||||
( or
|
||||
( hasVis (m ^. visibilityModel) . VisibilityLabel
|
||||
<$> [fileDetailDescriptorTreeHide, globalWidgetHideLabel]
|
||||
)
|
||||
)
|
||||
$ hsplit_
|
||||
[ splitIgnoreChildResize True
|
||||
, splitHandlePos
|
||||
(positioningModel . fileDetailAndDescriptorTreePosH)
|
||||
]
|
||||
( withStyleBasic [maxWidth 10000, borderR 1 $ black & a .~ 0.10]
|
||||
. box_ [ignoreEmptyArea]
|
||||
. withStyleBasic [maxWidth 0]
|
||||
$ spacer_ [resizeFactor (-1)]
|
||||
, withStyleBasic [bgColor $ yuiLightPeach & a .~ defaultElementOpacity]
|
||||
. vsplit_
|
||||
[ splitIgnoreChildResize True
|
||||
, splitHandlePos (positioningModel . fileDetailAndDescriptorTreePosV)
|
||||
]
|
||||
. bimap
|
||||
(withStyleBasic [borderB 1 black, paddingB 10])
|
||||
(withStyleBasic [borderT 1 black, paddingT 3])
|
||||
$ (FileDetail.widget m, DescriptorTree.widget m)
|
||||
)
|
||||
|
||||
selectionQueryHideLabel :: Text
|
||||
selectionQueryHideLabel = "selection-and-query-layer-hide"
|
||||
|
||||
selectionQueryLayer :: TaggerModel -> TaggerWidget
|
||||
selectionQueryLayer m =
|
||||
withNodeHidden
|
||||
( or
|
||||
( hasVis (m ^. visibilityModel) . VisibilityLabel
|
||||
<$> [selectionQueryHideLabel, globalWidgetHideLabel]
|
||||
)
|
||||
)
|
||||
$ hsplit_
|
||||
[ splitIgnoreChildResize True
|
||||
, splitHandlePos
|
||||
(positioningModel . selectionAndQueryPosH)
|
||||
]
|
||||
( withStyleBasic
|
||||
[bgColor $ yuiLightPeach & a .~ defaultElementOpacity]
|
||||
. vsplit_
|
||||
[ splitIgnoreChildResize True
|
||||
, splitHandlePos
|
||||
(positioningModel . selectionAndQueryPosV)
|
||||
]
|
||||
. bimap
|
||||
(withStyleBasic [borderB 1 black, paddingB 10])
|
||||
(withStyleBasic [borderT 1 black, paddingT 3])
|
||||
$ (Query.widget m, Selection.widget m)
|
||||
, withStyleBasic [maxWidth 10000, borderL 1 $ black & a .~ 0.10]
|
||||
. box_ [ignoreEmptyArea]
|
||||
. withStyleBasic [maxWidth 0]
|
||||
$ spacer_ [resizeFactor (-1)]
|
||||
)
|
||||
|
||||
globalKeystrokes :: TaggerModel -> TaggerWidget -> TaggerWidget
|
||||
globalKeystrokes m =
|
||||
keystroke_
|
||||
[ ("Ctrl-r", RefreshUI)
|
||||
, ("Ctrl-i", DoFileSelectionEvent CycleNextFile)
|
||||
, ("Ctrl-k", DoFileSelectionEvent CyclePrevFile)
|
||||
,
|
||||
( "Ctrl-t"
|
||||
, anonymousEvent $
|
||||
if (m ^. visibilityModel) `hasVis` VisibilityLabel fileDetailDescriptorTreeHide
|
||||
then
|
||||
[ Event . ToggleMainVisibility $ fileDetailDescriptorTreeHide
|
||||
, SetFocusOnKey . WidgetKey $ FileDetail.tagTextNodeKey
|
||||
]
|
||||
else [SetFocusOnKey . WidgetKey $ FileDetail.tagTextNodeKey]
|
||||
)
|
||||
,
|
||||
( "Ctrl-f"
|
||||
, anonymousEvent $
|
||||
if (m ^. visibilityModel) `hasVis` VisibilityLabel selectionQueryHideLabel
|
||||
then
|
||||
[ Event . ToggleMainVisibility $ selectionQueryHideLabel
|
||||
, SetFocusOnKey . WidgetKey $ Query.queryTextFieldKey
|
||||
]
|
||||
else [SetFocusOnKey . WidgetKey $ Query.queryTextFieldKey]
|
||||
)
|
||||
, ("Ctrl-g", DoFileSelectionEvent CycleNextSetOp)
|
||||
, ("Ctrl-Shift-g", DoFileSelectionEvent CyclePrevSetOp)
|
||||
, ("Ctrl-u", DoFileSelectionEvent ClearSelection)
|
||||
,
|
||||
( "Ctrl-h"
|
||||
, anonymousEvent
|
||||
[ Model $ m & positioningModel .~ createPositioningModel
|
||||
, Event . ToggleMainVisibility $ globalWidgetHideLabel
|
||||
]
|
||||
)
|
||||
,
|
||||
( "Ctrl-q"
|
||||
, anonymousEvent
|
||||
[ Model $
|
||||
m & positioningModel
|
||||
%~ defaultSelectionAndQueryPositioningModel
|
||||
, Event . ToggleMainVisibility $ selectionQueryHideLabel
|
||||
]
|
||||
)
|
||||
,
|
||||
( "Ctrl-e"
|
||||
, anonymousEvent
|
||||
[ Model $
|
||||
m & positioningModel
|
||||
%~ defaultFileDetailAndDescriptorTreePositioningModel
|
||||
, Event . ToggleMainVisibility $ fileDetailDescriptorTreeHide
|
||||
]
|
||||
)
|
||||
]
|
||||
[]
|
||||
|
||||
bimap :: (a -> b) -> (c -> d) -> (a, c) -> (b, d)
|
||||
bimap f g (x, y) = (f x, g y)
|
109
app/tagger/Interface/Widget/Internal/Core.hs
Normal file
109
app/tagger/Interface/Widget/Internal/Core.hs
Normal file
@ -0,0 +1,109 @@
|
||||
module Interface.Widget.Internal.Core (
|
||||
styledButton_,
|
||||
withStyleBasic,
|
||||
withStyleHover,
|
||||
withNodeKey,
|
||||
withNodeVisible,
|
||||
withNodeHidden,
|
||||
defaultElementOpacity,
|
||||
defaultOpacityModulator,
|
||||
modulateOpacity,
|
||||
) where
|
||||
|
||||
import Control.Lens ((&), (.~))
|
||||
import Data.Event (TaggerEvent)
|
||||
import Data.Model.Core (TaggerModel)
|
||||
import Data.Text (Text)
|
||||
import Interface.Theme (
|
||||
yuiLightPeach,
|
||||
yuiOrange,
|
||||
yuiPeach,
|
||||
yuiYellow,
|
||||
)
|
||||
import Interface.Widget.Internal.Type (TaggerWidget)
|
||||
import Monomer (
|
||||
ButtonCfg,
|
||||
CmbBgColor (bgColor),
|
||||
CmbBorder (border),
|
||||
CmbStyleBasic (styleBasic),
|
||||
CmbStyleHover (styleHover),
|
||||
StyleState,
|
||||
WidgetNode,
|
||||
button_,
|
||||
nodeKey,
|
||||
nodeVisible,
|
||||
)
|
||||
import Monomer.Graphics (Color)
|
||||
import Monomer.Lens (HasA (a))
|
||||
|
||||
styledButton_ ::
|
||||
[ButtonCfg TaggerModel TaggerEvent] ->
|
||||
Text ->
|
||||
TaggerEvent ->
|
||||
TaggerWidget
|
||||
styledButton_ opts t e =
|
||||
withStyleHover
|
||||
[ bgColor
|
||||
. modulateOpacity
|
||||
defaultElementOpacity
|
||||
$ yuiYellow
|
||||
, border 1
|
||||
. modulateOpacity
|
||||
defaultElementOpacity
|
||||
$ yuiOrange
|
||||
]
|
||||
. withStyleBasic
|
||||
[ bgColor
|
||||
. modulateOpacity
|
||||
(defaultElementOpacity - defaultOpacityModulator)
|
||||
$ yuiLightPeach
|
||||
, border 1
|
||||
. modulateOpacity
|
||||
(defaultElementOpacity - defaultOpacityModulator)
|
||||
$ yuiPeach
|
||||
]
|
||||
$ button_ t e opts
|
||||
|
||||
withStyleBasic ::
|
||||
[StyleState] ->
|
||||
WidgetNode TaggerModel TaggerEvent ->
|
||||
WidgetNode TaggerModel TaggerEvent
|
||||
withStyleBasic = flip styleBasic
|
||||
{-# INLINE withStyleBasic #-}
|
||||
|
||||
withStyleHover ::
|
||||
[StyleState] ->
|
||||
WidgetNode TaggerModel TaggerEvent ->
|
||||
WidgetNode TaggerModel TaggerEvent
|
||||
withStyleHover = flip styleHover
|
||||
{-# INLINE withStyleHover #-}
|
||||
|
||||
{- |
|
||||
Makes the given node visible when the predicate is true.
|
||||
-}
|
||||
withNodeVisible :: Bool -> TaggerWidget -> TaggerWidget
|
||||
withNodeVisible = flip nodeVisible
|
||||
{-# INLINE withNodeVisible #-}
|
||||
|
||||
{- |
|
||||
Hides the given node when the predicate is true.
|
||||
-}
|
||||
withNodeHidden :: Bool -> TaggerWidget -> TaggerWidget
|
||||
withNodeHidden = withNodeVisible . not
|
||||
{-# INLINE withNodeHidden #-}
|
||||
|
||||
withNodeKey :: Text -> TaggerWidget -> TaggerWidget
|
||||
withNodeKey = flip nodeKey
|
||||
{-# INLINE withNodeKey #-}
|
||||
|
||||
defaultElementOpacity :: Double
|
||||
defaultElementOpacity = 0.5
|
||||
{-# INLINE defaultElementOpacity #-}
|
||||
|
||||
defaultOpacityModulator :: Double
|
||||
defaultOpacityModulator = 0.35
|
||||
{-# INLINE defaultOpacityModulator #-}
|
||||
|
||||
modulateOpacity :: Double -> Color -> Color
|
||||
modulateOpacity d c = c & a .~ d
|
||||
{-# INLINE modulateOpacity #-}
|
375
app/tagger/Interface/Widget/Internal/DescriptorTree.hs
Normal file
375
app/tagger/Interface/Widget/Internal/DescriptorTree.hs
Normal file
@ -0,0 +1,375 @@
|
||||
{-# LANGUAGE FlexibleContexts #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE ViewPatterns #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
{-# HLINT ignore "Eta reduce" #-}
|
||||
|
||||
module Interface.Widget.Internal.DescriptorTree (widget) where
|
||||
|
||||
import Control.Lens ((&), (.~), (^.))
|
||||
import Data.Event (
|
||||
DescriptorTreeEvent (
|
||||
CreateRelation,
|
||||
DeleteDescriptor,
|
||||
InsertDescriptor,
|
||||
RefreshBothDescriptorTrees,
|
||||
RequestFocusedNode,
|
||||
RequestFocusedNodeParent,
|
||||
ToggleDescriptorTreeVisibility,
|
||||
UpdateDescriptor
|
||||
),
|
||||
TaggerEvent (DoDescriptorTreeEvent),
|
||||
)
|
||||
import qualified Data.List as L
|
||||
import Data.Model (
|
||||
HasDescriptorInfoMap (descriptorInfoMap),
|
||||
HasDescriptorIsMeta (descriptorIsMeta),
|
||||
HasDescriptorTreeModel (descriptorTreeModel),
|
||||
HasDescriptorTreeVis (descriptorTreeVis),
|
||||
HasFocusedNode (focusedNode),
|
||||
HasFocusedTree (focusedTree),
|
||||
HasNewDescriptorText (newDescriptorText),
|
||||
HasRenameText (renameText),
|
||||
HasUnrelated (unrelated),
|
||||
HasUnrelatedNode (unrelatedNode),
|
||||
TaggerModel,
|
||||
descriptorInfoAt,
|
||||
)
|
||||
import Data.Model.Shared (Visibility (VisibilityLabel), hasVis)
|
||||
import Data.Text (Text)
|
||||
import Database.Tagger (Descriptor (Descriptor, descriptor))
|
||||
import Interface.Theme (
|
||||
yuiBlue,
|
||||
yuiLightPeach,
|
||||
yuiOrange,
|
||||
yuiRed,
|
||||
yuiYellow,
|
||||
)
|
||||
import Interface.Widget.Internal.Core (
|
||||
defaultElementOpacity,
|
||||
defaultOpacityModulator,
|
||||
modulateOpacity,
|
||||
styledButton_,
|
||||
withNodeKey,
|
||||
withNodeVisible,
|
||||
withStyleBasic,
|
||||
withStyleHover,
|
||||
)
|
||||
import Interface.Widget.Internal.Type (TaggerWidget)
|
||||
import Monomer (
|
||||
CmbAlignBottom (alignBottom),
|
||||
CmbAlignLeft (alignLeft),
|
||||
CmbAlignMiddle (alignMiddle),
|
||||
CmbBgColor (bgColor),
|
||||
CmbBorder (border),
|
||||
CmbBorderL (borderL),
|
||||
CmbBorderR (borderR),
|
||||
CmbMergeRequired (mergeRequired),
|
||||
CmbResizeFactor (resizeFactor),
|
||||
CmbSizeReqUpdater (sizeReqUpdater),
|
||||
CmbTextColor (textColor),
|
||||
CmbTextLeft (textLeft),
|
||||
CmbWheelRate (wheelRate),
|
||||
black,
|
||||
box_,
|
||||
button,
|
||||
button_,
|
||||
draggable,
|
||||
dropTargetStyle,
|
||||
dropTarget_,
|
||||
expandContent,
|
||||
hsplit_,
|
||||
hstack_,
|
||||
keystroke_,
|
||||
label_,
|
||||
separatorLine,
|
||||
splitHandlePosV,
|
||||
splitIgnoreChildResize,
|
||||
textField_,
|
||||
vscroll_,
|
||||
vstack_,
|
||||
white,
|
||||
zstack_,
|
||||
)
|
||||
import Monomer.Core.Lens (fixed)
|
||||
import Util (both)
|
||||
|
||||
widget :: TaggerModel -> TaggerWidget
|
||||
widget m = descriptorTreeWidget m
|
||||
|
||||
descriptorTreeWidget :: TaggerModel -> TaggerWidget
|
||||
descriptorTreeWidget m =
|
||||
withNodeKey
|
||||
"descriptorTree"
|
||||
mainPane
|
||||
where
|
||||
mainPane =
|
||||
vstack_
|
||||
[]
|
||||
[ hstack_
|
||||
[]
|
||||
[ mainPaneLeftButtonStack
|
||||
, hsplit_
|
||||
[ splitIgnoreChildResize True
|
||||
, splitHandlePosV 0.75
|
||||
]
|
||||
( descriptorTreeFocusedNodeWidget m
|
||||
, descriptorTreeUnrelatedWidget m
|
||||
)
|
||||
]
|
||||
]
|
||||
where
|
||||
mainPaneLeftButtonStack =
|
||||
vstack_
|
||||
[]
|
||||
[ descriptorTreeRefreshBothButton
|
||||
, descriptorTreeRequestParentButton
|
||||
, descriptorTreeFixedRequestButton "#META#"
|
||||
]
|
||||
|
||||
descriptorTreeRequestParentButton :: TaggerWidget
|
||||
descriptorTreeRequestParentButton =
|
||||
styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"Up"
|
||||
(DoDescriptorTreeEvent RequestFocusedNodeParent)
|
||||
|
||||
descriptorTreeFocusedNodeWidget :: TaggerModel -> TaggerWidget
|
||||
descriptorTreeFocusedNodeWidget m =
|
||||
box_
|
||||
[ expandContent
|
||||
, mergeRequired
|
||||
( \_ ((^. descriptorTreeModel) -> dm1) ((^. descriptorTreeModel) -> dm2) ->
|
||||
dm1 /= dm2
|
||||
)
|
||||
]
|
||||
. withStyleBasic [borderR 1 black]
|
||||
. createRelationDropTarget
|
||||
$ descriptorTreeFocusedNodeWidgetBody
|
||||
where
|
||||
descriptorTreeFocusedNodeWidgetBody :: TaggerWidget
|
||||
descriptorTreeFocusedNodeWidgetBody =
|
||||
vstack_
|
||||
[]
|
||||
[ nodeHeader
|
||||
, separatorLine
|
||||
, focusedTreeLeafWidget
|
||||
]
|
||||
|
||||
focusedTreeLeafWidget :: TaggerWidget
|
||||
focusedTreeLeafWidget =
|
||||
let focusedDescriptors = {-L.nub?-} m ^. descriptorTreeModel . focusedTree
|
||||
metaDescriptors =
|
||||
L.sort
|
||||
. filter
|
||||
(descriptorIsMetaInInfoMap m)
|
||||
$ focusedDescriptors
|
||||
infraDescriptors =
|
||||
L.sort
|
||||
. filter
|
||||
(not . descriptorIsMetaInInfoMap m)
|
||||
$ focusedDescriptors
|
||||
in vscroll_ [wheelRate 50] . vstack_ [] $
|
||||
descriptorTreeLeaf m
|
||||
<$> (metaDescriptors ++ infraDescriptors)
|
||||
|
||||
nodeHeader :: TaggerWidget
|
||||
nodeHeader =
|
||||
flip label_ [resizeFactor (-1)]
|
||||
. descriptor
|
||||
$ m ^. descriptorTreeModel . focusedNode
|
||||
|
||||
createRelationDropTarget :: TaggerWidget -> TaggerWidget
|
||||
createRelationDropTarget =
|
||||
dropTarget_
|
||||
(DoDescriptorTreeEvent . CreateRelation (m ^. descriptorTreeModel . focusedNode))
|
||||
[dropTargetStyle [border 3 yuiBlue]]
|
||||
|
||||
descriptorTreeUnrelatedWidget :: TaggerModel -> TaggerWidget
|
||||
descriptorTreeUnrelatedWidget m =
|
||||
box_
|
||||
[ expandContent
|
||||
, mergeRequired
|
||||
( \_ ((^. descriptorTreeModel) -> dm1) ((^. descriptorTreeModel) -> dm2) ->
|
||||
dm1 /= dm2
|
||||
)
|
||||
]
|
||||
. withStyleBasic [borderL 1 black]
|
||||
. createUnrelationDropTargetWidget
|
||||
$descriptorTreeUnrelatedWidgetBody
|
||||
where
|
||||
descriptorTreeUnrelatedWidgetBody :: TaggerWidget
|
||||
descriptorTreeUnrelatedWidgetBody =
|
||||
vstack_
|
||||
[]
|
||||
[ label_ "Unrelated" [resizeFactor (-1)]
|
||||
, separatorLine
|
||||
, unrelatedTreeLeafWidget
|
||||
, descriptorManagementPane
|
||||
]
|
||||
|
||||
unrelatedTreeLeafWidget :: TaggerWidget
|
||||
unrelatedTreeLeafWidget =
|
||||
let unrelatedDescriptors = m ^. descriptorTreeModel . unrelated
|
||||
meta =
|
||||
L.sort
|
||||
. filter
|
||||
(descriptorIsMetaInInfoMap m)
|
||||
$ unrelatedDescriptors
|
||||
infra =
|
||||
L.sort
|
||||
. filter
|
||||
(not . descriptorIsMetaInInfoMap m)
|
||||
$ unrelatedDescriptors
|
||||
in vscroll_ [wheelRate 50] . vstack_ [] $ descriptorTreeLeaf m <$> (meta ++ infra)
|
||||
|
||||
createUnrelationDropTargetWidget :: TaggerWidget -> TaggerWidget
|
||||
createUnrelationDropTargetWidget =
|
||||
dropTarget_
|
||||
(DoDescriptorTreeEvent . CreateRelation (m ^. descriptorTreeModel . unrelatedNode))
|
||||
[dropTargetStyle [border 3 yuiBlue]]
|
||||
|
||||
descriptorTreeRefreshBothButton :: TaggerWidget
|
||||
descriptorTreeRefreshBothButton =
|
||||
styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"Refresh"
|
||||
(DoDescriptorTreeEvent RefreshBothDescriptorTrees)
|
||||
|
||||
descriptorTreeLeaf :: TaggerModel -> Descriptor -> TaggerWidget
|
||||
descriptorTreeLeaf
|
||||
model@((^. descriptorTreeModel . descriptorInfoMap) -> m)
|
||||
d@(Descriptor dk p) =
|
||||
let di = m ^. descriptorInfoAt (fromIntegral dk)
|
||||
in box_ [alignLeft] $
|
||||
zstack_
|
||||
[]
|
||||
[ withNodeVisible
|
||||
( not $
|
||||
(model ^. descriptorTreeModel . descriptorTreeVis)
|
||||
`hasVis` VisibilityLabel editDescriptorVis
|
||||
)
|
||||
$ mainDescriptorLeafPageWidget di
|
||||
, withNodeVisible
|
||||
( (model ^. descriptorTreeModel . descriptorTreeVis)
|
||||
`hasVis` VisibilityLabel editDescriptorVis
|
||||
)
|
||||
editDescriptorLeafPageWidget
|
||||
]
|
||||
where
|
||||
mainDescriptorLeafPageWidget di =
|
||||
hstack_
|
||||
[]
|
||||
[ draggable d
|
||||
. box_ [alignLeft]
|
||||
. withStyleHover
|
||||
[ bgColor
|
||||
. modulateOpacity
|
||||
defaultElementOpacity
|
||||
$ yuiYellow
|
||||
, border 1
|
||||
. modulateOpacity
|
||||
defaultElementOpacity
|
||||
$ yuiOrange
|
||||
]
|
||||
. withStyleBasic
|
||||
[ textColor (if di ^. descriptorIsMeta then yuiBlue else black)
|
||||
, textLeft
|
||||
, bgColor
|
||||
. modulateOpacity
|
||||
0.0
|
||||
$ yuiLightPeach
|
||||
, border 1 . modulateOpacity 0.0 $ yuiLightPeach
|
||||
]
|
||||
$ button p (DoDescriptorTreeEvent (RequestFocusedNode p))
|
||||
]
|
||||
editDescriptorLeafPageWidget =
|
||||
hstack_
|
||||
[]
|
||||
[ box_ [alignLeft]
|
||||
. keystroke_
|
||||
[("Enter", DoDescriptorTreeEvent (UpdateDescriptor dk))]
|
||||
[]
|
||||
. withStyleBasic
|
||||
[ bgColor
|
||||
. modulateOpacity
|
||||
(defaultElementOpacity - defaultOpacityModulator)
|
||||
$ yuiLightPeach
|
||||
]
|
||||
$ textField_
|
||||
( descriptorTreeModel
|
||||
. descriptorInfoMap
|
||||
. descriptorInfoAt (fromIntegral dk)
|
||||
. renameText
|
||||
)
|
||||
[]
|
||||
, box_ [alignLeft]
|
||||
. withStyleHover
|
||||
[ bgColor
|
||||
. modulateOpacity defaultElementOpacity $yuiRed
|
||||
, textColor white
|
||||
]
|
||||
. withStyleBasic
|
||||
[ textColor yuiRed
|
||||
, bgColor
|
||||
. modulateOpacity
|
||||
(defaultElementOpacity - defaultOpacityModulator)
|
||||
$ yuiLightPeach
|
||||
]
|
||||
$ button_
|
||||
"Delete"
|
||||
( DoDescriptorTreeEvent
|
||||
(DeleteDescriptor d)
|
||||
)
|
||||
[resizeFactor (-1)]
|
||||
]
|
||||
|
||||
descriptorTreeFixedRequestButton :: Text -> TaggerWidget
|
||||
descriptorTreeFixedRequestButton t =
|
||||
styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"Top"
|
||||
(DoDescriptorTreeEvent . RequestFocusedNode $ t)
|
||||
|
||||
descriptorIsMetaInInfoMap :: TaggerModel -> Descriptor -> Bool
|
||||
descriptorIsMetaInInfoMap
|
||||
((^. descriptorTreeModel . descriptorInfoMap) -> m)
|
||||
(Descriptor (fromIntegral -> dk) _) = m ^. descriptorInfoAt dk . descriptorIsMeta
|
||||
|
||||
descriptorManagementPane :: TaggerWidget
|
||||
descriptorManagementPane =
|
||||
insertDescriptorWidget
|
||||
where
|
||||
insertDescriptorWidget :: TaggerWidget
|
||||
insertDescriptorWidget =
|
||||
keystroke_ [("Enter", DoDescriptorTreeEvent InsertDescriptor)] [] . hstack_ [] $
|
||||
[ editDescriptorLeafButton
|
||||
, insertButton
|
||||
, box_
|
||||
[ alignBottom
|
||||
, alignMiddle
|
||||
, sizeReqUpdater
|
||||
(\(xs, xy) -> both (& fixed .~ 0) (xs, xy))
|
||||
]
|
||||
. withStyleBasic
|
||||
[ bgColor
|
||||
. modulateOpacity (defaultElementOpacity - defaultOpacityModulator)
|
||||
$ yuiLightPeach
|
||||
]
|
||||
$ textField_ (descriptorTreeModel . newDescriptorText) []
|
||||
]
|
||||
where
|
||||
editDescriptorLeafButton =
|
||||
styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"Edit"
|
||||
(DoDescriptorTreeEvent . ToggleDescriptorTreeVisibility $ editDescriptorVis)
|
||||
insertButton =
|
||||
styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"New"
|
||||
(DoDescriptorTreeEvent InsertDescriptor)
|
||||
|
||||
editDescriptorVis :: Text
|
||||
editDescriptorVis = "edit-descriptor"
|
353
app/tagger/Interface/Widget/Internal/FileDetail.hs
Normal file
353
app/tagger/Interface/Widget/Internal/FileDetail.hs
Normal file
@ -0,0 +1,353 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE ViewPatterns #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
{-# HLINT ignore "Eta reduce" #-}
|
||||
|
||||
module Interface.Widget.Internal.FileDetail (
|
||||
widget,
|
||||
tagTextNodeKey,
|
||||
) where
|
||||
|
||||
import Control.Lens ((^.))
|
||||
import Data.Event (
|
||||
FileSelectionEvent (RenameFile),
|
||||
FocusedFileEvent (
|
||||
AppendTagText,
|
||||
CommitTagText,
|
||||
DeleteTag,
|
||||
MoveTag,
|
||||
NextTagHist,
|
||||
PrevTagHist,
|
||||
ResetTagHistIndex,
|
||||
TagFile,
|
||||
ToggleFocusedFilePaneVisibility
|
||||
),
|
||||
TaggerEvent (DoFileSelectionEvent, DoFocusedFileEvent, IOEvent),
|
||||
)
|
||||
import qualified Data.HashSet as HS
|
||||
import Data.HierarchyMap (HierarchyMap)
|
||||
import qualified Data.HierarchyMap as HM
|
||||
import qualified Data.List as L
|
||||
import Data.Model (
|
||||
HasFileInfoRenameText (fileInfoRenameText),
|
||||
HasFileSelectionInfoMap (fileSelectionInfoMap),
|
||||
HasFileSelectionModel (fileSelectionModel),
|
||||
HasFocusedFile (focusedFile),
|
||||
HasFocusedFileModel (focusedFileModel),
|
||||
HasFocusedFileVis (focusedFileVis),
|
||||
HasTagText (tagText),
|
||||
TaggerModel,
|
||||
fileInfoAt,
|
||||
focusedFileDefaultRecordKey,
|
||||
)
|
||||
import Data.Model.Shared (Visibility (VisibilityLabel), hasVis)
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Database.Tagger (
|
||||
ConcreteTag (ConcreteTag, concreteTagDescriptor, concreteTagId),
|
||||
ConcreteTaggedFile (ConcreteTaggedFile, concreteTaggedFile),
|
||||
Descriptor (Descriptor, descriptor),
|
||||
File (fileId, filePath),
|
||||
RecordKey,
|
||||
Tag,
|
||||
)
|
||||
import Interface.Theme (yuiBlue, yuiLightPeach, yuiPeach, yuiRed)
|
||||
import Interface.Widget.Internal.Core (
|
||||
defaultElementOpacity,
|
||||
defaultOpacityModulator,
|
||||
modulateOpacity,
|
||||
styledButton_,
|
||||
withNodeKey,
|
||||
withNodeVisible,
|
||||
withStyleBasic,
|
||||
)
|
||||
import Interface.Widget.Internal.Type (TaggerWidget)
|
||||
import Monomer (
|
||||
CmbAcceptTab (acceptTab),
|
||||
CmbAlignLeft (alignLeft),
|
||||
CmbAlignTop (alignTop),
|
||||
CmbBgColor (bgColor),
|
||||
CmbBorder (border),
|
||||
CmbBorderB (borderB),
|
||||
CmbMaxHeight (maxHeight),
|
||||
CmbOnChange (onChange),
|
||||
CmbPaddingR (paddingR),
|
||||
CmbResizeFactor (resizeFactor),
|
||||
CmbStyleHover (styleHoverSet),
|
||||
CmbTextColor (textColor),
|
||||
CmbWheelRate (wheelRate),
|
||||
CmbWidth (width),
|
||||
WidgetNode,
|
||||
black,
|
||||
box_,
|
||||
buttonD_,
|
||||
draggable,
|
||||
dropTargetStyle,
|
||||
dropTarget_,
|
||||
hstack_,
|
||||
keystroke_,
|
||||
label,
|
||||
label_,
|
||||
separatorLine,
|
||||
spacer,
|
||||
spacer_,
|
||||
textArea_,
|
||||
textField_,
|
||||
vscroll_,
|
||||
vstack,
|
||||
vstack_,
|
||||
zstack_,
|
||||
)
|
||||
|
||||
widget :: TaggerModel -> TaggerWidget
|
||||
widget m = detailPane m
|
||||
|
||||
detailPane :: TaggerModel -> TaggerWidget
|
||||
detailPane m =
|
||||
hstack_
|
||||
[]
|
||||
[ separatorLine
|
||||
, detailPaneTagsWidget m
|
||||
]
|
||||
|
||||
detailPaneTagsWidget :: TaggerModel -> TaggerWidget
|
||||
detailPaneTagsWidget
|
||||
m@( (^. focusedFileModel . focusedFile) ->
|
||||
(ConcreteTaggedFile _ hm)
|
||||
) =
|
||||
withStyleBasic
|
||||
[paddingR 20]
|
||||
$ vstack_
|
||||
[]
|
||||
[ filePathWidget m
|
||||
, separatorLine
|
||||
, vstack
|
||||
[ vscroll_ [wheelRate 50] $
|
||||
vstack
|
||||
[ metaLeaves
|
||||
hm
|
||||
( L.sortOn (descriptor . concreteTagDescriptor)
|
||||
. filter
|
||||
( \x ->
|
||||
HM.metaMember x hm
|
||||
&& not (HM.infraMember x hm)
|
||||
)
|
||||
. HM.keys
|
||||
$ hm
|
||||
)
|
||||
, spacer_ [resizeFactor (-1)]
|
||||
, nullMemberLeaves
|
||||
( L.sortOn (descriptor . concreteTagDescriptor)
|
||||
. filter
|
||||
( \x ->
|
||||
not (HM.metaMember x hm)
|
||||
&& not (HM.infraMember x hm)
|
||||
)
|
||||
. HM.keys
|
||||
$ hm
|
||||
)
|
||||
]
|
||||
, tagTextField
|
||||
, deleteTagZone
|
||||
]
|
||||
]
|
||||
|
||||
filePathWidget :: TaggerModel -> TaggerWidget
|
||||
filePathWidget m =
|
||||
hstack_
|
||||
[]
|
||||
[ withNodeVisible
|
||||
( focusedFileDefaultRecordKey
|
||||
/= (fileId . concreteTaggedFile $ m ^. focusedFileModel . focusedFile)
|
||||
)
|
||||
$ styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"Rename"
|
||||
( DoFocusedFileEvent
|
||||
(ToggleFocusedFilePaneVisibility fileRenameModeVis)
|
||||
)
|
||||
, zstack_
|
||||
[]
|
||||
[ withNodeVisible (not $ isFileRenameMode m) $
|
||||
label_
|
||||
(filePath . concreteTaggedFile $ m ^. focusedFileModel . focusedFile)
|
||||
[resizeFactor (-1)]
|
||||
, withNodeVisible (isFileRenameMode m)
|
||||
. keystroke_
|
||||
[
|
||||
( "Enter"
|
||||
, DoFileSelectionEvent
|
||||
. RenameFile
|
||||
$ ( fileId . concreteTaggedFile $
|
||||
m ^. focusedFileModel . focusedFile
|
||||
)
|
||||
)
|
||||
]
|
||||
[]
|
||||
. withStyleBasic
|
||||
[ bgColor
|
||||
. modulateOpacity
|
||||
(defaultElementOpacity - defaultOpacityModulator)
|
||||
$ yuiLightPeach
|
||||
]
|
||||
$ textField_
|
||||
( fileSelectionModel
|
||||
. fileSelectionInfoMap
|
||||
. fileInfoAt
|
||||
( fromIntegral
|
||||
. fileId
|
||||
. concreteTaggedFile
|
||||
$ m ^. focusedFileModel . focusedFile
|
||||
)
|
||||
. fileInfoRenameText
|
||||
)
|
||||
[]
|
||||
]
|
||||
]
|
||||
|
||||
fileRenameModeVis :: Text
|
||||
fileRenameModeVis = "file-rename"
|
||||
|
||||
isFileRenameMode :: TaggerModel -> Bool
|
||||
isFileRenameMode m =
|
||||
(m ^. focusedFileModel . focusedFileVis)
|
||||
`hasVis` VisibilityLabel fileRenameModeVis
|
||||
{-# INLINE isFileRenameMode #-}
|
||||
|
||||
nullMemberLeaves ::
|
||||
Traversable t =>
|
||||
t ConcreteTag ->
|
||||
WidgetNode TaggerModel TaggerEvent
|
||||
nullMemberLeaves members =
|
||||
withStyleBasic [borderB 1 black]
|
||||
. vstack_ []
|
||||
$ ( \ct@(ConcreteTag tk (Descriptor _ dp) _) ->
|
||||
subTagDropTarget tk
|
||||
. box_ [alignLeft, alignTop]
|
||||
. draggable ct
|
||||
$ label dp
|
||||
)
|
||||
<$> members
|
||||
|
||||
metaLeaves ::
|
||||
HierarchyMap ConcreteTag ->
|
||||
[ConcreteTag] ->
|
||||
WidgetNode TaggerModel TaggerEvent
|
||||
metaLeaves hm members =
|
||||
vstack_ [] . L.intersperse spacer $
|
||||
(flip metaLeaf hm <$> members)
|
||||
|
||||
metaLeaf ::
|
||||
ConcreteTag ->
|
||||
HierarchyMap ConcreteTag ->
|
||||
TaggerWidget
|
||||
metaLeaf l@(ConcreteTag tk (Descriptor _ dp) _) hmap =
|
||||
let subtags =
|
||||
L.sortOn (descriptor . concreteTagDescriptor)
|
||||
. HS.toList
|
||||
$ HM.find l hmap
|
||||
in if null subtags
|
||||
then
|
||||
subTagDropTarget tk . box_ [alignLeft, alignTop]
|
||||
. draggable l
|
||||
$ label dp
|
||||
else
|
||||
vstack_
|
||||
[]
|
||||
[ hstack_
|
||||
[]
|
||||
[ subTagDropTarget tk
|
||||
. box_ [alignLeft, alignTop]
|
||||
. draggable l
|
||||
. withStyleBasic [textColor yuiBlue]
|
||||
$ label dp
|
||||
, spacer
|
||||
, label "{"
|
||||
]
|
||||
, hstack_
|
||||
[]
|
||||
[ metaTagLeafSpacer
|
||||
, box_ [alignLeft, alignTop] $
|
||||
vstack
|
||||
( flip metaLeaf hmap
|
||||
<$> subtags
|
||||
)
|
||||
]
|
||||
, label "}"
|
||||
]
|
||||
|
||||
metaTagLeafSpacer :: TaggerWidget
|
||||
metaTagLeafSpacer = spacer_ [width 20]
|
||||
{-# INLINE metaTagLeafSpacer #-}
|
||||
|
||||
subTagDropTarget ::
|
||||
RecordKey Tag ->
|
||||
TaggerWidget ->
|
||||
TaggerWidget
|
||||
subTagDropTarget tk =
|
||||
dropTarget_
|
||||
(\(Descriptor dk _) -> DoFocusedFileEvent (TagFile dk (Just tk)))
|
||||
[dropTargetStyle [border 1 yuiBlue]]
|
||||
. dropTarget_
|
||||
( \ct ->
|
||||
DoFocusedFileEvent
|
||||
(MoveTag ct (Just tk))
|
||||
)
|
||||
[dropTargetStyle [border 1 yuiRed]]
|
||||
|
||||
deleteTagZone :: TaggerWidget
|
||||
deleteTagZone =
|
||||
dropTarget_
|
||||
(DoFocusedFileEvent . DeleteTag . concreteTagId)
|
||||
[dropTargetStyle [border 1 yuiRed]]
|
||||
. flip styleHoverSet []
|
||||
. withStyleBasic
|
||||
[ bgColor
|
||||
. modulateOpacity
|
||||
(defaultElementOpacity - defaultOpacityModulator)
|
||||
$ yuiLightPeach
|
||||
, border 1
|
||||
. modulateOpacity
|
||||
(defaultElementOpacity - defaultOpacityModulator)
|
||||
$ yuiPeach
|
||||
]
|
||||
$ buttonD_ "Delete" [resizeFactor (-1)]
|
||||
|
||||
tagTextNodeKey :: Text
|
||||
tagTextNodeKey = "tag-text-field"
|
||||
|
||||
tagTextField :: TaggerWidget
|
||||
tagTextField =
|
||||
keystroke_
|
||||
[ ("Shift-Enter", DoFocusedFileEvent CommitTagText)
|
||||
, ("Shift-Up", DoFocusedFileEvent NextTagHist)
|
||||
, ("Shift-Down", DoFocusedFileEvent PrevTagHist)
|
||||
]
|
||||
[]
|
||||
. dropTarget_
|
||||
(DoFocusedFileEvent . AppendTagText . descriptor . concreteTagDescriptor)
|
||||
[dropTargetStyle [border 1 yuiRed]]
|
||||
. dropTarget_
|
||||
(DoFocusedFileEvent . AppendTagText . descriptor)
|
||||
[dropTargetStyle [border 1 yuiBlue]]
|
||||
. withNodeKey tagTextNodeKey
|
||||
. withStyleBasic
|
||||
[ bgColor
|
||||
. modulateOpacity
|
||||
(defaultElementOpacity - defaultOpacityModulator)
|
||||
$ yuiLightPeach
|
||||
, maxHeight 250
|
||||
]
|
||||
$ textArea_
|
||||
(focusedFileModel . tagText)
|
||||
[ onChange
|
||||
( \t ->
|
||||
if T.null . T.strip $ t
|
||||
then DoFocusedFileEvent ResetTagHistIndex
|
||||
else
|
||||
IOEvent
|
||||
()
|
||||
)
|
||||
, acceptTab
|
||||
]
|
76
app/tagger/Interface/Widget/Internal/FilePreview.hs
Normal file
76
app/tagger/Interface/Widget/Internal/FilePreview.hs
Normal file
@ -0,0 +1,76 @@
|
||||
{-# LANGUAGE FlexibleContexts #-}
|
||||
{-# LANGUAGE ViewPatterns #-}
|
||||
|
||||
module Interface.Widget.Internal.FilePreview (
|
||||
widget,
|
||||
) where
|
||||
|
||||
import Control.Lens ((^.))
|
||||
import Data.Event (
|
||||
FocusedFileEvent (PutFile, TagFile, UnSubTag),
|
||||
TaggerEvent (DoFocusedFileEvent),
|
||||
)
|
||||
import Data.Model (
|
||||
HasFocusedFile (focusedFile),
|
||||
HasFocusedFileModel (focusedFileModel),
|
||||
TaggerModel,
|
||||
)
|
||||
import Database.Tagger (
|
||||
ConcreteTag (concreteTagId),
|
||||
ConcreteTaggedFile (concreteTaggedFile),
|
||||
Descriptor (Descriptor),
|
||||
File (filePath),
|
||||
)
|
||||
import Interface.Theme (yuiBlue, yuiOrange, yuiRed)
|
||||
import Interface.Widget.Internal.Core (withStyleBasic)
|
||||
import Interface.Widget.Internal.Type (TaggerWidget)
|
||||
import Monomer (
|
||||
CmbAlignCenter (alignCenter),
|
||||
CmbBorder (border),
|
||||
CmbFitEither (fitEither),
|
||||
CmbMergeRequired (mergeRequired),
|
||||
box_,
|
||||
dropTargetStyle,
|
||||
dropTarget_,
|
||||
image_,
|
||||
)
|
||||
|
||||
widget :: TaggerModel -> TaggerWidget
|
||||
widget
|
||||
( filePath
|
||||
. concreteTaggedFile
|
||||
. (^. focusedFileModel . focusedFile) ->
|
||||
fp
|
||||
) =
|
||||
dropTargets
|
||||
. styles
|
||||
. box_
|
||||
[mergeRequired mergeRequirement]
|
||||
$ image_ fp [fitEither, alignCenter]
|
||||
|
||||
styles :: TaggerWidget -> TaggerWidget
|
||||
styles = withStyleBasic []
|
||||
|
||||
dropTargets :: TaggerWidget -> TaggerWidget
|
||||
dropTargets =
|
||||
dropTarget_
|
||||
(DoFocusedFileEvent . PutFile)
|
||||
[dropTargetStyle [border 3 yuiOrange]]
|
||||
. dropTarget_
|
||||
(\(Descriptor dk _) -> DoFocusedFileEvent (TagFile dk Nothing))
|
||||
[dropTargetStyle [border 3 yuiBlue]]
|
||||
. dropTarget_
|
||||
(DoFocusedFileEvent . UnSubTag . concreteTagId)
|
||||
[dropTargetStyle [border 3 yuiRed]]
|
||||
|
||||
{- |
|
||||
If the file changes or the concrete tags attached to the file change.
|
||||
-}
|
||||
mergeRequirement ::
|
||||
p ->
|
||||
TaggerModel ->
|
||||
TaggerModel ->
|
||||
Bool
|
||||
mergeRequirement _ m1 m2 =
|
||||
concreteTaggedFile (m1 ^. focusedFileModel . focusedFile)
|
||||
/= concreteTaggedFile (m2 ^. focusedFileModel . focusedFile)
|
49
app/tagger/Interface/Widget/Internal/InfoPanel.hs
Normal file
49
app/tagger/Interface/Widget/Internal/InfoPanel.hs
Normal file
@ -0,0 +1,49 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE ViewPatterns #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
{-# HLINT ignore "Eta reduce" #-}
|
||||
|
||||
-- unused for now because I don't really care for it.
|
||||
module Interface.Widget.Internal.InfoPanel (widget) where
|
||||
|
||||
import Control.Lens ((^.))
|
||||
import Data.Model (
|
||||
HasLastAccessed (lastAccessed),
|
||||
HasMessage (message),
|
||||
HasTaggerInfoModel (taggerInfoModel),
|
||||
HasVersion (version),
|
||||
HasVersionMessage (versionMessage),
|
||||
HasWorkingDirectory (workingDirectory),
|
||||
TaggerModel,
|
||||
)
|
||||
import Interface.Widget.Internal.Core (withStyleBasic)
|
||||
import Interface.Widget.Internal.Type (TaggerWidget)
|
||||
import Monomer (
|
||||
CmbAlignMiddle (alignMiddle),
|
||||
CmbPaddingB (paddingB),
|
||||
CmbPaddingT (paddingT),
|
||||
CmbResizeFactor (resizeFactor),
|
||||
box_,
|
||||
label_,
|
||||
vstack,
|
||||
)
|
||||
|
||||
widget :: TaggerModel -> TaggerWidget
|
||||
widget m = taggerInfoWidget m
|
||||
|
||||
taggerInfoWidget :: TaggerModel -> TaggerWidget
|
||||
taggerInfoWidget ((^. taggerInfoModel) -> tim) =
|
||||
box_ [alignMiddle] $
|
||||
vstack $
|
||||
withStyleBasic [paddingT 2.5, paddingB 2.5]
|
||||
<$> ( [ flip label_ [resizeFactor (-1)] $ tim ^. message
|
||||
, flip label_ [resizeFactor (-1)] $ tim ^. versionMessage
|
||||
]
|
||||
++ ( (\(h, t) -> label_ (h <> ": " <> (tim ^. t)) [resizeFactor (-1)])
|
||||
<$> [ ("In Directory", workingDirectory)
|
||||
, ("Version", version)
|
||||
, ("Last Accessed", lastAccessed)
|
||||
]
|
||||
)
|
||||
)
|
68
app/tagger/Interface/Widget/Internal/Query.hs
Normal file
68
app/tagger/Interface/Widget/Internal/Query.hs
Normal file
@ -0,0 +1,68 @@
|
||||
{-# LANGUAGE FlexibleContexts #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE TupleSections #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
{-# HLINT ignore "Eta reduce" #-}
|
||||
|
||||
module Interface.Widget.Internal.Query (
|
||||
queryTextFieldKey,
|
||||
widget,
|
||||
) where
|
||||
|
||||
import Control.Lens
|
||||
import Data.Event
|
||||
import Data.Model
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Database.Tagger
|
||||
import Interface.Theme
|
||||
import Interface.Widget.Internal.Core
|
||||
import Interface.Widget.Internal.Type (TaggerWidget)
|
||||
import Monomer
|
||||
import Monomer.Graphics.Lens
|
||||
|
||||
widget :: TaggerModel -> TaggerWidget
|
||||
widget _ =
|
||||
container
|
||||
queryTextField
|
||||
|
||||
queryTextField :: TaggerWidget
|
||||
queryTextField =
|
||||
keystroke_
|
||||
[ ("Enter", DoFileSelectionEvent Query)
|
||||
, ("Up", DoFileSelectionEvent NextQueryHist)
|
||||
, ("Down", DoFileSelectionEvent PrevQueryHist)
|
||||
]
|
||||
[]
|
||||
. dropTarget_
|
||||
(DoFileSelectionEvent . AppendQueryText . descriptor . concreteTagDescriptor)
|
||||
[dropTargetStyle [border 1 yuiRed]]
|
||||
. dropTarget_
|
||||
(DoFileSelectionEvent . AppendQueryText . filePath)
|
||||
[dropTargetStyle [border 1 yuiOrange]]
|
||||
. dropTarget_
|
||||
(DoFileSelectionEvent . AppendQueryText . descriptor)
|
||||
[dropTargetStyle [border 1 yuiBlue]]
|
||||
. withNodeKey queryTextFieldKey
|
||||
. withStyleBasic [bgColor (yuiLightPeach & a .~ defaultElementOpacity)]
|
||||
$ textField_
|
||||
(fileSelectionModel . queryText)
|
||||
[ onChange
|
||||
( \t ->
|
||||
if T.null . T.strip $ t
|
||||
then DoFileSelectionEvent ResetQueryHistIndex
|
||||
else IOEvent ()
|
||||
)
|
||||
]
|
||||
|
||||
container :: TaggerWidget -> TaggerWidget
|
||||
container w =
|
||||
withStyleBasic [paddingT 5, paddingL 10]
|
||||
. box_ [alignLeft, alignBottom, ignoreEmptyArea]
|
||||
-- . withStyleBasic [borderT 1 black, borderB 1 black, borderR 1 black]
|
||||
$ w
|
||||
|
||||
queryTextFieldKey :: Text
|
||||
queryTextFieldKey = "queryTextField"
|
||||
{-# INLINE queryTextFieldKey #-}
|
484
app/tagger/Interface/Widget/Internal/Selection.hs
Normal file
484
app/tagger/Interface/Widget/Internal/Selection.hs
Normal file
@ -0,0 +1,484 @@
|
||||
{-# LANGUAGE BangPatterns #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# HLINT ignore "Use ||" #-}
|
||||
{-# LANGUAGE ViewPatterns #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
module Interface.Widget.Internal.Selection (
|
||||
widget,
|
||||
fileSelectionScrollWidgetNodeKey,
|
||||
) where
|
||||
|
||||
import Control.Lens ((&), (.~), (^.))
|
||||
import Data.Event (
|
||||
FileSelectionEvent (
|
||||
AddFiles,
|
||||
ClearSelection,
|
||||
CycleTagOrderCriteria,
|
||||
CycleTagOrderDirection,
|
||||
DeleteFileFromFileSystem,
|
||||
DoFileSelectionWidgetEvent,
|
||||
NextAddFileHist,
|
||||
PrevAddFileHist,
|
||||
RefreshFileSelection,
|
||||
RemoveFileFromDatabase,
|
||||
RemoveFileFromSelection,
|
||||
RenameFile,
|
||||
ResetAddFileHistIndex,
|
||||
RunSelectionShellCommand,
|
||||
ShuffleSelection,
|
||||
TogglePaneVisibility,
|
||||
ToggleSelectionView
|
||||
),
|
||||
FileSelectionWidgetEvent (CycleNextChunk, CyclePrevChunk),
|
||||
FocusedFileEvent (RunFocusedFileShellCommand),
|
||||
TaggerEvent (DoFileSelectionEvent, DoFocusedFileEvent, IOEvent),
|
||||
)
|
||||
import qualified Data.List as L
|
||||
import Data.Model.Core (TaggerModel, getSelectionChunk)
|
||||
import Data.Model.Lens (
|
||||
HasAddFileText (addFileText),
|
||||
HasChunkSequence (chunkSequence),
|
||||
HasChunkSize (chunkSize),
|
||||
HasCurrentChunk (currentChunk),
|
||||
HasDeleteFileIsVis (deleteFileIsVis),
|
||||
HasFileInfoRenameText (fileInfoRenameText),
|
||||
HasFileSelectionInfoMap (fileSelectionInfoMap),
|
||||
HasFileSelectionModel (fileSelectionModel),
|
||||
HasFileSelectionVis (fileSelectionVis),
|
||||
HasIsMassOpMode (isMassOpMode),
|
||||
HasSelection (selection),
|
||||
HasSetOp (setOp),
|
||||
HasShellText (shellText),
|
||||
HasTagOccurrences (tagOccurrences),
|
||||
HasTagOrdering (tagOrdering),
|
||||
fileInfoAt,
|
||||
)
|
||||
import Data.Model.Shared.Core (
|
||||
OrderBy (OrderBy),
|
||||
OrderCriteria (Alphabetic, Numeric),
|
||||
OrderDirection (Asc, Desc),
|
||||
Visibility (VisibilityAlt, VisibilityLabel),
|
||||
hasVis,
|
||||
)
|
||||
import qualified Data.OccurrenceHashMap as OHM
|
||||
import qualified Data.Ord as O
|
||||
import Data.Sequence ((|>))
|
||||
import qualified Data.Sequence as Seq
|
||||
import Data.Tagger (SetOp (Difference, Intersect, Union))
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Database.Tagger (Descriptor (descriptor), File (File))
|
||||
import Interface.Theme (yuiLightPeach, yuiRed)
|
||||
import Interface.Widget.Internal.Core (
|
||||
styledButton_,
|
||||
withNodeKey,
|
||||
withNodeVisible,
|
||||
withStyleBasic,
|
||||
withStyleHover,
|
||||
)
|
||||
import Interface.Widget.Internal.Type (TaggerWidget)
|
||||
import Monomer (
|
||||
CmbAlignBottom (alignBottom),
|
||||
CmbAlignCenter (alignCenter),
|
||||
CmbAlignTop (alignTop),
|
||||
CmbBgColor (bgColor),
|
||||
CmbBorder (border),
|
||||
CmbBorderL (borderL),
|
||||
CmbChildSpacing (childSpacing_),
|
||||
CmbIgnoreChildrenEvts (ignoreChildrenEvts),
|
||||
CmbMaxWidth (maxWidth),
|
||||
CmbMergeRequired (mergeRequired),
|
||||
CmbMinValue (minValue),
|
||||
CmbMinWidth (minWidth),
|
||||
CmbOnChange (onChange),
|
||||
CmbPaddingL (paddingL),
|
||||
CmbPaddingR (paddingR),
|
||||
CmbResizeFactor (resizeFactor),
|
||||
CmbSizeReqUpdater (sizeReqUpdater),
|
||||
CmbTextColor (textColor),
|
||||
CmbTextLeft (textLeft),
|
||||
CmbTextRight (textRight),
|
||||
CmbWheelRate (wheelRate),
|
||||
black,
|
||||
box_,
|
||||
draggable,
|
||||
dropdown,
|
||||
hgrid_,
|
||||
hstack,
|
||||
hstack_,
|
||||
keystroke,
|
||||
keystroke_,
|
||||
label,
|
||||
label_,
|
||||
numericField_,
|
||||
separatorLine,
|
||||
textField_,
|
||||
toggleButton_,
|
||||
tooltipDelay,
|
||||
tooltip_,
|
||||
vscroll_,
|
||||
vstack_,
|
||||
white,
|
||||
zstack,
|
||||
zstack_,
|
||||
)
|
||||
import Monomer.Core.Lens (fixed)
|
||||
import Util (both)
|
||||
|
||||
widget :: TaggerModel -> TaggerWidget
|
||||
widget m =
|
||||
vstack_
|
||||
[]
|
||||
[ fileSelectionWidgetHeader
|
||||
, zstack_
|
||||
[]
|
||||
[ withNodeVisible (not selectionIsVisible) $ tagListWidget m
|
||||
, withNodeVisible selectionIsVisible $ fileSelectionFileList m
|
||||
]
|
||||
]
|
||||
where
|
||||
selectionIsVisible =
|
||||
(m ^. fileSelectionModel . fileSelectionVis) `hasVis` VisibilityAlt
|
||||
fileSelectionWidgetHeader =
|
||||
hstack_
|
||||
[]
|
||||
[ selectionSizeLabel m
|
||||
, setOpDrowpdown
|
||||
]
|
||||
|
||||
setOpDrowpdown :: TaggerWidget
|
||||
setOpDrowpdown =
|
||||
dropdown
|
||||
(fileSelectionModel . setOp)
|
||||
[Union, Intersect, Difference]
|
||||
(flip label_ [resizeFactor (-1)] . T.pack . show)
|
||||
(flip label_ [resizeFactor (-1)] . T.pack . show)
|
||||
|
||||
clearSelectionButton :: TaggerWidget
|
||||
clearSelectionButton =
|
||||
styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"Clear"
|
||||
(DoFileSelectionEvent ClearSelection)
|
||||
|
||||
selectionSizeLabel :: TaggerModel -> TaggerWidget
|
||||
selectionSizeLabel ((^. fileSelectionModel . selection) -> selSeq) =
|
||||
withStyleBasic [maxWidth 80]
|
||||
. box_ [alignCenter]
|
||||
. flip label_ [resizeFactor (-1)]
|
||||
$ ( T.pack . show
|
||||
. Seq.length
|
||||
$ selSeq
|
||||
)
|
||||
|
||||
tagListWidget :: TaggerModel -> TaggerWidget
|
||||
tagListWidget m =
|
||||
vstack_
|
||||
[]
|
||||
[ tagListHeader
|
||||
, separatorLine
|
||||
, vscroll_ [wheelRate 50]
|
||||
. box_
|
||||
[ alignTop
|
||||
, alignCenter
|
||||
, mergeRequired
|
||||
( \_ m1 m2 ->
|
||||
let neq l = m1 ^. fileSelectionModel . l /= m2 ^. fileSelectionModel . l
|
||||
in or [neq tagOccurrences, neq tagOrdering]
|
||||
)
|
||||
]
|
||||
$ vstack_ [] (tagListLeaf <$> sortedOccurrenceMapList)
|
||||
]
|
||||
where
|
||||
tagListHeader =
|
||||
hstack_
|
||||
[]
|
||||
[ toggleViewSelectionButton
|
||||
, clearSelectionButton
|
||||
, tagListOrderCritCycleButton
|
||||
, tagListOrderDirCycleButton
|
||||
]
|
||||
sortedOccurrenceMapList =
|
||||
let (OrderBy ordCrit ordDir) = m ^. fileSelectionModel . tagOrdering
|
||||
!occurrenceMapList = OHM.toList $ m ^. fileSelectionModel . tagOccurrences
|
||||
in case (ordCrit, ordDir) of
|
||||
(Alphabetic, Asc) -> L.sortOn (descriptor . fst) occurrenceMapList
|
||||
(Alphabetic, Desc) -> L.sortOn (O.Down . descriptor . fst) occurrenceMapList
|
||||
(Numeric, Asc) -> L.sortOn snd occurrenceMapList
|
||||
(Numeric, Desc) -> L.sortOn (O.Down . snd) occurrenceMapList
|
||||
tagListOrderCritCycleButton =
|
||||
let (OrderBy ordCrit _) = m ^. fileSelectionModel . tagOrdering
|
||||
btnText =
|
||||
case ordCrit of
|
||||
Alphabetic -> "ABC"
|
||||
Numeric -> "123"
|
||||
in styledButton_
|
||||
[resizeFactor (-1)]
|
||||
btnText
|
||||
(DoFileSelectionEvent CycleTagOrderCriteria)
|
||||
tagListOrderDirCycleButton =
|
||||
let (OrderBy _ ordDir) = m ^. fileSelectionModel . tagOrdering
|
||||
in styledButton_
|
||||
[resizeFactor (-1)]
|
||||
(T.pack . show $ ordDir)
|
||||
(DoFileSelectionEvent CycleTagOrderDirection)
|
||||
tagListLeaf (d, n) =
|
||||
hgrid_
|
||||
[childSpacing_ 0]
|
||||
[ draggable d . withStyleBasic [textRight, paddingR 1.5]
|
||||
. flip label_ []
|
||||
. descriptor
|
||||
$ d
|
||||
, withStyleBasic [paddingL 1.5, borderL 1 black] . label . T.pack . show $ n
|
||||
]
|
||||
|
||||
toggleViewSelectionButton :: TaggerWidget
|
||||
toggleViewSelectionButton =
|
||||
styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"View"
|
||||
(DoFileSelectionEvent ToggleSelectionView)
|
||||
|
||||
fileSelectionFileList :: TaggerModel -> TaggerWidget
|
||||
fileSelectionFileList m =
|
||||
vstack_
|
||||
[]
|
||||
[ fileSelectionHeader
|
||||
, separatorLine
|
||||
, fileListBody
|
||||
]
|
||||
where
|
||||
fileListBody =
|
||||
box_
|
||||
[ alignTop
|
||||
, alignCenter
|
||||
, fileListMergeRequirement
|
||||
]
|
||||
. withNodeKey fileSelectionScrollWidgetNodeKey
|
||||
. vscroll_
|
||||
[ wheelRate 50
|
||||
]
|
||||
. vstack_ []
|
||||
. flip (|>) (hstack [toggleFileEditMode, addFilesWidget])
|
||||
$ ( fmap fileSelectionLeaf renderedChunks
|
||||
Seq.>< Seq.fromList fileListPaginationWidgets
|
||||
)
|
||||
where
|
||||
fileListPaginationWidgets =
|
||||
[ box_ [alignBottom, alignCenter] $
|
||||
hstack_
|
||||
[]
|
||||
[ styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"<-"
|
||||
( DoFileSelectionEvent
|
||||
. DoFileSelectionWidgetEvent
|
||||
$ CyclePrevChunk
|
||||
)
|
||||
, label_
|
||||
( ( T.pack . show . succ $
|
||||
m ^. fileSelectionModel . currentChunk
|
||||
)
|
||||
<> "/"
|
||||
<> ( T.pack
|
||||
. show
|
||||
. Seq.length
|
||||
$ m ^. fileSelectionModel . chunkSequence
|
||||
)
|
||||
)
|
||||
[resizeFactor (-1)]
|
||||
, styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"->"
|
||||
( DoFileSelectionEvent
|
||||
. DoFileSelectionWidgetEvent
|
||||
$ CycleNextChunk
|
||||
)
|
||||
]
|
||||
]
|
||||
fileListMergeRequirement =
|
||||
mergeRequired
|
||||
( \_ m1 m2 ->
|
||||
let neq l = m1 ^. fileSelectionModel . l /= m2 ^. fileSelectionModel . l
|
||||
in or
|
||||
[ neq selection
|
||||
, neq fileSelectionInfoMap
|
||||
, neq currentChunk
|
||||
, neq chunkSequence
|
||||
, neq chunkSize
|
||||
, neq fileSelectionVis
|
||||
]
|
||||
)
|
||||
renderedChunks =
|
||||
getSelectionChunk m
|
||||
fileSelectionHeader :: TaggerWidget
|
||||
fileSelectionHeader =
|
||||
hstack_
|
||||
[]
|
||||
[ toggleViewSelectionButton
|
||||
, clearSelectionButton
|
||||
, shuffleSelectionButton
|
||||
, refreshFileSelectionButton
|
||||
, fileSelectionChunkSizeNumField
|
||||
, -- , toggleFileEditMode
|
||||
shellCommandWidget m
|
||||
]
|
||||
fileSelectionLeaf :: File -> TaggerWidget
|
||||
fileSelectionLeaf f@(File fk fp) =
|
||||
zstack_
|
||||
[]
|
||||
[ withNodeVisible
|
||||
( not isEditMode
|
||||
)
|
||||
. draggable f
|
||||
. withStyleBasic [textLeft]
|
||||
$ label_ fp [resizeFactor (-1)]
|
||||
, withNodeVisible isEditMode editModeWidget
|
||||
]
|
||||
where
|
||||
editModeWidget =
|
||||
hstack_
|
||||
[]
|
||||
[ removeFromSelectionButton
|
||||
, renameFileTextField
|
||||
, removeFileFromDatabaseButton
|
||||
, deleteFileFromFileSystemButton
|
||||
]
|
||||
where
|
||||
deleteFileFromFileSystemButton :: TaggerWidget
|
||||
deleteFileFromFileSystemButton =
|
||||
zstack
|
||||
[ withNodeVisible confirmDeleteVis
|
||||
. tooltip_
|
||||
"Deletes the file from the database and file system."
|
||||
[tooltipDelay 500]
|
||||
. withStyleHover [textColor white, bgColor yuiRed, border 1 black]
|
||||
. withStyleBasic [textColor yuiRed, bgColor yuiLightPeach, border 1 black]
|
||||
$ styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"Confirm"
|
||||
(DoFileSelectionEvent . DeleteFileFromFileSystem $ fk)
|
||||
, withNodeVisible
|
||||
(not confirmDeleteVis)
|
||||
. tooltip_
|
||||
"Deletes the file from the database and file system."
|
||||
[tooltipDelay 500]
|
||||
. withStyleHover [textColor white, bgColor yuiRed, border 1 black]
|
||||
. withStyleBasic [textColor yuiRed, bgColor yuiLightPeach, border 1 black]
|
||||
$ toggleButton_
|
||||
"Delete"
|
||||
( fileSelectionModel
|
||||
. fileSelectionInfoMap
|
||||
. fileInfoAt (fromIntegral fk)
|
||||
. deleteFileIsVis
|
||||
)
|
||||
[resizeFactor (-1)]
|
||||
]
|
||||
where
|
||||
confirmDeleteVis =
|
||||
m
|
||||
^. fileSelectionModel
|
||||
. fileSelectionInfoMap
|
||||
. fileInfoAt (fromIntegral fk)
|
||||
. deleteFileIsVis
|
||||
removeFileFromDatabaseButton :: TaggerWidget
|
||||
removeFileFromDatabaseButton =
|
||||
withStyleBasic [bgColor yuiLightPeach]
|
||||
. tooltip_ "Removes the file from the database only." [tooltipDelay 1500]
|
||||
. withStyleHover [bgColor yuiRed]
|
||||
$ styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"Remove"
|
||||
(DoFileSelectionEvent . RemoveFileFromDatabase $ fk)
|
||||
renameFileTextField :: TaggerWidget
|
||||
renameFileTextField =
|
||||
keystroke_
|
||||
[("Enter", DoFileSelectionEvent . RenameFile $ fk)]
|
||||
[ignoreChildrenEvts]
|
||||
$ textField_
|
||||
( fileSelectionModel
|
||||
. fileSelectionInfoMap
|
||||
. fileInfoAt (fromIntegral fk)
|
||||
. fileInfoRenameText
|
||||
)
|
||||
[]
|
||||
removeFromSelectionButton =
|
||||
styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"-"
|
||||
(DoFileSelectionEvent (RemoveFileFromSelection fk))
|
||||
isEditMode =
|
||||
(m ^. fileSelectionModel . fileSelectionVis)
|
||||
`hasVis` VisibilityLabel editFileMode
|
||||
|
||||
shellCommandWidget :: TaggerModel -> TaggerWidget
|
||||
shellCommandWidget ((^. isMassOpMode) -> isMassOpModeIsTrue) =
|
||||
box_ [sizeReqUpdater (both (& fixed .~ 0))] $
|
||||
hstack
|
||||
[ toggleButton_ "MassOp" isMassOpMode []
|
||||
, keystroke_
|
||||
[
|
||||
( "Enter"
|
||||
, if isMassOpModeIsTrue
|
||||
then DoFileSelectionEvent RunSelectionShellCommand
|
||||
else DoFocusedFileEvent RunFocusedFileShellCommand
|
||||
)
|
||||
]
|
||||
[ignoreChildrenEvts]
|
||||
. withStyleBasic [minWidth 80]
|
||||
$ textField_ shellText []
|
||||
]
|
||||
|
||||
fileSelectionChunkSizeNumField :: TaggerWidget
|
||||
fileSelectionChunkSizeNumField =
|
||||
withStyleBasic [maxWidth 80] $
|
||||
numericField_ (fileSelectionModel . chunkSize) [minValue 0]
|
||||
|
||||
refreshFileSelectionButton :: TaggerWidget
|
||||
refreshFileSelectionButton =
|
||||
styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"Refresh"
|
||||
(DoFileSelectionEvent RefreshFileSelection)
|
||||
|
||||
shuffleSelectionButton :: TaggerWidget
|
||||
shuffleSelectionButton =
|
||||
styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"Shuffle"
|
||||
(DoFileSelectionEvent ShuffleSelection)
|
||||
|
||||
addFilesWidget :: TaggerWidget
|
||||
addFilesWidget =
|
||||
keystroke
|
||||
[ ("Enter", DoFileSelectionEvent AddFiles)
|
||||
, ("Up", DoFileSelectionEvent NextAddFileHist)
|
||||
, ("Down", DoFileSelectionEvent PrevAddFileHist)
|
||||
]
|
||||
$ hstack_
|
||||
[]
|
||||
[ styledButton_ [resizeFactor (-1)] "Add" (DoFileSelectionEvent AddFiles)
|
||||
, textField_
|
||||
(fileSelectionModel . addFileText)
|
||||
[ onChange
|
||||
( \t ->
|
||||
if T.null t
|
||||
then DoFileSelectionEvent ResetAddFileHistIndex
|
||||
else IOEvent ()
|
||||
)
|
||||
]
|
||||
]
|
||||
|
||||
toggleFileEditMode :: TaggerWidget
|
||||
toggleFileEditMode =
|
||||
styledButton_
|
||||
[resizeFactor (-1)]
|
||||
"Edit"
|
||||
(DoFileSelectionEvent (TogglePaneVisibility editFileMode))
|
||||
|
||||
editFileMode :: Text
|
||||
editFileMode = "edit-file"
|
||||
|
||||
fileSelectionScrollWidgetNodeKey :: Text
|
||||
fileSelectionScrollWidgetNodeKey = "file-selection-scroll-widget"
|
9
app/tagger/Interface/Widget/Internal/Type.hs
Normal file
9
app/tagger/Interface/Widget/Internal/Type.hs
Normal file
@ -0,0 +1,9 @@
|
||||
module Interface.Widget.Internal.Type (
|
||||
TaggerWidget,
|
||||
) where
|
||||
|
||||
import Data.Event (TaggerEvent)
|
||||
import Data.Model (TaggerModel)
|
||||
import Monomer (WidgetNode)
|
||||
|
||||
type TaggerWidget = WidgetNode TaggerModel TaggerEvent
|
118
app/tagger/Main.hs
Normal file
118
app/tagger/Main.hs
Normal file
@ -0,0 +1,118 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
{-# HLINT ignore "Use lambda-case" #-}
|
||||
|
||||
import Control.Monad (guard, when)
|
||||
import Control.Monad.Trans.Except (
|
||||
ExceptT,
|
||||
runExceptT,
|
||||
throwE,
|
||||
withExceptT,
|
||||
)
|
||||
import Data.Model.Core (
|
||||
createTaggerModel,
|
||||
focusedFileDefaultDataFile,
|
||||
)
|
||||
import qualified Data.Text as T
|
||||
import Data.Version (showVersion)
|
||||
import Database.Tagger (Descriptor (Descriptor), open)
|
||||
import Interface (runTagger)
|
||||
import Paths_tagger (getDataFileName)
|
||||
import System.Console.GetOpt (
|
||||
ArgDescr (NoArg, ReqArg),
|
||||
ArgOrder (ReturnInOrder),
|
||||
OptDescr (..),
|
||||
getOpt,
|
||||
)
|
||||
import System.Directory (
|
||||
getCurrentDirectory,
|
||||
makeAbsolute,
|
||||
setCurrentDirectory,
|
||||
)
|
||||
import System.Environment (getArgs)
|
||||
import System.FilePath (takeDirectory)
|
||||
import System.IO (hPutStrLn, stderr)
|
||||
import Tagger.Info (taggerVersion)
|
||||
|
||||
data ProgArg
|
||||
= ProgVersion
|
||||
| ProgDBPath FilePath
|
||||
deriving (Show, Eq)
|
||||
|
||||
options :: [OptDescr ProgArg]
|
||||
options =
|
||||
[ Option
|
||||
"vV"
|
||||
["version"]
|
||||
(NoArg ProgVersion)
|
||||
"Show the version."
|
||||
, Option
|
||||
"pP"
|
||||
["path"]
|
||||
(ReqArg ProgDBPath "PATH")
|
||||
"The path to the tagger database."
|
||||
]
|
||||
|
||||
argOrder :: ArgOrder ProgArg
|
||||
argOrder = ReturnInOrder ProgDBPath
|
||||
|
||||
main :: IO ()
|
||||
main = do
|
||||
argString <- getArgs
|
||||
let p@(opts, _, _) =
|
||||
getOpt argOrder options argString
|
||||
when
|
||||
(ProgVersion `elem` opts)
|
||||
(putStrLn . showVersion $ taggerVersion)
|
||||
eitherDBPath <- runExceptT $ getConnString p
|
||||
either (hPutStrLn stderr) withDBPath eitherDBPath
|
||||
where
|
||||
head' [] = Nothing
|
||||
head' (x : _) = Just x
|
||||
|
||||
getConnString ::
|
||||
([ProgArg], [String], [String]) ->
|
||||
ExceptT String IO ProgArg
|
||||
getConnString (opts, nonOpts, errors) = do
|
||||
withExceptT
|
||||
(const ("Unknown options: " ++ unlines nonOpts))
|
||||
(guard (null nonOpts) :: ExceptT String IO ())
|
||||
withExceptT
|
||||
(const ("Errors reading options: " ++ unlines errors))
|
||||
(guard (null errors) :: ExceptT String IO ())
|
||||
maybe
|
||||
(throwE "No database path specified, use '-p PATH'")
|
||||
return
|
||||
( head'
|
||||
. filter
|
||||
(\x -> case x of (ProgDBPath _) -> True; _ -> False)
|
||||
$ opts
|
||||
)
|
||||
|
||||
withDBPath :: ProgArg -> IO ()
|
||||
withDBPath (ProgDBPath p) = do
|
||||
workingDir <- getCurrentDirectory
|
||||
dbDir <- makeAbsolute . takeDirectory $ p
|
||||
setCurrentDirectory dbDir
|
||||
runProgram p
|
||||
setCurrentDirectory workingDir
|
||||
withDBPath _ =
|
||||
hPutStrLn
|
||||
stderr
|
||||
"Something went wrong with the given database path option."
|
||||
|
||||
{- |
|
||||
Entry point for running the monomer program.
|
||||
-}
|
||||
runProgram :: FilePath -> IO ()
|
||||
runProgram p = do
|
||||
db <- open p
|
||||
defaultFile <- T.pack <$> getDataFileName focusedFileDefaultDataFile
|
||||
runTagger
|
||||
( createTaggerModel
|
||||
db
|
||||
(Descriptor (-1) "fake descriptor")
|
||||
(Descriptor (-2) "fake #UNRELATED#")
|
||||
defaultFile
|
||||
)
|
11
app/tagger/Util.hs
Normal file
11
app/tagger/Util.hs
Normal file
@ -0,0 +1,11 @@
|
||||
module Util (
|
||||
head',
|
||||
both,
|
||||
) where
|
||||
|
||||
head' :: [a] -> Maybe a
|
||||
head' [] = Nothing
|
||||
head' xs = Just . head $ xs
|
||||
|
||||
both :: (t -> b) -> (t, t) -> (b, b)
|
||||
both f (x, y) = (f x, f y)
|
89
app/taggercli/Main.hs
Normal file
89
app/taggercli/Main.hs
Normal file
@ -0,0 +1,89 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE ViewPatterns #-}
|
||||
{-# OPTIONS_GHC -Wno-typed-holes #-}
|
||||
|
||||
import Control.Lens ((^.))
|
||||
import Control.Monad (void, when, (<=<))
|
||||
import Control.Monad.IO.Class (MonadIO (liftIO))
|
||||
import Control.Monad.Trans.Reader (ReaderT (runReaderT), ask)
|
||||
import qualified Data.Foldable as F
|
||||
import qualified Data.HashSet as HS
|
||||
import Data.List (sortOn)
|
||||
import Data.Monoid (Any (..))
|
||||
import qualified Data.Text as T
|
||||
import qualified Data.Text.IO as T.IO
|
||||
import Data.Version (showVersion)
|
||||
import Database.Tagger (
|
||||
File (filePath),
|
||||
HasConnName (connName),
|
||||
TaggedConnection,
|
||||
open',
|
||||
)
|
||||
import Opt (mainReportAudit, showStats)
|
||||
import Opt.Data (
|
||||
TaggerCommand (TaggerCommand),
|
||||
TaggerDBCommand (TaggerDBCommand),
|
||||
TaggerEx (..),
|
||||
TaggerQueryCommand (TaggerQueryCommand),
|
||||
)
|
||||
import Opt.Parser (taggerExParser)
|
||||
import Options.Applicative (execParser)
|
||||
import System.Directory (
|
||||
getCurrentDirectory,
|
||||
makeAbsolute,
|
||||
setCurrentDirectory,
|
||||
)
|
||||
import System.FilePath (makeRelative, takeDirectory)
|
||||
import System.IO (stderr)
|
||||
import Tagger.Info (taggerVersion)
|
||||
import Text.TaggerQL (TaggerQLQuery (TaggerQLQuery), taggerQL)
|
||||
|
||||
main :: IO ()
|
||||
main = do
|
||||
p <- execParser taggerExParser
|
||||
runTaggerEx p
|
||||
|
||||
runTaggerEx :: TaggerEx -> IO ()
|
||||
runTaggerEx TaggerExVersion = putStrLn . showVersion $ taggerVersion
|
||||
runTaggerEx
|
||||
( TaggerExDB
|
||||
dbPath
|
||||
( TaggerDBCommand
|
||||
a
|
||||
s
|
||||
(TaggerCommand qc)
|
||||
)
|
||||
) =
|
||||
do
|
||||
curDir <- getCurrentDirectory
|
||||
let dbDir = takeDirectory dbPath
|
||||
setCurrentDirectory dbDir
|
||||
conn <- open' dbPath
|
||||
void . flip runReaderT conn $ do
|
||||
when (getAny a) mainReportAudit
|
||||
when (getAny s) showStats
|
||||
maybe (pure ()) runQuery qc
|
||||
setCurrentDirectory curDir
|
||||
where
|
||||
runQuery :: TaggerQueryCommand -> ReaderT TaggedConnection IO ()
|
||||
runQuery (TaggerQueryCommand q (Any rel)) = do
|
||||
tc <- ask
|
||||
let (T.unpack -> connPath) = tc ^. connName
|
||||
liftIO $ do
|
||||
queryResults <- taggerQL (TaggerQLQuery q) tc
|
||||
if HS.null queryResults
|
||||
then T.IO.hPutStrLn stderr "No Results."
|
||||
else
|
||||
mapM_
|
||||
( ( T.IO.putStrLn . T.pack
|
||||
<=< if rel
|
||||
then pure
|
||||
else makeAbsolute
|
||||
)
|
||||
. makeRelative connPath
|
||||
. T.unpack
|
||||
. filePath
|
||||
)
|
||||
. sortOn filePath
|
||||
. F.toList
|
||||
$ queryResults
|
223
app/taggercli/Opt.hs
Normal file
223
app/taggercli/Opt.hs
Normal file
@ -0,0 +1,223 @@
|
||||
{-# LANGUAGE BangPatterns #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE ViewPatterns #-}
|
||||
{-# OPTIONS_GHC -Wno-typed-holes #-}
|
||||
|
||||
module Opt (
|
||||
mainReportAudit,
|
||||
auditDatabase,
|
||||
reportAudit,
|
||||
showStats,
|
||||
getConcreteFiles,
|
||||
reportTags,
|
||||
) where
|
||||
|
||||
import Control.Lens ((&), (.~), (^.))
|
||||
import Control.Monad (filterM, unless, void, when)
|
||||
import Control.Monad.IO.Class (MonadIO (liftIO))
|
||||
import Control.Monad.Trans.Class (MonadTrans (lift))
|
||||
import Control.Monad.Trans.Maybe
|
||||
import Control.Monad.Trans.Reader (ReaderT (..), ask, asks)
|
||||
import Control.Monad.Trans.State.Strict (
|
||||
StateT,
|
||||
execStateT,
|
||||
modify,
|
||||
)
|
||||
import qualified Data.Foldable as F
|
||||
import Data.HashSet (HashSet)
|
||||
import qualified Data.HashSet as HS
|
||||
import Data.HierarchyMap (HierarchyMap)
|
||||
import qualified Data.HierarchyMap as HRM
|
||||
import qualified Data.IntMap.Strict as IM
|
||||
import Data.List (sortOn)
|
||||
import Data.Maybe (catMaybes)
|
||||
import qualified Data.OccurrenceMap as OM (
|
||||
OccurrenceMap (occurrenceMap),
|
||||
)
|
||||
import qualified Data.Text as T
|
||||
import qualified Data.Text.IO as T.IO
|
||||
import Database.Tagger (
|
||||
allDescriptors,
|
||||
allFiles,
|
||||
allTags,
|
||||
getAllInfra,
|
||||
getTagOccurrencesByDescriptorKeys,
|
||||
queryForConcreteTaggedFileWithFileId,
|
||||
)
|
||||
import Database.Tagger.Type (
|
||||
ConcreteTag (concreteTagDescriptor),
|
||||
ConcreteTaggedFile (ConcreteTaggedFile),
|
||||
Descriptor (..),
|
||||
File (fileId, filePath),
|
||||
HasConnName (connName),
|
||||
TaggedConnection,
|
||||
)
|
||||
import Opt.Data (TaggerDBAudit, TaggerDBStats (..))
|
||||
import Opt.Data.Lens (
|
||||
HasMissingFiles (missingFiles),
|
||||
HasUnusedDescriptorTrees (unusedDescriptorTrees),
|
||||
)
|
||||
import System.Directory (
|
||||
doesFileExist,
|
||||
)
|
||||
|
||||
mainReportAudit :: ReaderT TaggedConnection IO ()
|
||||
mainReportAudit = do
|
||||
tc <- ask
|
||||
let dbText = tc ^. connName
|
||||
void $
|
||||
do
|
||||
liftIO . T.IO.putStrLn $ "Running audit on: " <> dbText
|
||||
auditResult <- auditDatabase
|
||||
liftIO $ reportAudit auditResult
|
||||
|
||||
reportAudit :: TaggerDBAudit -> IO ()
|
||||
reportAudit a = do
|
||||
T.IO.putStrLn $
|
||||
"Files in database that are unable to be found in the filesystem: "
|
||||
<> (T.pack . show . length $ a ^. missingFiles)
|
||||
mapM_ (\f -> T.IO.putStrLn $ "\t" <> filePath f) (a ^. missingFiles)
|
||||
T.IO.putStrLn ""
|
||||
T.IO.putStrLn $
|
||||
"Descriptors that are unused and have no InfraDescriptors that are used: "
|
||||
<> (T.pack . show . length $ a ^. unusedDescriptorTrees)
|
||||
mapM_
|
||||
(\d -> T.IO.putStrLn $ "\t" <> descriptor d)
|
||||
(a ^. unusedDescriptorTrees)
|
||||
|
||||
auditDatabase :: ReaderT TaggedConnection IO TaggerDBAudit
|
||||
auditDatabase = mconcat <$> sequence [findMissingFiles, findUnusedDescriptorTrees]
|
||||
|
||||
{- |
|
||||
Reports all files that do not exist or are impossible to find from the current
|
||||
directory.
|
||||
-}
|
||||
findMissingFiles ::
|
||||
ReaderT
|
||||
TaggedConnection
|
||||
IO
|
||||
TaggerDBAudit
|
||||
findMissingFiles = do
|
||||
tc <- ask
|
||||
allDBFiles <- lift $ allFiles tc
|
||||
allMissingFiles <-
|
||||
sortOn filePath
|
||||
<$> filterM
|
||||
( lift
|
||||
. fmap not
|
||||
. doesFileExist
|
||||
. T.unpack
|
||||
. filePath
|
||||
)
|
||||
allDBFiles
|
||||
return $ mempty & missingFiles .~ allMissingFiles
|
||||
|
||||
{- |
|
||||
Reports all Descriptors which are not applied to any file
|
||||
nor are any descriptors infra to them.
|
||||
Signifying that they are safe to delete from the database.
|
||||
-}
|
||||
findUnusedDescriptorTrees ::
|
||||
ReaderT
|
||||
TaggedConnection
|
||||
IO
|
||||
TaggerDBAudit
|
||||
findUnusedDescriptorTrees = do
|
||||
tc <- ask
|
||||
allDBDescriptors <- lift (allDescriptors tc)
|
||||
unusedDescriptorTreeList <-
|
||||
filter
|
||||
( \(Descriptor _ dt) ->
|
||||
not
|
||||
("#" `T.isPrefixOf` dt && "#" `T.isSuffixOf` dt)
|
||||
)
|
||||
. F.toList
|
||||
<$> execStateT (scanDBDescriptorSet allDBDescriptors) mempty
|
||||
return $ mempty & unusedDescriptorTrees .~ sortOn descriptor unusedDescriptorTreeList
|
||||
where
|
||||
-- Treats the state as an accumulator as it traverses the given list.
|
||||
scanDBDescriptorSet ::
|
||||
[Descriptor] ->
|
||||
StateT
|
||||
(HashSet Descriptor)
|
||||
(ReaderT TaggedConnection IO)
|
||||
()
|
||||
scanDBDescriptorSet =
|
||||
mapM_ mutateIfUnused
|
||||
where
|
||||
mutateIfUnused ::
|
||||
Descriptor ->
|
||||
StateT (HashSet Descriptor) (ReaderT TaggedConnection IO) ()
|
||||
mutateIfUnused d@(Descriptor dk _) = do
|
||||
tc <- lift ask
|
||||
infraDescriptors <- liftIO $ getAllInfra dk tc
|
||||
infraOccurrences <-
|
||||
IM.foldl' (+) 0
|
||||
. OM.occurrenceMap
|
||||
<$> liftIO
|
||||
( getTagOccurrencesByDescriptorKeys
|
||||
(descriptorId <$> infraDescriptors)
|
||||
tc
|
||||
)
|
||||
when (infraOccurrences <= 0) (modify (HS.insert d))
|
||||
|
||||
showStats :: ReaderT TaggedConnection IO ()
|
||||
showStats = do
|
||||
connPath <- asks (^. connName)
|
||||
(TaggerDBStats fc dc tc) <- getStats
|
||||
liftIO $ do
|
||||
T.IO.putStrLn $ "The database, " <> connPath <> ", has:"
|
||||
T.IO.putStrLn $ (T.pack . show $ fc) <> " files"
|
||||
T.IO.putStrLn $ (T.pack . show $ dc) <> " descriptors"
|
||||
T.IO.putStrLn $ (T.pack . show $ tc) <> " applied tags"
|
||||
|
||||
getStats :: ReaderT TaggedConnection IO TaggerDBStats
|
||||
getStats = do
|
||||
tc <- ask
|
||||
liftIO $ do
|
||||
!numberOfFiles <- length <$> allFiles tc
|
||||
!numberOfDescriptors <- length <$> allDescriptors tc
|
||||
!numberOfTags <- length <$> allTags tc
|
||||
return (TaggerDBStats numberOfFiles numberOfDescriptors numberOfTags)
|
||||
|
||||
getConcreteFiles :: [File] -> ReaderT TaggedConnection IO [ConcreteTaggedFile]
|
||||
getConcreteFiles fs = do
|
||||
tc <- ask
|
||||
liftIO
|
||||
. fmap catMaybes
|
||||
. mapM (runMaybeT . flip queryForConcreteTaggedFileWithFileId tc)
|
||||
$ (fileId <$> fs)
|
||||
|
||||
reportTags :: ConcreteTaggedFile -> IO ()
|
||||
reportTags (ConcreteTaggedFile _ hrm) = do
|
||||
reportMetaTags hrm
|
||||
reportNormalTags hrm
|
||||
T.IO.putStrLn ""
|
||||
|
||||
reportMetaTags :: HierarchyMap ConcreteTag -> IO ()
|
||||
reportMetaTags hrm = do
|
||||
let topLevelMembers = getOnlyTopLevelMembers hrm
|
||||
unless (null topLevelMembers)
|
||||
. mapM_ (flip runReaderT hrm . reportHierarchyMap' 0)
|
||||
$ topLevelMembers
|
||||
where
|
||||
getOnlyTopLevelMembers hrm' =
|
||||
filter (\x -> HRM.metaMember x hrm' && not (HRM.infraMember x hrm')) . HRM.keys $ hrm'
|
||||
reportHierarchyMap' :: Int -> ConcreteTag -> ReaderT (HierarchyMap ConcreteTag) IO ()
|
||||
reportHierarchyMap' indentLevel ct@(concreteTagDescriptor -> (descriptor -> dp)) = do
|
||||
cts <-
|
||||
sortOn (descriptor . concreteTagDescriptor)
|
||||
. F.toList
|
||||
<$> (asks . HRM.find $ ct)
|
||||
liftIO . T.IO.putStrLn $
|
||||
T.replicate (2 * indentLevel) " "
|
||||
<> dp
|
||||
mapM_ (reportHierarchyMap' (indentLevel + 1)) cts
|
||||
|
||||
reportNormalTags :: HierarchyMap ConcreteTag -> IO ()
|
||||
reportNormalTags hrm =
|
||||
mapM_ (T.IO.putStrLn . descriptor . concreteTagDescriptor)
|
||||
. sortOn (descriptor . concreteTagDescriptor)
|
||||
. filter (\x -> not (HRM.metaMember x hrm) && not (HRM.infraMember x hrm))
|
||||
. HRM.keys
|
||||
$ hrm
|
110
app/taggercli/Opt/Data.hs
Normal file
110
app/taggercli/Opt/Data.hs
Normal file
@ -0,0 +1,110 @@
|
||||
{-# HLINT ignore "Use newtype instead of data" #-}
|
||||
{-# LANGUAGE InstanceSigs #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE StrictData #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
module Opt.Data (
|
||||
TaggerDBAudit (..),
|
||||
TaggerDBStats (..),
|
||||
TaggerCommand (..),
|
||||
TaggerQueryCommand (..),
|
||||
TaggerDBCommand (..),
|
||||
TaggerEx (..),
|
||||
) where
|
||||
|
||||
import Data.Monoid (Any)
|
||||
import Data.Text (Text)
|
||||
import Database.Tagger (Descriptor, File)
|
||||
|
||||
data TaggerEx
|
||||
= TaggerExVersion
|
||||
| TaggerExDB FilePath TaggerDBCommand
|
||||
deriving (Show, Eq)
|
||||
|
||||
data TaggerDBCommand = TaggerDBCommand
|
||||
{ _tdbcAudit :: Any
|
||||
, _tdbcStats :: Any
|
||||
, _tdbcTaggerCommand :: TaggerCommand
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
instance Semigroup TaggerDBCommand where
|
||||
(<>) :: TaggerDBCommand -> TaggerDBCommand -> TaggerDBCommand
|
||||
(TaggerDBCommand a s c) <> (TaggerDBCommand a' s' c') =
|
||||
TaggerDBCommand (a <> a') (s <> s') (c <> c')
|
||||
|
||||
instance Monoid TaggerDBCommand where
|
||||
mempty :: TaggerDBCommand
|
||||
mempty = TaggerDBCommand mempty mempty mempty
|
||||
|
||||
data TaggerCommand = TaggerCommand
|
||||
{ _tcQueryCommand :: Maybe TaggerQueryCommand
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
instance Semigroup TaggerCommand where
|
||||
(<>) :: TaggerCommand -> TaggerCommand -> TaggerCommand
|
||||
(TaggerCommand q) <> (TaggerCommand q') = TaggerCommand (q <> q')
|
||||
|
||||
instance Monoid TaggerCommand where
|
||||
mempty :: TaggerCommand
|
||||
mempty =
|
||||
TaggerCommand mempty
|
||||
|
||||
data TaggerQueryCommand = TaggerQueryCommand
|
||||
{ _tqcQuery :: Text
|
||||
, _tqcRelative :: Any
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
instance Semigroup TaggerQueryCommand where
|
||||
(<>) :: TaggerQueryCommand -> TaggerQueryCommand -> TaggerQueryCommand
|
||||
(TaggerQueryCommand q r) <> (TaggerQueryCommand q' r') =
|
||||
TaggerQueryCommand (q <> q') (r <> r')
|
||||
|
||||
instance Monoid TaggerQueryCommand where
|
||||
mempty :: TaggerQueryCommand
|
||||
mempty = TaggerQueryCommand mempty mempty
|
||||
|
||||
data TaggerDBStats = TaggerDBStats
|
||||
{ _taggerdbstatsNumberOfFiles :: Int
|
||||
, _taggerdbstatsNumberOfDescriptors :: Int
|
||||
, _taggerdbstatsNumberOfTags :: Int
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
emptyStats :: TaggerDBStats
|
||||
emptyStats =
|
||||
TaggerDBStats 0 0 0
|
||||
|
||||
instance Semigroup TaggerDBStats where
|
||||
(<>) :: TaggerDBStats -> TaggerDBStats -> TaggerDBStats
|
||||
(TaggerDBStats a b c) <> (TaggerDBStats x y z) =
|
||||
TaggerDBStats (a + x) (b + y) (c + z)
|
||||
|
||||
instance Monoid TaggerDBStats where
|
||||
mempty :: TaggerDBStats
|
||||
mempty = emptyStats
|
||||
|
||||
{- |
|
||||
A data structure to report the results of a database
|
||||
audit.
|
||||
-}
|
||||
data TaggerDBAudit = TaggerDBAudit
|
||||
{ _taggerdbauditMissingFiles :: [File]
|
||||
, _taggerdbauditUnusedDescriptorTrees :: [Descriptor]
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
emptyAudit :: TaggerDBAudit
|
||||
emptyAudit = TaggerDBAudit mempty mempty
|
||||
|
||||
instance Semigroup TaggerDBAudit where
|
||||
(<>) :: TaggerDBAudit -> TaggerDBAudit -> TaggerDBAudit
|
||||
(TaggerDBAudit mfx udtx) <> (TaggerDBAudit mfy udty) =
|
||||
TaggerDBAudit (mfx <> mfy) (udtx <> udty)
|
||||
|
||||
instance Monoid TaggerDBAudit where
|
||||
mempty :: TaggerDBAudit
|
||||
mempty = emptyAudit
|
17
app/taggercli/Opt/Data/Lens.hs
Normal file
17
app/taggercli/Opt/Data/Lens.hs
Normal file
@ -0,0 +1,17 @@
|
||||
{-# LANGUAGE FlexibleInstances #-}
|
||||
{-# LANGUAGE FunctionalDependencies #-}
|
||||
{-# LANGUAGE TemplateHaskell #-}
|
||||
|
||||
module Opt.Data.Lens where
|
||||
|
||||
import Control.Lens (abbreviatedFields, makeLensesWith)
|
||||
import Opt.Data
|
||||
|
||||
makeLensesWith abbreviatedFields ''TaggerDBAudit
|
||||
|
||||
makeLensesWith abbreviatedFields ''TaggerDBStats
|
||||
|
||||
makeLensesWith abbreviatedFields ''TaggerCommand
|
||||
|
||||
makeLensesWith abbreviatedFields ''TaggerQueryCommand
|
||||
makeLensesWith abbreviatedFields ''TaggerDBCommand
|
123
app/taggercli/Opt/Parser.hs
Normal file
123
app/taggercli/Opt/Parser.hs
Normal file
@ -0,0 +1,123 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE StrictData #-}
|
||||
{-# HLINT ignore "Use newtype instead of data" #-}
|
||||
{-# OPTIONS_GHC -Wno-typed-holes #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
{-# HLINT ignore "Use const" #-}
|
||||
{-# HLINT ignore "Redundant <$>" #-}
|
||||
|
||||
module Opt.Parser (
|
||||
taggerExParser,
|
||||
) where
|
||||
|
||||
import Data.Functor (($>))
|
||||
import Data.Monoid (Any (..))
|
||||
import Opt.Data (
|
||||
TaggerCommand (TaggerCommand),
|
||||
TaggerDBCommand (TaggerDBCommand),
|
||||
TaggerEx (..),
|
||||
TaggerQueryCommand (TaggerQueryCommand),
|
||||
)
|
||||
import Options.Applicative (
|
||||
Alternative ((<|>)),
|
||||
Parser,
|
||||
ParserInfo,
|
||||
argument,
|
||||
header,
|
||||
help,
|
||||
helper,
|
||||
info,
|
||||
long,
|
||||
metavar,
|
||||
optional,
|
||||
progDesc,
|
||||
short,
|
||||
str,
|
||||
switch,
|
||||
)
|
||||
|
||||
taggerExParser :: ParserInfo TaggerEx
|
||||
taggerExParser =
|
||||
info
|
||||
( helper
|
||||
<*> showVersionParser
|
||||
<|> (TaggerExDB <$> databasePathArgParser <*> taggerDBCommandParser)
|
||||
)
|
||||
( header
|
||||
"TaggerCLI"
|
||||
<> progDesc
|
||||
"Allows a user to perform a limited set of \
|
||||
\actions on a tagger database.\n\
|
||||
\It is also possible to print some stats and run an audit."
|
||||
)
|
||||
|
||||
taggerDBCommandParser :: Parser TaggerDBCommand
|
||||
taggerDBCommandParser =
|
||||
TaggerDBCommand
|
||||
<$> auditParser
|
||||
<*> statsParser
|
||||
<*> taggerCommandParser
|
||||
|
||||
taggerCommandParser :: Parser TaggerCommand
|
||||
taggerCommandParser =
|
||||
TaggerCommand
|
||||
<$> optional taggerQueryCommandParser
|
||||
where
|
||||
taggerQueryCommandParser =
|
||||
TaggerQueryCommand
|
||||
<$> argument str (metavar "QUERY")
|
||||
<*> ( Any
|
||||
<$> switch
|
||||
( long "relative"
|
||||
<> help
|
||||
"Output filepaths as they are\
|
||||
\ stored in the database."
|
||||
)
|
||||
)
|
||||
|
||||
auditParser :: Parser Any
|
||||
auditParser =
|
||||
Any
|
||||
<$> switch (long "audit" <> help "Audit the database.")
|
||||
|
||||
showVersionParser :: Parser TaggerEx
|
||||
showVersionParser =
|
||||
switch (short 'v' <> long "version" <> help "Show the version")
|
||||
$> TaggerExVersion
|
||||
|
||||
statsParser :: Parser Any
|
||||
statsParser =
|
||||
Any
|
||||
<$> switch (long "stats" <> help "Show statistics about the database")
|
||||
|
||||
-- addFileParser :: Parser (ReaderT TaggedConnection (ContT () IO) ())
|
||||
-- addFileParser =
|
||||
-- switch
|
||||
-- ( short 'a' <> long "add-files"
|
||||
-- <> help
|
||||
-- "Add files to the database. \
|
||||
-- \Recursively add any files found at PATH."
|
||||
-- )
|
||||
-- *> (addFileCont <$> many (argument str (metavar "PATH")))
|
||||
|
||||
-- addFileCont :: [FilePath] -> ReaderT TaggedConnection (ContT () IO) ()
|
||||
-- addFileCont fps =
|
||||
-- do
|
||||
-- tc <- ask
|
||||
-- liftIO . mapM_ (addFiles tc . T.pack) $ fps
|
||||
|
||||
databasePathArgParser :: Parser FilePath
|
||||
databasePathArgParser =
|
||||
argument str (metavar "DATABASE")
|
||||
|
||||
-- showAppliedTagsParser =
|
||||
-- switch (long "show-tags" <> help "Show tags applied to the given files")
|
||||
-- *> (showAppliedTagsCont <$> many (argument str (metavar "PATH")))
|
||||
|
||||
-- showAppliedTagsCont :: [FilePath] -> ReaderT TaggedConnection (ContT () IO) ()
|
||||
-- showAppliedTagsCont fps = do
|
||||
-- tc <- ask
|
||||
-- fs <- liftIO . fmap concat . mapM (flip queryForFileByPattern tc . T.pack) $ fps
|
||||
-- cfs <- mapReaderT liftIO $ getConcreteFiles fs
|
||||
-- liftIO $ mapM_ reportTags cfs
|
BIN
dist-newstyle/cache/compiler
vendored
Normal file
BIN
dist-newstyle/cache/compiler
vendored
Normal file
Binary file not shown.
BIN
dist-newstyle/cache/config
vendored
Normal file
BIN
dist-newstyle/cache/config
vendored
Normal file
Binary file not shown.
BIN
iosevka_bold.ttf
Normal file
BIN
iosevka_bold.ttf
Normal file
Binary file not shown.
BIN
iosevka_regular.ttf
Normal file
BIN
iosevka_regular.ttf
Normal file
Binary file not shown.
BIN
iosevka_thin.ttf
Normal file
BIN
iosevka_thin.ttf
Normal file
Binary file not shown.
124
lib/Data/Hierarchy/Internal.hs
Normal file
124
lib/Data/Hierarchy/Internal.hs
Normal file
@ -0,0 +1,124 @@
|
||||
{-# LANGUAGE DeriveFoldable #-}
|
||||
{-# LANGUAGE DeriveFunctor #-}
|
||||
{-# LANGUAGE StrictData #-}
|
||||
{-# OPTIONS_HADDOCK hide #-}
|
||||
|
||||
module Data.Hierarchy.Internal (
|
||||
module Data.Hierarchy.Internal,
|
||||
) where
|
||||
|
||||
import qualified Data.HashMap.Strict as HashMap
|
||||
import qualified Data.HashSet as HashSet
|
||||
import Data.Hashable (Hashable)
|
||||
import qualified Data.List as L
|
||||
import qualified Data.List.NonEmpty as NE
|
||||
|
||||
{- |
|
||||
A flat 'HashMap` that encodes hierarchical relationships
|
||||
|
||||
A \"meta\" relation means that some key
|
||||
'a` has a non-null HashSet of 'a` as it's value.
|
||||
|
||||
An \"infra\" relation means that some key 'a` has a 'null` 'HashSet` of values.
|
||||
|
||||
Both types of relations are accessable on one level of the 'HashMap`.
|
||||
|
||||
Relations can be nested arbitrarily deep or defined circularly
|
||||
but are still represented
|
||||
as a single flat 'HashMap` in the underlying implementation.
|
||||
-}
|
||||
newtype HierarchyMap a
|
||||
= HierarchyMap (HashMap.HashMap a (HashSet.HashSet a))
|
||||
deriving (Show, Eq)
|
||||
|
||||
{- |
|
||||
'union` two 'HierarchyMap a`
|
||||
-}
|
||||
instance Hashable a => Semigroup (HierarchyMap a) where
|
||||
(<>) = unionWith HashSet.union
|
||||
|
||||
instance Hashable a => Monoid (HierarchyMap a) where
|
||||
mempty = empty
|
||||
|
||||
{- |
|
||||
Inserts the given key or unions an existing entry's set if the key already exists.
|
||||
|
||||
Adds empty k-v entries for each member of the given set, representing Infra relations.
|
||||
|
||||
Does not prohibit circular relations.
|
||||
|
||||
Care should be taken that data inserted into the 'HierarchyMap` is not circularly related
|
||||
ex:
|
||||
|
||||
> insert 1 [1,2] empty
|
||||
|
||||
will create a map [(1, [1,2]), (2, [])] where 1 is circularly related to itself.
|
||||
This would cause an infinite hang if ever called.
|
||||
-}
|
||||
insert :: Hashable a => a -> HashSet.HashSet a -> HierarchyMap a -> HierarchyMap a
|
||||
insert k s (HierarchyMap m) =
|
||||
let keyInserted = HierarchyMap $ HashMap.insertWith HashSet.union k s m
|
||||
in HashSet.foldl' (\hm k' -> insert k' HashSet.empty hm) keyInserted s
|
||||
|
||||
unionWith ::
|
||||
Hashable a =>
|
||||
(HashSet.HashSet a -> HashSet.HashSet a -> HashSet.HashSet a) ->
|
||||
HierarchyMap a ->
|
||||
HierarchyMap a ->
|
||||
HierarchyMap a
|
||||
unionWith f (HierarchyMap x) (HierarchyMap y) = HierarchyMap $ HashMap.unionWith f x y
|
||||
|
||||
{- |
|
||||
Returns empty map.
|
||||
-}
|
||||
empty :: HierarchyMap a
|
||||
empty = HierarchyMap HashMap.empty
|
||||
|
||||
{- |
|
||||
A non-flat data structure that encodes hierarchical relationships as a tree.
|
||||
|
||||
Injective to a 'HierarchyMap` provided that its values are hashable.
|
||||
-}
|
||||
data HierarchyTree a
|
||||
= Infra a
|
||||
| Meta a (NE.NonEmpty (HierarchyTree a))
|
||||
deriving (Show, Eq, Functor, Foldable)
|
||||
|
||||
{- |
|
||||
Fetch the top node of the current tree.
|
||||
-}
|
||||
relationNode :: HierarchyTree p -> p
|
||||
relationNode tr =
|
||||
case tr of
|
||||
Infra x -> x
|
||||
Meta x _ -> x
|
||||
|
||||
{- |
|
||||
Inject a 'HierarchyTree` to a 'HierarchyMap`.
|
||||
-}
|
||||
hierarchyTreeToMap :: Hashable a => HierarchyTree a -> HierarchyMap a
|
||||
hierarchyTreeToMap = hierarchyTreeToMap' empty
|
||||
where
|
||||
hierarchyTreeToMap' ::
|
||||
Hashable a =>
|
||||
HierarchyMap a ->
|
||||
HierarchyTree a ->
|
||||
HierarchyMap a
|
||||
hierarchyTreeToMap' acc tr =
|
||||
case tr of
|
||||
Infra x -> insert x HashSet.empty acc
|
||||
Meta x is ->
|
||||
unionWith
|
||||
HashSet.union
|
||||
(insert x (HashSet.fromList . NE.toList . NE.map relationNode $ is) acc)
|
||||
( L.foldl1' (unionWith HashSet.union)
|
||||
. NE.toList
|
||||
. NE.map hierarchyTreeToMap
|
||||
$ is
|
||||
)
|
||||
|
||||
-- hierarchyKVToTree :: Hashable a => a -> HashSet.HashSet a -> HierarchyTree a
|
||||
-- hierarchyKVToTree k vs =
|
||||
-- if HashSet.null vs
|
||||
-- then Infra k
|
||||
-- else Meta
|
184
lib/Data/HierarchyMap.hs
Normal file
184
lib/Data/HierarchyMap.hs
Normal file
@ -0,0 +1,184 @@
|
||||
{-# LANGUAGE BangPatterns #-}
|
||||
{-# LANGUAGE StrictData #-}
|
||||
|
||||
{- |
|
||||
Module : Data.HierarchyMap
|
||||
Description : Definition of the HierarchyMap data type. A hierarchical structure of
|
||||
strict HashMaps
|
||||
|
||||
License : GPL-3
|
||||
Maintainer : monawasensei@gmail.com
|
||||
|
||||
A 'HierarchyMap` is a newtype wrapped hashmap that encodes 'Meta' and 'Infra' relations
|
||||
between its members. These relationships take on a tree structure, a 'HierarchyMap` is a
|
||||
flat encoding of that tree structure.
|
||||
|
||||
For the purposes of this library, the 'HierarchyMap` is meant to be used to encode similar
|
||||
structures found in the Tagger SQL databases.
|
||||
|
||||
Where a 'HierarchyMap` is roughly equivalent to any set of columns that have this definition:
|
||||
|
||||
@
|
||||
CREATE TABLE META_RELATION (
|
||||
meta INTEGER
|
||||
infra INTEGER
|
||||
FOREIGN KEY infra REFERENCES META_RELATION (meta)
|
||||
);
|
||||
@
|
||||
|
||||
Given that the tree of relations formed by this definition can be queried one layer at a time
|
||||
or via the whole tree with a recursive CTE, the 'HierarchyMap` can be queried likewise.
|
||||
|
||||
A 'HierarchyMap` does not check for circular relationships, which would cause an inifite loop
|
||||
upon evaluation. Therefore it is imperative that the relations inserted into a 'HierarchyMap`
|
||||
are not circular. A 'HierarchyMap` does support multiple meta parents, and branched infra relations,
|
||||
which makes it slightly more unique compared to some of the table definitions found in 'Database.Tagger.Script.schemaDefinition`
|
||||
-}
|
||||
module Data.HierarchyMap (
|
||||
HierarchyMap,
|
||||
mapHierarchyMap,
|
||||
union,
|
||||
member,
|
||||
find,
|
||||
Data.HierarchyMap.lookup,
|
||||
metaMember,
|
||||
infraMember,
|
||||
isInfraTo,
|
||||
insert,
|
||||
inserts,
|
||||
fromList,
|
||||
empty,
|
||||
Data.HierarchyMap.null,
|
||||
getAllInfraTo,
|
||||
getAllMetaTo,
|
||||
keys,
|
||||
) where
|
||||
|
||||
import qualified Data.Foldable as F
|
||||
import qualified Data.HashMap.Strict as HashMap
|
||||
import qualified Data.HashSet as HashSet
|
||||
import Data.Hashable (Hashable)
|
||||
import Data.Hierarchy.Internal (
|
||||
HierarchyMap (..),
|
||||
empty,
|
||||
insert,
|
||||
unionWith,
|
||||
)
|
||||
import Data.Maybe (fromMaybe)
|
||||
|
||||
{- |
|
||||
Map over all elements in the hierarchy.
|
||||
-}
|
||||
mapHierarchyMap :: Hashable a => (k1 -> a) -> HierarchyMap k1 -> HierarchyMap a
|
||||
mapHierarchyMap f (HierarchyMap m) =
|
||||
HierarchyMap . HashMap.mapKeys f . HashMap.map (HashSet.map f) $ m
|
||||
|
||||
{- |
|
||||
Union two 'HierarchyMap a` together. Combining the infra relations
|
||||
for any overlapping keys.
|
||||
-}
|
||||
union :: Hashable a => HierarchyMap a -> HierarchyMap a -> HierarchyMap a
|
||||
union = unionWith HashSet.union
|
||||
|
||||
{- |
|
||||
Insert a list of relation tuples.
|
||||
|
||||
> flip $ foldl' (flip (uncurry insert))
|
||||
-}
|
||||
inserts ::
|
||||
(Hashable a, Foldable t) =>
|
||||
t (a, HashSet.HashSet a) ->
|
||||
HierarchyMap a ->
|
||||
HierarchyMap a
|
||||
inserts = flip $ F.foldl' (flip (uncurry insert))
|
||||
|
||||
{- |
|
||||
Convert a list of relation tuples to a 'HierarchyMap`
|
||||
-}
|
||||
fromList :: (Hashable a, Foldable t) => t (a, HashSet.HashSet a) -> HierarchyMap a
|
||||
fromList = flip inserts empty
|
||||
|
||||
{- |
|
||||
'True` if the given value exists as either a meta or infra member.
|
||||
-}
|
||||
member :: Hashable a => a -> HierarchyMap a -> Bool
|
||||
member x (HierarchyMap m) = HashMap.member x m
|
||||
|
||||
{- |
|
||||
'True` if the map is empty.
|
||||
-}
|
||||
null :: HierarchyMap k -> Bool
|
||||
null (HierarchyMap m) = HashMap.null m
|
||||
|
||||
{- |
|
||||
Return empty set if the key is not in the map.
|
||||
-}
|
||||
find :: Hashable a => a -> HierarchyMap a -> HashSet.HashSet a
|
||||
find x (HierarchyMap m) = fromMaybe HashSet.empty $ HashMap.lookup x m
|
||||
|
||||
{- |
|
||||
Return 'Nothing` if the key is not in the map.
|
||||
-}
|
||||
lookup :: Hashable k => k -> HierarchyMap k -> Maybe (HashSet.HashSet k)
|
||||
lookup x (HierarchyMap m) = HashMap.lookup x m
|
||||
|
||||
{- |
|
||||
'True` if the given value has a meta relationship to any member of the map.
|
||||
|
||||
The value must be a key in the map and have a non-null HashSet value.
|
||||
-}
|
||||
metaMember :: Hashable k => k -> HierarchyMap k -> Bool
|
||||
metaMember x (HierarchyMap m) = maybe False (not . HashSet.null) (HashMap.lookup x m)
|
||||
|
||||
{- |
|
||||
'True` if the given value has an infra relationship to any member of the map.
|
||||
|
||||
That is:
|
||||
|
||||
- It exists in the map
|
||||
- It appears in the values of any key of the map.
|
||||
-}
|
||||
infraMember :: Hashable a => a -> HierarchyMap a -> Bool
|
||||
infraMember x (HierarchyMap m) =
|
||||
HashMap.member x m
|
||||
&& any (HashSet.member x) (HashMap.elems m)
|
||||
|
||||
{- |
|
||||
'True` if the first given value is infra to the second in the given map.
|
||||
-}
|
||||
isInfraTo :: Hashable a => a -> a -> HierarchyMap a -> Bool
|
||||
isInfraTo x y = HashSet.member x . getAllInfraTo y
|
||||
|
||||
{- |
|
||||
Retrieve a set of all values that are meta to the given value.
|
||||
|
||||
Does not include the given value.
|
||||
-}
|
||||
getAllMetaTo :: Hashable a => a -> HierarchyMap a -> HashSet.HashSet a
|
||||
getAllMetaTo x hm@(HierarchyMap m) =
|
||||
let !parentLayer = HashMap.keysSet $ HashMap.filter (HashSet.member x) m
|
||||
in HashSet.union parentLayer
|
||||
. HashSet.unions
|
||||
. map (`getAllMetaTo` hm)
|
||||
. HashSet.toList
|
||||
$ parentLayer
|
||||
|
||||
{- |
|
||||
Retrieve a set of all elements that are infra to the given value.
|
||||
|
||||
Does not include the given value.
|
||||
-}
|
||||
getAllInfraTo :: Hashable a => a -> HierarchyMap a -> HashSet.HashSet a
|
||||
getAllInfraTo x hm =
|
||||
let !layerInfra = Data.HierarchyMap.find x hm
|
||||
in HashSet.union layerInfra
|
||||
. HashSet.unions
|
||||
. map (`getAllInfraTo` hm)
|
||||
. HashSet.toList
|
||||
$ layerInfra
|
||||
|
||||
{- |
|
||||
Returns a list containing every member of the 'HierarchyMap`
|
||||
-}
|
||||
keys :: HierarchyMap k -> [k]
|
||||
keys (HierarchyMap m) = HashMap.keys m
|
23
lib/Data/OccurrenceHashMap.hs
Normal file
23
lib/Data/OccurrenceHashMap.hs
Normal file
@ -0,0 +1,23 @@
|
||||
module Data.OccurrenceHashMap (
|
||||
OccurrenceHashMap (..),
|
||||
get,
|
||||
set,
|
||||
occur,
|
||||
union,
|
||||
empty,
|
||||
unions,
|
||||
fromList,
|
||||
toList,
|
||||
) where
|
||||
|
||||
import Data.OccurrenceHashMap.Internal (
|
||||
OccurrenceHashMap (..),
|
||||
empty,
|
||||
fromList,
|
||||
get,
|
||||
occur,
|
||||
set,
|
||||
toList,
|
||||
union,
|
||||
unions,
|
||||
)
|
55
lib/Data/OccurrenceHashMap/Internal.hs
Normal file
55
lib/Data/OccurrenceHashMap/Internal.hs
Normal file
@ -0,0 +1,55 @@
|
||||
module Data.OccurrenceHashMap.Internal (
|
||||
OccurrenceHashMap (..),
|
||||
get,
|
||||
set,
|
||||
occur,
|
||||
union,
|
||||
empty,
|
||||
unions,
|
||||
fromList,
|
||||
toList,
|
||||
) where
|
||||
|
||||
import Data.HashMap.Strict (HashMap)
|
||||
import qualified Data.HashMap.Strict as HashMap
|
||||
import Data.Hashable (Hashable)
|
||||
import qualified Data.List as L
|
||||
import Data.Maybe (fromMaybe)
|
||||
|
||||
{- |
|
||||
The same as 'OccurrenceMap` except it stores a 'Hashable` value as a key
|
||||
instead of just an Int. Has the same interface as 'OccurrenceMap` so see that
|
||||
for function documentation.
|
||||
-}
|
||||
newtype OccurrenceHashMap a = OccurrenceHashMap {occurrenceHashMap :: HashMap a Int}
|
||||
deriving (Show, Eq)
|
||||
|
||||
get :: Hashable k => k -> OccurrenceHashMap k -> Int
|
||||
get x = fromMaybe 0 . HashMap.lookup x . occurrenceHashMap
|
||||
|
||||
set :: Hashable k => k -> Int -> OccurrenceHashMap k -> OccurrenceHashMap k
|
||||
set k n (OccurrenceHashMap m) = OccurrenceHashMap $ HashMap.insert k n m
|
||||
|
||||
occur :: Hashable k => k -> OccurrenceHashMap k -> OccurrenceHashMap k
|
||||
occur k (OccurrenceHashMap m) = OccurrenceHashMap $ HashMap.insertWith (+) k 1 m
|
||||
|
||||
union ::
|
||||
Hashable a =>
|
||||
OccurrenceHashMap a ->
|
||||
OccurrenceHashMap a ->
|
||||
OccurrenceHashMap a
|
||||
union (OccurrenceHashMap x) (OccurrenceHashMap y) =
|
||||
OccurrenceHashMap $ HashMap.unionWith (+) x y
|
||||
|
||||
empty :: OccurrenceHashMap a
|
||||
empty = OccurrenceHashMap HashMap.empty
|
||||
|
||||
unions :: Hashable a => [OccurrenceHashMap a] -> OccurrenceHashMap a
|
||||
unions [] = empty
|
||||
unions xs = L.foldl1' union xs
|
||||
|
||||
fromList :: Hashable k => [(k, Int)] -> OccurrenceHashMap k
|
||||
fromList = OccurrenceHashMap . HashMap.fromList
|
||||
|
||||
toList :: OccurrenceHashMap k -> [(k, Int)]
|
||||
toList = HashMap.toList . occurrenceHashMap
|
32
lib/Data/OccurrenceMap.hs
Normal file
32
lib/Data/OccurrenceMap.hs
Normal file
@ -0,0 +1,32 @@
|
||||
{- |
|
||||
Module : Data.OccurrenceMap
|
||||
Description : Definition of the OccurrenceMap data type.
|
||||
|
||||
License : GPL-3
|
||||
Maintainer : monawasensei@gmail.com
|
||||
|
||||
An 'OccurrenceMap` is simply an 'IntMap` of Ints. It has functions getting, and
|
||||
incrementing a key. An 'OccurrenceMap` holds every member of the set 'Int` and,
|
||||
when queried for a certain member, will return 0 unless that member has been incremented.
|
||||
|
||||
These queries are called occurrences.
|
||||
-}
|
||||
module Data.OccurrenceMap (
|
||||
OccurrenceMap (..),
|
||||
get,
|
||||
set,
|
||||
occur,
|
||||
empty,
|
||||
union,
|
||||
unions,
|
||||
) where
|
||||
|
||||
import Data.OccurrenceMap.Internal (
|
||||
OccurrenceMap (..),
|
||||
empty,
|
||||
get,
|
||||
occur,
|
||||
set,
|
||||
union,
|
||||
unions,
|
||||
)
|
65
lib/Data/OccurrenceMap/Internal.hs
Normal file
65
lib/Data/OccurrenceMap/Internal.hs
Normal file
@ -0,0 +1,65 @@
|
||||
{-# LANGUAGE ViewPatterns #-}
|
||||
{-# OPTIONS_HADDOCK hide #-}
|
||||
|
||||
module Data.OccurrenceMap.Internal (
|
||||
module Data.OccurrenceMap.Internal,
|
||||
) where
|
||||
|
||||
import Data.IntMap.Strict (IntMap)
|
||||
import qualified Data.IntMap.Strict as IntMap
|
||||
import qualified Data.List as L
|
||||
import Data.Maybe (fromMaybe)
|
||||
|
||||
{- |
|
||||
An 'IntMap` with some specialized functions. This type is usually used for
|
||||
counting how many times something occurs, in the case of Tagger, it's for counting
|
||||
how many times a 'Tag` occurs.
|
||||
-}
|
||||
newtype OccurrenceMap = OccurrenceMap {occurrenceMap :: IntMap Int} deriving (Show, Eq)
|
||||
|
||||
{- |
|
||||
Get the Occurrences that correspond to the given Int.
|
||||
|
||||
Returns 0 if it has not been incremented.
|
||||
-}
|
||||
get :: Integral k => k -> OccurrenceMap -> Int
|
||||
get (fromIntegral -> k) = fromMaybe 0 . IntMap.lookup k . occurrenceMap
|
||||
|
||||
{- |
|
||||
For the first given Int, set its occurrences with the second.
|
||||
-}
|
||||
set :: Integral k => k -> Int -> OccurrenceMap -> OccurrenceMap
|
||||
set (fromIntegral -> k) occurs (OccurrenceMap m) =
|
||||
OccurrenceMap $ IntMap.insert k occurs m
|
||||
|
||||
{- |
|
||||
Increment the location of the given Int.
|
||||
-}
|
||||
occur :: Integral k => k -> OccurrenceMap -> OccurrenceMap
|
||||
occur (fromIntegral -> k) (OccurrenceMap m) =
|
||||
OccurrenceMap $ IntMap.insertWith (+) k 1 m
|
||||
|
||||
{- |
|
||||
Combine two Maps, summing all of their locations.
|
||||
-}
|
||||
union :: OccurrenceMap -> OccurrenceMap -> OccurrenceMap
|
||||
union (OccurrenceMap x) (OccurrenceMap y) =
|
||||
OccurrenceMap $ IntMap.unionWith (+) x y
|
||||
|
||||
{- |
|
||||
Return an initialized Map where every location has 0 occurrences.
|
||||
-}
|
||||
empty :: OccurrenceMap
|
||||
empty = OccurrenceMap IntMap.empty
|
||||
|
||||
{- |
|
||||
Fold of many unions.
|
||||
-}
|
||||
unions :: [OccurrenceMap] -> OccurrenceMap
|
||||
unions [] = empty
|
||||
unions xs = L.foldl1' union xs
|
||||
|
||||
fromList :: Integral k => [(k, Int)] -> OccurrenceMap
|
||||
fromList = OccurrenceMap . IntMap.fromList . map (first fromIntegral)
|
||||
where
|
||||
first f (x, y) = (f x, y)
|
54
lib/Data/Tagger.hs
Normal file
54
lib/Data/Tagger.hs
Normal file
@ -0,0 +1,54 @@
|
||||
{-# LANGUAGE DeriveAnyClass #-}
|
||||
|
||||
{- |
|
||||
Module : Data.Tagger
|
||||
Description : Common and miscellaneous types.
|
||||
|
||||
License : GPL-3
|
||||
Maintainer : monawasensei@gmail.com
|
||||
|
||||
These types are multipurpose and are used in internal implementations
|
||||
of tagger-lib as well as being present in the GUI or internal implementations
|
||||
of tagger.
|
||||
-}
|
||||
module Data.Tagger (
|
||||
CyclicEnum (..),
|
||||
QueryCriteria (..),
|
||||
SetOp (..),
|
||||
) where
|
||||
|
||||
{- |
|
||||
Typeclass defining a bounded, ordered, cyclic enumeration.
|
||||
|
||||
The methods 'next` and 'prev` are wrappers for 'succ` and 'pred`
|
||||
that wrap to either 'minBound` or 'maxBound`.
|
||||
-}
|
||||
class (Bounded e, Ord e, Enum e) => CyclicEnum e where
|
||||
next :: e -> e
|
||||
next x = if x >= maxBound then minBound else succ x
|
||||
prev :: e -> e
|
||||
prev x = if x <= minBound then maxBound else pred x
|
||||
|
||||
{- |
|
||||
Type detailing how what criteria a query is meant to search on.
|
||||
-}
|
||||
data QueryCriteria
|
||||
= -- | Search for files that are tagged with 'Descriptor`s matching a given pattern.
|
||||
DescriptorCriteria
|
||||
| -- | Search for files that are tagged with an inclusive set of all
|
||||
--infra-related 'Descriptor`s matching a given pattern.
|
||||
MetaDescriptorCriteria
|
||||
| -- | Search for files that have a file path matching a given pattern.
|
||||
FilePatternCriteria
|
||||
| -- | Search for files that are untagged.
|
||||
UntaggedCriteria
|
||||
deriving (Show, Eq, Bounded, Enum, Ord, CyclicEnum)
|
||||
|
||||
{- |
|
||||
A type detailing how set-like collections are to be combined.
|
||||
-}
|
||||
data SetOp
|
||||
= Union
|
||||
| Intersect
|
||||
| Difference
|
||||
deriving (Show, Eq, Bounded, Enum, Ord, CyclicEnum)
|
105
lib/Database/Tagger.hs
Normal file
105
lib/Database/Tagger.hs
Normal file
@ -0,0 +1,105 @@
|
||||
{-# LANGUAGE ViewPatterns #-}
|
||||
|
||||
{- |
|
||||
Module : Database.Tagger
|
||||
Description : Exports Database operations.
|
||||
|
||||
License : GPL-3
|
||||
Maintainer : monawasensei@gmail.com
|
||||
-}
|
||||
module Database.Tagger (
|
||||
module Database.Tagger.Connection,
|
||||
module Database.Tagger.Query,
|
||||
module Database.Tagger.Type,
|
||||
rmFile,
|
||||
mvFile,
|
||||
) where
|
||||
|
||||
import qualified Control.Exception as Exception
|
||||
import Control.Monad (guard, when, (<=<))
|
||||
import Control.Monad.Trans.Class (MonadTrans (lift))
|
||||
import Control.Monad.Trans.Except (
|
||||
ExceptT,
|
||||
except,
|
||||
runExceptT,
|
||||
throwE,
|
||||
withExceptT,
|
||||
)
|
||||
import Control.Monad.Trans.Maybe (MaybeT (runMaybeT))
|
||||
import qualified Data.Either as E
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Database.Tagger.Connection
|
||||
import Database.Tagger.Query
|
||||
import Database.Tagger.Type
|
||||
import System.Directory (
|
||||
doesFileExist,
|
||||
doesPathExist,
|
||||
removeFile,
|
||||
renameFile,
|
||||
)
|
||||
import System.IO (hPrint, hPutStrLn, stderr)
|
||||
|
||||
{- |
|
||||
Delete a 'File` from the database and filesystem.
|
||||
|
||||
An error will be printed if the 'File` does not exist in the local filesystem,
|
||||
but the given 'File` is always removed from the database anyways.
|
||||
-}
|
||||
rmFile :: TaggedConnection -> RecordKey File -> IO ()
|
||||
rmFile tc fk = do
|
||||
result <- runExceptT $ do
|
||||
(File dbFk (T.unpack -> fp)) <- guardFileInDatabase tc fk
|
||||
lift $ deleteFiles [dbFk] tc
|
||||
rmResult <-
|
||||
lift . Exception.try $ removeFile fp ::
|
||||
ExceptT String IO (Either Exception.IOException ())
|
||||
withExceptT show . except $ rmResult
|
||||
either (hPutStrLn stderr) return result
|
||||
|
||||
{- |
|
||||
Renames a file in the database and file system at the same time.
|
||||
If the file does not exist in the db or it already exists in the file system,
|
||||
do nothing.
|
||||
|
||||
If there is an error that occurs during renaming in the filesystem, revert the
|
||||
db name change.
|
||||
-}
|
||||
mvFile :: TaggedConnection -> RecordKey File -> Text -> IO ()
|
||||
mvFile c fk (T.unpack -> newFilePath') = do
|
||||
result <- runExceptT $ renameFile' newFilePath'
|
||||
E.either (hPutStrLn stderr) pure result
|
||||
where
|
||||
renameFile' :: FilePath -> ExceptT String IO ()
|
||||
renameFile' newFilePath = do
|
||||
(File fkFromDB (T.unpack -> oldFilePath)) <- guardFileInDatabase c fk
|
||||
guardFileExists oldFilePath
|
||||
withExceptT
|
||||
(const ("Path, " ++ newFilePath ++ " already exists in filesystem."))
|
||||
. ((guard . not :: Bool -> ExceptT String IO ()) <=< lift . doesPathExist)
|
||||
$ newFilePath
|
||||
lift $ updateFilePaths [(newFilePath, fkFromDB)] c
|
||||
fileSystemRenameResult <-
|
||||
lift . Exception.try $
|
||||
renameFile oldFilePath newFilePath ::
|
||||
ExceptT String IO (Either Exception.IOException ())
|
||||
when (E.isLeft fileSystemRenameResult) $ do
|
||||
let (E.Left ioEx) = fileSystemRenameResult
|
||||
lift $ hPrint stderr ioEx
|
||||
lift $ updateFilePaths [(oldFilePath, fkFromDB)] c
|
||||
throwE "Reverting database changes."
|
||||
|
||||
guardFileExists :: FilePath -> ExceptT String IO ()
|
||||
guardFileExists p =
|
||||
withExceptT
|
||||
(const ("File, " ++ p ++ " not found in filesystem."))
|
||||
. ((guard :: Bool -> ExceptT String IO ()) <=< lift . doesFileExist)
|
||||
$ p
|
||||
|
||||
guardFileInDatabase :: TaggedConnection -> RecordKey File -> ExceptT String IO File
|
||||
guardFileInDatabase c fk = do
|
||||
maybeDBFile <- lift . runMaybeT $ queryForSingleFileByFileId fk c
|
||||
maybe
|
||||
(throwE ("File with id, " ++ show fk ++ " not found in database."))
|
||||
return
|
||||
maybeDBFile
|
357
lib/Database/Tagger/Connection.hs
Normal file
357
lib/Database/Tagger/Connection.hs
Normal file
@ -0,0 +1,357 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# OPTIONS_GHC -Wno-typed-holes #-}
|
||||
|
||||
{- |
|
||||
Module : Database.Tagger.Connection
|
||||
Description : Module to open, query, and close Tagger database connections.
|
||||
|
||||
License : GPL-3
|
||||
Maintainer : monawasensei@gmail.com
|
||||
-}
|
||||
module Database.Tagger.Connection (
|
||||
-- * Wrapped types
|
||||
open,
|
||||
open',
|
||||
close,
|
||||
query,
|
||||
queryNamed,
|
||||
query_,
|
||||
execute,
|
||||
execute_,
|
||||
executeNamed,
|
||||
executeMany,
|
||||
lastInsertRowId,
|
||||
initializeDatabase,
|
||||
teardownDatabase,
|
||||
|
||||
-- * Internal Connection types
|
||||
|
||||
-- | Functions exposing internal Connection representations. Exposed for convenience.
|
||||
withBareConnection,
|
||||
withConnection,
|
||||
withConnectionHandle,
|
||||
|
||||
-- * Database.SQLite.Simple types
|
||||
|
||||
-- | Types exported from Database.SQLite.Simple for use in 'Database.Tagger`
|
||||
Simple.Query,
|
||||
Simple.ToRow,
|
||||
Database.SQLite.Simple.ToField.ToField,
|
||||
Simple.FromRow,
|
||||
Simple.Only (..),
|
||||
Simple.NamedParam (..),
|
||||
) where
|
||||
|
||||
import Control.Monad (unless, when)
|
||||
import Data.Maybe
|
||||
import qualified Data.Text as T
|
||||
import Data.Time (getCurrentTime)
|
||||
import Data.Version
|
||||
import qualified Database.SQLite.Simple as Simple
|
||||
import qualified Database.SQLite.Simple.ToField
|
||||
import qualified Database.SQLite3 as SQLite3
|
||||
import Database.Tagger.Query.Type
|
||||
import Database.Tagger.Script (
|
||||
SQLiteScript (SQLiteScript),
|
||||
schemaDefinition,
|
||||
schemaTeardown,
|
||||
update0_3_4_0To0_3_4_2,
|
||||
)
|
||||
import Database.Tagger.Type
|
||||
import Database.Tagger.Type.Prim (BareConnection (..))
|
||||
import System.IO
|
||||
import Tagger.Info (taggerVersion)
|
||||
import Tagger.Util
|
||||
import Text.ParserCombinators.ReadP (readP_to_S)
|
||||
|
||||
{- |
|
||||
Open a new 'TaggedConnection` with the database at the given path.
|
||||
|
||||
The connection's label is set to the path and the lastAccessed time and database version
|
||||
is updated.
|
||||
|
||||
If the db info table is not found then the database is initialized, if this is undesired,
|
||||
use open'
|
||||
|
||||
Most Tagger connections should be made with this function.
|
||||
-}
|
||||
open :: FilePath -> IO TaggedConnection
|
||||
open p = do
|
||||
let tagName = T.pack p
|
||||
bc <- fmap BareConnection . Simple.open $ p
|
||||
dbInfoTableExists <- taggerDBInfoTableExists bc
|
||||
activateForeignKeyPragma bc
|
||||
let conn = TaggedConnection tagName bc
|
||||
unless dbInfoTableExists (initializeDatabase conn)
|
||||
updateTaggerDBInfoVersion bc
|
||||
updateTaggerDBInfoLastAccessed bc
|
||||
return conn
|
||||
|
||||
{- |
|
||||
Like 'open` but does NOT update the table with lastAccessedDateTime or the table version.
|
||||
|
||||
Also does not attempt to initialize the database if there is no db info table.
|
||||
-}
|
||||
open' :: FilePath -> IO TaggedConnection
|
||||
open' p = do
|
||||
let tagName = T.pack p
|
||||
bc <- fmap BareConnection . Simple.open $ p
|
||||
activateForeignKeyPragma bc
|
||||
return $ TaggedConnection tagName bc
|
||||
|
||||
{- |
|
||||
Closes a TaggedConnection
|
||||
-}
|
||||
close :: TaggedConnection -> IO ()
|
||||
close =
|
||||
withBareConnection
|
||||
(withConnection Simple.close)
|
||||
|
||||
{- |
|
||||
Run a query with a 'TaggedConnection`
|
||||
-}
|
||||
query ::
|
||||
(Simple.ToRow q, Simple.FromRow r) =>
|
||||
TaggedConnection ->
|
||||
TaggerQuery ->
|
||||
q ->
|
||||
IO [r]
|
||||
query tc (TaggerQuery queryStmnt) params =
|
||||
withBareConnection (\bc -> bareQuery bc queryStmnt params) tc
|
||||
|
||||
{- |
|
||||
Run a query with named parameters.
|
||||
-}
|
||||
queryNamed ::
|
||||
Simple.FromRow r =>
|
||||
TaggedConnection ->
|
||||
TaggerQuery ->
|
||||
[Simple.NamedParam] ->
|
||||
IO [r]
|
||||
queryNamed tc (TaggerQuery queryStmnt) params =
|
||||
withBareConnection (\bc -> bareQueryNamed bc queryStmnt params) tc
|
||||
|
||||
{- |
|
||||
Run a query taking no parameters with a 'TaggedConnection`
|
||||
|
||||
If the tagged connection's connection is 'Nothing` then an error is printed and
|
||||
an empty result list is returned.
|
||||
-}
|
||||
query_ ::
|
||||
Simple.FromRow r =>
|
||||
TaggedConnection ->
|
||||
TaggerQuery ->
|
||||
IO [r]
|
||||
query_ tc (TaggerQuery queryStmnt) = withBareConnection (`bareQuery_` queryStmnt) tc
|
||||
|
||||
{- |
|
||||
Execute a statement on a 'TaggedConnection`
|
||||
|
||||
Executions return no results.
|
||||
|
||||
If the tagged connection's connection is 'Nothing` then an error is printed.
|
||||
-}
|
||||
execute ::
|
||||
Simple.ToRow q =>
|
||||
TaggedConnection ->
|
||||
TaggerQuery ->
|
||||
q ->
|
||||
IO ()
|
||||
execute tc (TaggerQuery queryStmnt) params =
|
||||
withBareConnection
|
||||
(\bc -> bareExecute bc queryStmnt params)
|
||||
tc
|
||||
|
||||
{- |
|
||||
Execute a statement taking no parameters on a 'TaggedConnection`
|
||||
|
||||
Executions return no results.
|
||||
|
||||
If the tagged connection's connection is 'Nothing` then an error is printed.
|
||||
-}
|
||||
execute_ ::
|
||||
TaggedConnection ->
|
||||
TaggerQuery ->
|
||||
IO ()
|
||||
execute_ tc (TaggerQuery queryStmnt) =
|
||||
withBareConnection
|
||||
(`bareExecute_` queryStmnt)
|
||||
tc
|
||||
|
||||
{- |
|
||||
Execute a statement with named parameters.
|
||||
-}
|
||||
executeNamed :: TaggedConnection -> TaggerQuery -> [Simple.NamedParam] -> IO ()
|
||||
executeNamed tc (TaggerQuery queryStmnt) params =
|
||||
withBareConnection (\c -> bareExecuteNamed c queryStmnt params) tc
|
||||
|
||||
{- |
|
||||
Execute a statement on a list of parameters.
|
||||
-}
|
||||
executeMany :: Simple.ToRow q => TaggedConnection -> TaggerQuery -> [q] -> IO ()
|
||||
executeMany tc (TaggerQuery queryStmnt) params =
|
||||
withBareConnection
|
||||
(\bc -> bareExecuteMany bc queryStmnt params)
|
||||
tc
|
||||
|
||||
{- |
|
||||
Gets the ID of the row last inserted into the database.
|
||||
-}
|
||||
lastInsertRowId :: RowId r => TaggedConnection -> IO (RecordKey r)
|
||||
lastInsertRowId = withBareConnection bareLastInsertRowId
|
||||
|
||||
{- |
|
||||
Run the Tagger schema definition script on the given connection.
|
||||
|
||||
Should ideally not do anything on a database that is already up-to-date with the current
|
||||
schema definition, but it would be best to avoid doing that anyways.
|
||||
-}
|
||||
initializeDatabase :: TaggedConnection -> IO ()
|
||||
initializeDatabase tc = do
|
||||
initScript <- schemaDefinition
|
||||
withBareConnection
|
||||
( withConnection
|
||||
( withConnectionHandle
|
||||
(`SQLite3.exec` (\(SQLiteScript s) -> s) initScript)
|
||||
)
|
||||
)
|
||||
tc
|
||||
|
||||
{- |
|
||||
DROP all tables defined in the schemaDefinition.
|
||||
|
||||
This is really only used for generating and tearing down test databases.
|
||||
-}
|
||||
teardownDatabase :: TaggedConnection -> IO ()
|
||||
teardownDatabase tc = do
|
||||
teardownScript <- schemaTeardown
|
||||
withBareConnection
|
||||
( withConnection
|
||||
( withConnectionHandle
|
||||
(`SQLite3.exec` (\(SQLiteScript s) -> s) teardownScript)
|
||||
)
|
||||
)
|
||||
tc
|
||||
|
||||
{- |
|
||||
Run an action using a 'TaggedConnection`'s 'BareConnection`
|
||||
-}
|
||||
withBareConnection :: (BareConnection -> t) -> TaggedConnection -> t
|
||||
withBareConnection f (TaggedConnection _ bc) = f bc
|
||||
|
||||
{- |
|
||||
Run an action using a 'BareConnection`'s Connection.
|
||||
-}
|
||||
withConnection :: (Simple.Connection -> t) -> BareConnection -> t
|
||||
withConnection f = f . _bareConnection
|
||||
|
||||
{- |
|
||||
Run an action using a Connection's ConnectionHandle.
|
||||
-}
|
||||
withConnectionHandle :: (SQLite3.Database -> c) -> Simple.Connection -> c
|
||||
withConnectionHandle f = f . Simple.connectionHandle
|
||||
|
||||
activateForeignKeyPragma :: BareConnection -> IO ()
|
||||
activateForeignKeyPragma = flip bareExecute_ "PRAGMA foreign_keys = on"
|
||||
|
||||
taggerDBInfoTableExists :: BareConnection -> IO Bool
|
||||
taggerDBInfoTableExists c = do
|
||||
r <-
|
||||
bareQuery_
|
||||
c
|
||||
"SELECT COUNT(*) \
|
||||
\FROM sqlite_master \
|
||||
\WHERE type = 'table' AND name = 'TaggerDBInfo'" ::
|
||||
IO [Simple.Only Int]
|
||||
return . all ((> 0) . (\(Simple.Only n) -> n)) $ r
|
||||
|
||||
updateTaggerDBInfoLastAccessed :: BareConnection -> IO ()
|
||||
updateTaggerDBInfoLastAccessed bc = do
|
||||
dbInfoTableExists <- taggerDBInfoTableExists bc
|
||||
when dbInfoTableExists $ do
|
||||
currentTime <- getCurrentTime
|
||||
withConnection
|
||||
( \c ->
|
||||
Simple.execute
|
||||
c
|
||||
"UPDATE TaggerDBInfo SET lastAccessed = ?"
|
||||
[currentTime]
|
||||
)
|
||||
bc
|
||||
|
||||
updateTaggerDBInfoVersion :: BareConnection -> IO ()
|
||||
updateTaggerDBInfoVersion bc = do
|
||||
dbInfoTableExists <- taggerDBInfoTableExists bc
|
||||
maybeCurrentVersion <-
|
||||
head'
|
||||
. mapMaybe (readVersion . (\(Simple.Only x) -> x))
|
||||
<$> bareQuery_ bc "SELECT version FROM TaggerDBInfo LIMIT 1"
|
||||
patchDatabase maybeCurrentVersion
|
||||
when
|
||||
(dbInfoTableExists && isJust maybeCurrentVersion)
|
||||
( withConnection
|
||||
( \c ->
|
||||
Simple.execute
|
||||
c
|
||||
"UPDATE TaggerDBInfo SET version = ?"
|
||||
[showVersion taggerVersion]
|
||||
)
|
||||
bc
|
||||
)
|
||||
where
|
||||
readVersion :: String -> Maybe Version
|
||||
readVersion = last' . map fst . readP_to_S parseVersion
|
||||
patchDatabase :: Maybe Version -> IO ()
|
||||
patchDatabase Nothing =
|
||||
hPutStrLn stderr "Unable to determine database version, some operations may fail."
|
||||
patchDatabase (Just v) =
|
||||
if v /= taggerVersion
|
||||
then do
|
||||
when
|
||||
(makeVersion [0, 3, 4, 0] <= v && v < makeVersion [0, 3, 4, 2])
|
||||
v0_3_4_0_v_0_3_4_2
|
||||
else pure ()
|
||||
where
|
||||
v0_3_4_0_v_0_3_4_2 =
|
||||
runPatch =<< update0_3_4_0To0_3_4_2
|
||||
runPatch p =
|
||||
withConnection
|
||||
( withConnectionHandle
|
||||
(`SQLite3.exec` (\(SQLiteScript s) -> s) p)
|
||||
)
|
||||
bc
|
||||
|
||||
bareQuery ::
|
||||
(Simple.ToRow q, Simple.FromRow r) =>
|
||||
BareConnection ->
|
||||
Simple.Query ->
|
||||
q ->
|
||||
IO [r]
|
||||
bareQuery = withConnection Simple.query
|
||||
|
||||
bareQueryNamed ::
|
||||
(Simple.FromRow r) =>
|
||||
BareConnection ->
|
||||
Simple.Query ->
|
||||
[Simple.NamedParam] ->
|
||||
IO [r]
|
||||
bareQueryNamed = withConnection Simple.queryNamed
|
||||
|
||||
bareQuery_ :: Simple.FromRow r => BareConnection -> Simple.Query -> IO [r]
|
||||
bareQuery_ = withConnection Simple.query_
|
||||
|
||||
bareExecute :: Simple.ToRow q => BareConnection -> Simple.Query -> q -> IO ()
|
||||
bareExecute = withConnection Simple.execute
|
||||
|
||||
bareExecute_ :: BareConnection -> Simple.Query -> IO ()
|
||||
bareExecute_ = withConnection Simple.execute_
|
||||
|
||||
bareExecuteNamed :: BareConnection -> Simple.Query -> [Simple.NamedParam] -> IO ()
|
||||
bareExecuteNamed = withConnection Simple.executeNamed
|
||||
|
||||
bareExecuteMany :: Simple.ToRow q => BareConnection -> Simple.Query -> [q] -> IO ()
|
||||
bareExecuteMany = withConnection Simple.executeMany
|
||||
|
||||
bareLastInsertRowId :: RowId r => BareConnection -> IO (RecordKey r)
|
||||
bareLastInsertRowId =
|
||||
withConnection (fmap RecordKey . Simple.lastInsertRowId)
|
1175
lib/Database/Tagger/Query.hs
Normal file
1175
lib/Database/Tagger/Query.hs
Normal file
File diff suppressed because it is too large
Load Diff
40
lib/Database/Tagger/Query/Type.hs
Normal file
40
lib/Database/Tagger/Query/Type.hs
Normal file
@ -0,0 +1,40 @@
|
||||
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
{-# HLINT ignore "Use newtype instead of data" #-}
|
||||
|
||||
{- |
|
||||
Module : Database.Tagger.Query.Type
|
||||
Description : Types for different kinds of Queries.
|
||||
|
||||
License : GPL-3
|
||||
Maintainer : monawasensei@gmail.com
|
||||
-}
|
||||
module Database.Tagger.Query.Type (
|
||||
TaggerQuery (..),
|
||||
qcat,
|
||||
) where
|
||||
|
||||
import Data.String
|
||||
import Database.SQLite.Simple
|
||||
|
||||
{- |
|
||||
newtype wrapper for a Database.SQLite.Simple.Query type
|
||||
-}
|
||||
newtype TaggerQuery = TaggerQuery {taggerQuery :: Query}
|
||||
deriving
|
||||
( Show
|
||||
, Eq
|
||||
, Monoid
|
||||
, Semigroup
|
||||
, IsString
|
||||
)
|
||||
|
||||
{- |
|
||||
Concatenate two 'TaggerQuery`s together with a single space between them
|
||||
to prevent syntax errors from combined keywords or search terms when combining
|
||||
queries.
|
||||
-}
|
||||
qcat :: TaggerQuery -> TaggerQuery -> TaggerQuery
|
||||
x `qcat` y = x <> " " <> y
|
58
lib/Database/Tagger/Script.hs
Normal file
58
lib/Database/Tagger/Script.hs
Normal file
@ -0,0 +1,58 @@
|
||||
{-# LANGUAGE BangPatterns #-}
|
||||
{-# LANGUAGE QuasiQuotes #-}
|
||||
{-# OPTIONS_HADDOCK prune #-}
|
||||
|
||||
{- |
|
||||
Module : Database.Tagger.Script
|
||||
Description : Scripts for initialization or maintenance of a Tagger database.
|
||||
|
||||
License : GPL-3
|
||||
Maintainer : monawasensei@gmail.com
|
||||
-}
|
||||
module Database.Tagger.Script (
|
||||
SQLiteScript (..),
|
||||
schemaDefinition,
|
||||
schemaTeardown,
|
||||
update0_3_4_0To0_3_4_2,
|
||||
) where
|
||||
|
||||
import Data.String (IsString (..))
|
||||
import Data.Text (Text)
|
||||
import Paths_tagger
|
||||
import System.IO
|
||||
import Text.RawString.QQ (r)
|
||||
|
||||
newtype SQLiteScript = SQLiteScript Text deriving (Show, Eq)
|
||||
|
||||
{- |
|
||||
Defines the tables of a Tagger database and inserts some
|
||||
default information.
|
||||
-}
|
||||
schemaDefinition :: IO SQLiteScript
|
||||
schemaDefinition =
|
||||
getScriptContents "TaggerSchemaDefinition.sql"
|
||||
|
||||
{- |
|
||||
DROPS all tables in a Tagger database.
|
||||
-}
|
||||
schemaTeardown :: IO SQLiteScript
|
||||
schemaTeardown =
|
||||
getScriptContents "TaggerSchemaTeardown.sql"
|
||||
|
||||
update0_3_4_0To0_3_4_2 :: IO SQLiteScript
|
||||
update0_3_4_0To0_3_4_2 =
|
||||
return
|
||||
. SQLiteScript
|
||||
. fromString
|
||||
$ [r|
|
||||
DROP TABLE IF EXISTS Representative;
|
||||
|]
|
||||
|
||||
getScriptContents :: FilePath -> IO SQLiteScript
|
||||
getScriptContents p = do
|
||||
scriptFile <- getDataFileName p
|
||||
scriptHandle <- openFile scriptFile ReadMode
|
||||
scriptContents <- hGetContents scriptHandle
|
||||
let !script = SQLiteScript . fromString $ scriptContents
|
||||
hClose scriptHandle
|
||||
return script
|
193
lib/Database/Tagger/Type.hs
Normal file
193
lib/Database/Tagger/Type.hs
Normal file
@ -0,0 +1,193 @@
|
||||
{-# LANGUAGE DeriveAnyClass #-}
|
||||
{-# LANGUAGE DeriveGeneric #-}
|
||||
{-# LANGUAGE DerivingStrategies #-}
|
||||
{-# LANGUAGE GeneralisedNewtypeDeriving #-}
|
||||
{-# LANGUAGE StrictData #-}
|
||||
{-# OPTIONS_HADDOCK show-extensions #-}
|
||||
|
||||
{- |
|
||||
Module : Database.Tagger.Type
|
||||
Description : Data types used in tagger-lib and tagger-lib dependencies.
|
||||
|
||||
License : GPL-3
|
||||
Maintainer : monawasensei@gmail.com
|
||||
-}
|
||||
module Database.Tagger.Type (
|
||||
module Database.Tagger.Type.Prim,
|
||||
Database.Tagger.Type.Prim.BareConnection,
|
||||
|
||||
-- * Database Types
|
||||
RowId,
|
||||
RecordKey (..),
|
||||
File (..),
|
||||
Descriptor (..),
|
||||
Tag (..),
|
||||
isSubTag,
|
||||
isSubTagOf,
|
||||
MetaDescriptor (..),
|
||||
DescriptorTree,
|
||||
ConcreteTag (..),
|
||||
TaggedFile (..),
|
||||
ConcreteTaggedFile (..),
|
||||
|
||||
-- * Lenses
|
||||
module Database.Tagger.Type.Lens,
|
||||
) where
|
||||
|
||||
import qualified Data.HashSet as HashSet
|
||||
import Data.Hashable (Hashable)
|
||||
import Data.HierarchyMap (HierarchyMap)
|
||||
import Data.Int (Int64)
|
||||
import Data.Maybe (isJust)
|
||||
import Data.Text (Text)
|
||||
import Database.SQLite.Simple (FromRow (..), field)
|
||||
import Database.SQLite.Simple.FromField (FromField (..))
|
||||
import Database.SQLite.Simple.ToField (ToField (..))
|
||||
import Database.Tagger.Type.Lens
|
||||
import Database.Tagger.Type.Prim hiding (BareConnection (..))
|
||||
import qualified Database.Tagger.Type.Prim
|
||||
import GHC.Generics (Generic)
|
||||
|
||||
{- |
|
||||
Representing a Primary Key or RowId for a certain type specified in the type parameter.
|
||||
-}
|
||||
newtype RecordKey a = RecordKey Int64
|
||||
deriving (Generic)
|
||||
deriving newtype (Show, Eq, Hashable, Bounded, Enum, Num, Ord, Real, Read, Integral)
|
||||
|
||||
instance FromField (RecordKey a) where
|
||||
fromField = fmap RecordKey . fromField
|
||||
|
||||
instance ToField (RecordKey a) where
|
||||
toField (RecordKey k) = toField k
|
||||
|
||||
{- |
|
||||
An empty class for types that are identifiable by a RowId or Primary Key.
|
||||
-}
|
||||
class RowId r
|
||||
|
||||
{- |
|
||||
Type synonym for a 'HierarchyMap` of 'Descriptor`s.
|
||||
-}
|
||||
type DescriptorTree = HierarchyMap Descriptor
|
||||
|
||||
{- |
|
||||
Data type representing a single row in the File table.
|
||||
-}
|
||||
data File = File
|
||||
{ -- | Unique primary key identifying a File record.
|
||||
fileId :: RecordKey File
|
||||
, -- | Unique absolute path to a File.
|
||||
filePath :: Text
|
||||
}
|
||||
deriving (Show, Eq, Generic, Hashable, RowId)
|
||||
|
||||
{- |
|
||||
Ord instance that ignores the RecordKey.
|
||||
-}
|
||||
instance Ord File where
|
||||
compare (File _ x) (File _ y) = compare x y
|
||||
|
||||
instance FromRow File where
|
||||
fromRow = File <$> field <*> field
|
||||
|
||||
{- |
|
||||
Data type corresponding to a single row in the Descriptor table.
|
||||
-}
|
||||
data Descriptor = Descriptor
|
||||
{ -- | Unique Primary key identifying a Descriptor record.
|
||||
descriptorId :: RecordKey Descriptor
|
||||
, -- | Descriptor text.
|
||||
descriptor :: Text
|
||||
}
|
||||
deriving (Show, Eq, Generic, Hashable, RowId)
|
||||
|
||||
{- |
|
||||
Ord instance that ignores the RecordKey.
|
||||
-}
|
||||
instance Ord Descriptor where
|
||||
compare (Descriptor _ dx) (Descriptor _ dy) = compare dx dy
|
||||
|
||||
instance FromRow Descriptor where
|
||||
fromRow = Descriptor <$> field <*> field
|
||||
|
||||
{- |
|
||||
Data type corresponding to a single row in the Tag table.
|
||||
-}
|
||||
data Tag = Tag
|
||||
{ -- | Unique id identifying a single tag record.
|
||||
tagId :: RecordKey Tag
|
||||
, -- | Foreign key to a File record.
|
||||
tagFileId :: RecordKey File
|
||||
, -- | Foreign key to a Descriptor record.
|
||||
tagDescriptorId :: RecordKey Descriptor
|
||||
, -- | Linking key to another Tag record if this tag is a subtag.
|
||||
tagSubtagOfId :: Maybe (RecordKey Tag)
|
||||
}
|
||||
deriving (Show, Eq, Generic, Hashable, RowId)
|
||||
|
||||
instance FromRow Tag where
|
||||
fromRow = Tag <$> field <*> field <*> field <*> field
|
||||
|
||||
{- |
|
||||
Returns 'True` if the given 'Tag` is a subtag.
|
||||
-}
|
||||
isSubTag :: Tag -> Bool
|
||||
isSubTag (Tag _ _ _ s) = isJust s
|
||||
|
||||
{- |
|
||||
Typically used infix.
|
||||
-}
|
||||
isSubTagOf :: Tag -> Tag -> Bool
|
||||
(Tag _ _ _ s) `isSubTagOf` (Tag tid _ _ _) = Just tid == s
|
||||
|
||||
{- |
|
||||
Data type corresponding to one row in the MetaDescriptor Table.
|
||||
-}
|
||||
data MetaDescriptor = MetaDescriptor
|
||||
{ -- | Foreign key to a Descriptor record.
|
||||
metaDescriptorId :: RecordKey Descriptor
|
||||
, -- | Foreign key to a Descriptor record.
|
||||
infraDescriptorId :: RecordKey Descriptor
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
{- |
|
||||
Data type representing a single file and all of the tags it contains.
|
||||
|
||||
Is an encoding of a recursive query on a joined table of Tag - File - Tag
|
||||
-}
|
||||
data TaggedFile = TaggedFile
|
||||
{ taggedFileId :: RecordKey File
|
||||
, taggedFileTags :: HashSet.HashSet Tag
|
||||
}
|
||||
deriving (Show, Eq, Generic, Hashable)
|
||||
|
||||
{- |
|
||||
Data type corresponding to a \"dereferenced\" 'Tag`.
|
||||
|
||||
Contains the ID of the 'Tag`, its 'Descriptor` and the ID of its supertag if it is
|
||||
a subtag.
|
||||
|
||||
Does not contain the 'File` the 'Tag` is attached to because this type is only meant
|
||||
for use in the 'ConcreteTaggedFile` where the 'File` would be redundant.
|
||||
-}
|
||||
data ConcreteTag = ConcreteTag
|
||||
{ concreteTagId :: RecordKey Tag
|
||||
, concreteTagDescriptor :: Descriptor
|
||||
, concreteTagSubTagOfId :: Maybe (RecordKey Tag)
|
||||
}
|
||||
deriving (Show, Eq, Generic, Hashable)
|
||||
|
||||
{- |
|
||||
Data type representing a \"dereferenced\" TaggedFile
|
||||
|
||||
Contains the actual file and a 'HierarchyMap` of the 'Descriptor`s it is tagged with.
|
||||
|
||||
For visual or human-readable representation.
|
||||
-}
|
||||
data ConcreteTaggedFile = ConcreteTaggedFile
|
||||
{ concreteTaggedFile :: File
|
||||
, concreteTaggedFileDescriptors :: HierarchyMap ConcreteTag
|
||||
}
|
||||
deriving (Show, Eq)
|
28
lib/Database/Tagger/Type/Lens.hs
Normal file
28
lib/Database/Tagger/Type/Lens.hs
Normal file
@ -0,0 +1,28 @@
|
||||
{-# LANGUAGE FlexibleInstances #-}
|
||||
{-# LANGUAGE FunctionalDependencies #-}
|
||||
{-# LANGUAGE TemplateHaskell #-}
|
||||
{-# OPTIONS_HADDOCK prune, hide #-}
|
||||
|
||||
{- |
|
||||
Module : Database.Tagger.Type.Lens
|
||||
|
||||
License : GPL-3
|
||||
Maintainer : monawasensei@gmail.com
|
||||
-}
|
||||
module Database.Tagger.Type.Lens (
|
||||
module Database.Tagger.Type.Lens,
|
||||
) where
|
||||
|
||||
import Control.Lens (
|
||||
abbreviatedFields,
|
||||
makeLenses,
|
||||
makeLensesWith,
|
||||
)
|
||||
import Database.Tagger.Type.Prim (
|
||||
BareConnection,
|
||||
TaggedConnection,
|
||||
)
|
||||
|
||||
makeLensesWith abbreviatedFields ''TaggedConnection
|
||||
|
||||
makeLenses ''BareConnection
|
46
lib/Database/Tagger/Type/Prim.hs
Normal file
46
lib/Database/Tagger/Type/Prim.hs
Normal file
@ -0,0 +1,46 @@
|
||||
{-# OPTIONS_GHC -Wno-unused-top-binds #-}
|
||||
{-# OPTIONS_HADDOCK hide, ignore-exports, prune #-}
|
||||
|
||||
{- |
|
||||
Module : Database.Tagger.Type.Prim
|
||||
Description : Types that have lenses defined in "Database.Tagger.Type.Lens"
|
||||
|
||||
License : GPL-3
|
||||
Maintainer : monawasensei@gmail.com
|
||||
|
||||
The types defined here all have lenses defined in the module "Database.Tagger.Type.Lens".
|
||||
The two modules are separated purely to make exporting lenses and lens instances together
|
||||
with non-TemplateHaskell generated code simpler.
|
||||
-}
|
||||
module Database.Tagger.Type.Prim (
|
||||
BareConnection (..),
|
||||
TaggedConnection (..),
|
||||
) where
|
||||
|
||||
import Data.Text
|
||||
import Database.SQLite.Simple
|
||||
|
||||
-- * Connection Types
|
||||
|
||||
{- |
|
||||
A newtype that wraps a 'Connection` to create instances of Show and Eq.
|
||||
-}
|
||||
newtype BareConnection = BareConnection {_bareConnection :: Connection}
|
||||
|
||||
instance Show BareConnection where
|
||||
show = const "Bare Connection"
|
||||
|
||||
instance Eq BareConnection where
|
||||
_ == _ = True
|
||||
|
||||
{- |
|
||||
A data type that manages connections to a Tagger database.
|
||||
-}
|
||||
data TaggedConnection = TaggedConnection
|
||||
{ -- | Connection name,
|
||||
-- typically the absolute path of the file connected to, but could be anything.
|
||||
_taggedconnectionConnName :: !Text
|
||||
, -- | Connection to a database, if it is open.
|
||||
_taggedconnectionConnInstance :: !BareConnection
|
||||
}
|
||||
deriving (Eq, Show)
|
17
lib/Tagger/Info.hs
Normal file
17
lib/Tagger/Info.hs
Normal file
@ -0,0 +1,17 @@
|
||||
{- |
|
||||
Module : Tagger.Info
|
||||
Description : Basic information detailing runtime information of tagger-lib
|
||||
|
||||
License : GPL-3
|
||||
Maintainer : monawasensei@gmail.com
|
||||
-}
|
||||
module Tagger.Info (
|
||||
taggerVersion,
|
||||
) where
|
||||
|
||||
import qualified Data.Version as Version
|
||||
import qualified Paths_tagger
|
||||
|
||||
{-# INLINE taggerVersion #-}
|
||||
taggerVersion :: Version.Version
|
||||
taggerVersion = Paths_tagger.version
|
39
lib/Tagger/Util.hs
Normal file
39
lib/Tagger/Util.hs
Normal file
@ -0,0 +1,39 @@
|
||||
{-# OPTIONS_HADDOCK hide #-}
|
||||
|
||||
module Tagger.Util (
|
||||
head',
|
||||
tail',
|
||||
last',
|
||||
hoistMaybe,
|
||||
catMaybeTM,
|
||||
) where
|
||||
|
||||
import Control.Monad.Trans.Maybe
|
||||
import Data.Maybe
|
||||
|
||||
{-# INLINE head' #-}
|
||||
head' :: [a] -> Maybe a
|
||||
head' [] = Nothing
|
||||
head' (x : _) = Just x
|
||||
|
||||
{-# INLINE tail' #-}
|
||||
tail' :: [a] -> [a]
|
||||
tail' [] = []
|
||||
tail' xs = tail xs
|
||||
|
||||
{-# INLINE last' #-}
|
||||
last' :: [a] -> Maybe a
|
||||
last' [] = Nothing
|
||||
last' xs = Just . last $ xs
|
||||
|
||||
{-# INLINE hoistMaybe #-}
|
||||
hoistMaybe :: Monad m => Maybe a -> MaybeT m a
|
||||
hoistMaybe = MaybeT . return
|
||||
|
||||
{-# INLINE catMaybeTM #-}
|
||||
|
||||
{- |
|
||||
> catMaybeTM f = fmap catMaybes . mapM (runMaybeT . f)
|
||||
-}
|
||||
catMaybeTM :: Monad f => (a1 -> MaybeT f a2) -> [a1] -> f [a2]
|
||||
catMaybeTM f = fmap catMaybes . mapM (runMaybeT . f)
|
196
lib/Text/TaggerQL.hs
Normal file
196
lib/Text/TaggerQL.hs
Normal file
@ -0,0 +1,196 @@
|
||||
{-# LANGUAGE OverloadedLists #-}
|
||||
{-# LANGUAGE TupleSections #-}
|
||||
{-# LANGUAGE ViewPatterns #-}
|
||||
{-# HLINT ignore "Redundant if" #-}
|
||||
{-# OPTIONS_GHC -Wno-typed-holes #-}
|
||||
{-# HLINT ignore "Use concatMap" #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
{- |
|
||||
Module : Text.TaggerQL
|
||||
Description : The front-end and interface for running TaggerQL queries on a Tagger database.
|
||||
|
||||
License : GPL-3
|
||||
Maintainer : monawasensei@gmail.com
|
||||
-}
|
||||
module Text.TaggerQL (
|
||||
-- * Query with TaggerQL
|
||||
TaggerQLQuery (..),
|
||||
taggerQL,
|
||||
queryRequest,
|
||||
|
||||
-- * Tag with TaggerQL
|
||||
TaggerQLTagStmnt (..),
|
||||
taggerQLTag,
|
||||
|
||||
-- * Other
|
||||
CombinableSentenceResult,
|
||||
combinableSentenceResultSetOp,
|
||||
combinableSentenceResultSet,
|
||||
) where
|
||||
|
||||
import Control.Monad (void)
|
||||
import Control.Monad.Trans.Class (MonadTrans (lift))
|
||||
import Control.Monad.Trans.Reader (
|
||||
ReaderT (runReaderT),
|
||||
ask,
|
||||
asks,
|
||||
local,
|
||||
)
|
||||
import qualified Data.List as L
|
||||
import Data.List.NonEmpty (NonEmpty ((:|)))
|
||||
import Data.Maybe (fromJust)
|
||||
import Data.String (IsString (..))
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Database.Tagger.Query (
|
||||
insertTags,
|
||||
queryForDescriptorByPattern,
|
||||
queryForTagByFileKeyAndDescriptorPatternAndNullSubTagOf,
|
||||
queryForTagBySubTagTriple,
|
||||
)
|
||||
import Database.Tagger.Type (
|
||||
Descriptor (descriptorId),
|
||||
File,
|
||||
RecordKey,
|
||||
Tag (tagId),
|
||||
TaggedConnection,
|
||||
)
|
||||
import System.IO (hPrint, stderr)
|
||||
import Text.TaggerQL.AST (
|
||||
ComplexTerm (..),
|
||||
Sentence (Sentence),
|
||||
SimpleTerm (..),
|
||||
Term (Term),
|
||||
TermTree (..),
|
||||
complexTermNode,
|
||||
)
|
||||
import Text.TaggerQL.Engine.QueryEngine (
|
||||
CombinableSentenceResult,
|
||||
TaggerQLQuery (..),
|
||||
combinableSentenceResultSet,
|
||||
combinableSentenceResultSetOp,
|
||||
queryRequest,
|
||||
taggerQL,
|
||||
)
|
||||
import Text.TaggerQL.Parser.Internal (
|
||||
parse,
|
||||
sentenceParser,
|
||||
)
|
||||
|
||||
{- |
|
||||
newtype wrapper for 'Text`
|
||||
|
||||
is an instance of IsString
|
||||
-}
|
||||
newtype TaggerQLTagStmnt = TaggerQLTagStmnt Text deriving (Show, Eq)
|
||||
|
||||
instance IsString TaggerQLTagStmnt where
|
||||
fromString = TaggerQLTagStmnt . T.pack
|
||||
|
||||
newtype TermTag = TermTag (Term Text) deriving (Show, Eq)
|
||||
|
||||
newtype TermSubTag = TermSubTag (Term Text) deriving (Show, Eq)
|
||||
|
||||
type TaggingEnvironment = (TaggedConnection, [RecordKey Tag])
|
||||
|
||||
type TaggingReader a = ReaderT TaggingEnvironment IO a
|
||||
|
||||
setTagList :: [RecordKey Tag] -> TaggingEnvironment -> TaggingEnvironment
|
||||
setTagList t (c, _) = (c, t)
|
||||
|
||||
{- |
|
||||
Run a subset of the TaggerQL as 'Descriptor` patterns to insert as tags on the given
|
||||
'File`.
|
||||
|
||||
Because it is a subset of TaggerQL, 'QueryCriteria` Literals can be parsed, but they
|
||||
will be ignored during insertion. If it is desired to 'Tag` a 'File` with 'Descriptor`s
|
||||
that look like 'QueryCriteria` Literals, then use escape characters.
|
||||
-}
|
||||
taggerQLTag :: RecordKey File -> TaggerQLTagStmnt -> TaggedConnection -> IO ()
|
||||
taggerQLTag fk (TaggerQLTagStmnt q) tc = do
|
||||
let tagStmnt = parse sentenceParser "TaggerQLStmnt" q
|
||||
either
|
||||
(hPrint stderr)
|
||||
(insertTagSentence tc . zipDescriptorPatternsWithFileKey fk)
|
||||
tagStmnt
|
||||
where
|
||||
zipDescriptorPatternsWithFileKey ::
|
||||
RecordKey File ->
|
||||
Sentence Text ->
|
||||
Sentence (RecordKey File, Text)
|
||||
zipDescriptorPatternsWithFileKey fk' = fmap (fk',)
|
||||
|
||||
insertTagSentence :: TaggedConnection -> Sentence (RecordKey File, Text) -> IO ()
|
||||
insertTagSentence tc (Sentence tts) = mapM_ (insertTagTree tc) tts
|
||||
|
||||
insertTagTree :: TaggedConnection -> TermTree (RecordKey File, Text) -> IO ()
|
||||
insertTagTree tc tt =
|
||||
case tt of
|
||||
Simple t -> void (runReaderT (insertSimpleTerm t) (tc, []))
|
||||
Complex t ->
|
||||
void
|
||||
(runReaderT (insertComplexTerm True t) (tc, []))
|
||||
|
||||
insertComplexTerm ::
|
||||
Bool -> ComplexTerm (RecordKey File, Text) -> TaggingReader [RecordKey Tag]
|
||||
insertComplexTerm _ (Bottom _) = return []
|
||||
insertComplexTerm True ct = do
|
||||
newEnvList <- insertTopLevelComplexTerm ct
|
||||
local (setTagList newEnvList) $ insertComplexTerm False ct
|
||||
where
|
||||
insertTopLevelComplexTerm ::
|
||||
ComplexTerm (RecordKey File, Text) ->
|
||||
TaggingReader [RecordKey Tag]
|
||||
insertTopLevelComplexTerm (complexTermNode -> t@(Term _ (fk, p))) = do
|
||||
void $ insertTerm t
|
||||
c <- asks fst
|
||||
map tagId
|
||||
<$> lift
|
||||
( queryForTagByFileKeyAndDescriptorPatternAndNullSubTagOf
|
||||
fk
|
||||
p
|
||||
c
|
||||
)
|
||||
insertComplexTerm _ (currentTerm :<- (ct :| sts)) = do
|
||||
void $ case ct of
|
||||
Bottom t -> insertSubTag t
|
||||
(complexTermNode -> ctt) -> do
|
||||
lowerLayerEnv <- insertSubTag ctt
|
||||
local (setTagList lowerLayerEnv) $ insertComplexTerm False ct
|
||||
mapM_ (\ct' -> insertComplexTerm False (currentTerm :<- (ct' :| []))) sts
|
||||
return []
|
||||
|
||||
insertSubTag ::
|
||||
Term (RecordKey File, Text) ->
|
||||
ReaderT TaggingEnvironment IO [RecordKey Tag]
|
||||
insertSubTag (Term _ (fk, p)) = do
|
||||
te <- ask
|
||||
subTagDescriptorIds <-
|
||||
map descriptorId
|
||||
<$> lift (queryForDescriptorByPattern p (fst te))
|
||||
let subTagTriples = (fk,,) <$> subTagDescriptorIds <*> (Just <$> snd te)
|
||||
lift . void $ insertTags subTagTriples (fst te)
|
||||
map tagId . unions
|
||||
<$> lift
|
||||
( mapM
|
||||
(`queryForTagBySubTagTriple` fst te)
|
||||
(third fromJust <$> subTagTriples)
|
||||
)
|
||||
where
|
||||
third f (x, y, z) = (x, y, f z)
|
||||
|
||||
insertSimpleTerm ::
|
||||
SimpleTerm (RecordKey File, Text) ->
|
||||
TaggingReader [RecordKey Tag]
|
||||
insertSimpleTerm (SimpleTerm t) = insertTerm t
|
||||
|
||||
insertTerm :: Term (RecordKey File, Text) -> TaggingReader [RecordKey Tag]
|
||||
insertTerm (Term _ (fk, p)) = do
|
||||
c <- asks fst
|
||||
ds <- map descriptorId <$> lift (queryForDescriptorByPattern p c)
|
||||
let tagTriples = (fk,,Nothing) <$> ds
|
||||
lift $ insertTags tagTriples c
|
||||
|
||||
unions :: (Foldable t, Eq a) => t [a] -> [a]
|
||||
unions xs = if null xs then [] else L.foldl' L.union [] xs
|
152
lib/Text/TaggerQL/AST.hs
Normal file
152
lib/Text/TaggerQL/AST.hs
Normal file
@ -0,0 +1,152 @@
|
||||
{-# LANGUAGE DeriveFunctor #-}
|
||||
{-# LANGUAGE StrictData #-}
|
||||
|
||||
{- |
|
||||
Module : Text.TaggerQL.AST
|
||||
Description : Defines the components of a TaggerQL AST.
|
||||
|
||||
License : GPL-3
|
||||
Maintainer : monawasensei@gmail.com
|
||||
-}
|
||||
module Text.TaggerQL.AST (
|
||||
Request (..),
|
||||
SentenceTree (..),
|
||||
SentenceSet (..),
|
||||
Sentence (..),
|
||||
TermTree (..),
|
||||
ComplexTerm (..),
|
||||
SimpleTerm (..),
|
||||
Term (..),
|
||||
termTreeNode,
|
||||
complexTermNode,
|
||||
simplifyTermTree,
|
||||
newPredicates,
|
||||
) where
|
||||
|
||||
import qualified Data.List.NonEmpty as N
|
||||
import Data.Tagger (QueryCriteria (..), SetOp (..))
|
||||
|
||||
{- |
|
||||
A newtype wrapper for a list of 'SentenceTree`s.
|
||||
|
||||
The 'Request` type is the final and most complete representation of a TaggerQL query.
|
||||
It essentially consists of a recursive list of queries, all represented in the
|
||||
'Request` type as the terminal parent of them all.
|
||||
-}
|
||||
newtype Request a = Request {request :: [SentenceTree a]}
|
||||
deriving (Show, Eq, Functor)
|
||||
|
||||
{- |
|
||||
A data type encompassing either a single 'SentenceSet` or a recursive list of
|
||||
'SentenceTree`s
|
||||
-}
|
||||
data SentenceTree a
|
||||
= SentenceNode (SentenceSet a)
|
||||
| SentenceBranch SetOp [SentenceTree a]
|
||||
deriving (Show, Eq, Functor)
|
||||
|
||||
{- |
|
||||
A data type encompassing a 'SetOp` Literal and a 'Sentence`
|
||||
|
||||
The 'SetOp` Literal is to inform how this 'Sentence` is combined with others
|
||||
in a left-associative combination.
|
||||
-}
|
||||
data SentenceSet a
|
||||
= CombinableSentence SetOp (Sentence a)
|
||||
deriving (Show, Eq, Functor)
|
||||
|
||||
{- |
|
||||
A list of 'TermTree`s, one 'Sentence` technically makes up a complete TaggerQL query
|
||||
but is not implemented this way.
|
||||
-}
|
||||
newtype Sentence a = Sentence {sentence :: [TermTree a]}
|
||||
deriving (Show, Eq, Functor)
|
||||
|
||||
{- |
|
||||
A sum of 'SimpleTerm` and 'ComplexTerm`
|
||||
-}
|
||||
data TermTree a
|
||||
= Simple (SimpleTerm a)
|
||||
| Complex (ComplexTerm a)
|
||||
deriving (Show, Eq, Functor)
|
||||
|
||||
{- |
|
||||
A data type that represents either a 'Term` that has 1 or more nested predicates
|
||||
|
||||
or a 'Term` with no predicates that is the bottom of a relationship, and is therefore
|
||||
not queried by itself, but only in relation to the 'Term` above it.
|
||||
-}
|
||||
data ComplexTerm a
|
||||
= Term a :<- (N.NonEmpty (ComplexTerm a))
|
||||
| Bottom (Term a)
|
||||
deriving (Show, Eq, Functor)
|
||||
|
||||
{- |
|
||||
newtype wrapper for a 'Term` that signifies a 'Term` is top-level in the request
|
||||
and has no predicates.
|
||||
-}
|
||||
newtype SimpleTerm a = SimpleTerm (Term a) deriving (Show, Eq, Functor)
|
||||
|
||||
{- |
|
||||
Smallest unit of a TaggerQL AST.
|
||||
-}
|
||||
data Term a = Term {termCriteria :: QueryCriteria, termPattern :: a}
|
||||
deriving (Show, Eq, Functor)
|
||||
|
||||
{- |
|
||||
Return the 'Term` in the given 'TermTree` node.
|
||||
-}
|
||||
termTreeNode :: TermTree a -> Term a
|
||||
termTreeNode b =
|
||||
case b of
|
||||
Simple (SimpleTerm t) -> t
|
||||
(Complex c) -> complexTermNode c
|
||||
|
||||
{- |
|
||||
Retrieve the 'Term` from a 'ComplexTerm`
|
||||
-}
|
||||
complexTermNode :: ComplexTerm a -> Term a
|
||||
complexTermNode x =
|
||||
case x of
|
||||
t :<- _ -> t
|
||||
Bottom t -> t
|
||||
|
||||
{- |
|
||||
To the first given 'ComplexTerm`, add a list of predicate 'ComplexTerm`s to
|
||||
the right of its current predicates.
|
||||
|
||||
Automatically converts 'Bottom` terms.
|
||||
-}
|
||||
newPredicates :: ComplexTerm a -> [ComplexTerm a] -> ComplexTerm a
|
||||
newPredicates basis [] = basis
|
||||
newPredicates basis ts =
|
||||
case basis of
|
||||
Bottom t -> t :<- N.fromList ts
|
||||
t :<- ps -> t :<- N.fromList (N.toList ps ++ ts)
|
||||
|
||||
{- |
|
||||
Converts 'Bottom` 'ComplexTerm`s in a 'TermTree` to 'Simple` nodes.
|
||||
|
||||
Does nothing to existing 'Simple` nodes or ':<-` nodes.
|
||||
-}
|
||||
simplifyTermTree :: TermTree a -> TermTree a
|
||||
simplifyTermTree t@(Simple _) = t
|
||||
simplifyTermTree t@(Complex c) =
|
||||
case c of
|
||||
Bottom rawTerm -> Simple . SimpleTerm $ rawTerm
|
||||
_ -> t
|
||||
|
||||
-- formatCriteria :: QueryCriteria -> String
|
||||
-- formatCriteria qc =
|
||||
-- case qc of
|
||||
-- DescriptorCriteria -> "D."
|
||||
-- MetaDescriptorCriteria -> "R."
|
||||
-- FilePatternCriteria -> "P."
|
||||
-- UntaggedCriteria -> "U."
|
||||
|
||||
-- formatSetOp :: SetOp -> String
|
||||
-- formatSetOp so =
|
||||
-- case so of
|
||||
-- Union -> "U| "
|
||||
-- Intersect -> "I| "
|
||||
-- Difference -> "D| "
|
287
lib/Text/TaggerQL/Engine/QueryEngine.hs
Normal file
287
lib/Text/TaggerQL/Engine/QueryEngine.hs
Normal file
@ -0,0 +1,287 @@
|
||||
{-# HLINT ignore "Use <&>" #-}
|
||||
{-# LANGUAGE BangPatterns #-}
|
||||
{-# LANGUAGE DeriveFunctor #-}
|
||||
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
|
||||
{-# LANGUAGE ViewPatterns #-}
|
||||
{-# OPTIONS_GHC -Wno-typed-holes #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
{-# OPTIONS_HADDOCK hide #-}
|
||||
|
||||
{- |
|
||||
Module : Text.TaggerQL.Engine.Query
|
||||
Description : This module houses the internal workings of the TaggerQL's query engine.
|
||||
|
||||
License : GPL-3
|
||||
Maintainer : monawasensei@gmail.com
|
||||
-}
|
||||
module Text.TaggerQL.Engine.QueryEngine (
|
||||
TaggerQLQuery (..),
|
||||
taggerQL,
|
||||
queryRequest,
|
||||
CombinableSentenceResult (..),
|
||||
combinableSentenceResultSetOp,
|
||||
combinableSentenceResultSet,
|
||||
) where
|
||||
|
||||
import Control.Monad ((<=<))
|
||||
import Control.Monad.Trans.Reader (
|
||||
ReaderT (runReaderT),
|
||||
asks,
|
||||
local,
|
||||
)
|
||||
import Data.HashSet (HashSet)
|
||||
import qualified Data.HashSet as HS
|
||||
import Data.Hashable (Hashable)
|
||||
import qualified Data.List as L
|
||||
import Data.List.NonEmpty (NonEmpty ((:|)))
|
||||
import qualified Data.List.NonEmpty as NE
|
||||
import Data.String (IsString (..))
|
||||
import Data.Tagger (
|
||||
QueryCriteria (
|
||||
DescriptorCriteria,
|
||||
FilePatternCriteria,
|
||||
MetaDescriptorCriteria,
|
||||
UntaggedCriteria
|
||||
),
|
||||
SetOp (..),
|
||||
)
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Database.Tagger.Query (
|
||||
flatQueryForFileByTagDescriptorPattern,
|
||||
flatQueryForFileOnMetaRelationPattern,
|
||||
queryForFileByPattern,
|
||||
queryForUntaggedFiles,
|
||||
)
|
||||
import Database.Tagger.Type (File, Tag (..), TaggedConnection)
|
||||
import System.IO (hPrint, stderr)
|
||||
import Text.TaggerQL.AST (
|
||||
ComplexTerm (..),
|
||||
Request (Request),
|
||||
Sentence (Sentence),
|
||||
SentenceSet (..),
|
||||
SentenceTree (..),
|
||||
SimpleTerm (..),
|
||||
Term (Term),
|
||||
TermTree (..),
|
||||
)
|
||||
import Text.TaggerQL.Engine.QueryEngine.Query (
|
||||
QueryEnv (QueryEnv, envSuperTerm, envTagSet),
|
||||
Sub (..),
|
||||
Super (..),
|
||||
getFileSetFromTagSet,
|
||||
queryTerm,
|
||||
queryTerms,
|
||||
)
|
||||
import Text.TaggerQL.Parser.Internal (parse, requestParser)
|
||||
|
||||
data CombinableSentenceResult
|
||||
= CombinableSentenceResult SetOp (HashSet File)
|
||||
deriving (Show, Eq)
|
||||
|
||||
combinableSentenceResultSetOp :: CombinableSentenceResult -> SetOp
|
||||
combinableSentenceResultSetOp (CombinableSentenceResult so _) = so
|
||||
|
||||
combinableSentenceResultSet :: CombinableSentenceResult -> HashSet File
|
||||
combinableSentenceResultSet (CombinableSentenceResult _ s) = s
|
||||
|
||||
{- |
|
||||
newtype wrapper for 'Text`
|
||||
|
||||
is an instance of IsString
|
||||
-}
|
||||
newtype TaggerQLQuery = TaggerQLQuery Text deriving (Show, Eq)
|
||||
|
||||
instance IsString TaggerQLQuery where
|
||||
fromString = TaggerQLQuery . T.pack
|
||||
|
||||
newtype TermResult = TermResult {runTermResult :: HashSet File}
|
||||
deriving (Show, Eq, Semigroup, Monoid)
|
||||
|
||||
{- |
|
||||
Run a 'TaggerQLQuery` on a connection.
|
||||
-}
|
||||
taggerQL :: TaggerQLQuery -> TaggedConnection -> IO (HashSet File)
|
||||
taggerQL (TaggerQLQuery q) tc = do
|
||||
let parseResult = parse requestParser "TaggerQL" q
|
||||
either
|
||||
(const (return HS.empty) <=< hPrint stderr)
|
||||
(fmap combinableSentenceResultSet . queryRequest tc)
|
||||
parseResult
|
||||
|
||||
{- |
|
||||
Run a query given the 'Request` AST of the result of parsing a 'TaggerQLQuery`
|
||||
|
||||
Can be used to programmatically generate queries using TaggerQL alongside the
|
||||
Text.TaggerQL.AST module to create the structure.
|
||||
-}
|
||||
queryRequest ::
|
||||
TaggedConnection ->
|
||||
Request Text ->
|
||||
IO CombinableSentenceResult
|
||||
queryRequest tc (Request strs) = combineSentences <$> mapM (querySentenceTree tc) strs
|
||||
|
||||
querySentenceTree ::
|
||||
TaggedConnection ->
|
||||
SentenceTree Text ->
|
||||
IO CombinableSentenceResult
|
||||
querySentenceTree tc tr =
|
||||
case tr of
|
||||
SentenceNode ss -> querySentenceSet tc ss
|
||||
SentenceBranch so sss -> do
|
||||
(CombinableSentenceResult _ sentenceResults) <-
|
||||
combineSentences <$> mapM (querySentenceTree tc) sss
|
||||
return $ CombinableSentenceResult so sentenceResults
|
||||
|
||||
querySentenceSet ::
|
||||
TaggedConnection ->
|
||||
SentenceSet Text ->
|
||||
IO CombinableSentenceResult
|
||||
querySentenceSet tc (CombinableSentence so s) =
|
||||
CombinableSentenceResult so . runTermResult <$> querySentence tc s
|
||||
|
||||
{- |
|
||||
All 'TermTree`s in a 'Sentence` are intersected with each other.
|
||||
-}
|
||||
querySentence ::
|
||||
TaggedConnection ->
|
||||
Sentence Text ->
|
||||
IO TermResult
|
||||
querySentence tc (Sentence tts) =
|
||||
intersectTermResults
|
||||
<$> mapM (queryTermTree tc) tts
|
||||
|
||||
{- |
|
||||
Return 'Nothing` if the given 'TermTree` is Complex and Bottom.
|
||||
-}
|
||||
queryTermTree ::
|
||||
TaggedConnection ->
|
||||
TermTree Text ->
|
||||
IO TermResult
|
||||
queryTermTree tc tt =
|
||||
case tt of
|
||||
Simple st -> querySimpleTerm tc st
|
||||
Complex ct -> queryComplexTerm tc ct
|
||||
|
||||
queryComplexTerm :: TaggedConnection -> ComplexTerm Text -> IO TermResult
|
||||
queryComplexTerm _ (Bottom _) = return mempty
|
||||
queryComplexTerm tc (t :<- nestedTerms) = flip runReaderT (QueryEnv mempty t tc) $ do
|
||||
-- The same term as t, but using the reader's for the sake of clarity.
|
||||
givenSuperTerm <- asks envSuperTerm
|
||||
initialTagSet <- Super <$> queryTerm givenSuperTerm
|
||||
queryResult <-
|
||||
local (\e -> e{envTagSet = initialTagSet})
|
||||
. queryParallelSubTerms
|
||||
$ nestedTerms
|
||||
TermResult <$> (getFileSetFromTagSet . runSuper $ queryResult)
|
||||
|
||||
{- |
|
||||
width-wise query
|
||||
-}
|
||||
queryParallelSubTerms ::
|
||||
NonEmpty (ComplexTerm Text) ->
|
||||
ReaderT QueryEnv IO (Super (HashSet Tag))
|
||||
queryParallelSubTerms (widthTerminal :| []) = queryNestedSubTerm widthTerminal
|
||||
queryParallelSubTerms (term :| parallelTerms) = do
|
||||
(runSuper -> currentTermQueryResults) <- queryNestedSubTerm term
|
||||
(runSuper -> parallelResults) <- queryParallelSubTerms . NE.fromList $ parallelTerms
|
||||
return . Super $
|
||||
HS.intersection
|
||||
currentTermQueryResults
|
||||
parallelResults
|
||||
|
||||
{- |
|
||||
depth-wise query
|
||||
-}
|
||||
queryNestedSubTerm :: ComplexTerm Text -> ReaderT QueryEnv IO (Super (HashSet Tag))
|
||||
queryNestedSubTerm (Bottom t) = do
|
||||
currentTermResult <- runSubQuery t
|
||||
currentSuperSet <- asks envTagSet
|
||||
return . joinOnSuperTag currentSuperSet $ currentTermResult
|
||||
queryNestedSubTerm (t :<- nestedTerms) = do
|
||||
subQueryResults <- do
|
||||
currentTermResults <- runSubQuery t
|
||||
Sub . runSuper
|
||||
<$> ( local
|
||||
( \e ->
|
||||
e
|
||||
{ envTagSet = Super . runSub $ currentTermResults
|
||||
, envSuperTerm = t
|
||||
}
|
||||
)
|
||||
. queryParallelSubTerms
|
||||
$ nestedTerms
|
||||
)
|
||||
currentSuperSet <- asks envTagSet
|
||||
return . joinOnSuperTag currentSuperSet $ subQueryResults
|
||||
|
||||
runSubQuery :: Term Text -> ReaderT QueryEnv IO (Sub (HashSet Tag))
|
||||
runSubQuery t = do
|
||||
superTerm <- asks envSuperTerm
|
||||
queryTerms superTerm t
|
||||
|
||||
joinOnSuperTag :: Super (HashSet Tag) -> Sub (HashSet Tag) -> Super (HashSet Tag)
|
||||
joinOnSuperTag (runSuper -> superSet) (runSub -> subSet) =
|
||||
let !subTagOfIdSet = HS.map tagSubtagOfId subSet
|
||||
in Super . HS.filter (flip HS.member subTagOfIdSet . Just . tagId) $ superSet
|
||||
|
||||
querySimpleTerm ::
|
||||
TaggedConnection ->
|
||||
SimpleTerm Text ->
|
||||
IO TermResult
|
||||
querySimpleTerm tc (SimpleTerm (Term qc p)) =
|
||||
case qc of
|
||||
DescriptorCriteria ->
|
||||
TermResult . HS.fromList <$> flatQueryForFileByTagDescriptorPattern p tc
|
||||
MetaDescriptorCriteria ->
|
||||
TermResult . HS.fromList <$> flatQueryForFileOnMetaRelationPattern p tc
|
||||
FilePatternCriteria ->
|
||||
TermResult . HS.fromList <$> queryForFileByPattern p tc
|
||||
UntaggedCriteria ->
|
||||
TermResult . HS.fromList <$> queryForUntaggedFiles tc
|
||||
|
||||
{- |
|
||||
Should perform an associative strict intersection of the given 'TermResult`s.
|
||||
-}
|
||||
intersectTermResults :: [TermResult] -> TermResult
|
||||
intersectTermResults [] = emptyTermResult
|
||||
intersectTermResults trs = L.foldl1' intersectTermResult trs
|
||||
|
||||
intersectTermResult :: TermResult -> TermResult -> TermResult
|
||||
intersectTermResult (TermResult x) (TermResult y) = TermResult $ HS.intersection x y
|
||||
|
||||
combineSentences :: [CombinableSentenceResult] -> CombinableSentenceResult
|
||||
combineSentences [] = emptyCombinableSentenceResult
|
||||
combineSentences cs = L.foldl1' combineSentence cs
|
||||
|
||||
{- |
|
||||
Left-associative combination of the results of a combinable sentence query.
|
||||
-}
|
||||
combineSentence ::
|
||||
CombinableSentenceResult ->
|
||||
CombinableSentenceResult ->
|
||||
CombinableSentenceResult
|
||||
combineSentence
|
||||
(CombinableSentenceResult sox sx)
|
||||
(CombinableSentenceResult soy sy) = CombinableSentenceResult sox $ combFun soy sx sy
|
||||
|
||||
{- |
|
||||
Return an empty result with a default 'SetOp` of Union.
|
||||
-}
|
||||
emptyCombinableSentenceResult :: CombinableSentenceResult
|
||||
emptyCombinableSentenceResult = CombinableSentenceResult Union HS.empty
|
||||
|
||||
emptyTermResult :: TermResult
|
||||
emptyTermResult = TermResult HS.empty
|
||||
|
||||
combFun ::
|
||||
Hashable a =>
|
||||
SetOp ->
|
||||
HashSet a ->
|
||||
HashSet a ->
|
||||
HashSet a
|
||||
combFun so =
|
||||
case so of
|
||||
Union -> HS.union
|
||||
Intersect -> HS.intersection
|
||||
Difference -> HS.difference
|
383
lib/Text/TaggerQL/Engine/QueryEngine/Query.hs
Normal file
383
lib/Text/TaggerQL/Engine/QueryEngine/Query.hs
Normal file
@ -0,0 +1,383 @@
|
||||
{-# LANGUAGE BangPatterns #-}
|
||||
{-# HLINT ignore "Eta reduce" #-}
|
||||
{-# LANGUAGE DeriveFunctor #-}
|
||||
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE QuasiQuotes #-}
|
||||
{-# LANGUAGE ViewPatterns #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
{-# OPTIONS_HADDOCK hide #-}
|
||||
|
||||
module Text.TaggerQL.Engine.QueryEngine.Query (
|
||||
QueryEnv (..),
|
||||
Super (..),
|
||||
Sub (..),
|
||||
QueryReader,
|
||||
queryTerms,
|
||||
queryTerm,
|
||||
getFileSetFromTagSet,
|
||||
) where
|
||||
|
||||
import Control.Monad.Trans.Class (MonadTrans (lift))
|
||||
import Control.Monad.Trans.Reader (ReaderT, asks)
|
||||
import Data.HashSet (HashSet)
|
||||
import qualified Data.HashSet as HS
|
||||
import Data.Hashable (Hashable)
|
||||
import Data.Tagger (
|
||||
QueryCriteria (
|
||||
DescriptorCriteria,
|
||||
FilePatternCriteria,
|
||||
MetaDescriptorCriteria
|
||||
),
|
||||
)
|
||||
import Data.Text (Text)
|
||||
import Database.Tagger.Connection (
|
||||
NamedParam (..),
|
||||
ToField,
|
||||
query,
|
||||
queryNamed,
|
||||
)
|
||||
import Database.Tagger.Query.Type (TaggerQuery)
|
||||
import Database.Tagger.Type (File, Tag (tagId), TaggedConnection)
|
||||
import Text.RawString.QQ (r)
|
||||
import Text.TaggerQL.AST (Term (Term))
|
||||
|
||||
newtype Super a = Super {runSuper :: a} deriving (Show, Eq, Functor, Hashable, Semigroup, Monoid)
|
||||
|
||||
newtype Sub a = Sub {runSub :: a} deriving (Show, Eq, Functor, Hashable, Semigroup, Monoid)
|
||||
|
||||
data QueryEnv = QueryEnv
|
||||
{ envTagSet :: Super (HashSet Tag)
|
||||
, envSuperTerm :: Term Text
|
||||
, envConn :: TaggedConnection
|
||||
}
|
||||
deriving (Show, Eq)
|
||||
|
||||
type QueryReader a = ReaderT QueryEnv IO a
|
||||
|
||||
{- |
|
||||
Given two terms, run a subtag style search using their given 'QueryCriteria` and
|
||||
patterns.
|
||||
-}
|
||||
queryTerms :: Term Text -> Term Text -> QueryReader (Sub (HashSet Tag))
|
||||
queryTerms (Term qcx px) (Term qcy py) =
|
||||
dispatchQuery qcx qcy px py
|
||||
|
||||
dispatchQuery ::
|
||||
QueryCriteria ->
|
||||
QueryCriteria ->
|
||||
(Text -> Text -> QueryReader (Sub (HashSet Tag)))
|
||||
dispatchQuery x y =
|
||||
case x of
|
||||
DescriptorCriteria -> case y of
|
||||
DescriptorCriteria -> dSubD
|
||||
MetaDescriptorCriteria -> dSubR
|
||||
FilePatternCriteria -> dSubP
|
||||
_ -> uSubAnything
|
||||
MetaDescriptorCriteria -> case y of
|
||||
DescriptorCriteria -> rSubD
|
||||
MetaDescriptorCriteria -> rSubR
|
||||
FilePatternCriteria -> rSubP
|
||||
_ -> uSubAnything
|
||||
FilePatternCriteria -> case y of
|
||||
DescriptorCriteria -> pSubD
|
||||
MetaDescriptorCriteria -> pSubR
|
||||
FilePatternCriteria -> pSubP
|
||||
_ -> uSubAnything
|
||||
_ -> uSubAnything
|
||||
|
||||
{- |
|
||||
Run a query on a single term and produce an environment with corresponding 'Tag`s
|
||||
|
||||
Naturally, querying with 'UntaggedCriteria` will always produce an empty set.
|
||||
-}
|
||||
queryTerm :: Term Text -> QueryReader (HashSet Tag)
|
||||
queryTerm (Term qc p) = dispatchSimpleQuery qc p
|
||||
where
|
||||
dispatchSimpleQuery :: QueryCriteria -> Text -> QueryReader (HashSet Tag)
|
||||
dispatchSimpleQuery qc' p' =
|
||||
case qc' of
|
||||
DescriptorCriteria ->
|
||||
runSimpleDispatchQuery
|
||||
p'
|
||||
[r|
|
||||
SELECT
|
||||
t.id
|
||||
,t.fileId
|
||||
,t.descriptorId
|
||||
,t.subTagOfId
|
||||
FROM Tag t
|
||||
JOIN Descriptor d ON t.descriptorId = d.id
|
||||
WHERE d.descriptor LIKE ? ESCAPE '\'|]
|
||||
MetaDescriptorCriteria ->
|
||||
runSimpleDispatchQuery
|
||||
p'
|
||||
[r|
|
||||
SELECT
|
||||
t.id
|
||||
,t.fileId
|
||||
,t.descriptorId
|
||||
,t.subTagOfId
|
||||
FROM Tag t
|
||||
JOIN (
|
||||
WITH RECURSIVE r(id) AS (
|
||||
SELECT id
|
||||
FROM Descriptor
|
||||
WHERE descriptor LIKE ? ESCAPE '\'
|
||||
UNION
|
||||
SELECT infraDescriptorId
|
||||
FROM MetaDescriptor md
|
||||
JOIN r ON md.metaDescriptorId = r.id
|
||||
)
|
||||
SELECT id FROM r
|
||||
) AS d ON t.descriptorId = d.id|]
|
||||
FilePatternCriteria ->
|
||||
runSimpleDispatchQuery
|
||||
p'
|
||||
[r|
|
||||
SELECT
|
||||
t.id
|
||||
,t.fileId
|
||||
,t.descriptorId
|
||||
,t.subTagOfId
|
||||
FROM Tag t
|
||||
JOIN File f ON t.fileId = f.id
|
||||
WHERE f.filePath LIKE ? ESCAPE '\'|]
|
||||
_ -> return mempty
|
||||
where
|
||||
runSimpleDispatchQuery :: Text -> TaggerQuery -> QueryReader (HashSet Tag)
|
||||
runSimpleDispatchQuery p'' q'' = do
|
||||
conn <- asks envConn
|
||||
results <- lift $ query conn q'' [p''] :: QueryReader [Tag]
|
||||
return . HS.fromList $ results
|
||||
|
||||
getFileSetFromTagSet :: HashSet Tag -> QueryReader (HashSet File)
|
||||
getFileSetFromTagSet (map tagId . HS.toList -> ts) = do
|
||||
conn <- asks envConn
|
||||
results <-
|
||||
lift $
|
||||
mapM (query conn q . (: [])) ts ::
|
||||
QueryReader [[File]]
|
||||
return . HS.unions . map HS.fromList $ results
|
||||
where
|
||||
q =
|
||||
[r|
|
||||
SELECT
|
||||
f.id
|
||||
,f.filePath
|
||||
FROM File f
|
||||
JOIN Tag t ON f.id = t.fileId
|
||||
WHERE t.id = ?
|
||||
|]
|
||||
|
||||
{-
|
||||
____
|
||||
| _ \
|
||||
| | | |
|
||||
| |_| |
|
||||
|____/
|
||||
-}
|
||||
|
||||
withDSuper ::
|
||||
(ToField v1, ToField a) =>
|
||||
TaggerQuery ->
|
||||
v1 ->
|
||||
a ->
|
||||
QueryReader (Sub (HashSet Tag))
|
||||
withDSuper q = (subTagQuery (constructQuery superDSubQuery q) .) . superSubParams
|
||||
where
|
||||
superDSubQuery :: TaggerQuery
|
||||
superDSubQuery =
|
||||
[r|
|
||||
SELECT
|
||||
t.id
|
||||
,t.fileId
|
||||
,t.descriptorId
|
||||
,t.subTagOfId
|
||||
FROM Tag t
|
||||
JOIN Descriptor d ON t.descriptorId = d.id
|
||||
WHERE d.descriptor LIKE :super ESCAPE '\'|]
|
||||
|
||||
dSubP :: Text -> Text -> QueryReader (Sub (HashSet Tag))
|
||||
dSubP = withDSuper subPSubQuery
|
||||
|
||||
dSubR :: Text -> Text -> QueryReader (Sub (HashSet Tag))
|
||||
dSubR = withDSuper subRSubQuery
|
||||
|
||||
dSubD :: Text -> Text -> QueryReader (Sub (HashSet Tag))
|
||||
dSubD = withDSuper subDSubQuery
|
||||
|
||||
{-
|
||||
____
|
||||
| _ \
|
||||
| |_) |
|
||||
| _ <
|
||||
|_| \_\
|
||||
-}
|
||||
|
||||
withRSuper ::
|
||||
(ToField v1, ToField a) =>
|
||||
TaggerQuery ->
|
||||
v1 ->
|
||||
a ->
|
||||
QueryReader (Sub (HashSet Tag))
|
||||
withRSuper q = (subTagQuery (constructQuery superRSubQuery q) .) . superSubParams
|
||||
where
|
||||
superRSubQuery :: TaggerQuery
|
||||
superRSubQuery =
|
||||
[r|
|
||||
SELECT
|
||||
t.id
|
||||
,t.fileId
|
||||
,t.descriptorId
|
||||
,t.subTagOfId
|
||||
FROM Tag t
|
||||
JOIN (
|
||||
WITH RECURSIVE qr (id) AS (
|
||||
SELECT id
|
||||
FROM Descriptor
|
||||
WHERE descriptor LIKE :super ESCAPE '\'
|
||||
UNION
|
||||
SELECT infraDescriptorId
|
||||
FROM MetaDescriptor md
|
||||
JOIN qr ON md.metaDescriptorId = qr.id
|
||||
)
|
||||
SELECT id FROM qr
|
||||
) AS d ON t.descriptorId = d.id|]
|
||||
|
||||
rSubP :: Text -> Text -> QueryReader (Sub (HashSet Tag))
|
||||
rSubP = withRSuper subPSubQuery
|
||||
|
||||
rSubR :: Text -> Text -> QueryReader (Sub (HashSet Tag))
|
||||
rSubR = withRSuper subRSubQuery
|
||||
|
||||
rSubD :: Text -> Text -> QueryReader (Sub (HashSet Tag))
|
||||
rSubD = withRSuper subDSubQuery
|
||||
|
||||
{-
|
||||
____
|
||||
| _ \
|
||||
| |_) |
|
||||
| __/
|
||||
|_|
|
||||
-}
|
||||
|
||||
withPSuper ::
|
||||
(ToField v1, ToField a) =>
|
||||
TaggerQuery ->
|
||||
v1 ->
|
||||
a ->
|
||||
QueryReader (Sub (HashSet Tag))
|
||||
withPSuper q = (subTagQuery (constructQuery superPSubQuery q) .) . superSubParams
|
||||
where
|
||||
superPSubQuery =
|
||||
[r|
|
||||
SELECT
|
||||
t.id
|
||||
,t.fileId
|
||||
,t.descriptorId
|
||||
,t.subTagOfId
|
||||
FROM Tag t
|
||||
JOIN File f ON t.fileId = f.id
|
||||
WHERE f.filePath LIKE :super ESCAPE '\'|]
|
||||
|
||||
pSubP :: Text -> Text -> QueryReader (Sub (HashSet Tag))
|
||||
pSubP = withPSuper subPSubQuery
|
||||
|
||||
pSubR :: Text -> Text -> QueryReader (Sub (HashSet Tag))
|
||||
pSubR = withPSuper subRSubQuery
|
||||
|
||||
pSubD :: Text -> Text -> QueryReader (Sub (HashSet Tag))
|
||||
pSubD = withPSuper subDSubQuery
|
||||
|
||||
{-
|
||||
_ _
|
||||
| | | |
|
||||
| | | |
|
||||
| |_| |
|
||||
\___/
|
||||
-}
|
||||
|
||||
uSubAnything :: Text -> Text -> QueryReader (Sub (HashSet Tag))
|
||||
uSubAnything _ _ = return mempty
|
||||
|
||||
constructQuery :: TaggerQuery -> TaggerQuery -> TaggerQuery
|
||||
constructQuery super sub =
|
||||
[r|
|
||||
SELECT
|
||||
t1.id
|
||||
,t1.fileId
|
||||
,t1.descriptorId
|
||||
,t1.subTagOfId
|
||||
FROM (
|
||||
|]
|
||||
<> super
|
||||
<> [r|
|
||||
) AS t
|
||||
JOIN (|]
|
||||
<> sub
|
||||
<> [r|) AS t1 ON t.id = t1.subTagOfId
|
||||
|]
|
||||
|
||||
subDSubQuery :: TaggerQuery
|
||||
subDSubQuery =
|
||||
[r|
|
||||
SELECT
|
||||
t.id
|
||||
,t.fileId
|
||||
,t.descriptorId
|
||||
,t.subTagOfId
|
||||
FROM Tag t
|
||||
JOIN Descriptor d ON t.descriptorId = d.id
|
||||
WHERE d.descriptor LIKE :sub ESCAPE '\'
|
||||
|]
|
||||
|
||||
subRSubQuery :: TaggerQuery
|
||||
subRSubQuery =
|
||||
[r|
|
||||
SELECT
|
||||
t.id
|
||||
,t.fileId
|
||||
,t.descriptorId
|
||||
,t.subTagOfId
|
||||
FROM Tag t
|
||||
JOIN (
|
||||
WITH RECURSIVE qr (id) AS (
|
||||
SELECT id
|
||||
FROM Descriptor
|
||||
WHERE descriptor LIKE :sub ESCAPE '\'
|
||||
UNION
|
||||
SELECT infraDescriptorId
|
||||
FROM MetaDescriptor md
|
||||
JOIN qr ON md.metaDescriptorId = qr.id
|
||||
)
|
||||
SELECT id FROM qr
|
||||
) AS d ON t.descriptorId = d.id
|
||||
|]
|
||||
|
||||
subPSubQuery :: TaggerQuery
|
||||
subPSubQuery =
|
||||
[r|
|
||||
SELECT
|
||||
t.id
|
||||
,t.fileId
|
||||
,t.descriptorId
|
||||
,t.subTagOfId
|
||||
FROM Tag t
|
||||
JOIN File f ON t.fileId = f.id
|
||||
WHERE f.filePath LIKE :sub ESCAPE '\'
|
||||
|]
|
||||
|
||||
subTagQuery ::
|
||||
TaggerQuery ->
|
||||
[NamedParam] ->
|
||||
QueryReader (Sub (HashSet Tag))
|
||||
subTagQuery q params = do
|
||||
conn <- asks envConn
|
||||
results <-
|
||||
lift $ queryNamed conn q params ::
|
||||
ReaderT QueryEnv IO [Tag]
|
||||
return . Sub . HS.fromList $ results
|
||||
|
||||
superSubParams :: (ToField v1, ToField v2) => v1 -> v2 -> [NamedParam]
|
||||
superSubParams super sub = [":super" := super, ":sub" := sub]
|
275
lib/Text/TaggerQL/Parser/Internal.hs
Normal file
275
lib/Text/TaggerQL/Parser/Internal.hs
Normal file
@ -0,0 +1,275 @@
|
||||
{-# LANGUAGE FlexibleContexts #-}
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
{-# LANGUAGE StrictData #-}
|
||||
{-# HLINT ignore "Use <$>" #-}
|
||||
{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}
|
||||
|
||||
module Text.TaggerQL.Parser.Internal (
|
||||
-- * Parsers
|
||||
requestParser,
|
||||
sentenceTreeParser,
|
||||
sentenceParser,
|
||||
complexTermParser,
|
||||
complexTermChildrenParser,
|
||||
bottomTermParser,
|
||||
termParser,
|
||||
|
||||
-- * Additional
|
||||
parse,
|
||||
|
||||
-- ** 'SetOp` Literals
|
||||
-- $SetOp
|
||||
|
||||
-- ** 'QueryCriteria` Literals
|
||||
-- $QueryCriteria
|
||||
) where
|
||||
|
||||
import Control.Monad (void, when)
|
||||
import Data.Char (toLower)
|
||||
|
||||
import Data.Maybe (isJust)
|
||||
import Data.Tagger (QueryCriteria (..), SetOp (..))
|
||||
import qualified Data.Text as T
|
||||
import Text.Parsec (
|
||||
Parsec,
|
||||
ParsecT,
|
||||
Stream,
|
||||
between,
|
||||
choice,
|
||||
many1,
|
||||
noneOf,
|
||||
notFollowedBy,
|
||||
oneOf,
|
||||
optionMaybe,
|
||||
parse,
|
||||
satisfy,
|
||||
sepBy1,
|
||||
spaces,
|
||||
try,
|
||||
(<?>),
|
||||
(<|>),
|
||||
)
|
||||
import Text.TaggerQL.AST
|
||||
|
||||
type Parser a = Parsec T.Text () a
|
||||
|
||||
type QueryCriteriaLiteralParser = Parser QueryCriteria
|
||||
|
||||
type SetOpParser = Parser SetOp
|
||||
|
||||
{- $SetOp
|
||||
A 'SetOp` is a data type that describes how data structures can be combined together.
|
||||
|
||||
A 'SetOp` literal is TaggerQL's representation of this type's constructors.
|
||||
Any reference to either a 'SetOp` or 'SetOp` Literal probably refers to these:
|
||||
|
||||
* u| == 'Union`
|
||||
* i| == 'Intersect`
|
||||
* d| == 'Difference`
|
||||
|
||||
Note that 'SetOp` Literals are case-insensitive.
|
||||
-}
|
||||
|
||||
{- $QueryCriteria
|
||||
A 'QueryCriteria` is a data type that determines what a search is performed on.
|
||||
|
||||
TaggerQL's representation of its constructors as literals are as follows:
|
||||
|
||||
* d. == 'DescriptorCriteria`
|
||||
* r. == 'MetaDescriptorCriteria` \*
|
||||
* p. == 'FilePatternCriteria`
|
||||
* u. == 'UntaggedCriteria`
|
||||
|
||||
Note that the literals are case-insensitive.
|
||||
|
||||
\* this literal is 'r.' to refer to a "relation"
|
||||
-}
|
||||
|
||||
{- |
|
||||
Parse many 'SentenceTree`s and store them in a list.
|
||||
|
||||
'SentenceTree`s will later be subject to querying and a left-associative fold
|
||||
to combine their results, so order of sentences in this parser is important.
|
||||
-}
|
||||
requestParser :: Parser (Request T.Text)
|
||||
requestParser = Request <$> between spaces spaces (many1 sentenceTreeParser)
|
||||
|
||||
{- |
|
||||
Parse a 'SentenceTree` which is either:
|
||||
|
||||
* A 'Sentence` preceded by an optional 'SetOp` literal, defaults to 'Union`
|
||||
* An explicit 'SetOp` literal and 1 or more 'SentenceTree`s wrapped in ().
|
||||
The 'SentenceTree` parser is recursive and can nest arbitrary amounts of times.
|
||||
-}
|
||||
sentenceTreeParser :: Parser (SentenceTree T.Text)
|
||||
sentenceTreeParser =
|
||||
try sentenceTreeBranchParser
|
||||
<|> sentenceTreeNodeParser
|
||||
|
||||
sentenceTreeBranchParser :: Parser (SentenceTree T.Text)
|
||||
sentenceTreeBranchParser = do
|
||||
so <- explicitOpParser
|
||||
spaces
|
||||
queryOpenParser
|
||||
cs <- sepBy1 sentenceTreeParser spaces
|
||||
queryCloseParser
|
||||
spaces
|
||||
return $ SentenceBranch so cs
|
||||
|
||||
sentenceTreeNodeParser :: Parser (SentenceTree T.Text)
|
||||
sentenceTreeNodeParser = SentenceNode <$> combinableSentenceParser
|
||||
|
||||
combinableSentenceParser :: Parser (SentenceSet T.Text)
|
||||
combinableSentenceParser = do
|
||||
-- is it ever possible to get this default SetOp value from a query?
|
||||
-- -- yes, "a d| (b u| c) d e f" produces this default value in the SentenceNode
|
||||
-- -- containing [d, e, f] so that:
|
||||
-- -- SentenceNode (SentenceSet {DefaultValue} (Sentence [d, e, f]))
|
||||
so <- explicitOpParser <|> pure Intersect
|
||||
spaces
|
||||
s <- sentenceParser
|
||||
return $ CombinableSentence so s
|
||||
|
||||
{- |
|
||||
Parses 1 or more 'TermTree`s that are separated by spaces.
|
||||
|
||||
This parser parses a list of 'ComplexTerm`s and lifts them to a 'TermTree` before
|
||||
mapping over the list and calling 'simplifyTermTree` to convert all of the top-level
|
||||
'Bottom`s to 'SimpleTerm`s.
|
||||
-}
|
||||
sentenceParser :: Parser (Sentence T.Text)
|
||||
sentenceParser = do
|
||||
cts <- map (simplifyTermTree . Complex) <$> sepBy1 (try complexTermParser) spaces
|
||||
return . Sentence $ cts
|
||||
|
||||
{- |
|
||||
Parse a 'ComplexTerm` with 0 or more nested 'ComplexTerm` predicates.
|
||||
|
||||
Defaults to a 'Bottom` if there are no predicates.
|
||||
-}
|
||||
complexTermParser :: Parser (ComplexTerm T.Text)
|
||||
complexTermParser = do
|
||||
basis <- bottomTermParser
|
||||
spaces
|
||||
predicates <- optionMaybe complexTermChildrenParser
|
||||
when
|
||||
(isJust predicates && (termCriteria . complexTermNode $ basis) == UntaggedCriteria)
|
||||
(fail "Cannot use UntaggedCriteria literal \"U.\" with a subquery.")
|
||||
spaces
|
||||
let node = maybe basis (newPredicates basis) predicates
|
||||
return node
|
||||
|
||||
{- |
|
||||
Parse all 'ComplexTerm`s inside of a given subclause surrounded by {}
|
||||
-}
|
||||
complexTermChildrenParser :: Parser [ComplexTerm T.Text]
|
||||
complexTermChildrenParser = do
|
||||
subClauseScopeOpenParser
|
||||
t <- sepBy1 complexTermParser spaces
|
||||
subClauseScopeCloseParser
|
||||
return t
|
||||
|
||||
{- |
|
||||
Parse a 'Term` and return it as 'Bottom`.
|
||||
-}
|
||||
bottomTermParser :: Parser (ComplexTerm T.Text)
|
||||
bottomTermParser = Bottom <$> termParser
|
||||
|
||||
{- |
|
||||
Parse a 'Term` from a 'QueryCriteria` literal and text pattern.
|
||||
|
||||
The pattern may not contain members of the set 'charRequiringEscape` except if
|
||||
an escape character '\' is placed before one.
|
||||
-}
|
||||
termParser :: Parser (Term T.Text)
|
||||
termParser = do
|
||||
qc <- anyCriteriaLiteralParser
|
||||
p <- acceptablePatternParser
|
||||
return $ Term qc p
|
||||
|
||||
{- |
|
||||
Parses a 'SetOp` literal or nothing.
|
||||
-}
|
||||
explicitOpParser :: SetOpParser
|
||||
explicitOpParser = choice . map try $ [unionOpParser, intersectOpParser, diffOpParser]
|
||||
|
||||
unionOpParser :: SetOpParser
|
||||
unionOpParser = ichar 'u' >> ichar '|' >> return Union
|
||||
|
||||
intersectOpParser :: SetOpParser
|
||||
intersectOpParser = ichar 'i' >> ichar '|' >> return Intersect
|
||||
|
||||
diffOpParser :: SetOpParser
|
||||
diffOpParser = ichar 'd' >> ichar '|' >> return Difference
|
||||
|
||||
queryOpenParser :: Parser ()
|
||||
queryOpenParser = void (ichar '(') >> spaces
|
||||
|
||||
queryCloseParser :: Parser ()
|
||||
queryCloseParser = void spaces >> void (ichar ')')
|
||||
|
||||
subClauseScopeOpenParser :: Parser ()
|
||||
subClauseScopeOpenParser = void (ichar '{') >> spaces
|
||||
|
||||
subClauseScopeCloseParser :: Parser ()
|
||||
subClauseScopeCloseParser = spaces >> void (ichar '}')
|
||||
|
||||
anyCriteriaLiteralParser :: QueryCriteriaLiteralParser
|
||||
anyCriteriaLiteralParser =
|
||||
( choice . map try $
|
||||
[ descriptorCriteriaLiteralParser
|
||||
, metaDescriptorCriteriaLiteralParser
|
||||
, filePatternCriteriaLiteralParser
|
||||
, untaggedCriteriaLiteralParser
|
||||
]
|
||||
)
|
||||
<|> pure MetaDescriptorCriteria
|
||||
|
||||
descriptorCriteriaLiteralParser :: QueryCriteriaLiteralParser
|
||||
descriptorCriteriaLiteralParser = ichar 'd' >> ichar '.' >> return DescriptorCriteria
|
||||
|
||||
metaDescriptorCriteriaLiteralParser :: QueryCriteriaLiteralParser
|
||||
metaDescriptorCriteriaLiteralParser =
|
||||
ichar 'r' >> ichar '.' >> return MetaDescriptorCriteria
|
||||
|
||||
filePatternCriteriaLiteralParser :: QueryCriteriaLiteralParser
|
||||
filePatternCriteriaLiteralParser = ichar 'p' >> ichar '.' >> return FilePatternCriteria
|
||||
|
||||
untaggedCriteriaLiteralParser :: QueryCriteriaLiteralParser
|
||||
untaggedCriteriaLiteralParser = ichar 'u' >> ichar '.' >> return UntaggedCriteria
|
||||
|
||||
{- |
|
||||
Case-insensitive 'Char` parser.
|
||||
-}
|
||||
ichar :: Stream s m Char => Char -> ParsecT s u m Char
|
||||
ichar c = satisfy (\c' -> toLower c == toLower c')
|
||||
|
||||
acceptablePatternParser :: Parser T.Text
|
||||
acceptablePatternParser =
|
||||
(fmap T.pack . many1 $ acceptableCharParser)
|
||||
<?> ( "an acceptable pattern of characters not in the set, '"
|
||||
++ charRequiringEscape
|
||||
++ "' or any of those characters with an escape char, \\, before it."
|
||||
)
|
||||
|
||||
acceptableCharParser :: Parser Char
|
||||
acceptableCharParser = do
|
||||
c <-
|
||||
( try
|
||||
( do
|
||||
void $ ichar '\\'
|
||||
oneOf charRequiringEscape
|
||||
)
|
||||
<|> ichar '\\'
|
||||
)
|
||||
<|> notDisallowedChars
|
||||
when (c `elem` ("ud" :: String)) (notFollowedBy (ichar '|' <|> ichar '.'))
|
||||
when (c `elem` ("rp" :: String)) (notFollowedBy $ ichar '.')
|
||||
when (c == 'i') (notFollowedBy $ ichar '|')
|
||||
return c
|
||||
|
||||
notDisallowedChars :: Parser Char
|
||||
notDisallowedChars = noneOf charRequiringEscape
|
||||
|
||||
charRequiringEscape :: [Char]
|
||||
charRequiringEscape = "{}().| \t\n\r"
|
42
lib/tagger-exe-internal/Tagger/Shared.hs
Normal file
42
lib/tagger-exe-internal/Tagger/Shared.hs
Normal file
@ -0,0 +1,42 @@
|
||||
{-# LANGUAGE ViewPatterns #-}
|
||||
|
||||
module Tagger.Shared (
|
||||
addFiles,
|
||||
) where
|
||||
|
||||
import Data.Text (Text)
|
||||
import qualified Data.Text as T
|
||||
import Database.Tagger
|
||||
import System.Directory (
|
||||
doesDirectoryExist,
|
||||
doesFileExist,
|
||||
getCurrentDirectory,
|
||||
listDirectory,
|
||||
)
|
||||
import System.FilePath (makeRelative, (</>))
|
||||
|
||||
{- |
|
||||
Add all files recursively beginning at the given filepath to the database.
|
||||
|
||||
The given path is made relative to the current working directory, then
|
||||
subsequent nested paths are made relative to that.
|
||||
-}
|
||||
addFiles :: TaggedConnection -> Text -> IO ()
|
||||
addFiles c (T.unpack -> givenPath) = do
|
||||
curDir <- getCurrentDirectory
|
||||
let fpRelativeToCurDir = makeRelative curDir givenPath
|
||||
getPathsToAdd [] fpRelativeToCurDir >>= flip insertFiles c
|
||||
where
|
||||
getPathsToAdd :: [FilePath] -> FilePath -> IO [FilePath]
|
||||
getPathsToAdd acc fp = do
|
||||
pathIsDir <- doesDirectoryExist fp
|
||||
if pathIsDir
|
||||
then do
|
||||
dirContents <- listDirectory fp
|
||||
addedContents <- concat <$> mapM (\dp -> getPathsToAdd [] (fp </> dp)) dirContents
|
||||
return $ addedContents ++ acc
|
||||
else do
|
||||
pathIsFile <- doesFileExist fp
|
||||
if pathIsFile
|
||||
then return (fp : acc)
|
||||
else return acc
|
199
tagger.cabal
Normal file
199
tagger.cabal
Normal file
@ -0,0 +1,199 @@
|
||||
cabal-version: 2.4
|
||||
|
||||
name: tagger
|
||||
version: 1.0.2.1
|
||||
synopsis: A file/image tagger that connects to or initializes sqlite databases.
|
||||
-- description:
|
||||
-- bug-reports:
|
||||
license: GPL-3.0-only
|
||||
license-file: LICENSE
|
||||
author: monawasensei
|
||||
maintainer: monawasensei@gmail.com
|
||||
-- copyright:
|
||||
category: Database
|
||||
extra-source-files: CHANGELOG.md
|
||||
data-files: Yui_signature_SS.bmp
|
||||
,Yui_signature_SS.png
|
||||
,iosevka_thin.ttf
|
||||
,iosevka_regular.ttf
|
||||
,iosevka_bold.ttf
|
||||
,TaggerSchemaDefinition.sql
|
||||
,TaggerSchemaTeardown.sql
|
||||
|
||||
common haskell-common
|
||||
default-language: Haskell2010
|
||||
|
||||
ghc-options: -Wall
|
||||
|
||||
build-depends: base ^>= 4.13.0.0
|
||||
,Cabal
|
||||
|
||||
common tagger-common
|
||||
other-extensions: OverloadedStrings
|
||||
,TemplateHaskell
|
||||
,FlexibleContexts
|
||||
,FlexibleInstances
|
||||
,FunctionalDependencies
|
||||
,StrictData
|
||||
,ViewPatterns
|
||||
|
||||
other-modules: Paths_tagger
|
||||
|
||||
build-depends: lens == 5.1
|
||||
,text == 1.2.4.0
|
||||
,transformers == 0.5.6.2
|
||||
,hashable == 1.4.0.2
|
||||
,containers == 0.6.2.1
|
||||
,unordered-containers == 0.2.18.0
|
||||
|
||||
executable tagger
|
||||
import: haskell-common
|
||||
,tagger-common
|
||||
|
||||
main-is: Main.hs
|
||||
|
||||
other-modules: Config
|
||||
,Data.Event
|
||||
,Data.Model
|
||||
,Data.Model.Core
|
||||
,Data.Model.Lens
|
||||
,Data.Model.Shared
|
||||
,Data.Model.Shared.Core
|
||||
,Data.Model.Shared.Lens
|
||||
,Interface
|
||||
,Interface.Handler
|
||||
,Interface.Handler.Internal
|
||||
,Interface.Theme
|
||||
,Interface.Widget
|
||||
,Interface.Widget.Internal.Core
|
||||
,Interface.Widget.Internal.DescriptorTree
|
||||
,Interface.Widget.Internal.FileDetail
|
||||
,Interface.Widget.Internal.FilePreview
|
||||
,Interface.Widget.Internal.InfoPanel
|
||||
,Interface.Widget.Internal.Query
|
||||
,Interface.Widget.Internal.Selection
|
||||
,Interface.Widget.Internal.Type
|
||||
,Util
|
||||
|
||||
other-extensions: RankNTypes
|
||||
,MultiWayIf
|
||||
|
||||
-- ghc-options:
|
||||
|
||||
build-depends: tagger-lib
|
||||
,tagger-exe-internal
|
||||
,monomer == 1.4.1.0
|
||||
,directory == 1.3.6.0
|
||||
,filepath == 1.4.2.1
|
||||
,random
|
||||
,process
|
||||
,tomland
|
||||
|
||||
hs-source-dirs: app/tagger
|
||||
|
||||
executable taggercli
|
||||
import: haskell-common
|
||||
,tagger-common
|
||||
|
||||
main-is: Main.hs
|
||||
|
||||
other-modules: Opt
|
||||
,Opt.Data
|
||||
,Opt.Data.Lens
|
||||
,Opt.Parser
|
||||
|
||||
-- other-extensions:
|
||||
|
||||
-- ghc-options:
|
||||
|
||||
build-depends: tagger-lib
|
||||
,tagger-exe-internal
|
||||
,optparse-applicative
|
||||
,directory
|
||||
,filepath
|
||||
|
||||
hs-source-dirs: app/taggercli
|
||||
|
||||
library tagger-exe-internal
|
||||
import:
|
||||
haskell-common
|
||||
,tagger-common
|
||||
|
||||
exposed-modules:
|
||||
Tagger.Shared
|
||||
|
||||
build-depends:
|
||||
tagger-lib
|
||||
,directory
|
||||
,filepath
|
||||
|
||||
hs-source-dirs:
|
||||
lib/tagger-exe-internal
|
||||
|
||||
library tagger-lib
|
||||
import: haskell-common
|
||||
,tagger-common
|
||||
|
||||
exposed-modules: Database.Tagger
|
||||
,Database.Tagger.Type
|
||||
,Data.HierarchyMap
|
||||
,Data.OccurrenceHashMap
|
||||
,Data.OccurrenceMap
|
||||
,Data.Tagger
|
||||
,Tagger.Info
|
||||
,Text.TaggerQL
|
||||
,Text.TaggerQL.Parser.Internal
|
||||
,Text.TaggerQL.AST
|
||||
|
||||
other-modules: Database.Tagger.Script
|
||||
,Database.Tagger.Type.Lens
|
||||
,Database.Tagger.Type.Prim
|
||||
,Database.Tagger.Query
|
||||
,Database.Tagger.Query.Type
|
||||
,Database.Tagger.Connection
|
||||
,Data.Hierarchy.Internal
|
||||
,Data.OccurrenceHashMap.Internal
|
||||
,Data.OccurrenceMap.Internal
|
||||
,Tagger.Util
|
||||
,Text.TaggerQL.Engine.QueryEngine
|
||||
,Text.TaggerQL.Engine.QueryEngine.Query
|
||||
|
||||
other-extensions: DeriveGeneric
|
||||
,DeriveAnyClass
|
||||
,GeneralisedNewtypeDeriving
|
||||
,DerivingStrategies
|
||||
,OverloadedLists
|
||||
,DeriveFunctor
|
||||
,DeriveFoldable
|
||||
,BangPatterns
|
||||
,QuasiQuotes
|
||||
,TupleSections
|
||||
,BangPatterns
|
||||
|
||||
hs-source-dirs: lib
|
||||
|
||||
-- ghc-options:
|
||||
|
||||
build-depends: sqlite-simple == 0.4.18.0
|
||||
,direct-sqlite == 2.3.26
|
||||
,raw-strings-qq
|
||||
,time == 1.9.3
|
||||
,parsec
|
||||
,directory
|
||||
|
||||
default-language: Haskell2010
|
||||
|
||||
test-suite tagger-test
|
||||
import: tagger-common
|
||||
,haskell-common
|
||||
|
||||
type: exitcode-stdio-1.0
|
||||
|
||||
main-is: Main.hs
|
||||
|
||||
build-depends: tagger-lib
|
||||
,tasty
|
||||
,tasty-hunit
|
||||
,parsec
|
||||
|
||||
hs-source-dirs: test/
|
190
test/Main.hs
Normal file
190
test/Main.hs
Normal file
@ -0,0 +1,190 @@
|
||||
{-# LANGUAGE OverloadedStrings #-}
|
||||
|
||||
import Data.List.NonEmpty
|
||||
import Data.Tagger
|
||||
import Test.Tasty
|
||||
import Test.Tasty.HUnit
|
||||
import Text.TaggerQL.AST
|
||||
import Text.TaggerQL.Parser.Internal
|
||||
|
||||
main :: IO ()
|
||||
main = defaultMain (testGroup "Test" [parserEdgeCases])
|
||||
|
||||
parserEdgeCases :: TestTree
|
||||
parserEdgeCases =
|
||||
testGroup
|
||||
"Parser Edge Cases"
|
||||
[ testCase
|
||||
"Parse a nested subquery with trailing whitespace"
|
||||
( assertEqual
|
||||
""
|
||||
( Right
|
||||
( Request
|
||||
[ SentenceNode
|
||||
( CombinableSentence
|
||||
Union
|
||||
( Sentence
|
||||
[ Simple
|
||||
( SimpleTerm
|
||||
(Term MetaDescriptorCriteria "otsuki%")
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
, SentenceBranch
|
||||
Difference
|
||||
[ SentenceNode
|
||||
( CombinableSentence
|
||||
Union
|
||||
( Sentence
|
||||
[ Simple
|
||||
( SimpleTerm
|
||||
(Term MetaDescriptorCriteria "bruh")
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
, SentenceBranch
|
||||
Union
|
||||
[ SentenceNode
|
||||
( CombinableSentence
|
||||
Union
|
||||
( Sentence
|
||||
[ Simple
|
||||
( SimpleTerm
|
||||
(Term MetaDescriptorCriteria "squad")
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
]
|
||||
]
|
||||
]
|
||||
)
|
||||
)
|
||||
(parse requestParser "test" "otsuki% d|(bruh u| (squad) )")
|
||||
)
|
||||
, testCase
|
||||
"Parse a nested subquery without trailing whitespace."
|
||||
( assertEqual
|
||||
""
|
||||
( Right
|
||||
( Request
|
||||
[ SentenceNode
|
||||
( CombinableSentence
|
||||
Union
|
||||
( Sentence
|
||||
[ Simple
|
||||
( SimpleTerm
|
||||
(Term MetaDescriptorCriteria "otsuki%")
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
, SentenceBranch
|
||||
Difference
|
||||
[ SentenceNode
|
||||
( CombinableSentence
|
||||
Union
|
||||
( Sentence
|
||||
[ Simple
|
||||
( SimpleTerm
|
||||
(Term MetaDescriptorCriteria "bruh")
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
, SentenceBranch
|
||||
Union
|
||||
[ SentenceNode
|
||||
( CombinableSentence
|
||||
Union
|
||||
( Sentence
|
||||
[ Simple
|
||||
( SimpleTerm
|
||||
(Term MetaDescriptorCriteria "squad")
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
]
|
||||
]
|
||||
]
|
||||
)
|
||||
)
|
||||
(parse requestParser "test" "otsuki% d|(bruh u| (squad))")
|
||||
)
|
||||
, testCase
|
||||
"Use a parenthetical query in the middle of a query"
|
||||
( assertEqual
|
||||
""
|
||||
( Right
|
||||
( Request
|
||||
[ SentenceNode
|
||||
( CombinableSentence
|
||||
Union
|
||||
( Sentence
|
||||
[ Simple
|
||||
( SimpleTerm
|
||||
(Term MetaDescriptorCriteria "kazuho")
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
, SentenceNode
|
||||
( CombinableSentence
|
||||
Union
|
||||
( Sentence
|
||||
[ Simple
|
||||
( SimpleTerm
|
||||
(Term MetaDescriptorCriteria "kaede")
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
, SentenceBranch
|
||||
Union
|
||||
[ SentenceNode
|
||||
( CombinableSentence
|
||||
Union
|
||||
( Sentence
|
||||
[ Simple
|
||||
( SimpleTerm
|
||||
(Term MetaDescriptorCriteria "%kirari")
|
||||
)
|
||||
, Simple
|
||||
( SimpleTerm
|
||||
(Term MetaDescriptorCriteria "hold")
|
||||
)
|
||||
, Simple
|
||||
( SimpleTerm
|
||||
(Term MetaDescriptorCriteria "f%anzu")
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
]
|
||||
, SentenceNode
|
||||
( CombinableSentence
|
||||
Union
|
||||
( Sentence
|
||||
[ Complex
|
||||
( Term MetaDescriptorCriteria "k%akane"
|
||||
:<- ( Bottom
|
||||
(Term MetaDescriptorCriteria "smile")
|
||||
:| []
|
||||
)
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
( parse
|
||||
requestParser
|
||||
"test"
|
||||
"kazuho u| kaede u| (%kirari hold f%anzu) u| k%akane {smile}"
|
||||
)
|
||||
)
|
||||
]
|
Loading…
x
Reference in New Issue
Block a user